diff --git a/Assets/EchoCloudMat.mat b/Assets/EchoCloudMat.mat index 3a4aab7..19d4789 100644 --- a/Assets/EchoCloudMat.mat +++ b/Assets/EchoCloudMat.mat @@ -65,9 +65,9 @@ Material: - _WaveRadius: 0 m_Colors: - _EchoColor: {r: 4, g: 3.0263731, b: 1.0490564, a: 1} - - _EchoPosition1: {r: -3.3826168, g: 1.08, b: -18.187862, a: 0} - - _EchoPosition2: {r: -4.4241714, g: 1.08, b: -17.579414, a: 0} - - _EchoPosition3: {r: 5.3247437, g: 1.08, b: -11.604252, a: 0} + - _EchoPosition1: {r: -0.7661393, g: 1.0800002, b: -5.49929, a: 0} + - _EchoPosition2: {r: -0.76614004, g: 1.0800002, b: -10.013806, a: 0} + - _EchoPosition3: {r: 9.670952, g: 1.08, b: -10.500203, a: 0} - _WaveCenter: {r: 0, g: 0, b: 0, a: 0} m_BuildTextureStacks: [] m_AllowLocking: 1 diff --git a/Assets/Scenes/SampleScene.meta b/Assets/Scenes/SampleScene.meta new file mode 100644 index 0000000..82cb600 --- /dev/null +++ b/Assets/Scenes/SampleScene.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c8b8aab7372901b48a31d7b157b272b3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scenes/SampleScene.unity b/Assets/Scenes/SampleScene.unity index 1eca96d..2e77012 100644 --- a/Assets/Scenes/SampleScene.unity +++ b/Assets/Scenes/SampleScene.unity @@ -119,6 +119,392 @@ NavMeshSettings: debug: m_Flags: 0 m_NavMeshData: {fileID: 0} +--- !u!1 &136077227 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 136077228} + m_Layer: 0 + m_Name: 1 (2) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &136077228 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 136077227} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 4.62, y: -0, z: 3.8} + 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 &219490551 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 219490552} + m_Layer: 0 + m_Name: 1 (5) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &219490552 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 219490551} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -17.6, y: -0, z: -2.5} + 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 &258821922 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 258821923} + - component: {fileID: 258821927} + - component: {fileID: 258821926} + - component: {fileID: 258821925} + - component: {fileID: 258821924} + - component: {fileID: 258821928} + - component: {fileID: 258821929} + m_Layer: 0 + m_Name: enemy + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &258821923 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 258821922} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -2.286, y: -41.57, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 588162212} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!195 &258821924 +NavMeshAgent: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 258821922} + m_Enabled: 1 + m_AgentTypeID: 0 + m_Radius: 0.5 + m_Speed: 3.5 + m_Acceleration: 8 + avoidancePriority: 50 + m_AngularSpeed: 120 + m_StoppingDistance: 0 + m_AutoTraverseOffMeshLink: 1 + m_AutoBraking: 1 + m_AutoRepath: 1 + m_Height: 2 + m_BaseOffset: 1 + m_WalkableMask: 4294967295 + m_ObstacleAvoidanceType: 4 +--- !u!136 &258821925 +CapsuleCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 258821922} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Radius: 0.5 + m_Height: 2 + m_Direction: 1 + m_Center: {x: 0, y: 0, z: 0} +--- !u!23 &258821926 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 258821922} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 31321ba15b8f8eb4c954353edc038b1d, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!33 &258821927 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 258821922} + m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} +--- !u!114 &258821928 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 258821922} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: f3d9f888882b414fa76928f75aeae432, type: 3} + m_Name: + m_EditorClassIdentifier: Assembly-CSharp::BlindMutantAI + walkSpeed: 2 + runSpeed: 5 + patrolPoints: + - {fileID: 1964883892} + - {fileID: 753568976} + - {fileID: 136077228} + - {fileID: 288582346} + - {fileID: 397005050} + - {fileID: 219490552} + - {fileID: 1559800262} + - {fileID: 2147433586} + - {fileID: 1880967028} + - {fileID: 382267036} + - {fileID: 999495414} + - {fileID: 1164529818} + - {fileID: 1949454378} + - {fileID: 1551773958} +--- !u!114 &258821929 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 258821922} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: d6839ff47a4d4bfdaf87b5a0a6e65646, type: 3} + m_Name: + m_EditorClassIdentifier: Assembly-CSharp::MutantHealth + maxHealth: 50 +--- !u!1 &288582345 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 288582346} + m_Layer: 0 + m_Name: 1 (3) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &288582346 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 288582345} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -2.3, y: -0, z: 3.7} + 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 &324229102 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 324229103} + - component: {fileID: 324229106} + - component: {fileID: 324229105} + - component: {fileID: 324229104} + m_Layer: 0 + m_Name: Wall_V_X2_South + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &324229103 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 324229102} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -3.8, y: 1.75, z: -15.25} + m_LocalScale: {x: 0.4, y: 3.5, z: 4.5} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &324229104 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 324229102} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &324229105 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 324229102} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &324229106 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 324229102} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!1 &330585543 GameObject: m_ObjectHideFlags: 0 @@ -273,6 +659,118 @@ MonoBehaviour: distance: 4 height: 1.5 mouseSensitivity: 200 +--- !u!1 &356244610 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 356244611} + - component: {fileID: 356244614} + - component: {fileID: 356244613} + - component: {fileID: 356244612} + m_Layer: 0 + m_Name: Wall_V_X3_Mid + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &356244611 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 356244610} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 1.75, z: -8.8} + m_LocalScale: {x: 0.4, y: 3.5, z: 7.6} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &356244612 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 356244610} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &356244613 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 356244610} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &356244614 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 356244610} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!1 &373882230 stripped GameObject: m_CorrespondingSourceObject: {fileID: 919132149155446097, guid: 44fed6aff454809469effaac1a0b86ed, type: 3} @@ -301,6 +799,388 @@ CapsuleCollider: m_Height: 0.12867661 m_Direction: 1 m_Center: {x: -0.000000039115548, y: 0.06363914, z: 0} +--- !u!1 &382267035 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 382267036} + m_Layer: 0 + m_Name: 1 (9) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &382267036 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 382267035} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 3.26, y: -0, z: -27.09} + 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 &397005049 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 397005050} + m_Layer: 0 + m_Name: 1 (4) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &397005050 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 397005049} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -8.03, y: -0, z: 1.98} + 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 &588162210 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 588162212} + - component: {fileID: 588162211} + m_Layer: 0 + m_Name: NavMesh Surface + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &588162211 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 588162210} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 7a5ac11cc976e418e8d13136b07e1f52, type: 3} + m_Name: + m_EditorClassIdentifier: Unity.AI.Navigation::Unity.AI.Navigation.NavMeshSurface + m_SerializedVersion: 0 + m_AgentTypeID: 0 + m_CollectObjects: 0 + m_Size: {x: 10, y: 10, z: 10} + m_Center: {x: 0, y: 2, z: 0} + m_LayerMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_UseGeometry: 0 + m_DefaultArea: 0 + m_GenerateLinks: 0 + m_IgnoreNavMeshAgent: 1 + m_IgnoreNavMeshObstacle: 1 + m_OverrideTileSize: 0 + m_TileSize: 256 + m_OverrideVoxelSize: 0 + m_VoxelSize: 0.16666667 + m_MinRegionArea: 2 + m_NavMeshData: {fileID: 23800000, guid: 04474af175727c244920a0e1e783b4f4, type: 2} + m_BuildHeightMesh: 0 +--- !u!4 &588162212 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 588162210} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 20.1, y: 42.55472, z: 1.46628} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: + - {fileID: 258821923} + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &753568975 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 753568976} + m_Layer: 0 + m_Name: 1 (1) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &753568976 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 753568975} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 12.41, y: -0, z: 0.68} + 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 &788600110 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 788600111} + - component: {fileID: 788600114} + - component: {fileID: 788600113} + - component: {fileID: 788600112} + m_Layer: 0 + m_Name: Wall_H_Col2_Row2 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &788600111 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 788600110} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -5.3, y: 1.75, z: -14.5} + m_LocalScale: {x: 3, y: 3.5, z: 0.4} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &788600112 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 788600110} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &788600113 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 788600110} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &788600114 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 788600110} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &817448384 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 817448385} + - component: {fileID: 817448388} + - component: {fileID: 817448387} + - component: {fileID: 817448386} + m_Layer: 0 + m_Name: Wall_H_Col1_Row3 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &817448385 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 817448384} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -8.15, y: 1.75, z: -11} + m_LocalScale: {x: 2.7, y: 3.5, z: 0.4} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &817448386 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 817448384} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &817448387 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 817448384} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &817448388 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 817448384} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!1 &832575517 GameObject: m_ObjectHideFlags: 0 @@ -350,6 +1230,118 @@ Transform: m_Children: [] m_Father: {fileID: 0} m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &834173993 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 834173994} + - component: {fileID: 834173997} + - component: {fileID: 834173996} + - component: {fileID: 834173995} + m_Layer: 0 + m_Name: Wall_H_Col2_Row5 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &834173994 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 834173993} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -5.3, y: 1.75, z: -4} + m_LocalScale: {x: 3, y: 3.5, z: 0.4} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &834173995 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 834173993} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &834173996 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 834173993} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &834173997 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 834173993} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!1 &997583200 GameObject: m_ObjectHideFlags: 0 @@ -381,6 +1373,373 @@ Transform: m_Children: [] m_Father: {fileID: 1085429061} m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &999495413 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 999495414} + m_Layer: 0 + m_Name: 1 (10) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &999495414 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 999495413} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 12.95, y: -0, z: -27.66} + 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 &1004291066 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1004291067} + - component: {fileID: 1004291070} + - component: {fileID: 1004291069} + - component: {fileID: 1004291068} + m_Layer: 0 + m_Name: Wall_H_Col5_Row2 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &1004291067 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1004291066} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 6.495, y: 1.75, z: -14.5} + m_LocalScale: {x: 2.99, y: 3.5, z: 0.4} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &1004291068 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1004291066} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &1004291069 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1004291066} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &1004291070 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1004291066} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &1054546572 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1054546573} + - component: {fileID: 1054546576} + - component: {fileID: 1054546575} + - component: {fileID: 1054546574} + m_Layer: 0 + m_Name: Wall_H_Col3_Row5 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &1054546573 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1054546572} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -1.9, y: 1.75, z: -4} + m_LocalScale: {x: 3.8, y: 3.5, z: 0.4} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &1054546574 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1054546572} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &1054546575 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1054546572} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &1054546576 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1054546572} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &1055135848 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1055135849} + - component: {fileID: 1055135852} + - component: {fileID: 1055135851} + - component: {fileID: 1055135850} + m_Layer: 0 + m_Name: Wall_H_Col4_Row2 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &1055135849 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1055135848} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 1.9, y: 1.75, z: -11.5} + m_LocalScale: {x: 3.8, y: 3.5, z: 0.4} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &1055135850 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1055135848} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &1055135851 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1055135848} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &1055135852 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1055135848} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!1 &1085429057 GameObject: m_ObjectHideFlags: 0 @@ -397,6 +1756,8 @@ GameObject: - component: {fileID: 1085429062} - component: {fileID: 1085429064} - component: {fileID: 1085429065} + - component: {fileID: 1085429066} + - component: {fileID: 1085429067} m_Layer: 0 m_Name: Capsule m_TagString: Untagged @@ -582,6 +1943,403 @@ MonoBehaviour: m_Bits: 4294967295 chargeRate: 15 maxThrowForce: 25 +--- !u!114 &1085429066 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1085429057} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: d886578ed27947c99a182706c67a3e92, type: 3} + m_Name: + m_EditorClassIdentifier: Assembly-CSharp::PlayerNoise + sneakRadius: 3 + walkRadius: 8 + runRadius: 18 + stepInterval: 0.5 + wavePrefab: {fileID: 551056912785264054, guid: 9ec19d47555264d4d8ec8994d27f981b, type: 3} +--- !u!114 &1085429067 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1085429057} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: bcc771dbd5104a2590e3f952b62120db, type: 3} + m_Name: + m_EditorClassIdentifier: Assembly-CSharp::PlayerHealth + maxHealth: 100 +--- !u!1 &1116876490 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1116876491} + - component: {fileID: 1116876494} + - component: {fileID: 1116876493} + - component: {fileID: 1116876492} + m_Layer: 0 + m_Name: Wall_H_Col1_Row1 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &1116876491 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1116876490} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -9.63, y: 1.75, z: -17} + m_LocalScale: {x: 2.26, y: 3.5, z: 0.4} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &1116876492 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1116876490} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &1116876493 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1116876490} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &1116876494 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1116876490} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &1164529817 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1164529818} + m_Layer: 0 + m_Name: 1 (11) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1164529818 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1164529817} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 16.75, y: -0, z: -9.68} + 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 &1175213201 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1175213202} + - component: {fileID: 1175213205} + - component: {fileID: 1175213204} + - component: {fileID: 1175213203} + m_Layer: 0 + m_Name: Wall_V_X3_South + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &1175213202 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1175213201} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 1.75, z: -17.31} + m_LocalScale: {x: 0.4, y: 3.5, z: 6.62} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &1175213203 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1175213201} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &1175213204 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1175213201} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &1175213205 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1175213201} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &1231578424 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1231578425} + - component: {fileID: 1231578428} + - component: {fileID: 1231578427} + - component: {fileID: 1231578426} + m_Layer: 0 + m_Name: Wall_H_Col1_Row4 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &1231578425 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1231578424} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -9.63, y: 1.75, z: -6.5} + m_LocalScale: {x: 2.26, y: 3.5, z: 0.4} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &1231578426 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1231578424} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &1231578427 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1231578424} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &1231578428 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1231578424} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!1 &1249823623 GameObject: m_ObjectHideFlags: 0 @@ -759,6 +2517,343 @@ MonoBehaviour: m_EditorClassIdentifier: Assembly-CSharp::ImpactWave minImpactForce: 0.1 wavePrefab: {fileID: 551056912785264054, guid: 9ec19d47555264d4d8ec8994d27f981b, type: 3} + soundRadius: 89.6 +--- !u!1 &1253278592 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1253278593} + - component: {fileID: 1253278596} + - component: {fileID: 1253278595} + - component: {fileID: 1253278594} + m_Layer: 0 + m_Name: Wall_H_Col5_Row5 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &1253278593 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1253278592} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 5.15, y: 1.75, z: -5.5} + m_LocalScale: {x: 2.7, y: 3.5, z: 0.4} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &1253278594 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1253278592} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &1253278595 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1253278592} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &1253278596 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1253278592} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &1288006896 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1288006897} + - component: {fileID: 1288006900} + - component: {fileID: 1288006899} + - component: {fileID: 1288006898} + m_Layer: 0 + m_Name: Wall_V_X2_North + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &1288006897 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1288006896} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -3.8, y: 1.75, z: -6.5} + m_LocalScale: {x: 0.4, y: 3.5, z: 5} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &1288006898 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1288006896} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &1288006899 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1288006896} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &1288006900 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1288006896} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &1489454794 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1489454795} + - component: {fileID: 1489454798} + - component: {fileID: 1489454797} + - component: {fileID: 1489454796} + m_Layer: 0 + m_Name: Wall_V_X1_North + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &1489454795 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1489454794} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -6.8, y: 1.75, z: -7} + m_LocalScale: {x: 0.4, y: 3.5, z: 7} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &1489454796 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1489454794} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &1489454797 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1489454794} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &1489454798 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1489454794} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!1 &1501546939 GameObject: m_ObjectHideFlags: 0 @@ -776,7 +2871,7 @@ GameObject: m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 + m_StaticEditorFlags: 2147483647 m_IsActive: 1 --- !u!65 &1501546940 BoxCollider: @@ -865,12 +2960,74 @@ Transform: m_GameObject: {fileID: 1501546939} serializedVersion: 2 m_LocalRotation: {x: -0.7071068, y: 0, z: 0, w: 0.7071068} - m_LocalPosition: {x: -1.42857, y: -0, z: -1.81} - m_LocalScale: {x: 2, y: 2, z: 2} + m_LocalPosition: {x: -1.4286, y: 0, z: 17.8} + m_LocalScale: {x: 13.590724, y: 13.590724, z: 13.590724} m_ConstrainProportionsScale: 1 m_Children: [] m_Father: {fileID: 0} m_LocalEulerAnglesHint: {x: -90, y: 0, z: 0} +--- !u!1 &1551773957 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1551773958} + m_Layer: 0 + m_Name: 1 (13) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1551773958 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1551773957} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 2.28, y: -0, z: -16.17} + 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 &1559800261 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1559800262} + m_Layer: 0 + m_Name: 1 (6) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1559800262 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1559800261} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -16.2, y: -0, z: -23.7} + 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!1001 &1573496782 PrefabInstance: m_ObjectHideFlags: 0 @@ -949,7 +3106,7 @@ GameObject: m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 + m_StaticEditorFlags: 2147483647 m_IsActive: 1 --- !u!65 &1576995128 BoxCollider: @@ -1038,8 +3195,8 @@ Transform: m_GameObject: {fileID: 1576995127} serializedVersion: 2 m_LocalRotation: {x: 0.7071068, y: 0, z: 0, w: 0.7071068} - m_LocalPosition: {x: -1.42857, y: 0, z: -20.62} - m_LocalScale: {x: 2, y: 2, z: 2} + m_LocalPosition: {x: -1.4286, y: 0, z: -36.5} + m_LocalScale: {x: 7.78884, y: 7.78884, z: 7.78884} m_ConstrainProportionsScale: 1 m_Children: [] m_Father: {fileID: 0} @@ -1061,7 +3218,7 @@ GameObject: m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 + m_StaticEditorFlags: 2147483647 m_IsActive: 1 --- !u!65 &1648126183 BoxCollider: @@ -1150,12 +3307,124 @@ Transform: m_GameObject: {fileID: 1648126182} serializedVersion: 2 m_LocalRotation: {x: -0.5, y: 0.5, z: 0.5, w: 0.5} - m_LocalPosition: {x: 7.99, y: -0, z: -10} - m_LocalScale: {x: 2, y: 2, z: 2} + m_LocalPosition: {x: 20.1, y: -0, z: -10} + m_LocalScale: {x: 9.967763, y: 9.967763, z: 9.967763} m_ConstrainProportionsScale: 1 m_Children: [] m_Father: {fileID: 0} m_LocalEulerAnglesHint: {x: -90, y: 90, z: 0} +--- !u!1 &1696459731 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1696459732} + - component: {fileID: 1696459735} + - component: {fileID: 1696459734} + - component: {fileID: 1696459733} + m_Layer: 0 + m_Name: Wall_V_X4_North + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &1696459732 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1696459731} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 3.8, y: 1.75, z: -3.655} + m_LocalScale: {x: 0.4, y: 3.5, z: 3.69} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &1696459733 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1696459731} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &1696459734 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1696459731} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &1696459735 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1696459731} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!1 &1710282937 GameObject: m_ObjectHideFlags: 0 @@ -1173,7 +3442,7 @@ GameObject: m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 + m_StaticEditorFlags: 2147483647 m_IsActive: 1 --- !u!65 &1710282938 BoxCollider: @@ -1262,8 +3531,8 @@ Transform: m_GameObject: {fileID: 1710282937} serializedVersion: 2 m_LocalRotation: {x: -0.5, y: -0.5, z: -0.5, w: 0.5} - m_LocalPosition: {x: -10.76, y: -0, z: -10} - m_LocalScale: {x: 2, y: 2, z: 2} + m_LocalPosition: {x: -25.8, y: -0, z: -10} + m_LocalScale: {x: 7.855047, y: 7.855047, z: 7.855047} m_ConstrainProportionsScale: 1 m_Children: [] m_Father: {fileID: 0} @@ -1285,7 +3554,7 @@ GameObject: m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 + m_StaticEditorFlags: 2147483647 m_IsActive: 1 --- !u!23 &1743818062 MeshRenderer: @@ -1353,8 +3622,8 @@ Transform: m_GameObject: {fileID: 1743818060} serializedVersion: 2 m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} - m_LocalPosition: {x: -1.42857, y: 0, z: -11.42857} - m_LocalScale: {x: 2, y: 2, z: 2} + m_LocalPosition: {x: -1.4286, y: 0, z: -11.42857} + m_LocalScale: {x: 4.9846, y: 4.9846, z: 4.9846} m_ConstrainProportionsScale: 1 m_Children: [] m_Father: {fileID: 0} @@ -1380,6 +3649,118 @@ BoxCollider: serializedVersion: 3 m_Size: {x: 10, y: 2.220446e-16, z: 10} m_Center: {x: 0, y: 0, z: 0} +--- !u!1 &1755455828 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1755455829} + - component: {fileID: 1755455832} + - component: {fileID: 1755455831} + - component: {fileID: 1755455830} + m_Layer: 0 + m_Name: Wall_H_Col3_Row1 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &1755455829 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1755455828} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -2.3, y: 1.75, z: -17.5} + m_LocalScale: {x: 3, y: 3.5, z: 0.4} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &1755455830 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1755455828} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &1755455831 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1755455828} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &1755455832 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1755455828} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!1001 &1788629398 PrefabInstance: m_ObjectHideFlags: 0 @@ -1456,6 +3837,403 @@ PrefabInstance: insertIndex: -1 addedObject: {fileID: 373882231} m_SourcePrefab: {fileID: 100100000, guid: 44fed6aff454809469effaac1a0b86ed, type: 3} +--- !u!1 &1867908077 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1867908078} + - component: {fileID: 1867908081} + - component: {fileID: 1867908080} + - component: {fileID: 1867908079} + m_Layer: 0 + m_Name: Wall_V_X4_South + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &1867908078 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1867908077} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 3.8, y: 1.75, z: -16.25} + m_LocalScale: {x: 0.4, y: 3.5, z: 6.5} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &1867908079 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1867908077} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &1867908080 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1867908077} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &1867908081 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1867908077} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &1880967027 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1880967028} + m_Layer: 0 + m_Name: 1 (8) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1880967028 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1880967027} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -1.42, y: -0, z: -28.59} + 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 &1949454377 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1949454378} + m_Layer: 0 + m_Name: 1 (12) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1949454378 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1949454377} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 8.6, y: -0, z: -11.48} + 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 &1964883891 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1964883892} + m_Layer: 0 + m_Name: 1 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1964883892 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1964883891} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 15.14, y: -0, z: 0.42295} + 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 &2085304735 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2085304736} + - component: {fileID: 2085304739} + - component: {fileID: 2085304738} + - component: {fileID: 2085304737} + m_Layer: 0 + m_Name: Wall_V_X1_South + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &2085304736 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2085304735} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -6.8, y: 1.75, z: -17.31} + m_LocalScale: {x: 0.4, y: 3.5, z: 6.62} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 2112862739} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &2085304737 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2085304735} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_StaticShadowCaster: 0 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RayTracingMode: 2 + m_RayTraceProcedural: 0 + m_RayTracingAccelStructBuildFlagsOverride: 0 + m_RayTracingAccelStructBuildFlags: 1 + m_SmallMeshCulling: 1 + m_ForceMeshLod: -1 + m_MeshLodSelectionBias: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_ReceiveGI: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 1 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_GlobalIlluminationMeshLod: 0 + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_MaskInteraction: 0 + m_AdditionalVertexStreams: {fileID: 0} +--- !u!65 &2085304738 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2085304735} + m_Material: {fileID: 0} + m_IncludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_ExcludeLayers: + serializedVersion: 2 + m_Bits: 0 + m_LayerOverridePriority: 0 + m_IsTrigger: 0 + m_ProvidesContacts: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &2085304739 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2085304735} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &2112862738 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2112862739} + m_Layer: 0 + m_Name: Maze + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 2147483647 + m_IsActive: 1 +--- !u!4 &2112862739 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2112862738} + 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: + - {fileID: 2085304736} + - {fileID: 1489454795} + - {fileID: 324229103} + - {fileID: 1288006897} + - {fileID: 1175213202} + - {fileID: 356244611} + - {fileID: 1867908078} + - {fileID: 1696459732} + - {fileID: 1116876491} + - {fileID: 817448385} + - {fileID: 1231578425} + - {fileID: 788600111} + - {fileID: 834173994} + - {fileID: 1755455829} + - {fileID: 1054546573} + - {fileID: 1055135849} + - {fileID: 1004291067} + - {fileID: 1253278593} + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &2147433585 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2147433586} + m_Layer: 0 + m_Name: 1 (7) + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &2147433586 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2147433585} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -7.05, y: -0, z: -29.63} + 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 @@ -1471,3 +4249,19 @@ SceneRoots: - {fileID: 1573496782} - {fileID: 1788629398} - {fileID: 1249823629} + - {fileID: 2112862739} + - {fileID: 588162212} + - {fileID: 1964883892} + - {fileID: 753568976} + - {fileID: 136077228} + - {fileID: 288582346} + - {fileID: 397005050} + - {fileID: 219490552} + - {fileID: 1559800262} + - {fileID: 2147433586} + - {fileID: 1880967028} + - {fileID: 382267036} + - {fileID: 999495414} + - {fileID: 1164529818} + - {fileID: 1949454378} + - {fileID: 1551773958} diff --git a/Assets/Scenes/SampleScene/NavMesh-NavMesh Surface.asset b/Assets/Scenes/SampleScene/NavMesh-NavMesh Surface.asset new file mode 100644 index 0000000..aff56a2 Binary files /dev/null and b/Assets/Scenes/SampleScene/NavMesh-NavMesh Surface.asset differ diff --git a/Assets/Scenes/SampleScene/NavMesh-NavMesh Surface.asset.meta b/Assets/Scenes/SampleScene/NavMesh-NavMesh Surface.asset.meta new file mode 100644 index 0000000..b662c99 --- /dev/null +++ b/Assets/Scenes/SampleScene/NavMesh-NavMesh Surface.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 04474af175727c244920a0e1e783b4f4 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 23800000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/BlindMutantAI.cs b/Assets/Scripts/BlindMutantAI.cs index c410b28..515e158 100644 --- a/Assets/Scripts/BlindMutantAI.cs +++ b/Assets/Scripts/BlindMutantAI.cs @@ -1,7 +1,55 @@ -namespace DefaultNamespace +using UnityEngine; +using UnityEngine.AI; + +public class BlindMutantAI : MonoBehaviour { - public class BlindMutantAI + private NavMeshAgent agent; + + [Header("Настройки скорости")] + public float walkSpeed = 2f; + public float runSpeed = 5f; + + [Header("Патрулирование")] + public Transform[] patrolPoints; + private int currentPatrolIndex; + private bool isInvestigating = false; + + void Start() { - + agent = GetComponent(); + agent.speed = walkSpeed; + + if (patrolPoints.Length > 0) GoToNextPatrolPoint(); + } + + void Update() + { + if (!agent.pathPending && agent.remainingDistance < 0.5f) + { + if (isInvestigating) + { + isInvestigating = false; + agent.speed = walkSpeed; + if (patrolPoints.Length > 0) GoToNextPatrolPoint(); + } + else if (patrolPoints.Length > 0) + { + GoToNextPatrolPoint(); + } + } + } + + private void GoToNextPatrolPoint() + { + if (patrolPoints.Length == 0) return; + agent.destination = patrolPoints[currentPatrolIndex].position; + currentPatrolIndex = (currentPatrolIndex + 1) % patrolPoints.Length; + } + + public void HearSound(Vector3 soundPosition) + { + isInvestigating = true; + agent.speed = runSpeed; + agent.SetDestination(soundPosition); } } \ No newline at end of file diff --git a/Assets/Scripts/EchoTrigger.cs b/Assets/Scripts/EchoTrigger.cs index 0bc0904..397013e 100644 --- a/Assets/Scripts/EchoTrigger.cs +++ b/Assets/Scripts/EchoTrigger.cs @@ -1,4 +1,4 @@ -using UnityEngine; +using UnityEngine; using UnityEngine.InputSystem; public class EchoTrigger : MonoBehaviour @@ -27,9 +27,16 @@ public class EchoTrigger : MonoBehaviour private float[] waveIntensities = new float[MAX_WAVES]; // Память для яркости каждой волны private bool[] waveActive = new bool[MAX_WAVES]; + public static EchoTrigger Instance; + private Vector3 lastPosition; private float distanceMoved = 0f; + void Awake() + { + if (Instance == null) Instance = this; + } + void Start() { if (echoMaterial != null) @@ -103,6 +110,11 @@ public class EchoTrigger : MonoBehaviour targetIntensity = sneakIntensity; } + TriggerExternalWave(transform.position, targetMax, targetIntensity); + } + + public void TriggerExternalWave(Vector3 position, float targetMax, float targetIntensity) + { // Ищем свободный слот int waveIndex = -1; for (int i = 0; i < MAX_WAVES; i++) @@ -135,6 +147,6 @@ public class EchoTrigger : MonoBehaviour waveActive[waveIndex] = true; echoMaterial.SetFloat("_EchoOpacity" + (waveIndex + 1), targetIntensity); - echoMaterial.SetVector("_EchoPosition" + (waveIndex + 1), transform.position); + echoMaterial.SetVector("_EchoPosition" + (waveIndex + 1), position); } } \ No newline at end of file diff --git a/Assets/Scripts/ImpactWave.cs b/Assets/Scripts/ImpactWave.cs index 3766f14..b93ea7e 100644 --- a/Assets/Scripts/ImpactWave.cs +++ b/Assets/Scripts/ImpactWave.cs @@ -1,40 +1,55 @@ -using UnityEngine; +using UnityEngine; public class ImpactWave : MonoBehaviour { [Header("Настройки эхолокации")] [Tooltip("Минимальная сила удара, при которой появится волна")] public float minImpactForce = 2f; - + [Tooltip("Префаб звуковой волны (или источника света)")] public GameObject wavePrefab; + [Header("Настройки слуха врагов")] + [Tooltip("Радиус, в котором мутанты услышат падение предмета")] + public float soundRadius = 15f; + private void OnCollisionEnter(Collision collision) { - // Эта строчка выведет сообщение красным текстом в консоль Unity при любом касании - Debug.Log("УДАР! Сила: " + collision.relativeVelocity.magnitude); - - if (collision.relativeVelocity.magnitude >= minImpactForce && wavePrefab != null) - { - Instantiate(wavePrefab, collision.contacts[0].point, Quaternion.identity); - } - // Считаем силу, с которой предмет врезался в препятствие float impactForce = collision.relativeVelocity.magnitude; + Debug.Log("УДАР! Сила: " + impactForce); if (impactForce >= minImpactForce) { - // Берем конкретную точку в пространстве, где произошло касание ContactPoint contact = collision.contacts[0]; - // Если префаб назначен, создаем его в точке удара + // 1. ТВОЯ ЛОГИКА: Отрисовка света и волны через EchoTrigger if (wavePrefab != null) { Instantiate(wavePrefab, contact.point, Quaternion.identity); } - // Подсказка: если у предмета есть компонент AudioSource, - // здесь можно вызывать звук падения, громкость которого зависит от impactForce + if (EchoTrigger.Instance != null) + { + // Вычисляем интенсивность и радиус волны в зависимости от силы удара + float intensity = Mathf.Clamp(impactForce / 5f, 0.5f, 3.0f); + float radius = Mathf.Clamp(impactForce * 2f, 5f, 25f); + + EchoTrigger.Instance.TriggerExternalWave(contact.point, radius, intensity); + } + + // 2. НОВАЯ ЛОГИКА: Оповещение мутантов о шуме + Collider[] colliders = Physics.OverlapSphere(contact.point, soundRadius); + + foreach (Collider hit in colliders) + { + BlindMutantAI mutant = hit.GetComponent(); + + if (mutant != null) + { + // Заставляем мутанта бежать в точку удара + mutant.HearSound(contact.point); + } + } } } - -} +} \ No newline at end of file diff --git a/Assets/Scripts/MutantHealth.cs b/Assets/Scripts/MutantHealth.cs index b4275e7..1587f1d 100644 --- a/Assets/Scripts/MutantHealth.cs +++ b/Assets/Scripts/MutantHealth.cs @@ -1,7 +1,21 @@ -namespace DefaultNamespace +using UnityEngine; + +public class MutantHealth : MonoBehaviour { - public class MutantHealth + public float maxHealth = 50f; + private float currentHealth; + + void Start() { currentHealth = maxHealth; } + + public void TakeDamage(float damage) { + currentHealth -= damage; + Debug.Log("Мутант получил урон! Осталось: " + currentHealth); + if (currentHealth <= 0) + { + Debug.Log("МУТАНТ УМЕР!"); + Destroy(gameObject); // Уничтожаем модельку мутанта + } } } \ No newline at end of file diff --git a/Assets/Scripts/PlayerHealth.cs b/Assets/Scripts/PlayerHealth.cs index c2a7414..97f3ad8 100644 --- a/Assets/Scripts/PlayerHealth.cs +++ b/Assets/Scripts/PlayerHealth.cs @@ -1,7 +1,21 @@ -namespace DefaultNamespace +using UnityEngine; + +public class PlayerHealth : MonoBehaviour { - public class PlayerHealth + public float maxHealth = 100f; + private float currentHealth; + + void Start() { currentHealth = maxHealth; } + + public void TakeDamage(float damage) { + currentHealth -= damage; + Debug.Log("Игрок получил урон! Осталось здоровья: " + currentHealth); + if (currentHealth <= 0) + { + Debug.Log("ИГРОК МЕРТВ! Конец игры."); + // Здесь позже можно будет добавить перезагрузку уровня + } } } \ No newline at end of file diff --git a/Assets/Scripts/PlayerNoise.cs b/Assets/Scripts/PlayerNoise.cs index 642aaf5..cf8bacd 100644 --- a/Assets/Scripts/PlayerNoise.cs +++ b/Assets/Scripts/PlayerNoise.cs @@ -1,7 +1,62 @@ -namespace DefaultNamespace +using UnityEngine; +using UnityEngine.InputSystem; + +public class PlayerNoise : MonoBehaviour { - public class PlayerNoise + [Header("Радиус шума от шагов")] + public float sneakRadius = 3f; + public float walkRadius = 8f; + public float runRadius = 18f; + + [Header("Настройки генерации")] + public float stepInterval = 0.5f; + private float stepTimer = 0f; + + public GameObject wavePrefab; + + void Update() { + if (Keyboard.current == null) return; + + bool isMoving = Keyboard.current.wKey.isPressed || + Keyboard.current.aKey.isPressed || + Keyboard.current.sKey.isPressed || + Keyboard.current.dKey.isPressed; + + if (isMoving) + { + stepTimer -= Time.deltaTime; + if (stepTimer <= 0f) + { + EmitStepNoise(); + stepTimer = stepInterval; + } + } + else + { + stepTimer = 0f; + } + } + + private void EmitStepNoise() + { + float currentRadius = walkRadius; + + if (Keyboard.current.leftShiftKey.isPressed) currentRadius = runRadius; + else if (Keyboard.current.leftCtrlKey.isPressed || Keyboard.current.cKey.isPressed) currentRadius = sneakRadius; + + if (wavePrefab != null) + { + Vector3 footPosition = transform.position - new Vector3(0, transform.localScale.y / 2, 0); + Instantiate(wavePrefab, footPosition, Quaternion.identity); + } + + Collider[] colliders = Physics.OverlapSphere(transform.position, currentRadius); + foreach (Collider hit in colliders) + { + BlindMutantAI mutant = hit.GetComponent(); + if (mutant != null) mutant.HearSound(transform.position); + } } } \ No newline at end of file diff --git a/Assets/Tremble Sync Settings.asset b/Assets/Tremble Sync Settings.asset new file mode 100644 index 0000000..08b2de6 --- /dev/null +++ b/Assets/Tremble Sync Settings.asset @@ -0,0 +1,237 @@ +%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: 4a88c8a3ff11450b94453ed26fba8f5c, type: 3} + m_Name: Tremble Sync Settings + m_EditorClassIdentifier: TinyGoose.Tremble::TinyGoose.Tremble.TrembleSyncSettings + m_AutoSyncOnCompile: 1 + m_AllowStandaloneImport: 0 + m_TrenchBroomVersion: 4 + m_TemplateMap: {fileID: 0} + m_WorldspawnScript: + m_ScriptName: + m_TypeNamingConvention: 3 + m_FieldNamingConvention: 0 + m_SpawnFlagNamingConvention: 4 + m_MaterialNamingConvention: 3 + m_IdentityPropertyName: targetname + m_MaterialGroups: [] + m_MaterialRenderData: + - m_Material: {fileID: 2100000, guid: 5071cc7251fe57a4fa8619c2a51c0273, type: 2} + m_ExportMode: 0 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: 0d818995ecc78104783c45254a1f390a, type: 2} + m_ExportMode: 0 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: 13e991eaf862a0547b1ebf116c9f502b, type: 2} + m_ExportMode: 0 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: 62dad06c47d1d1a448901a67f077f0b6, type: 2} + m_ExportMode: 1 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: a0b376915f4283c4e9db27aa35394b89, type: 2} + m_ExportMode: 0 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: 935190269a0097e468613dae1055aa8f, type: 2} + m_ExportMode: 0 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: bf1b930b1fba9db409872196db946d5c, type: 2} + m_ExportMode: 1 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: 9cccea665b138ec4c9a38c405f8554cf, type: 2} + m_ExportMode: 1 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: d987ec024d9a90d4c8deb0ba94e48b99, type: 2} + m_ExportMode: 1 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: 5c4854f1dd0cbe84a92d1ba0e1baffc6, type: 2} + m_ExportMode: 1 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: 65529ac748f009d4dbdee8d40e2e6402, type: 2} + m_ExportMode: 1 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: 94c11be5b5b74c440a5c2fc75dc65d88, type: 2} + m_ExportMode: 1 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: 2bece4266c1175a4faabdb2e7063f6fb, type: 2} + m_ExportMode: 1 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: 3b92f9721b48ca749ad0da0028d7fab5, type: 2} + m_ExportMode: 0 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: 7edb3177958782c49aa980429ae5fbf4, type: 2} + m_ExportMode: 1 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: 90f4f98d221d05a4eb3eafb584cd4f5f, type: 2} + m_ExportMode: 1 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: dc793a62afe53bd4b83fdf94cf34b95b, type: 2} + m_ExportMode: 1 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + - m_Material: {fileID: 2100000, guid: 88605e96331069a4ca2e4f191c7f2cbe, type: 2} + m_ExportMode: 1 + m_IsResolutionOverridden: 0 + m_ResolutionX: 2 + m_ResolutionY: 2 + m_Dirty: 0 + m_PipelineSplitMesh: 1 + m_PipelineSmoothMeshNormals: 1 + m_PipelineSimplifyCollisionMeshes: 1 + m_PipelineUnwrapUV2: 1 + m_PipelineRunMapProcessors: 1 + m_MapProcessors: [] + m_LogOnImportAndSync: 0 + m_UseLiveUpdate: 1 + m_AutomaticallyReimportWhenDependencyChanges: 1 + m_EntityIconStyle: 1 + m_PrefabOverrideHandling: 2 + m_UseClassicQuakeCulling: 0 + m_Q3Map2ResultDisplayType: 1 + m_FgdFormattingStyle: 1 + m_SubdivideAllLeafs: 0 + m_AlwaysPackBoolsIntoSpawnFlags: 1 + m_SyncEnumsAsStringValue: 1 + m_SyncSerializedFields: 1 + m_SyncMaterialsAndPrefabs: 1 + m_WorldspawnLayer: Default + m_DiscardMapGroups: 0 + m_MainMeshName: worldspawn + m_AutoDeleteMapBackups: 0 + m_ExtraCommandLineArgs: -threads 8 -meta -v + m_MaterialExportSize: 5 + m_MaterialCaptureLightIntensity: 0.5 + m_MaterialCaptureLightAngle: 0.75 + m_ExportClipSkipTextures: 1 + m_ImportScale: 0.015625 + m_AssetMetadatas: + - MapName: game/Laboratory03_Floor_BaseMap + Path: Assets/3D Laboratory Environment with Appratus/Materials/Laboratory03_Floor_BaseMap.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/Laboratory03_Glass_BaseMap_1 + Path: Assets/3D Laboratory Environment with Appratus/Materials/Laboratory03_Glass_BaseMap 1.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/Laboratory03_Glass_BaseMap_2 + Path: Assets/3D Laboratory Environment with Appratus/Materials/Laboratory03_Glass_BaseMap 2.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/Laboratory03_Glass_BaseMap + Path: Assets/3D Laboratory Environment with Appratus/Materials/Laboratory03_Glass_BaseMap.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/Laboratory03_Other_01_BaseMap + Path: Assets/3D Laboratory Environment with Appratus/Materials/Laboratory03_Other_01_BaseMap.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/Laboratory03_Others_BaseMap + Path: Assets/3D Laboratory Environment with Appratus/Materials/Laboratory03_Others_BaseMap.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/Laboratory03_Wood_BaseMap + Path: Assets/3D Laboratory Environment with Appratus/Materials/Laboratory03_Wood_BaseMap.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/lambert1 + Path: Assets/3D Laboratory Environment with Appratus/Materials/lambert1.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/Liquid_1 + Path: Assets/3D Laboratory Environment with Appratus/Materials/Liquid 1.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/Liquid_2 + Path: Assets/3D Laboratory Environment with Appratus/Materials/Liquid 2.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/Liquid_3 + Path: Assets/3D Laboratory Environment with Appratus/Materials/Liquid 3.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/Liquid + Path: Assets/3D Laboratory Environment with Appratus/Materials/Liquid.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/New_Material + Path: Assets/3D Laboratory Environment with Appratus/Materials/New Material.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/roof_and_blub_other02_BaseMap + Path: Assets/3D Laboratory Environment with Appratus/Materials/roof and blub_other02_BaseMap.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/water + Path: Assets/3D Laboratory Environment with Appratus/Materials/water.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/EchoCloudMat + Path: Assets/EchoCloudMat.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/EchoMat + Path: Assets/EchoMat.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} + - MapName: game/Player + Path: Assets/Player.mat + FullTypeName: UnityEngine.Material + SpawnOffset: {x: 0, y: 0, z: 0} diff --git a/Assets/Tremble Sync Settings.asset.meta b/Assets/Tremble Sync Settings.asset.meta new file mode 100644 index 0000000..1ed1b0b --- /dev/null +++ b/Assets/Tremble Sync Settings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 16cbdb81617a4e8449f94971a7a65877 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tremble.meta b/Assets/Tremble.meta new file mode 100644 index 0000000..163ec27 --- /dev/null +++ b/Assets/Tremble.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: abc48365bb69e4068a69a38d3ff4ae52 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tremble/AssetLoading.meta b/Assets/Tremble/AssetLoading.meta new file mode 100644 index 0000000..59a7a67 --- /dev/null +++ b/Assets/Tremble/AssetLoading.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 874b1f1fda434715b9e8cb37b2936050 +timeCreated: 1716200660 \ No newline at end of file diff --git a/Assets/Tremble/AssetLoading/Adaptors.meta b/Assets/Tremble/AssetLoading/Adaptors.meta new file mode 100644 index 0000000..f9a58a6 --- /dev/null +++ b/Assets/Tremble/AssetLoading/Adaptors.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 8b895dc7f3a74ac1a27fec3a77248e5d +timeCreated: 1716201044 \ No newline at end of file diff --git a/Assets/Tremble/AssetLoading/Adaptors/AddressablesLoaderAdaptor.cs b/Assets/Tremble/AssetLoading/Adaptors/AddressablesLoaderAdaptor.cs new file mode 100644 index 0000000..f878c9e --- /dev/null +++ b/Assets/Tremble/AssetLoading/Adaptors/AddressablesLoaderAdaptor.cs @@ -0,0 +1,159 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +#if ADDRESSABLES_INSTALLED + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using UnityEngine; +using UnityEngine.AddressableAssets; +using UnityEngine.ResourceManagement.AsyncOperations; +using UnityEngine.ResourceManagement.ResourceLocations; +using Debug = UnityEngine.Debug; +using Object = UnityEngine.Object; + +namespace TinyGoose.Tremble +{ + public class AddressablesLoaderAdaptor : IAssetLoaderAdaptor + { + public bool SupportsPreloading => true; + + private readonly List m_OwnedHandles = new(1024); + private readonly Dictionary m_LoadedAssets = new(1024); + + public string[] FindAssetPaths(Type type, string name = "") + { + return TrembleAssetLoader.FindAssetDataMany(a => a.Path.ContainsInvariant(name)) + .Where(a => a.FullTypeName.EqualsInvariant(type.FullName)) + .Select(a => a.Path) + .ToArray(); + } + + public TAsset LoadAssetByPath(string path) where TAsset : Object + { + if (path.IsNullOrEmpty()) + return null; + + if (!TrembleAssetLoader.TryGetAssetDataFromPath(path, out AssetMetadata assetData)) + { + Debug.LogError($"Not loading invalid addressable: {path}"); + return null; + } + + if (m_LoadedAssets.TryGetValue(assetData.AddressableName, out object existingAsset) && + existingAsset is TAsset tAsset) + { + return tAsset; + } + + AsyncOperationHandle handle = Addressables.LoadAssetAsync(assetData.AddressableName); + TAsset asset = handle.WaitForCompletion(); + if (!asset) + { + Addressables.Release(handle); + return null; + } + + m_OwnedHandles.Add(handle); + m_LoadedAssets[path] = handle; + return asset; + } + + public async Task PreloadAssetsByPaths(IList paths) + { + if (paths.Count == 0) + return; + + List addresses = new(paths.Count); + + // First, remove dupes, invalid and ones we already loaded + for (int i = 0; i < paths.Count; i++) + { + string path = paths[i]; + + if (path.IsNullOrEmpty() || !TrembleAssetLoader.TryGetAssetDataFromPath(path, out AssetMetadata assetData)) + { + Debug.LogError($"Not loading invalid addressable: {path}"); + paths.RemoveAt(i--); + continue; + } + + if (m_LoadedAssets.ContainsKey(assetData.AddressableName)) + { + paths.RemoveAt(i--); + continue; + } + + if (paths.IndexOf(path) != i) + { + paths.RemoveAt(i--); + continue; + } + + // This is valid - add to list of addresses + addresses.Add(assetData.AddressableName); + } + + if (addresses.Count == 0) + return; + + AsyncOperationHandle> resultsHandle = Addressables.LoadAssetsAsync(addresses, null, Addressables.MergeMode.Union); + await resultsHandle.Task; + + for (int i = 0; i < paths.Count; i++) + { + string path = paths[i]; + if (TrembleAssetLoader.TryGetAssetDataFromPath(path, out AssetMetadata assetData)) + { + m_LoadedAssets[assetData.AddressableName] = resultsHandle.Result[i]; + } + } + m_OwnedHandles.Add(resultsHandle); + } + + public string GetPath(Object obj) + { + Debug.LogError("GetPath is not implemented in Addressables (yet!)"); + return null; + } + + public TrembleSyncSettings LoadSyncSettings() + { + return Addressables + .LoadAssetAsync(TrembleSyncSettings.ADDRESSABLE_KEY) + .WaitForCompletion(); + } + + public Material LoadClipMaterial() + { + return Addressables.LoadAssetAsync("M_NullRender").WaitForCompletion(); + } + + public void ReleaseAll() + { + foreach (AsyncOperationHandle handle in m_OwnedHandles) + { + Addressables.Release(handle); + } + m_OwnedHandles.Clear(); + } + + private static bool IsAddressablePathValid(string path) + { + if (path == null) + return false; + + AsyncOperationHandle> locationLoadOperation = Addressables.LoadResourceLocationsAsync(path); + IList results = locationLoadOperation.WaitForCompletion(); + bool isValidPath = results is { Count: > 0 }; + Addressables.Release(locationLoadOperation); + + return isValidPath; + } + } +} +#endif \ No newline at end of file diff --git a/Assets/Tremble/AssetLoading/Adaptors/AddressablesLoaderAdaptor.cs.meta b/Assets/Tremble/AssetLoading/Adaptors/AddressablesLoaderAdaptor.cs.meta new file mode 100644 index 0000000..8447294 --- /dev/null +++ b/Assets/Tremble/AssetLoading/Adaptors/AddressablesLoaderAdaptor.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: f4959867e61442c2aa78844ff6cd8e06 +timeCreated: 1716201342 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/AssetLoading/Adaptors/AddressablesLoaderAdaptor.cs + uploadId: 939664 diff --git a/Assets/Tremble/AssetLoading/Adaptors/EditorLoaderAdaptor.cs b/Assets/Tremble/AssetLoading/Adaptors/EditorLoaderAdaptor.cs new file mode 100644 index 0000000..c41e6e9 --- /dev/null +++ b/Assets/Tremble/AssetLoading/Adaptors/EditorLoaderAdaptor.cs @@ -0,0 +1,105 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using UnityEditor; +using UnityEngine; +using Object = UnityEngine.Object; + +#if UNITY_EDITOR + +namespace TinyGoose.Tremble +{ + public class EditorLoaderAdaptor : IAssetLoaderAdaptor + { + public bool SupportsPreloading => false; + + private static readonly Dictionary s_CachedQueryResults = new(1024); + + public string[] FindAssetPaths(Type type, string name = "") + { + string typeString = type == typeof(GameObject) ? "prefab" : type.Name; + string fullQuery = $"t:{typeString} {name}"; + + if (!s_CachedQueryResults.TryGetValue(fullQuery, out string[] results)) + { + results = AssetDatabase + .FindAssets(fullQuery, new[] { "Assets" }) + .Select(AssetDatabase.GUIDToAssetPath) + .ToArray(); + + if (results.Length > 0) + { + s_CachedQueryResults[fullQuery] = results; + } + } + + return results; + } + + public TAsset LoadAssetByPath(string path) where TAsset : Object + => AssetDatabase.LoadAssetAtPath(path); + + public Task PreloadAssetsByPaths(IList paths) + { + // We don't need to preload in Editor ;) + return Task.CompletedTask; + } + + public async Task PreloadAssetsByPathsAsync(IList paths) + { + // We don't need to preload in Editor ;) + await Task.CompletedTask; + } + + public string GetPath(Object obj) => AssetDatabase.GetAssetPath(obj); + + + public TrembleSyncSettings GetSyncSettings() => TrembleSyncSettings.Get(); + + public Material LoadClipMaterial() + { + string clipPath = Path.Combine(TrembleConsts.EDITOR_GetTrembleInstallFolder(), "Materials", "M_NullRender.mat"); + return LoadAssetByPath(clipPath); + } + + public TrembleSyncSettings LoadSyncSettings() + { + string[] paths = FindAssetPaths(typeof(TrembleSyncSettings)); + + switch (paths.Length) + { + case 0: + return null; + + case >1: + Debug.LogError("More than one Tremble Sync Settings file found!"); + foreach (string path in paths) + { + Debug.LogWarning($"Found at: {path}", AssetDatabase.LoadAssetAtPath(path)); + } + Debug.LogError("There should be only one! Picking one arbitrarily for now."); + + goto default; + default: + return AssetDatabase.LoadAssetAtPath(paths[0]); + } + } + + public void ReleaseAll() { } + + + public static void DropCachedAssetPaths() + { + s_CachedQueryResults.Clear(); + } + } +} + +#endif \ No newline at end of file diff --git a/Assets/Tremble/AssetLoading/Adaptors/EditorLoaderAdaptor.cs.meta b/Assets/Tremble/AssetLoading/Adaptors/EditorLoaderAdaptor.cs.meta new file mode 100644 index 0000000..49c0764 --- /dev/null +++ b/Assets/Tremble/AssetLoading/Adaptors/EditorLoaderAdaptor.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a410384015ae43959c21d5c273d941a0 +timeCreated: 1716201389 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/AssetLoading/Adaptors/EditorLoaderAdaptor.cs + uploadId: 939664 diff --git a/Assets/Tremble/AssetLoading/Adaptors/IAssetLoaderAdaptor.cs b/Assets/Tremble/AssetLoading/Adaptors/IAssetLoaderAdaptor.cs new file mode 100644 index 0000000..d47c43b --- /dev/null +++ b/Assets/Tremble/AssetLoading/Adaptors/IAssetLoaderAdaptor.cs @@ -0,0 +1,36 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace TinyGoose.Tremble +{ + public interface IAssetLoaderAdaptor + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Finding & loading assets + // ----------------------------------------------------------------------------------------------------------------------------- + string[] FindAssetPaths(Type type, string name = ""); + TAsset LoadAssetByPath(string path) where TAsset : Object; + Task PreloadAssetsByPaths(IList paths); + bool SupportsPreloading { get; } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Getting path for a loaded asset + // ----------------------------------------------------------------------------------------------------------------------------- + string GetPath(Object obj); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Misc + // ----------------------------------------------------------------------------------------------------------------------------- + TrembleSyncSettings LoadSyncSettings(); + Material LoadClipMaterial(); + void ReleaseAll(); + } +} \ No newline at end of file diff --git a/Assets/Tremble/AssetLoading/Adaptors/IAssetLoaderAdaptor.cs.meta b/Assets/Tremble/AssetLoading/Adaptors/IAssetLoaderAdaptor.cs.meta new file mode 100644 index 0000000..9c9c5e5 --- /dev/null +++ b/Assets/Tremble/AssetLoading/Adaptors/IAssetLoaderAdaptor.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 7271c3afa0854533a18a87ea7a9690c8 +timeCreated: 1716201055 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/AssetLoading/Adaptors/IAssetLoaderAdaptor.cs + uploadId: 939664 diff --git a/Assets/Tremble/AssetLoading/Adaptors/NullLoaderAdaptor.cs b/Assets/Tremble/AssetLoading/Adaptors/NullLoaderAdaptor.cs new file mode 100644 index 0000000..304ce9a --- /dev/null +++ b/Assets/Tremble/AssetLoading/Adaptors/NullLoaderAdaptor.cs @@ -0,0 +1,61 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace TinyGoose.Tremble +{ + public class NullLoaderAdaptor : IAssetLoaderAdaptor + { + public bool SupportsPreloading => false; + + public string[] FindAssetPaths(Type type, string name = "") + { + Debug.LogError("No valid loader adaptor - ensure you have Addressables installed or are in editor!"); + return Array.Empty(); + } + + public TAsset LoadAssetByPath(string path) where TAsset : Object + { + Debug.LogError("No valid loader adaptor - ensure you have Addressables installed or are in editor!"); + return null; + } + + public Task PreloadAssetsByPaths(IList paths) + { + Debug.LogError("No valid loader adaptor - ensure you have Addressables installed or are in editor!"); + return Task.CompletedTask; + } + + public string GetPath(Object obj) + { + Debug.LogError("No valid loader adaptor - ensure you have Addressables installed or are in editor!"); + return null; + } + + public TrembleSyncSettings GetSyncSettings() + { + Debug.LogError("No valid loader adaptor - ensure you have Addressables installed or are in editor!"); + return null; + } + + public TrembleSyncSettings LoadSyncSettings() + { + Debug.LogError("No valid loader adaptor - ensure you have Addressables installed or are in editor!"); + return null; + } + + public Material LoadClipMaterial() + { + Debug.LogError("No valid loader adaptor - ensure you have Addressables installed or are in editor!"); + return null; + } + public void ReleaseAll() { } + } +} \ No newline at end of file diff --git a/Assets/Tremble/AssetLoading/Adaptors/NullLoaderAdaptor.cs.meta b/Assets/Tremble/AssetLoading/Adaptors/NullLoaderAdaptor.cs.meta new file mode 100644 index 0000000..72fe641 --- /dev/null +++ b/Assets/Tremble/AssetLoading/Adaptors/NullLoaderAdaptor.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a3c2e961a9234fcb94549e1f5bb3e8f2 +timeCreated: 1716201662 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/AssetLoading/Adaptors/NullLoaderAdaptor.cs + uploadId: 939664 diff --git a/Assets/Tremble/AssetLoading/TrembleAssetLoader.cs b/Assets/Tremble/AssetLoading/TrembleAssetLoader.cs new file mode 100644 index 0000000..413d76d --- /dev/null +++ b/Assets/Tremble/AssetLoading/TrembleAssetLoader.cs @@ -0,0 +1,170 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +//#define USE_ADDRESSABLES_IN_EDITOR + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace TinyGoose.Tremble +{ + public static class TrembleAssetLoader + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Adaptor + // ----------------------------------------------------------------------------------------------------------------------------- + private static IAssetLoaderAdaptor s_LoaderAdaptor; + + private static IAssetLoaderAdaptor LoaderAdaptor + { + get + { + if (s_LoaderAdaptor == null) + { +#if UNITY_EDITOR && !USE_ADDRESSABLES_IN_EDITOR + s_LoaderAdaptor = new EditorLoaderAdaptor(); +#elif UNITY_SERVER + s_LoaderAdaptor = new NullLoaderAdaptor(); +#elif ADDRESSABLES_INSTALLED + s_LoaderAdaptor = new AddressablesLoaderAdaptor(); +#else + s_LoaderAdaptor = new NullLoaderAdaptor(); +#endif + } + + return s_LoaderAdaptor; + } + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Generic + // ----------------------------------------------------------------------------------------------------------------------------- + public static string FindAssetPath(string name = "") where TAsset : Object + { + string[] paths = FindAssetPaths(name); + + switch (paths.Length) + { + // Nothing matched - return null :( + case 0: + return null; + + // Multiple matches - check if we have an EXACT match + case > 1: + { + foreach (string path in paths) + { + string filename = Path.GetFileNameWithoutExtension(path); + if (!filename.EqualsInvariant(name)) + continue; + + return path; + } + + break; + } + } + + // Only a single match, or couldn't disambiguate - return first + return paths[0]; + } + + public static string[] FindAssetPaths(string name = "") where TAsset : Object => FindAssetPaths(typeof(TAsset), name); + + public static string[] FindAssetPaths(Type type, string name = "") => LoaderAdaptor.FindAssetPaths(type, name); + + public static string GetPath(Object obj) => LoaderAdaptor.GetPath(obj); + + public static GameObject LoadPrefabByName(string name) => LoadAssetByName(name); + public static GameObject LoadPrefabByPath(string path) => LoadAssetByPath(path); + + public static TAsset LoadAssetByName(string name) where TAsset : Object + { + string path = FindAssetPath(name); + return LoadAssetByPath(path); + } + + public static TAsset LoadAssetByPath(string path) where TAsset : Object + => LoaderAdaptor.LoadAssetByPath(path); + + public static async Task PreloadAssetsByPaths(IList paths) + => await LoaderAdaptor.PreloadAssetsByPaths(paths); + + public static bool SupportsPreloading => LoaderAdaptor.SupportsPreloading; + + public static void ReleaseAll() => LoaderAdaptor.ReleaseAll(); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Queries + // ----------------------------------------------------------------------------------------------------------------------------- + private static int s_NumAssetMetadatas; + private static readonly Dictionary s_MapNameToMetadataIndex = new(); + private static readonly Dictionary s_PathToMetadataIndex = new(); + + public static bool TryGetAssetDataFromMapName(string mapName, out AssetMetadata foundMetadata) + { + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + CreateLookups(syncSettings); + + bool found = s_MapNameToMetadataIndex.TryGetValue(mapName, out int index); + foundMetadata = found ? syncSettings.AssetMetadatas[index] : default; + return found; + } + + public static bool TryGetAssetDataFromPath(string path, out AssetMetadata foundMetadata) + { + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + CreateLookups(syncSettings); + + bool found = s_PathToMetadataIndex.TryGetValue(path, out int index); + foundMetadata = found ? syncSettings.AssetMetadatas[index] : default; + return found; + } + + private static void CreateLookups(TrembleSyncSettings syncSettings) + { + if (syncSettings.AssetMetadatas == null) + return; + + if (s_NumAssetMetadatas == syncSettings.AssetMetadatas.Length) + return; + + s_NumAssetMetadatas = syncSettings.AssetMetadatas.Length; + s_MapNameToMetadataIndex.Clear(); + s_PathToMetadataIndex.Clear(); + + for (int i = 0; i < syncSettings.AssetMetadatas.Length; i++) + { + s_MapNameToMetadataIndex[syncSettings.AssetMetadatas[i].MapName] = i; + s_PathToMetadataIndex[syncSettings.AssetMetadatas[i].Path] = i; + } + } + + public static AssetMetadata[] FindAssetDataMany(Func filter) + { + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + return syncSettings.AssetMetadatas != null + ? syncSettings.AssetMetadatas.Where(filter).ToArray() + : Array.Empty(); + } + public static bool TryFindAssetData(Func filter, out AssetMetadata found) + { + AssetMetadata[] results = FindAssetDataMany(filter); + found = results.Length > 0 ? results[0] : default; + return results.Length > 0; + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Specifics + // ----------------------------------------------------------------------------------------------------------------------------- + public static Material LoadClipMaterial() => LoaderAdaptor.LoadClipMaterial(); + public static TrembleSyncSettings LoadSyncSettings() => LoaderAdaptor.LoadSyncSettings(); + } +} \ No newline at end of file diff --git a/Assets/Tremble/AssetLoading/TrembleAssetLoader.cs.meta b/Assets/Tremble/AssetLoading/TrembleAssetLoader.cs.meta new file mode 100644 index 0000000..4375f00 --- /dev/null +++ b/Assets/Tremble/AssetLoading/TrembleAssetLoader.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: fe12c1abce564e1d8163e2f1197f500b +timeCreated: 1715666874 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/AssetLoading/TrembleAssetLoader.cs + uploadId: 939664 diff --git a/Assets/Tremble/Attributes.meta b/Assets/Tremble/Attributes.meta new file mode 100644 index 0000000..1379ca5 --- /dev/null +++ b/Assets/Tremble/Attributes.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: aef5a15ddfbd44629a019e803c317adf +timeCreated: 1698412693 \ No newline at end of file diff --git a/Assets/Tremble/Attributes/Classes.meta b/Assets/Tremble/Attributes/Classes.meta new file mode 100644 index 0000000..84e450f --- /dev/null +++ b/Assets/Tremble/Attributes/Classes.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c60f610e41f242fca42d8547953f86a0 +timeCreated: 1711702716 \ No newline at end of file diff --git a/Assets/Tremble/Attributes/Classes/BrushEntityAttribute.cs b/Assets/Tremble/Attributes/Classes/BrushEntityAttribute.cs new file mode 100644 index 0000000..4494208 --- /dev/null +++ b/Assets/Tremble/Attributes/Classes/BrushEntityAttribute.cs @@ -0,0 +1,73 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public enum CheckerboardStyle + { + None, + Light, + Dark, + } + + public enum BrushType + { + // Solid brush with a texture (default) + Solid, + + // Liquid brush (trigger collision) with a texture + Liquid, + + // An invisible brush which is a Unity trigger + Trigger, + + // An invisible (but solid) brush + Invisible + } + + /// + /// Marks this MonoBehaviour as a component which can be added to arbitrary Brush entities from a map. + /// + [AttributeUsage(AttributeTargets.Class)] + public class BrushEntityAttribute : EntityAttributeBase + { + /// + /// A Tremble-compatible Brush entity. + /// + /// The name in TrenchBroom. e.g. "cool_entity". + /// The category for TrenchBroom. e.g. "ent". + /// The brush type. e.g. Trigger, Solid, Liquid. + /// The colour of this brush's texture. + /// The type of checkerboard for this brush's texture. + /// The layer name to put this brush on. + public BrushEntityAttribute( + string trenchBroomName = null, + string category = null, + BrushType type = BrushType.Solid, + string colour = "", + CheckerboardStyle checkerStyle = CheckerboardStyle.None, + string layer = "") + : base(trenchBroomName, category) + { + m_BrushType = type; + m_Colour = colour.TryParseQ3Colour(out Color value) ? value : null; + m_CheckerStyle = checkerStyle; + m_LayerName = layer; + } + + private readonly BrushType m_BrushType; + private readonly Color? m_Colour; + private readonly CheckerboardStyle m_CheckerStyle; + private readonly string m_LayerName; + + public BrushType BrushType => m_BrushType; + public Color? Colour => m_Colour; + public CheckerboardStyle CheckerStyle => m_CheckerStyle; + public string LayerName => m_LayerName; + } +} \ No newline at end of file diff --git a/Assets/Tremble/Attributes/Classes/BrushEntityAttribute.cs.meta b/Assets/Tremble/Attributes/Classes/BrushEntityAttribute.cs.meta new file mode 100644 index 0000000..91a91f4 --- /dev/null +++ b/Assets/Tremble/Attributes/Classes/BrushEntityAttribute.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 36b1eeadd99b4fd9bfd817b15f131f87 +timeCreated: 1711702807 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Attributes/Classes/BrushEntityAttribute.cs + uploadId: 939664 diff --git a/Assets/Tremble/Attributes/Classes/EntityAttributeBase.cs b/Assets/Tremble/Attributes/Classes/EntityAttributeBase.cs new file mode 100644 index 0000000..3e2f6cb --- /dev/null +++ b/Assets/Tremble/Attributes/Classes/EntityAttributeBase.cs @@ -0,0 +1,26 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [AttributeUsage(AttributeTargets.Class)] + public abstract class EntityAttributeBase : SelectionBaseAttribute + { + protected EntityAttributeBase(string trenchBroomName = null, string category = null) + { + m_TrenchBroomName = trenchBroomName.Sanitise(); + m_Category = category.Sanitise(); + } + + private readonly string m_TrenchBroomName; + private readonly string m_Category; + + public string TrenchBroomName => m_TrenchBroomName; + public string Category => m_Category; + } +} \ No newline at end of file diff --git a/Assets/Tremble/Attributes/Classes/EntityAttributeBase.cs.meta b/Assets/Tremble/Attributes/Classes/EntityAttributeBase.cs.meta new file mode 100644 index 0000000..bb6e31e --- /dev/null +++ b/Assets/Tremble/Attributes/Classes/EntityAttributeBase.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 84c2d0a79b3844d98271142f9df938e3 +timeCreated: 1711702912 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Attributes/Classes/EntityAttributeBase.cs + uploadId: 939664 diff --git a/Assets/Tremble/Attributes/Classes/PointEntityAttribute.cs b/Assets/Tremble/Attributes/Classes/PointEntityAttribute.cs new file mode 100644 index 0000000..fd34b6d --- /dev/null +++ b/Assets/Tremble/Attributes/Classes/PointEntityAttribute.cs @@ -0,0 +1,41 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + /// + /// Marks this MonoBehaviour as a component which can be added to empty GameObjects as a Point entity. + /// + [AttributeUsage(AttributeTargets.Class)] + public class PointEntityAttribute : EntityAttributeBase + { + /// + /// A Tremble-compatible Point entity. + /// + /// The name in TrenchBroom. e.g. "cool_entity". + /// The category for TrenchBroom. e.g. "ent". + /// The colour of the entity in TrenchBroom. e.g. green is "0.0 1.0 0.0". + /// The sprite to show in TrenchBroom. Must be the name of a texture in your project. e.g. "T_MyTexture". + /// The size of the cube for this entity in TrenchBroom. e.g. 5. + public PointEntityAttribute(string trenchBroomName = null, string category = null, string colour = null, string sprite = null, float size = 0.25f) + : base(trenchBroomName, category) + { + m_Size = size; + m_Sprite = sprite; + m_Colour = colour.TryParseQ3Colour(out Color value) ? value : Color.white; + } + + private readonly Color? m_Colour; + private readonly string m_Sprite; + private readonly float m_Size; + + public Color Colour => m_Colour ?? Color.white; + public string Sprite => m_Sprite; + public float Size => m_Size; + } +} \ No newline at end of file diff --git a/Assets/Tremble/Attributes/Classes/PointEntityAttribute.cs.meta b/Assets/Tremble/Attributes/Classes/PointEntityAttribute.cs.meta new file mode 100644 index 0000000..9f88a75 --- /dev/null +++ b/Assets/Tremble/Attributes/Classes/PointEntityAttribute.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ac6bd87f35f74bf6b78590e9038c0ee4 +timeCreated: 1711702870 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Attributes/Classes/PointEntityAttribute.cs + uploadId: 939664 diff --git a/Assets/Tremble/Attributes/Classes/PrefabEntityAttribute.cs b/Assets/Tremble/Attributes/Classes/PrefabEntityAttribute.cs new file mode 100644 index 0000000..a96d069 --- /dev/null +++ b/Assets/Tremble/Attributes/Classes/PrefabEntityAttribute.cs @@ -0,0 +1,71 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; + +namespace TinyGoose.Tremble +{ + /// + /// Marks this MonoBehaviour as being usable as a Point entity in TrenchBroom, using one or more prefabs in the project. + /// + [AttributeUsage(AttributeTargets.Class)] + public class PrefabEntityAttribute : EntityAttributeBase + { + /// + /// A Tremble-compatible Prefab entity. + /// + /// The name in TrenchBroom. e.g. "P_MyPrefab". + /// The category for TrenchBroom. e.g. "game". + /// Which prefabs containing this script to exclude. e.g. "P_BaseCoinPrefab". + /// Which prefabs containing this script to include. e.g. "P_TrembleCoinPrefab". + /// Which prefabs containing this script to exclude. e.g. "P_BasePrefab". + /// Which prefabs containing this script to include. e.g. "P_TrembleCoinPrefab". + /// Only export variants, not root prefabs + public PrefabEntityAttribute(string trenchBroomName = null, string category = null, string[] excludePrefabs = null, string[] onlyIncludePrefabs = null, string excludePrefab = null, string onlyIncludePrefab = null, bool onlyVariants = false, string overrideSprite = null) + : base(trenchBroomName: trenchBroomName, category: category) + { + m_ExcludedPrefabNames = excludePrefab != null ? new [] { excludePrefab } : excludePrefabs; + m_OnlyIncludedPrefabNames = onlyIncludePrefab != null ? new [] { onlyIncludePrefab } : onlyIncludePrefabs; + + m_OverrideSprite = overrideSprite; + m_OnlyVariants = onlyVariants; + } + + private readonly string[] m_ExcludedPrefabNames; + private readonly string[] m_OnlyIncludedPrefabNames; + + private readonly string m_OverrideSprite; + private readonly bool m_OnlyVariants; + + public bool IsPrefabIncluded(string prefabName) + { + // Is excluded explicitly? + if (m_ExcludedPrefabNames != null) + { + foreach (string excluded in m_ExcludedPrefabNames) + { + if (excluded.ToSimpleRegex().IsMatch(prefabName)) + return true; + } + } + + // Include everything? + if (m_OnlyIncludedPrefabNames == null) + return true; + + // See if it's on the whitelist + foreach (string included in m_OnlyIncludedPrefabNames) + { + if (included.ToSimpleRegex().IsMatch(prefabName)) + return true; + } + + return false; + } + + public string OverrideSprite => m_OverrideSprite; + public bool OnlyVariants => m_OnlyVariants; + } +} \ No newline at end of file diff --git a/Assets/Tremble/Attributes/Classes/PrefabEntityAttribute.cs.meta b/Assets/Tremble/Attributes/Classes/PrefabEntityAttribute.cs.meta new file mode 100644 index 0000000..3d6f506 --- /dev/null +++ b/Assets/Tremble/Attributes/Classes/PrefabEntityAttribute.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 7573313e4df24673a7c5cbbc3763e392 +timeCreated: 1711702750 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Attributes/Classes/PrefabEntityAttribute.cs + uploadId: 939664 diff --git a/Assets/Tremble/Attributes/Classes/SimpleRegexUtil.cs b/Assets/Tremble/Attributes/Classes/SimpleRegexUtil.cs new file mode 100644 index 0000000..6c26e9a --- /dev/null +++ b/Assets/Tremble/Attributes/Classes/SimpleRegexUtil.cs @@ -0,0 +1,19 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Text.RegularExpressions; + +namespace TinyGoose.Tremble +{ + public static class SimpleRegexUtil + { + public static Regex ToSimpleRegex(this string pattern) + { + // This is overly simplistic. But essentially, changes a pattern like + // "my*thing" into a Regex like "^my.+thing$" + return new($"^{pattern.Replace("*", ".+")}$"); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Attributes/Classes/SimpleRegexUtil.cs.meta b/Assets/Tremble/Attributes/Classes/SimpleRegexUtil.cs.meta new file mode 100644 index 0000000..b22818c --- /dev/null +++ b/Assets/Tremble/Attributes/Classes/SimpleRegexUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: eab674612dfd47fd833e72b6bbd5f974 +timeCreated: 1713786722 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Attributes/Classes/SimpleRegexUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Attributes/Fields.meta b/Assets/Tremble/Attributes/Fields.meta new file mode 100644 index 0000000..be5e006 --- /dev/null +++ b/Assets/Tremble/Attributes/Fields.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5fa882a49b914d46a6bdb96c4d52677a +timeCreated: 1711702720 \ No newline at end of file diff --git a/Assets/Tremble/Attributes/Fields/SpawnFlagsAttribute.cs b/Assets/Tremble/Attributes/Fields/SpawnFlagsAttribute.cs new file mode 100644 index 0000000..b305d0c --- /dev/null +++ b/Assets/Tremble/Attributes/Fields/SpawnFlagsAttribute.cs @@ -0,0 +1,36 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; + +namespace TinyGoose.Tremble +{ + /// + /// Marks this boolean as being a spawnflags field. + /// You can either provide an explicit bit to use, or omit and let the system guess based on order. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class SpawnFlagsAttribute : Attribute + { + public SpawnFlagsAttribute(int bit = -1) + { + //NOTE: Change MapBspGetters if this changes!! + m_Bit = bit; + } + + private readonly int m_Bit; + public int Bit => m_Bit; + } + + /// + /// Marks this boolean as never being a spawnflags field. + /// Use this is you have the auto-spawnflags flag set for booleans. + /// + [AttributeUsage(AttributeTargets.Field)] + public class NoSpawnFlagsAttribute : Attribute + { + //NOTE: Change MapBspGetters if this changes!! + } +} \ No newline at end of file diff --git a/Assets/Tremble/Attributes/Fields/SpawnFlagsAttribute.cs.meta b/Assets/Tremble/Attributes/Fields/SpawnFlagsAttribute.cs.meta new file mode 100644 index 0000000..4ecba61 --- /dev/null +++ b/Assets/Tremble/Attributes/Fields/SpawnFlagsAttribute.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 0102725e5aa1439cbb30a9675ce4513d +timeCreated: 1705750006 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Attributes/Fields/SpawnFlagsAttribute.cs + uploadId: 939664 diff --git a/Assets/Tremble/Attributes/Fields/TrembleAttribute.cs b/Assets/Tremble/Attributes/Fields/TrembleAttribute.cs new file mode 100644 index 0000000..ecf8872 --- /dev/null +++ b/Assets/Tremble/Attributes/Fields/TrembleAttribute.cs @@ -0,0 +1,39 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; + +namespace TinyGoose.Tremble +{ + /// + /// Marks a field as being serialised for maps (even if [SerializeField] is absent) + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class TrembleAttribute : Attribute + { + public TrembleAttribute(string name = null, bool isRotation = false) + { + //NOTE: Change MapBspGetters if this changes!! + m_OverrideName = name; + m_IsRotation = isRotation; + } + + private readonly string m_OverrideName; + private readonly bool m_IsRotation; + + public string OverrideName => m_OverrideName; + public bool IsRotation => m_IsRotation; + } + + + /// + /// Marks a field as NEVER being serialised for maps (even if [SerializeField] is on) + /// + [AttributeUsage(AttributeTargets.Field)] + public class NoTrembleAttribute : Attribute + { + //NOTE: Change MapBspGetters if this changes!! + } +} \ No newline at end of file diff --git a/Assets/Tremble/Attributes/Fields/TrembleAttribute.cs.meta b/Assets/Tremble/Attributes/Fields/TrembleAttribute.cs.meta new file mode 100644 index 0000000..bfdf76f --- /dev/null +++ b/Assets/Tremble/Attributes/Fields/TrembleAttribute.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 071a562d7c7647a18ebeb57869dfad3a +timeCreated: 1711702937 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Attributes/Fields/TrembleAttribute.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor.meta b/Assets/Tremble/Editor.meta new file mode 100644 index 0000000..5c7518a --- /dev/null +++ b/Assets/Tremble/Editor.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 0a01f5c71da3c76438e49ca9f447b5a1 +folderAsset: yes +timeCreated: 1628505674 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tremble/Editor/AssetImporters.meta b/Assets/Tremble/Editor/AssetImporters.meta new file mode 100644 index 0000000..3e64ee4 --- /dev/null +++ b/Assets/Tremble/Editor/AssetImporters.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 613ba1a10f2f46bf811791d8497c3047 +timeCreated: 1715620765 \ No newline at end of file diff --git a/Assets/Tremble/Editor/AssetImporters/FgdFileAssetImporter.cs b/Assets/Tremble/Editor/AssetImporters/FgdFileAssetImporter.cs new file mode 100644 index 0000000..cd8f20f --- /dev/null +++ b/Assets/Tremble/Editor/AssetImporters/FgdFileAssetImporter.cs @@ -0,0 +1,31 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEditor.AssetImporters; +using UnityEngine; +using System.IO; + +namespace TinyGoose.Tremble.Editor +{ + [ScriptedImporter(1, "fgd", -1000)] + public class FgdFileAssetImporter : ScriptedImporter + { + [SerializeField] private bool m_Test; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Entry Point + // ----------------------------------------------------------------------------------------------------------------------------- + public override void OnImportAsset(AssetImportContext ctx) + { + string assetName = Path.GetFileNameWithoutExtension(ctx.assetPath); + + FgdFileAsset wadAsset = ScriptableObject.CreateInstance(); + wadAsset.name = assetName; + + ctx.AddObjectToAsset(assetName, wadAsset); + ctx.SetMainObject(wadAsset); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/AssetImporters/FgdFileAssetImporter.cs.meta b/Assets/Tremble/Editor/AssetImporters/FgdFileAssetImporter.cs.meta new file mode 100644 index 0000000..131a580 --- /dev/null +++ b/Assets/Tremble/Editor/AssetImporters/FgdFileAssetImporter.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: fa734ddeb7244212a39e586474ae10a2 +timeCreated: 1724694974 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/AssetImporters/FgdFileAssetImporter.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/AssetImporters/TrembleMapAssetImporter.cs b/Assets/Tremble/Editor/AssetImporters/TrembleMapAssetImporter.cs new file mode 100644 index 0000000..4b022aa --- /dev/null +++ b/Assets/Tremble/Editor/AssetImporters/TrembleMapAssetImporter.cs @@ -0,0 +1,231 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// This class based on BSP Map Tools for Unity by John Evans (evans3d512@gmail.com) +// + +using System; +using System.Collections.Generic; +using UnityEditor.AssetImporters; +using UnityEngine; +using System.IO; +using System.Linq; +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + [ScriptedImporter(1, "map", importQueueOffset: 20000)] + public class TrembleMapAssetImporter : ScriptedImporter + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Exposed + // ----------------------------------------------------------------------------------------------------------------------------- + [SerializeField, Tooltip("The Map Processors to use (or none). Used to perform logic for individual entities from the map or on the map as a whole.")] + private MapProcessorClass[] m_Processors; + + [SerializeField, Tooltip("Whether to split the mesh when surface area is too large?")] + private bool m_SplitMesh = true; + + [SerializeField, Tooltip("Maximum surface area (in m^2) before splitting meshes")] + private float m_MaxMeshSurfaceArea = 3000; + + [SerializeField, Tooltip("The angle above which to smooth edges.")] + private float m_SmoothingAngle = 45; + + [SerializeField, Tooltip("Extra commandline to pass to Q3Map2 - see https://en.wikibooks.org/wiki/Q3Map2 for more details")] + private string m_ExtraCommandLineArgs = ""; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Entry Point + // ----------------------------------------------------------------------------------------------------------------------------- + public override async void OnImportAsset(AssetImportContext ctx) + { + // Check autosave and bail + if (String.Equals(Path.GetFileName(Path.GetDirectoryName(ctx.assetPath)), "autosave", StringComparison.InvariantCultureIgnoreCase)) + { + return; + } + + // Check we have a functioning setup (not first import, for example) + if (!Directory.Exists(TrembleConsts.BASEQ3_PATH)) + { + ctx.LogImportWarning($"Can't import map {Path.GetFileName(ctx.assetPath)}. Please sync first."); + return; + } + + if (MapRepairWindow.IsMapForeign(ctx.assetPath, out string gameName)) + { + gameName ??= "Quake(?)"; + + bool repairNow = EditorUtility.DisplayDialog( + title: "Map Repair Required", + message: $"You are trying to import a map from '{gameName}'. Before you can use this map, " + + "we'll need to repair it. This converts it for use with Tremble " + + $"and '{TrembleConsts.GAME_NAME}'. Shall we?", + "Repair and Resave", "Not Now"); + + if (repairNow) + { + MapRepairWindow.OpenMapRepair(ctx.assetPath); + } + + ctx.LogImportError($"Map '{Path.GetFileNameWithoutExtension(ctx.assetPath)}' needs repair to function with Tremble. Right-click the map and select 'Repair Map'."); + return; + } + + // Clear our cached asset lists + UnityObjectFieldConverterStatics.s_CachedAssetLists.Clear(); + + MapProcessorClass[] allProcessors = TrembleSyncSettings.Get().PipelineRunMapProcessors // global processors + ? TrembleSyncSettings.Get().EnabledMapProcessors + : Array.Empty(); + + if (m_Processors != null) + { + allProcessors = allProcessors.Concat(m_Processors).Distinct().ToArray(); // map-based processors + } + + TrembleMapImport importer = new(new() + { + ProcessorClasses = allProcessors, + SplitMesh = m_SplitMesh, + MaxMeshSurfaceArea = m_MaxMeshSurfaceArea, + SmoothingAngle = m_SmoothingAngle, + ExtraCommandLineArgs = m_ExtraCommandLineArgs, + AssetGUID = AssetDatabase.GUIDFromAssetPath(ctx.assetPath).ToString(), + + OnObjectAdded = ctx.AddObjectToAsset, + OnDependencyAdded = o => + { + if (TrembleSyncSettings.Get().AutomaticallyReimportWhenDependencyChanges) + { + ctx.DependsOnSourceAsset(AssetDatabase.GetAssetPath(o)); + } + }, + OnWadsFound = OnWadsFound, + OnEntityAdded = OnEntityAdded, + + OnError = err => ctx.LogImportError(err), + OnWarning = warn => ctx.LogImportWarning(warn), + OnQ3Map2Result = OnQ3Map2Result + }); + + TrembleTimer.BeginSession($"Tremble Map Import for {Path.GetFileNameWithoutExtension(ctx.assetPath)}"); + MapDocument document = await importer.ImportMapAndCreatePrefab(ctx.assetPath); + TrembleTimer.EndSession(); + + ctx.AddObjectToAsset("map", document.gameObject); + ctx.SetMainObject(document.gameObject); + } + + private void OnEntityAdded(GameObject gameObject, Type entityType) + { + if (entityType == null) + return; + + // Point entity with explicit icon? + entityType.GetCustomAttributes(out PointEntityAttribute pea); + + if (pea is { Sprite: not null }) + { + string spritePath = TrembleAssetLoader.FindAssetPath(pea.Sprite); + Texture2D texture = AssetDatabase.LoadAssetAtPath(spritePath); + + EditorGUIUtility.SetIconForObject(gameObject, texture); + return; + } + + // Implicit + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + if (syncSettings.EntityIconStyle == EntityIconStyle.Nothing) + return; + + if (entityType.FullName == null) + return; + + int hash = Math.Abs(entityType.FullName.GetHashCode()); + + switch (syncSettings.EntityIconStyle) + { + case EntityIconStyle.ColouredDiamondShapes: + int shapeIdx = hash % (int)EditorGameObjectIconUtil.EditorIcon.MAX; + gameObject.SetEditorIcon((EditorGameObjectIconUtil.EditorIcon)shapeIdx); + break; + case EntityIconStyle.ColouredLabels: + int labelIdx = hash % (int)EditorGameObjectIconUtil.EditorLabel.MAX; + gameObject.SetEditorIcon((EditorGameObjectIconUtil.EditorLabel)labelIdx); + break; + } + } + + private void OnWadsFound(string[] allWads) + { + string[] validWads = allWads.Where(File.Exists).ToArray(); + + foreach (string wad in validWads) + { + Debug.LogWarning($"Wad file found in map: {Path.GetFileName(wad)}. You should drop this file into your Unity project in order to use its materials!"); + } + + // bool copyThem = false; + // + // if (validWads.Length == 0) + // { + // EditorUtility.DisplayDialog( + // title: "Wad Files", + // message: $"Your map contains {allWads.Length} unknown wad file reference(s). " + + // "These are not directly supported by Tremble. If you want to use the textures " + + // "from your wad file(s), drag them into your Unity project and extract them.", "Ahh, okay"); + // } + // else if (validWads.Length == allWads.Length) + // { + // copyThem = EditorUtility.DisplayDialog( + // title: "Wad Files", + // message: $"Your map contains {validWads.Length} wad file reference(s). " + + // "These are not directly supported by Tremble. If you want to use the textures " + + // "from your wad file(s), they need extracting into your Unity project. Want to import them now?", "Yup!", "Nope"); + // } + // else + // { + // int numMissing = allWads.Length - validWads.Length; + // + // copyThem = EditorUtility.DisplayDialog( + // title: "Wad Files", + // message: $"Your map contains {validWads.Length} valid wad file reference(s), and {numMissing} which Tremble couldn't locate. " + + // "These are not directly supported by Tremble. If you want to use the textures " + + // "from your wad file(s), they need extracting into your Unity project. Want to import the ones we could find now?", "Yup!", "Nope"); + // } + // + // if (copyThem) + // { + // string folderName = Path.GetDirectoryName(assetPath); + // + // foreach (string existingPath in validWads) + // { + // string filename = Path.GetFileName(existingPath); + // File.Copy(existingPath, Path.Combine(folderName, filename)); + // } + // + // EditorApplication.delayCall += () => AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); + // } + } + + private void OnQ3Map2Result(Q3Map2Result result, List output) + { + // Show results? + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + + bool alwaysShowResult = syncSettings.Q3Map2ResultDisplayType == Q3Map2ResultDisplayType.AlwaysShow; + bool showWarnings = syncSettings.Q3Map2ResultDisplayType == Q3Map2ResultDisplayType.ShowWhenWarningsOccur; + + bool showWindow = result is Q3Map2Result.Failed or Q3Map2Result.FailedWithMissingTextures; + showWindow |= (result is Q3Map2Result.SucceededWithWarnings && showWarnings); + showWindow |= alwaysShowResult; + + if (showWindow) + { + Q3Map2OutputWindow.Open(output, alwaysShowResult); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/AssetImporters/TrembleMapAssetImporter.cs.meta b/Assets/Tremble/Editor/AssetImporters/TrembleMapAssetImporter.cs.meta new file mode 100644 index 0000000..0566100 --- /dev/null +++ b/Assets/Tremble/Editor/AssetImporters/TrembleMapAssetImporter.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ab79840212e84ded961df5ef93736275 +timeCreated: 1698136122 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/AssetImporters/TrembleMapAssetImporter.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/AssetImporters/WadFileAssetImporter.cs b/Assets/Tremble/Editor/AssetImporters/WadFileAssetImporter.cs new file mode 100644 index 0000000..5062aba --- /dev/null +++ b/Assets/Tremble/Editor/AssetImporters/WadFileAssetImporter.cs @@ -0,0 +1,42 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEditor.AssetImporters; +using UnityEngine; +using System.IO; +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + [ScriptedImporter(1, "wad", -1000)] + public class WadFileAssetImporter : ScriptedImporter + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Entry Point + // ----------------------------------------------------------------------------------------------------------------------------- + public override void OnImportAsset(AssetImportContext ctx) + { + string assetName = Path.GetFileNameWithoutExtension(ctx.assetPath); + + WadFileAsset wadAsset = ScriptableObject.CreateInstance(); + wadAsset.Modify(so => + { + SerializedProperty materials = so.FindBackedProperty(nameof(wadAsset.MaterialNames)); + + WadParser parser = new(ctx.assetPath); + WadFile wadFile = parser.Parse(); + + foreach (WadEntry entry in wadFile.Entries) + { + materials.AppendArrayElement().stringValue = entry.Name; + } + }); + wadAsset.name = assetName; + + ctx.AddObjectToAsset(assetName, wadAsset); + ctx.SetMainObject(wadAsset); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/AssetImporters/WadFileAssetImporter.cs.meta b/Assets/Tremble/Editor/AssetImporters/WadFileAssetImporter.cs.meta new file mode 100644 index 0000000..9bc7d12 --- /dev/null +++ b/Assets/Tremble/Editor/AssetImporters/WadFileAssetImporter.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: aa9cb8112a5643be99429353283f1858 +timeCreated: 1722847571 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/AssetImporters/WadFileAssetImporter.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/AssetProcessors.meta b/Assets/Tremble/Editor/AssetProcessors.meta new file mode 100644 index 0000000..c141d81 --- /dev/null +++ b/Assets/Tremble/Editor/AssetProcessors.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ab61355f926040629a80ee28e5683483 +timeCreated: 1709458791 \ No newline at end of file diff --git a/Assets/Tremble/Editor/AssetProcessors/FgdFileAssetPostprocessor.cs b/Assets/Tremble/Editor/AssetProcessors/FgdFileAssetPostprocessor.cs new file mode 100644 index 0000000..5a3e687 --- /dev/null +++ b/Assets/Tremble/Editor/AssetProcessors/FgdFileAssetPostprocessor.cs @@ -0,0 +1,39 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + public class FgdFileAssetPostprocessor : AssetPostprocessor + { + private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) + { + foreach (string requestFileName in importedAssets) + { + // We imported something, but not a MapFileAsset + if (AssetDatabase.GetMainAssetTypeAtPath(requestFileName) != typeof(FgdFileAsset)) + continue; + + bool success = false; + + try + { + FgdParser.Import(requestFileName); + success = true; + } + finally + { + if (!success) + { + EditorUtility.DisplayDialog("Import Failed!", "Failed to import FGD file :(, try again!", "Okay"); + } + AssetDatabase.DeleteAsset(requestFileName); + } + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/AssetProcessors/FgdFileAssetPostprocessor.cs.meta b/Assets/Tremble/Editor/AssetProcessors/FgdFileAssetPostprocessor.cs.meta new file mode 100644 index 0000000..deabcba --- /dev/null +++ b/Assets/Tremble/Editor/AssetProcessors/FgdFileAssetPostprocessor.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 04f793041d9e49d7822ba5068a727bb7 +timeCreated: 1724694689 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/AssetProcessors/FgdFileAssetPostprocessor.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/AssetProcessors/MapFileAssetPostprocessor.cs b/Assets/Tremble/Editor/AssetProcessors/MapFileAssetPostprocessor.cs new file mode 100644 index 0000000..24ea671 --- /dev/null +++ b/Assets/Tremble/Editor/AssetProcessors/MapFileAssetPostprocessor.cs @@ -0,0 +1,146 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public class MapFileAssetPostprocessor : AssetPostprocessor + { + private static readonly Stack s_MapsToConvert = new(); + private static string s_LastMapPath; + + private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) + { + foreach (string requestFileName in importedAssets) + { + // We imported something, but not a MapFileAsset + if (AssetDatabase.GetMainAssetTypeAtPath(requestFileName) != typeof(MapFileAsset)) + continue; + + // Check we haven't already processed this map, or already plan to + string mapFileName = GetMapFileName(requestFileName); + if (File.Exists(mapFileName) || s_MapsToConvert.Contains(requestFileName)) + continue; + + // Add to the work queue + s_MapsToConvert.Push(requestFileName); + + // Start conversion process + EditorApplication.update -= PerformConversionOnUpdate; + EditorApplication.update += PerformConversionOnUpdate; + } + } + + private static string GetMapFileName(string requestFileName) => requestFileName.Replace(".asset", ".map"); + + private static void PerformConversionOnUpdate() + { + // Nothing left to do - stop! + if (s_MapsToConvert.Count == 0) + { + EditorApplication.update -= PerformConversionOnUpdate; + return; + } + + string requestFileName = s_MapsToConvert.Pop(); + + // Delete the request file + string mapFileName = GetMapFileName(requestFileName); + AssetDatabase.DeleteAsset(requestFileName); + + // Open new file for write + using FileStream file = File.Create(mapFileName); + using StreamWriter sw = new(file, Encoding.ASCII); + + // Write a blank map, or copy template + TrembleSyncSettings trembleSyncSettings = TrembleSyncSettings.Get(); + if (trembleSyncSettings.TemplateMap && trembleSyncSettings.TemplateMap.TryGetComponent(out MapDocument _)) + { + string templatePath = AssetDatabase.GetAssetPath(trembleSyncSettings.TemplateMap); + + using FileStream templateFile = File.OpenRead(templatePath); + using StreamReader sr = new(templateFile, Encoding.ASCII); + + while (!sr.EndOfStream) + { + sw.WriteLine(sr.ReadLine()); + } + sr.Close(); + } + else + { + // New file + sw.WriteLine($"// Game: {TrembleConsts.GAME_NAME}"); + sw.WriteLine("// Format: Quake3 (Valve)"); + sw.WriteLine("// entity 0"); + sw.WriteLine("{"); + sw.WriteLine("\"mapversion\" \"220\""); + + sw.Write("\"_tb_textures\" \""); + List materialGroups = trembleSyncSettings.GetMaterialGroupsOrDefault(); + sw.Write(String.Join(';', materialGroups.Select(mg => $"textures/{mg.Name}"))); + sw.WriteLine("\""); + + sw.WriteLine("\"classname\" \"worldspawn\""); + sw.WriteLine("// brush 0"); + sw.WriteLine("{"); + sw.WriteLine("( -128 -128 -64 ) ( -128 -127 -64 ) ( -128 -128 -63 ) __TB_empty [ 0 -1 0 0 ] [ 0 0 -1 0 ] 0 0.5 0.5"); + sw.WriteLine("( -128 -128 -64 ) ( -128 -128 -63 ) ( -127 -128 -64 ) __TB_empty [ 1 0 0 0 ] [ 0 0 -1 0 ] 0 0.5 0.5"); + sw.WriteLine("( -128 -128 -64 ) ( -127 -128 -64 ) ( -128 -127 -64 ) __TB_empty [ -1 0 0 0 ] [ 0 -1 0 0 ] 0 0.5 0.5"); + sw.WriteLine("( 128 128 64 ) ( 128 129 64 ) ( 129 128 64 ) __TB_empty [ 1 0 0 0 ] [ 0 -1 0 0 ] 0 0.5 0.5"); + sw.WriteLine("( 128 128 64 ) ( 129 128 64 ) ( 128 128 65 ) __TB_empty [ -1 0 0 0 ] [ 0 0 -1 0 ] 0 0.5 0.5"); + sw.WriteLine("( 128 128 64 ) ( 128 128 65 ) ( 128 129 64 ) __TB_empty [ 0 1 0 0 ] [ 0 0 -1 0 ] 0 0.5 0.5"); + sw.WriteLine("}"); + sw.WriteLine("}"); + } + + sw.Close(); + + // Open in TB? + if (EditorUtility.DisplayDialog("Map Created!", "Want to open it now in TrenchBroom?", "Yep!", "Not now...")) + { + TrembleEditorAPI.SyncToTrenchBroom(); + TrenchBroomUtil.OpenWithTrenchBroom(mapFileName); + + s_LastMapPath = mapFileName; + + EditorApplication.update -= PromptToOpenMapOnFocus; + EditorApplication.update += PromptToOpenMapOnFocus; + } + } + + private static void PromptToOpenMapOnFocus() + { +#if UNITY_2022_1_OR_NEWER + if (!EditorApplication.isFocused) + return; +#endif + + EditorApplication.update -= PromptToOpenMapOnFocus; + + // Place in world? + if (EditorUtility.DisplayDialog("Welcome back!", "Want to place your brand new map in this Unity scene?", "Yep!", "No thanks")) + { + AssetDatabase.Refresh(); + + GameObject mapPrefab = AssetDatabase.LoadAssetAtPath(s_LastMapPath); + if (!mapPrefab) + { + EditorUtility.DisplayDialog("Oh no!", "Your new map failed to import. You may need to restart Unity and then reimport it. (this is a rare bug)", "Okay :("); + return; + } + GameObject mapObject = (GameObject)PrefabUtility.InstantiatePrefab(mapPrefab); + mapObject.transform.position = Vector3.zero; + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/AssetProcessors/MapFileAssetPostprocessor.cs.meta b/Assets/Tremble/Editor/AssetProcessors/MapFileAssetPostprocessor.cs.meta new file mode 100644 index 0000000..1bd0994 --- /dev/null +++ b/Assets/Tremble/Editor/AssetProcessors/MapFileAssetPostprocessor.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 6642958d88f3475995ac5c15d631af2d +timeCreated: 1707842798 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/AssetProcessors/MapFileAssetPostprocessor.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/AssetProcessors/MapLiveUpdatePostprocessor.cs b/Assets/Tremble/Editor/AssetProcessors/MapLiveUpdatePostprocessor.cs new file mode 100644 index 0000000..523beae --- /dev/null +++ b/Assets/Tremble/Editor/AssetProcessors/MapLiveUpdatePostprocessor.cs @@ -0,0 +1,202 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Diagnostics; +using System.Linq; +using UnityEditor; +using UnityEngine; +using UnityEngine.SceneManagement; +using Debug = UnityEngine.Debug; + +namespace TinyGoose.Tremble.Editor +{ + public class MapLiveUpdatePostprocessor : AssetPostprocessor + { + private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) + { + if (!Application.isPlaying || !TrembleSyncSettings.Get().UseLiveUpdate) + return; + + // Get list of imported GUIDs as strings + string[] importedGUIDs = importedAssets + .Select(path => AssetDatabase.GUIDFromAssetPath(path).ToString()) + .ToArray(); + + // If we reimport during gameplay, disable and re-enable the map to refresh the collision + Scene scene = SceneManager.GetActiveScene(); + MapDocument[] updatedMaps = scene.GetRootGameObjects() + .SelectMany(go => go.GetComponentsInChildren()) + .Where(doc => importedGUIDs.Contains(doc.OriginalAssetGuid)) + .ToArray(); + + foreach (MapDocument map in updatedMaps) + { + Stopwatch timer = new(); + timer.Start(); + + string assetPath = AssetDatabase.GUIDToAssetPath(map.OriginalAssetGuid); + GameObject prefabMap = AssetDatabase.LoadAssetAtPath(assetPath); + MapDocument prefabMapDocument = prefabMap.GetComponent(); + + // Re-instance worldspawn + GameObject newWorldspawn = InstanceNewWorldspawn(map, prefabMapDocument); + + // Spawn any new objects, and transfer vars to existing + int numNewlySpawned = 0; + int numUpdated = 0; + foreach (Transform prefabChild in prefabMap.transform) + { + if (prefabChild.gameObject == prefabMapDocument.WorldspawnObject) + continue; + + bool isNew = true; + foreach (Transform mapChild in map.transform) + { + if (mapChild.name != prefabChild.name) + continue; + + numUpdated++; + + // Object is static :( grab it from the map instead + if (mapChild.gameObject.isStatic && HasEntityMoved(mapChild, prefabChild)) + { + Debug.LogWarning($"Tremble LiveUpdate: Replacing static object '{mapChild.name}' with new copy. This could cause issues!"); + GameObject.Destroy(mapChild.gameObject); + break; + } + + if (TryFindTrembleComponent(prefabChild.gameObject, out Component prefabComp) && + TryFindTrembleComponent(mapChild.gameObject, out Component mapComp)) + { + // Disable, copy across data, re-enable + mapComp.gameObject.SetActive(false); + CopySafeSerialisedData(from: prefabComp, to: mapComp); + mapComp.gameObject.SetActive(true); + + // Handle live update callbacks + switch (mapComp) + { + case IOnLiveUpdate_Simple: + mapComp.SendMessage("OnDestroy", SendMessageOptions.DontRequireReceiver); + mapComp.SendMessage("Awake", SendMessageOptions.DontRequireReceiver); + mapComp.SendMessage("Start", SendMessageOptions.DontRequireReceiver); + break; + + case IOnLiveUpdate liveUpdateable: + liveUpdateable.OnLiveUpdated(); + break; + } + } + + isNew = false; + break; + } + + if (isNew) + { + numNewlySpawned++; + GameObject.Instantiate(prefabChild.gameObject, newWorldspawn.transform); + } + } + + timer.Stop(); + + TryShowGameViewNotification($"Tremble LiveUpdate:\n{numNewlySpawned} new ents\n{numUpdated} updates\nin {timer.ElapsedMilliseconds}ms"); + } + } + + private static bool HasEntityMoved(Transform mapChild, Transform prefabChild) + { + if (Vector3.SqrMagnitude(mapChild.position - prefabChild.position) > 0f) + return true; + + if (Vector3.SqrMagnitude(mapChild.rotation.eulerAngles - prefabChild.rotation.eulerAngles) > 0f) + return true; + + return false; + } + + private static GameObject InstanceNewWorldspawn(MapDocument map, MapDocument prefabMapDocument) + { + // Remove worldspawn + GameObject.Destroy(map.WorldspawnObject); + + // Reinstance worldspawn + GameObject newWorldspawn = GameObject.Instantiate(prefabMapDocument.WorldspawnObject, map.transform, true); + newWorldspawn.transform.localPosition = Vector3.zero; + newWorldspawn.transform.localRotation = Quaternion.identity; + map.Modify(so => so.FindProperty("m_WorldspawnObject").objectReferenceValue = newWorldspawn); + newWorldspawn.transform.SetAsFirstSibling(); + + // Disable and re-enable - if you don't do this, Unity does not update the colliders + map.gameObject.SetActive(false); + map.gameObject.SetActive(true); + return newWorldspawn; + } + + private static bool TryShowGameViewNotification(string note) + { + Type gameViewT = typeof(EditorWindow).Assembly.GetType("UnityEditor.GameView"); + + EditorWindow[] windows = Resources.FindObjectsOfTypeAll(gameViewT).Cast().ToArray(); + foreach (EditorWindow win in windows) + { + win.ShowNotification(new(note), 1f); + } + + return windows.Length > 0; + } + + private static bool TryFindTrembleComponent(GameObject go, out Component component) + { + foreach (Component c in go.GetComponents()) + { + if (!c.GetType().HasCustomAttribute()) + continue; + + component = c; + return true; + } + + component = default; + return false; + } + + private static void CopySafeSerialisedData(Component from, Component to) + { + // For now, we just copy simple data - floats, colours, vectors etc. + // References and assets are a bit spoopier and we can't do too much there sadly! + + SerializedObject fromObject = new(from); + SerializedObject toObject = new(to); + + SerializedProperty iterator = fromObject.GetIterator(); + iterator.NextVisible(true); + + do + { + if (iterator.propertyType + is SerializedPropertyType.ObjectReference + or SerializedPropertyType.ManagedReference) + { + if (iterator.objectReferenceValue is Component) + continue; + } + + toObject.CopyFromSerializedProperty(iterator); + } while (iterator.NextVisible(false)); + + toObject.ApplyModifiedPropertiesWithoutUndo(); + + // Also copy basic positioning information + Transform fromTransform = from.transform; + Transform toTransform = to.transform; + + toTransform.localPosition = fromTransform.localPosition; + toTransform.localRotation = fromTransform.localRotation; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/AssetProcessors/MapLiveUpdatePostprocessor.cs.meta b/Assets/Tremble/Editor/AssetProcessors/MapLiveUpdatePostprocessor.cs.meta new file mode 100644 index 0000000..e8664a4 --- /dev/null +++ b/Assets/Tremble/Editor/AssetProcessors/MapLiveUpdatePostprocessor.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: de0e937a05b84f928a4e0c9ff6d32146 +timeCreated: 1708536137 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/AssetProcessors/MapLiveUpdatePostprocessor.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/AssetProcessors/TrembleCacheDropperPostprocessor.cs b/Assets/Tremble/Editor/AssetProcessors/TrembleCacheDropperPostprocessor.cs new file mode 100644 index 0000000..c3ee06f --- /dev/null +++ b/Assets/Tremble/Editor/AssetProcessors/TrembleCacheDropperPostprocessor.cs @@ -0,0 +1,22 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + public class TrembleCacheDropperPostprocessor : AssetPostprocessor + { + private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) + { + if (!TrembleSyncSettings.Get().AutomaticallyReimportWhenDependencyChanges) + { + MapHierarchyIcons.ResetModifiedTimes(); + } + + EditorLoaderAdaptor.DropCachedAssetPaths(); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/AssetProcessors/TrembleCacheDropperPostprocessor.cs.meta b/Assets/Tremble/Editor/AssetProcessors/TrembleCacheDropperPostprocessor.cs.meta new file mode 100644 index 0000000..14fd518 --- /dev/null +++ b/Assets/Tremble/Editor/AssetProcessors/TrembleCacheDropperPostprocessor.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 5e639ddfe46c434eb843b1bd7ee8259c +timeCreated: 1713956404 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/AssetProcessors/TrembleCacheDropperPostprocessor.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/AssetProcessors/WadFileAssetPostprocessor.cs b/Assets/Tremble/Editor/AssetProcessors/WadFileAssetPostprocessor.cs new file mode 100644 index 0000000..1dd0ead --- /dev/null +++ b/Assets/Tremble/Editor/AssetProcessors/WadFileAssetPostprocessor.cs @@ -0,0 +1,38 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + public class WadFileAssetPostprocessor : AssetPostprocessor + { + private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) + { + foreach (string requestFileName in importedAssets) + { + // We imported something, but not a WadFileAsset + if (AssetDatabase.GetMainAssetTypeAtPath(requestFileName) != typeof(WadFileAsset)) + continue; + + bool success = false; + + try + { + WadAssetImporterEditor.Extract(requestFileName); + success = true; + } + finally + { + if (!success) + { + EditorUtility.DisplayDialog("Import Failed!", "Failed to import WAD file :(, try again!", "Okay"); + } + AssetDatabase.DeleteAsset(requestFileName); + } + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/AssetProcessors/WadFileAssetPostprocessor.cs.meta b/Assets/Tremble/Editor/AssetProcessors/WadFileAssetPostprocessor.cs.meta new file mode 100644 index 0000000..2c2523e --- /dev/null +++ b/Assets/Tremble/Editor/AssetProcessors/WadFileAssetPostprocessor.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: c83945126e2c4fa9aa009f1463530bad +timeCreated: 1722936486 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/AssetProcessors/WadFileAssetPostprocessor.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI.meta b/Assets/Tremble/Editor/EditorUI.meta new file mode 100644 index 0000000..9372c99 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b41c2b89aca249e7a68bc85e07f144ed +timeCreated: 1707741796 \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/DiagnosticsWindow.cs b/Assets/Tremble/Editor/EditorUI/DiagnosticsWindow.cs new file mode 100644 index 0000000..dd01c9a --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/DiagnosticsWindow.cs @@ -0,0 +1,146 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public class DiagnosticsWindow : EditorWindow + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Menu Items + // ----------------------------------------------------------------------------------------------------------------------------- + [MenuItem("Tools/Tremble/Advanced/Debug/Diagnostics")] + public static void OpenDiagnosticsWindow() + { + DiagnosticsWindow window = GetWindow(true, "Tremble Diagnostics", true); + + Vector2 size = new(900f, 800f); + window.minSize = size; + window.position = new(EditorGUIUtility.GetMainWindowPosition().center - size / 2f, size); + window.Show(); + } + + private Vector2 m_ScrollPosition = Vector2.zero; + private FgdWriter m_FgdWriter; + private string m_TrenchbroomInstallPath; + private Q3Map2VersionInfo m_Q3Map2VersionInfo; + + + private void OnEnable() + { + m_Q3Map2VersionInfo = Q3Map2Dll.GetTinyGooseVersionInfo(); + m_FgdWriter = TrembleSync.GatherEntities(); + m_TrenchbroomInstallPath = Path.GetFullPath(TrenchBroomUtil.TrenchBroomPath); + } + + private void OnGUI() + { + m_ScrollPosition = GUILayout.BeginScrollView(m_ScrollPosition); + { + Header("Basic Info"); + { + Diagnostic("Tremble Version", () => TrembleConsts.VERSION_STRING); + Diagnostic("Unity Version", () => Application.unityVersion); + Diagnostic("Configured TB Version", () => TrembleSyncSettings.Get().TrenchBroomVersion); + Diagnostic("OS", () => Application.platform.ToString()); + Diagnostic("OS Locale", () => CultureInfo.CurrentCulture.DisplayName); + } + + Header("Project Info"); + { + Diagnostic("Project Name", () => Application.productName); + Diagnostic("Company Name", () => Application.companyName); + Diagnostic("TB Game Name", () => TrembleConsts.GAME_NAME); + } + + Header("Paths"); + { + Diagnostic("User Path", () => Environment.GetFolderPath(Environment.SpecialFolder.Personal)); + Diagnostic("Map Staging Path", () => Application.temporaryCachePath); + Diagnostic("Project Path", () => Path.GetFullPath(Directory.GetCurrentDirectory())); + Diagnostic("BaseQ3 Path", () => TrembleConsts.BASEQ3_PATH); + Diagnostic("TB Game Path", () => Path.GetFullPath(TrenchBroomUtil.GetGameFolder())); + Diagnostic("TB Install Path", () => m_TrenchbroomInstallPath); + } + + Header("Q3Map2"); + { + Diagnostic("Q3Map2 Loaded?", () => Q3Map2Dll.IsLoaded); + Diagnostic("Q3Map2 Version", () => $"{m_Q3Map2VersionInfo.Major}.{m_Q3Map2VersionInfo.Minor}.{m_Q3Map2VersionInfo.Patch}"); + Diagnostic("Q3Map2 Hash", () => m_Q3Map2VersionInfo.GitHash); + Diagnostic("Q3Map2 Cmdline", () => TrembleSyncSettings.Get().ExtraCommandLineArgs); + } + + Header("Game"); + { + Diagnostic("Worldspawn Entity", () => m_FgdWriter.WorldspawnClass.Name); + Diagnostic("Map Processors", () => TrembleSyncSettings.Get().EnabledMapProcessors.Select(m => m.Class.Name)); + + int numMaterials = TrembleSyncSettings.Get().MaterialGroups.Sum(mg => mg.Materials.Length); + Diagnostic("Material Groups", () => TrembleSyncSettings.Get().MaterialGroups.Select(mg => $"{mg.Name} ({mg.Materials.Length})").Append($"= {numMaterials} total materials")); + + int numBases = m_FgdWriter.BaseClasses.Count; + int numPoints = m_FgdWriter.Classes.Count(e => e.Type == FgdClassType.Point); + int numBrushes = m_FgdWriter.Classes.Count(e => e.Type == FgdClassType.Brush); + Diagnostic("Entity Counts", () => $"{numBases} base(s), {numPoints} point(s), {numBrushes} brush(es)"); + } + } + GUILayout.EndScrollView(); + } + + private void Header(string header) + { + GUILayout.Space(20f); + GUILayout.Label(header, EditorStyles.boldLabel); + } + + private void Diagnostic(string labelTitle, Func contents) + { + GUILayout.BeginHorizontal(); + { + GUILayout.Space(20f); + GUILayout.Label(labelTitle, GUILayout.Width(200f)); + + try + { + object contentObject = contents(); + if (contentObject is IEnumerable contentObjects and not string) + { + GUILayout.BeginVertical(); + { + IEnumerator objectEnumerator = contentObjects.GetEnumerator(); + using IDisposable _ = objectEnumerator as IDisposable; // ensure disposed + + while (objectEnumerator.MoveNext()) + { + GUILayout.Label(objectEnumerator.Current?.ToString() ?? "", ManualStyles.Styles.Code, GUILayout.ExpandWidth(true)); + } + } + GUILayout.EndVertical(); + } + else + { + GUILayout.Label(contentObject.ToString(), ManualStyles.Styles.Code, GUILayout.ExpandWidth(true)); + } + } + catch (Exception ex) + { + GUI.color = Color.red; + GUILayout.Label($"FAILED: {ex.Message}", ManualStyles.Styles.Code, GUILayout.ExpandWidth(true)); + GUI.color = Color.white; + } + } + GUILayout.EndHorizontal(); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/DiagnosticsWindow.cs.meta b/Assets/Tremble/Editor/EditorUI/DiagnosticsWindow.cs.meta new file mode 100644 index 0000000..f28df2b --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/DiagnosticsWindow.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: da8c52d53f104a499424ec4d338cb7d1 +timeCreated: 1740735928 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/DiagnosticsWindow.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/Drawers.meta b/Assets/Tremble/Editor/EditorUI/Drawers.meta new file mode 100644 index 0000000..14d193f --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Drawers.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: de5403ed015546f98e39cd02b728ba9b +timeCreated: 1710244760 \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Drawers/BaseClassPickerDrawer.cs b/Assets/Tremble/Editor/EditorUI/Drawers/BaseClassPickerDrawer.cs new file mode 100644 index 0000000..00b7410 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Drawers/BaseClassPickerDrawer.cs @@ -0,0 +1,125 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public abstract class BaseClassPickerDrawer : PropertyDrawer + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Consts + // ----------------------------------------------------------------------------------------------------------------------------- + private const string INDENT_STRING = " "; + private const string NONE_STRING = "(none)"; + + protected abstract string ClassNamePropertyName { get; } + + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private List m_AllClasses; + private int m_SelectedClass; + + private bool m_Inited; + + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + // Lazy-load class catalog if needed + if (!m_Inited) + { + m_Inited = true; + GenerateClassCatalog(); + } + + // Draw label & icon + position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label); + EditorGUI.indentLevel = 0; + + // Generate class list + string[] classDisplayNames = m_AllClasses.Select(t => GetHumanClassName(t)).ToArray(); + + // Calculate current index + SerializedProperty classProperty = property.FindPropertyRelative(ClassNamePropertyName); + int prevSelectedClass = m_AllClasses.FindIndex(c => c.FullName == classProperty.stringValue); + if (prevSelectedClass == -1) + { + prevSelectedClass = 0; + } + + m_SelectedClass = EditorGUI.Popup(position, "", prevSelectedClass, classDisplayNames); + + EditorGUI.BeginProperty(position, GUIContent.none, property); + classProperty.stringValue = m_AllClasses[m_SelectedClass].FullName; + EditorGUI.EndProperty(); + + // Draw icon overlay + Rect iconRect = position; + iconRect.width = position.height; + iconRect.x += 2f; + iconRect.y += 2f; + iconRect.width -= 4f; + iconRect.height -= 4f; + + position.x += position.height; + position.width -= position.height; + + GUI.DrawTexture(iconRect, EditorGUIUtility.FindTexture("cs Script Icon")); + } + + private void GenerateClassCatalog() + { + List allClasses = TypeCache.GetTypesDerivedFrom(typeof(TClassType)).ToList(); + m_AllClasses = new(allClasses.Count + 1); + + if (!typeof(TClassType).IsAbstract) + { + m_AllClasses.Add(typeof(TClassType)); + } + m_AllClasses.AddRange(allClasses); + } + + private static string GetHumanClassName(Type type, bool indent = true) + { + string fullClassName = type.FullName; + if (fullClassName == null) + return indent ? (INDENT_STRING + NONE_STRING) : NONE_STRING; + + int lastDot = fullClassName.LastIndexOf('.'); + + // If it ends in dot (?!) or has no dot - return class as-is + if (lastDot == -1 || lastDot == fullClassName.Length - 1) + return fullClassName; + + string shortClassName = fullClassName.Substring(lastDot + 1); + + if (shortClassName.StartsWithInvariant("Null", caseSensitive: true)) + { + return indent ? (INDENT_STRING + NONE_STRING) : NONE_STRING; + } + + bool doneFirst = false; + List output = new(shortClassName.Length + 10); + + foreach (char c in shortClassName) + { + if (Char.IsUpper(c) && doneFirst) + { + output.Add(' '); + } + + output.Add(c); + doneFirst = true; + } + + string humanName = new(output.ToArray()); + return indent ? (INDENT_STRING + humanName) : humanName; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Drawers/BaseClassPickerDrawer.cs.meta b/Assets/Tremble/Editor/EditorUI/Drawers/BaseClassPickerDrawer.cs.meta new file mode 100644 index 0000000..101c953 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Drawers/BaseClassPickerDrawer.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 7b7aeb7420ec45cda02dea687dbd8e57 +timeCreated: 1710244772 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/Drawers/BaseClassPickerDrawer.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/Drawers/MapProcessorClassDrawer.cs b/Assets/Tremble/Editor/EditorUI/Drawers/MapProcessorClassDrawer.cs new file mode 100644 index 0000000..0f5ee71 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Drawers/MapProcessorClassDrawer.cs @@ -0,0 +1,15 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + [CustomPropertyDrawer(typeof(MapProcessorClass), useForChildren: true)] + public class MapProcessorClassDrawer : BaseClassPickerDrawer + { + protected override string ClassNamePropertyName => "m_MapClassName"; + } +} diff --git a/Assets/Tremble/Editor/EditorUI/Drawers/MapProcessorClassDrawer.cs.meta b/Assets/Tremble/Editor/EditorUI/Drawers/MapProcessorClassDrawer.cs.meta new file mode 100644 index 0000000..a5a1199 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Drawers/MapProcessorClassDrawer.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 85a89c98c61044e08811ba3fb0fbe957 +timeCreated: 1707730234 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/Drawers/MapProcessorClassDrawer.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/Drawers/WorldspawnScriptDrawer.cs b/Assets/Tremble/Editor/EditorUI/Drawers/WorldspawnScriptDrawer.cs new file mode 100644 index 0000000..dc55d13 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Drawers/WorldspawnScriptDrawer.cs @@ -0,0 +1,15 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + [CustomPropertyDrawer(typeof(WorldspawnScript), useForChildren: true)] + public class WorldspawnScriptDrawer : BaseClassPickerDrawer + { + protected override string ClassNamePropertyName => "m_ScriptName"; + } +} diff --git a/Assets/Tremble/Editor/EditorUI/Drawers/WorldspawnScriptDrawer.cs.meta b/Assets/Tremble/Editor/EditorUI/Drawers/WorldspawnScriptDrawer.cs.meta new file mode 100644 index 0000000..0d0bc73 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Drawers/WorldspawnScriptDrawer.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 513c5345701d4a0894054ae3c25184fb +timeCreated: 1710152511 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/Drawers/WorldspawnScriptDrawer.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/Editors.meta b/Assets/Tremble/Editor/EditorUI/Editors.meta new file mode 100644 index 0000000..519af88 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Editors.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d4361d4c49a24bea8a532781a1d0119f +timeCreated: 1722851165 \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Editors/WadAssetImporterEditor.cs b/Assets/Tremble/Editor/EditorUI/Editors/WadAssetImporterEditor.cs new file mode 100644 index 0000000..29b1da8 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Editors/WadAssetImporterEditor.cs @@ -0,0 +1,139 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [CustomEditor(typeof(WadFileAssetImporter))] + public class WadAssetImporterEditor : UnityEditor.Editor + { + private Vector2 m_ScrollPos = Vector2.zero; + private bool m_Running = false; + + public override void OnInspectorGUI() + { + if (target is not WadFileAssetImporter wadAssetImporter) + return; + + WadFileAsset wadAsset = AssetDatabase.LoadAssetAtPath(wadAssetImporter.assetPath); + + GUILayout.Label($"{wadAsset.MaterialNames.Length} material(s):"); + + GUI.color = new Color(0.8f, 0.8f, 0.8f); + { + m_ScrollPos = GUILayout.BeginScrollView(m_ScrollPos, GUILayout.Height(100f)); + { + foreach (string material in wadAsset.MaterialNames) + { + GUILayout.BeginHorizontal(); + { + GUIContent materialIcon = EditorGUIUtility.IconContent("Material Icon"); + GUILayout.Label(materialIcon, GUILayout.Width(16f), GUILayout.Height(16f)); + GUILayout.Label(material); + } + GUILayout.EndHorizontal(); + } + } + GUILayout.EndScrollView(); + } + GUI.color = Color.white; + + GUI.enabled = !m_Running; + if (GUILayout.Button("Extract Wad Materials")) + { + m_Running = true; + Extract(wadAssetImporter.assetPath); + m_Running = false; + } + } + + public static void Extract(string wadFilePath) + { + WadParser parser = new(wadFilePath); + WadFile wadFile = parser.Parse(); + + // Create folder + string folderPath = Path.ChangeExtension(wadFilePath, null); + string texturesPath = Path.Combine(folderPath, "Textures"); + string materialsPath = Path.Combine(folderPath, "Materials"); + DirectoryUtil.EmptyAndCreateDirectory(texturesPath); + DirectoryUtil.EmptyAndCreateDirectory(materialsPath); + + // Step 1: write textures + try + { + AssetDatabase.StartAssetEditing(); + EditorUtility.DisplayProgressBar("Extracting Wad Textures", "One mo..", 0f); + + for (int entryIdx = 0; entryIdx < wadFile.Entries.Count; entryIdx++) + { + WadEntry entry = wadFile.Entries[entryIdx]; + + float progress = (float)entryIdx / wadFile.Entries.Count; + EditorUtility.DisplayProgressBar("Extracting Wad Textures", $"{entry.Name} ({entryIdx + 1} of {wadFile.Entries.Count}) - {progress * 100:F0}%", progress); + + string texturePath = Path.Combine(texturesPath, $"T_{entry.Name}.png"); + parser.WriteTextureToFile(entry, texturePath); + } + } + finally + { + EditorUtility.ClearProgressBar(); + AssetDatabase.StopAssetEditing(); + } + + AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); + EditorApplication.delayCall += () => CreateMaterials(materialsPath, wadFilePath, wadFile); + } + + private static void CreateMaterials(string materialFolderPath, string wadFilePath, WadFile wadFile) + { + List createdMaterials = new(wadFile.Entries.Count); + + // Step 2: Create materials + try + { + AssetDatabase.StartAssetEditing(); + EditorUtility.DisplayProgressBar("Creating Materials", "One mo..", 0f); + + string texturesPath = Path.Combine(Path.GetDirectoryName(materialFolderPath), "Textures"); + + for (int entryIdx = 0; entryIdx < wadFile.Entries.Count; entryIdx++) + { + WadEntry entry = wadFile.Entries[entryIdx]; + + float progress = (float)entryIdx / wadFile.Entries.Count; + EditorUtility.DisplayProgressBar("Creating Materials", $"{entry.Name} ({entryIdx + 1} of {wadFile.Entries.Count}) - {progress * 100:F0}%", progress); + + string texturePath = Path.Combine(texturesPath, $"T_{entry.Name}.png"); + string materialPath = Path.Combine(materialFolderPath, $"{entry.Name}.mat"); + + Material mat = TrembleMapImport.CreateEditorMaterial(texturePath, smoothness: 0.1f, metallic: 0f); + AssetDatabase.CreateAsset(mat, materialPath); + + createdMaterials.Add(mat); + } + } + finally + { + EditorUtility.ClearProgressBar(); + AssetDatabase.StopAssetEditing(); + } + + // Add to material group, if project is using them + if (TrembleSyncSettings.Get().MaterialGroups.Length > 0) + { + string wadName = Path.GetFileNameWithoutExtension(wadFilePath); + MaterialGroupUtil.MoveMaterialsToGroup(createdMaterials.ToArray(), wadName, createIfNotExist: true); + } + + TrembleEditorAPI.SyncToTrenchBroom(); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Editors/WadAssetImporterEditor.cs.meta b/Assets/Tremble/Editor/EditorUI/Editors/WadAssetImporterEditor.cs.meta new file mode 100644 index 0000000..de66cd8 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Editors/WadAssetImporterEditor.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: eaf1a772c03e4686be2389348cf42bf1 +timeCreated: 1722851222 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/Editors/WadAssetImporterEditor.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/MapHierarchyIcons.cs b/Assets/Tremble/Editor/EditorUI/MapHierarchyIcons.cs new file mode 100644 index 0000000..b8c0c18 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/MapHierarchyIcons.cs @@ -0,0 +1,141 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [InitializeOnLoad] + public static class MapHierarchyIcons + { + static MapHierarchyIcons() + { + TrembleEditorUtility.RegisterOnHierarchyItem(OnHierarchyItem); + } + public static void ResetModifiedTimes() => s_CachedModifiedTimes.Clear(); + + private static readonly Dictionary s_CachedModifiedTimes = new(); + + private static void OnHierarchyItem(GameObject go, Rect selectionRect) + { + Rect r = new(selectionRect); + r.x -= 28; + r.width = 20; + + bool areDependenciesUpToDate = TrembleSyncSettings.Get().AutomaticallyReimportWhenDependencyChanges; + + if (go.TryGetComponent(out MapDocument thisMap)) + { + if (!areDependenciesUpToDate) + { + ulong maxTimestamp = 0ul; + List outOfDate = new(512); + + for (int childIdx = 0; childIdx < thisMap.transform.childCount; childIdx++) + { + Transform child = thisMap.transform.GetChild(childIdx); + if (!IsGameObjectOutOfDate(thisMap, child.gameObject, out ulong time)) + continue; + + outOfDate.Add(child.name); + maxTimestamp = Math.Max(time, maxTimestamp); + } + + if (outOfDate.Count > 0) + { + const string PREFIX = "\n * "; + string oodPrefabs = String.Join(PREFIX, outOfDate); + GUI.Label(r, MakeWarningIcon($"Map may require reimport ({FormatTimespanSince(maxTimestamp)} out of date)! Possible out of date entities are:{PREFIX}{oodPrefabs}")); + } + } + + // Edit button + Rect buttonRect = new(selectionRect); + buttonRect.width = 62; + buttonRect.x = selectionRect.width; + + if (GUI.Button(buttonRect, "edit map", EditorStyles.miniButton)) + { + string mapPath = Path.GetFullPath(AssetDatabase.GUIDToAssetPath(thisMap.OriginalAssetGuid)); + TrenchBroomUtil.OpenWithTrenchBroom(mapPath); + } + } + else if (!areDependenciesUpToDate) + { + MapDocument parentMap = go.GetComponentInParent(); + if (!parentMap) + return; + + if (!IsGameObjectOutOfDate(parentMap, go, out ulong timestamp)) + return; + + string tooltip = $"This entity may be using an older version of its prefab, from {FormatTimespanSince(timestamp)} ago - reimport the map!"; + GUI.Label(r, MakeWarningIcon(tooltip)); + } + } + + private static GUIContent MakeWarningIcon(string tooltip) => new(EditorGUIUtility.IconContent("console.warnicon.sml").image, tooltip); + + private static bool IsGameObjectOutOfDate(MapDocument map, GameObject objectInstance, out ulong timestamp) + { + foreach (Transform child in objectInstance.transform) + { + if (IsGameObjectOutOfDate(map, child.gameObject, out timestamp)) + return true; + } + + GameObject prefab = objectInstance; + while (prefab) + { + prefab = PrefabUtility.GetCorrespondingObjectFromSource(prefab); + + if (!prefab) + { + timestamp = 0ul; + return false; + } + + ulong mapTime = map.MapImportedTime; + + if (!s_CachedModifiedTimes.TryGetValue(prefab, out ulong time)) + { + time = ModTimeDB.CalcModelModifiedTime(prefab); + s_CachedModifiedTimes[prefab] = time; + } + + if (mapTime < time) + { + timestamp = time; + return true; + } + } + + timestamp = 0ul; + return false; + } + + private static string FormatTimespanSince(ulong timestamp) + { + DateTime fileTime = new DateTime((long)timestamp).ToLocalTime(); + DateTime now = DateTime.Now; + + TimeSpan span = now - fileTime; + if (span.TotalDays >= 1.0) + return $"{(int)span.TotalDays} day(s)"; + + if (span.TotalHours >= 1.0) + return $"{(int)span.TotalHours} hour(s)"; + + if (span.TotalMinutes >= 1.0) + return $"{(int)span.TotalMinutes} min(s)"; + + return "mere moments"; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/MapHierarchyIcons.cs.meta b/Assets/Tremble/Editor/EditorUI/MapHierarchyIcons.cs.meta new file mode 100644 index 0000000..a82fd4b --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/MapHierarchyIcons.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 986da32076bc407e9d805d1b0de7da27 +timeCreated: 1713948862 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/MapHierarchyIcons.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/MapRepairWindow.cs b/Assets/Tremble/Editor/EditorUI/MapRepairWindow.cs new file mode 100644 index 0000000..04a7460 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/MapRepairWindow.cs @@ -0,0 +1,642 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public class MapRepairWindow : EditorWindow + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Menu Items + // ----------------------------------------------------------------------------------------------------------------------------- + [MenuItem("Tools/Tremble/Repair Map...")] + public static void OpenMapRepair() => OpenMapRepairImpl(); + public static void OpenMapRepair(string mapPath) => OpenMapRepairImpl(mapPath); + + [MenuItem("Assets/Repair Map")] + private static void RepairMap() + { + string assetPath = AssetDatabase.GetAssetPath(Selection.activeObject); + OpenMapRepairImpl(assetPath); + } + [MenuItem("Assets/Repair Map", true)] + private static bool RepairMap_Validation() + { + string assetPath = AssetDatabase.GetAssetPath(Selection.activeObject); + return AssetDatabaseUtil.GetAllTrembleMapPaths().Contains(assetPath); + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Utility + // ----------------------------------------------------------------------------------------------------------------------------- + public static string GetGameNameFromMap(string mapPath) + { + Dictionary metadata = MapParser.ParseMetadataOnly(mapPath); + return metadata.GetValueOrDefault("Game"); + } + + public static bool IsMapForeign(string mapPath, out string gameName) + { + gameName = GetGameNameFromMap(mapPath); + if (gameName == null) + return true; + + return !gameName.EqualsInvariant(TrembleConsts.GAME_NAME, caseSensitive: true) && + !gameName.EqualsInvariant(TrembleConsts.ASSET_STORE_GAME_NAME, caseSensitive: true); + } + + private static void OpenMapRepairImpl(string mapPath = null) + { + MapRepairWindow window = GetWindow(true, "Map Repair", true); + window.m_MapPath = mapPath; + + Vector2 size = new(520f, 640f); + window.minSize = size; + window.position = new(EditorGUIUtility.GetMainWindowPosition().center - size / 2f, size); + window.Show(); + } + + + // ----------------------------------------------------------------------------------------------------------------------------- + // Consts + // ----------------------------------------------------------------------------------------------------------------------------- + record ClassData(string MappedClassname, FgdClass GeneratedClass); + + private const float PADDING_SIZE = 10f; + private GUIStyle m_TitleStyle; + + + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private readonly List m_AvailableMapPaths = new(); + private readonly List m_AvailableTrembleEntityClassnames = new(); + private readonly List m_AvailableTextureNames = new(); + + private readonly Dictionary m_MapClassToData = new(); + private readonly Dictionary m_MapTextureNameToMappedName = new(); + + private TrembleSyncSettings m_SyncSettings; + private MapTypeLookup m_MapTypeLookup; + private PrefabNameLookup m_PrefabNameLookup; + private MaterialNameLookup m_MaterialNameLookup; + + private int m_EditingMapIdx; + private string m_MapPath; + private Map m_EditingMap; + private bool m_ClassSettingsFoldOutOpen; + + private string m_OutputPath= "Code/Entities"; + private string m_GeneratedNamespace = "TrembleEntities"; + + private readonly string[] m_Tabs = { "Textures/Materials", "Entities" }; + private int m_SelectedTab; + private Vector2 m_ScrollPosition = Vector2.zero; + + private void OnEnable() + { + m_SyncSettings = TrembleSyncSettings.Get(); + m_MapTypeLookup = new(m_SyncSettings); + m_PrefabNameLookup = new(m_SyncSettings); + m_MaterialNameLookup = new(m_SyncSettings); + + m_AvailableTrembleEntityClassnames.Clear(); + foreach (Type entityType in m_MapTypeLookup.AllTypes) + { + if (!m_MapTypeLookup.TryGetMapNameFromClass(entityType, out string mapName)) + continue; + + m_AvailableTrembleEntityClassnames.Add(mapName); + } + + foreach (string prefabPath in m_PrefabNameLookup.AllPrefabPaths) + { + if (!m_PrefabNameLookup.TryGetMapNameFromPrefabPath(prefabPath, out string prefabName)) + continue; + + m_AvailableTrembleEntityClassnames.Add(prefabName); + } + + m_AvailableTextureNames.Clear(); + foreach (MaterialGroup matGroup in m_SyncSettings.GetMaterialGroupsOrDefault()) + { + foreach (Material material in matGroup.Materials) + { + string matPath = AssetDatabase.GetAssetPath(material); + + if (matPath.IsNullOrEmpty() || !m_MaterialNameLookup.TryGetMapNameFromMaterialPath(matPath, out string mapName)) + continue; + + m_AvailableTextureNames.Add(mapName); + } + } + + m_AvailableTrembleEntityClassnames.Sort(); + m_AvailableTrembleEntityClassnames.Insert(0, "(generate new entity class)"); + + m_AvailableTextureNames.Sort(); + m_AvailableTextureNames.Insert(0, "(leave as is)"); + + m_AvailableMapPaths.Add("(select a map)"); + m_AvailableMapPaths.AddRange(AssetDatabaseUtil.GetAllTrembleMapPaths()); + + if (m_EditingMapIdx != 0) + { + Init(m_EditingMapIdx); // Re-init + } + } + + private void Init(int mapIndex) + { + if (mapIndex == 0) + { + m_EditingMap = null; + return; + } + + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + m_EditingMap = MapParser.Parse(m_AvailableMapPaths[mapIndex]); + m_EditingMapIdx = mapIndex; + + // Format title + string mapFilename = Path.GetFileName(m_AvailableMapPaths[mapIndex]); + titleContent = new($"Repairing '{mapFilename}' - {GetGameOriginInfo()}"); + + // Parse! + m_MapClassToData.Clear(); + m_MapTextureNameToMappedName.Clear(); + + foreach (MapEntity entity in m_EditingMap.Entities) + { + bool isBrushEntity = entity.Brushes.Count > 0; + + if (!entity.Classname.EqualsInvariant("worldspawn", caseSensitive: true) + && !entity.Classname.EqualsInvariant("func_group", caseSensitive: true)) + { + // Find or create class + if (!m_MapClassToData.TryGetValue(entity.Classname, out ClassData classData)) + { + FgdClass newClass = new(isBrushEntity ? FgdClassType.Brush : FgdClassType.Point, entity.Classname, $"Class {entity.Classname}"); + newClass.AddBaseClass(FgdConsts.CLASS_MAP_BASE); + + if (!isBrushEntity) + { + newClass.AddBaseClass(FgdConsts.CLASS_MAP_POINT_BASE); + } + + string existingClassname = entity.Classname; + if (!m_MapTypeLookup.TryGetClassFromMapName(entity.Classname, out _) && + !m_PrefabNameLookup.TryGetPrefabPathFromMapName(entity.Classname, out _)) + { + existingClassname = null; + } + classData = new(GeneratedClass: newClass, MappedClassname: existingClassname); + m_MapClassToData[entity.Classname] = classData; + } + + foreach ((string key, string value) in entity.Entries) + { + if (key.EqualsInvariant("classname")) + continue; + + if (classData.GeneratedClass.HasField(key)) + continue; + + classData.GeneratedClass.TryAddInferredField(key, value); + } + } + + foreach (MapBrush brush in entity.Brushes) + { + foreach (MapBrushFace face in brush.Faces) + { + if (m_MapTextureNameToMappedName.ContainsKey(face.TextureName)) + continue; + + if (face.TextureName.EqualsInvariant(TBConsts.EMPTY_TEXTURE, caseSensitive: true)) + continue; + + // Try to find material + string group = null; + string textureName = face.TextureName; + int slashIdx = textureName.IndexOf('/'); + + if (slashIdx != -1) + { + group = face.TextureName.Substring(0, slashIdx); + textureName = face.TextureName.Substring(slashIdx + 1); + + if (group.EqualsInvariant(TBConsts.SPECIAL_TEXTURE, caseSensitive: true)) + continue; + } + + MaterialGroup materialGroup = MaterialGroup.CreateDefault(); + if (!group.IsNullOrEmpty()) + { + MaterialGroup[] mg = syncSettings.MaterialGroups + .Where(mg => mg.Name.EqualsInvariant(group)) + .ToArray(); + + if (mg.Length > 0) + { + materialGroup = mg[0]; + } + } + + string matchingMaterialPath; + Material matchingMaterial = materialGroup.Materials.FirstOrDefault(m => m && m.name.ContainsInvariant(textureName)); + + if (matchingMaterial) + { + matchingMaterialPath = AssetDatabase.GetAssetPath(matchingMaterial); + } + else + { + matchingMaterialPath = AssetDatabase.FindAssets($"t:material {textureName}") + .Select(AssetDatabase.GUIDToAssetPath) + .FirstOrDefault(); + } + + if (!matchingMaterialPath.IsNullOrEmpty() && m_MaterialNameLookup.TryGetMapNameFromMaterialPath(matchingMaterialPath, out string mapName)) + { + m_MapTextureNameToMappedName.Add(face.TextureName, mapName); + } + else + { + m_MapTextureNameToMappedName.Add(face.TextureName, null); + } + } + } + } + } + + private void OnGUI() + { + if (m_EditingMapIdx == 0) + { + m_TitleStyle ??= new(EditorStyles.boldLabel) + { + fontSize = EditorStyles.boldLabel.fontSize + 5 + }; + + if (m_MapPath.IsNullOrEmpty()) + { + GUILayout.Label("Select a map to repair:", m_TitleStyle); + + int currentMapIdx = EditorGUILayout.Popup(m_EditingMapIdx, m_AvailableMapPaths.ToArray()); + Init(currentMapIdx); + + GUILayout.Label("Choose a map above to repair it. Repairing a map allows you to fix up broken" + + " materials and entity references.\n\nIt can also be used to try to import \"foreign\" maps from" + + " other games, although using it in this way is experimental - particularly you may find that" + + " texture UVs are completely incorrect for foreign maps.\n\nTremble will however attempt to" + + " generate new MonoBehaviour classes for any missing entities - but these are best-guesses" + + " based on the map file and will need manual editing.", EditorStyles.helpBox); + } + else + { + int mapIdx = Math.Max(0, m_AvailableMapPaths.IndexOf(m_MapPath)); + Init(mapIdx); + } + } + else + { + m_SelectedTab = GUILayout.Toolbar(m_SelectedTab, m_Tabs, "LargeButton"); + + using (EditorGUILayout.ScrollViewScope scroll = new(m_ScrollPosition, GUILayout.ExpandHeight(true))) + { + EditorGUILayoutUtil.Pad(PADDING_SIZE, () => + { + switch (m_SelectedTab) + { + case 0: OnTexturesGUI(); break; + case 1: OnClassesGUI(); break; + } + }); + m_ScrollPosition = scroll.scrollPosition; + } + + if (GUILayout.Button("Repair and Resave!", GUILayout.Height(50f))) + { + RepairAndSave(); + } + } + } + + private void OnTexturesGUI() + { + bool hasMissingTextures = m_MapTextureNameToMappedName.Any(kv => kv.Value == null); + if (hasMissingTextures) + { + GUI.color = Color.yellow; + { + GUILayout.BeginVertical(EditorStyles.helpBox); + { + GUILayout.Label("If you have a WAD file for this game, you should first import that to generate Materials for the map's textures.", EditorStyles.wordWrappedLabel); + if (GUILayout.Button("Import WAD")) + { + string wadFilePath = EditorUtility.OpenFilePanel("Select WAD file", "Assets", "wad"); + if (wadFilePath.IsNullOrEmpty()) + return; + + string mapBasePath = Path.GetDirectoryName(m_AvailableMapPaths[m_EditingMapIdx]); + File.Copy(wadFilePath, Path.Combine(mapBasePath, Path.GetFileName(wadFilePath))); + + AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); + + EditorApplication.delayCall += () => + { + EditorUtility.DisplayDialog("WAD Imported!", "The WAD file was imported successfully!", "Okay"); + OnEnable(); + }; + } + } + GUILayout.EndVertical(); + + GUILayout.Space(20f); + } + GUI.color = Color.white; + } + + GUILayoutOption fixedHalfWidth = GUILayout.Width(position.width / 2f - PADDING_SIZE * 2f); + GUILayoutOption smallerHalfWidth = GUILayout.Width(position.width / 2f - PADDING_SIZE * 2f - 25f); + + GUILayout.BeginHorizontal(); + { + GUILayout.Label("Texture from Map:", EditorStyles.boldLabel, fixedHalfWidth); + GUILayout.Label("Unity Material:", EditorStyles.boldLabel, fixedHalfWidth); + } + GUILayout.EndHorizontal(); + + GUILayout.Space(5f); + + foreach (string textureName in m_MapTextureNameToMappedName.Keys.OrderBy(mt => mt)) + { + if (textureName.EqualsInvariant(TBConsts.CLIP_TEXTURE) || + textureName.EqualsInvariant(TBConsts.SKIP_TEXTURE) || + textureName.EqualsInvariant(TBConsts.TRIGGER_TEXTURE) || + textureName.StartsWithInvariant(TBConsts.SPECIAL_TEXTURE)) + continue; + + GUILayout.BeginHorizontal(); + { + GUILayout.Label(textureName, fixedHalfWidth); + + Color colour = Color.white; + + int prevSelectedIdx = Math.Max(0, m_AvailableTextureNames.IndexOf(m_MapTextureNameToMappedName[textureName])); + if (prevSelectedIdx == 0) + { + colour = Color.red; + } + else if (!m_MapTextureNameToMappedName[textureName].EqualsInvariant(textureName, caseSensitive: true)) + { + colour = Color.yellow; + } + + GUI.color = colour; + int selectedIdx = EditorGUILayout.Popup(prevSelectedIdx, m_AvailableTextureNames.ToArray(), smallerHalfWidth); + GUI.color = Color.white; + + if (prevSelectedIdx != selectedIdx) + { + m_MapTextureNameToMappedName[textureName] = m_AvailableTextureNames[selectedIdx]; + } + + if (GUILayout.Button(new GUIContent("!", "Copy to all missing"), GUILayout.Width(20f), GUILayout.Height(20f))) + { + foreach (string mapTextureName in m_MapTextureNameToMappedName.Keys.ToArray()) + { + if (m_MapTextureNameToMappedName[mapTextureName].IsNullOrEmpty()) + { + m_MapTextureNameToMappedName[mapTextureName] = m_AvailableTextureNames[selectedIdx]; + } + } + GUILayout.EndHorizontal(); + return; + } + } + GUILayout.EndHorizontal(); + } + } + + private void OnClassesGUI() + { + bool hasMissingClasses = m_MapClassToData.Any(kv => !kv.Key.EqualsInvariant(kv.Value.MappedClassname)); + if (hasMissingClasses) + { + GUI.color = Color.yellow; + { + GUILayout.BeginVertical(EditorStyles.helpBox); + { + GUILayout.Label("If you have an FGD file for this game, you should first import that to generate MonoBehaviours for the game's entities. If you do this, the classes generated from Map Repair will have much more accurate names and descriptions!", EditorStyles.wordWrappedLabel); + if (GUILayout.Button("Import FGD")) + { + string fgdFilePath = EditorUtility.OpenFilePanel("Select FGD file", "Assets", "fgd"); + if (fgdFilePath.IsNullOrEmpty()) + return; + + string mapBasePath = Path.GetDirectoryName(m_AvailableMapPaths[m_EditingMapIdx]); + File.Copy(fgdFilePath, Path.Combine(mapBasePath, Path.GetFileName(fgdFilePath))); + EditorCompileUtil.CompileThen(typeof(MapRepairWindow), nameof(OnPostCompileAfterFGDImport)); + } + } + GUILayout.EndVertical(); + + GUILayout.Space(20f); + } + GUI.color = Color.white; + } + + GUILayoutOption fixedHalfWidth = GUILayout.Width(position.width / 2f - PADDING_SIZE * 2f - 10f); + + GUILayout.BeginHorizontal(); + { + GUILayout.Label("Entity Class from Map:", EditorStyles.boldLabel, fixedHalfWidth); + GUILayout.Label("MonoBehaviour:", EditorStyles.boldLabel, fixedHalfWidth); + } + GUILayout.EndHorizontal(); + + GUILayout.Space(5f); + + foreach (string className in m_MapClassToData.Keys.OrderBy(cn => cn)) + { + GUILayout.BeginHorizontal(); + { + GUILayout.Label(className, fixedHalfWidth); + + Color colour = Color.white; + + int prevSelectedIdx = Math.Max(0, m_AvailableTrembleEntityClassnames.IndexOf(m_MapClassToData[className].MappedClassname)); + if (prevSelectedIdx == 0) + { + colour = Color.green; + } + else if (!m_MapClassToData[className].MappedClassname.EqualsInvariant(className, caseSensitive: true)) + { + colour = Color.yellow; + } + + GUI.color = colour; + int selectedIdx = EditorGUILayout.Popup(prevSelectedIdx, m_AvailableTrembleEntityClassnames.ToArray(), fixedHalfWidth); + GUI.color = Color.white; + + if (prevSelectedIdx != selectedIdx) + { + m_MapClassToData[className] = m_MapClassToData[className] with + { + MappedClassname = m_AvailableTrembleEntityClassnames[selectedIdx] + }; + } + } + GUILayout.EndHorizontal(); + } + + EditorGUILayout.Space(10f); + + m_ClassSettingsFoldOutOpen = EditorGUILayout.Foldout(m_ClassSettingsFoldOutOpen, "Class Generation Settings", true); + if (m_ClassSettingsFoldOutOpen) + { + EditorGUI.indentLevel++; + + m_OutputPath = EditorGUILayout.TextField("Save To", m_OutputPath); + GUILayout.Label("There is the folder where Tremble will store any new classes for the entities found in the map. This path is relative to your Assets folder. If it doesn't exist, it'll be created!", EditorStyles.helpBox); + + m_GeneratedNamespace = EditorGUILayout.TextField("C# Namespace", m_GeneratedNamespace); + GUILayout.Label("This namespace is only applied to newly-generated entity MonoBehaviours.", EditorStyles.helpBox); + + EditorGUI.indentLevel--; + } + } + + private string GetGameOriginInfo() + { + string gameName = m_EditingMap.Metadata.GetValueOrDefault("Game"); + + if (gameName.IsNullOrEmpty()) + return "map from Quake(?)"; + + if (gameName.EqualsInvariant(TrembleConsts.GAME_NAME, caseSensitive: true)) + return "map from this game"; + + if (gameName.EqualsInvariant(TrembleConsts.ASSET_STORE_GAME_NAME, caseSensitive: true)) + return "map from Tremble sample"; + + if (gameName.ContainsInvariant("unity:")) + return "map from another Tremble game"; + + return $"map from {gameName}"; + } + + private void RepairAndSave() + { + if (m_EditingMap == null) + return; + + string mapFilename = Path.GetFileName(m_AvailableMapPaths[m_EditingMapIdx]); + + if (TrenchBroomUtil.IsTrenchBroomRunning) + { + EditorUtility.DisplayDialog( + title: "Uh oh - TrenchBroom appears to be running!", + message: $"Hey - if you have {mapFilename} open in TrenchBroom right now, you should " + + "close it before repairing the map", + "Closed, continue repairing!"); + } + + bool generatedAnyNewClasses = false; + + // Write out classes for any missing entities + foreach ((string _, ClassData classData) in m_MapClassToData) + { + if (!classData.MappedClassname.IsNullOrEmpty()) + continue; + + string rootFolder = Path.Combine("Assets", m_OutputPath); + classData.GeneratedClass.Name.Split('_', out string category, out string classname); + + // Use category as folder + if (!category.IsNullOrEmpty()) + { + rootFolder = Path.Combine(rootFolder, category.ToNamingConvention(NamingConvention.UpperCamelCase)); + } + + string fileName = classname.ToNamingConvention(NamingConvention.UpperCamelCase) + ".cs"; + + string filePath = Path.Combine(rootFolder, fileName); + DirectoryUtil.CreateAllDirectories(filePath); + classData.GeneratedClass.WriteCSharp(filePath, namespaceName: m_GeneratedNamespace); + + generatedAnyNewClasses = true; + } + + // Pass 1: remap entity classes & strip 'wad' from worldspawn + foreach (MapEntity entity in m_EditingMap.Entities) + { + // Remove Wad files + if (entity.Classname.EqualsInvariant("worldspawn", caseSensitive: true) && entity.Entries.ContainsKey("wad")) + { + entity.Entries.Remove("wad"); + } + + if (!m_MapClassToData.TryGetValue(entity.Classname, out ClassData classData)) + continue; + + // Not remapped? + if (classData.MappedClassname.IsNullOrEmpty()) + continue; + + entity.Entries["classname"] = classData.MappedClassname; + } + + // Pass 2: remap textures + foreach (MapEntity entity in m_EditingMap.Entities) + { + foreach (MapBrush brush in entity.Brushes) + { + foreach (MapBrushFace face in brush.Faces) + { + // Ignore if not mapped, or mapped texture is something like "(leave as is)" + if (m_MapTextureNameToMappedName.TryGetValue(face.TextureName, out string mappedTexture) && + !mappedTexture.IsNullOrEmpty() && !mappedTexture.ContainsInvariant("(")) + { + face.TextureName = mappedTexture; + } + } + } + } + + // Rebuild new code + AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); + + // Import fixed map + string mapPath = m_AvailableMapPaths[m_EditingMapIdx]; + m_EditingMap.WriteTo(mapPath); + AssetDatabase.ImportAsset(mapPath); + + // Warn about re-importing + if (generatedAnyNewClasses) + { + EditorUtility.DisplayDialog("New Classes Generated", "Tremble has generated new MonoBehaviours for your map entities. You might need to manually Reimport the map file once in order for these to be picked up.", "Sure thing!"); + } + + Close(); + } + + private static void OnPostCompileAfterFGDImport() + { + EditorUtility.DisplayDialog("FGD Imported!", "The FGD file was imported successfully!", "Okay"); + + MapRepairWindow mrw = GetWindow(); + mrw.OnEnable(); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/MapRepairWindow.cs.meta b/Assets/Tremble/Editor/EditorUI/MapRepairWindow.cs.meta new file mode 100644 index 0000000..a93d561 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/MapRepairWindow.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 75858ce0fbcd4493a482f6081646f26a +timeCreated: 1712045460 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/MapRepairWindow.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/Materials.meta b/Assets/Tremble/Editor/EditorUI/Materials.meta new file mode 100644 index 0000000..daa4ca6 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Materials.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3b73ae349f8c4f7dbebc23a21f5ab8e2 +timeCreated: 1710848964 \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Materials/MaterialInspectorGUI.cs b/Assets/Tremble/Editor/EditorUI/Materials/MaterialInspectorGUI.cs new file mode 100644 index 0000000..9d32c31 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Materials/MaterialInspectorGUI.cs @@ -0,0 +1,198 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [InitializeOnLoad] + public class MaterialInspectorGUI + { + static MaterialInspectorGUI() + { + UnityEditor.Editor.finishedDefaultHeaderGUI -= OnPostHeaderGUI; + UnityEditor.Editor.finishedDefaultHeaderGUI += OnPostHeaderGUI; + } + + private static bool s_IsFoldoutOpen; + + static void OnPostHeaderGUI(UnityEditor.Editor editor) + { + if (editor is not MaterialEditor) + return; + + GUIContent content = new("Material Settings for Tremble"); + Rect rect = GUILayoutUtility.GetRect(content, EditorStyles.foldoutHeader); + rect.x += 20f; + s_IsFoldoutOpen = EditorGUI.BeginFoldoutHeaderGroup(rect, s_IsFoldoutOpen, content, menuIcon: EditorStyles.foldoutHeaderIcon); + + if (s_IsFoldoutOpen) + { + EditorGUI.indentLevel++; + + TrembleSyncSettings trembleSyncSettings = TrembleSyncSettings.Get(); + + // Get selected materials and their groups + Material[] selectedMaterials = editor.targets.Cast().ToArray(); + HashSet uniqueGroups = new(selectedMaterials.Select(m => GetMaterialGroupName(trembleSyncSettings, m))); + + // Gather list of material groups + List groups = trembleSyncSettings.MaterialGroups.ToList(); + + List titles = new() { "(none)" }; + titles.AddRange(groups.Select(g => g.Name)); + titles.Add(" + Create New Group"); + + EditorGUI.showMixedValue = uniqueGroups.Count > 1; + { + int selectedIdx = uniqueGroups.Count > 1 ? -1 : titles.IndexOf(uniqueGroups.First()); + int newSelectedIdx = EditorGUILayout.Popup("Material Group", selectedIdx, titles.ToArray(), EditorStyles.miniPullDown); + + if (selectedIdx != newSelectedIdx) + { + if (newSelectedIdx > groups.Count) + { + Rect targetRect = new() + { + x = Event.current.mousePosition.x, + y = Event.current.mousePosition.y, + width = 400f, + height = 50f + }; + + //Add new? + NewMaterialGroupWindow newGroup = EditorWindow.GetWindow(true, "New Material Group Name", true); + newGroup.Show(targetRect, groups.ToArray(), (groupName) => MaterialGroupUtil.MoveMaterialsToGroup(selectedMaterials, groupName, createIfNotExist: true)); + return; + } + + // Shift from 1-based to 0-based, with -1 meaning none + int index = newSelectedIdx - 1; + if (index == -1) + { + MaterialGroupUtil.RemoveMaterialsFromGroups(selectedMaterials); + } + else + { + string groupName = groups[index].Name; + MaterialGroupUtil.MoveMaterialsToGroup(selectedMaterials, groupName); + } + } + } + EditorGUI.showMixedValue = false; + + + MaterialRenderData[] datas = selectedMaterials.Select(trembleSyncSettings.GetMaterialRenderData).ToArray(); + MaterialRenderData data = trembleSyncSettings.GetMaterialRenderData(selectedMaterials[0]); + + EditorGUI.showMixedValue = datas.Select(x => x.ExportMode).Distinct().Count() > 1; + { + int mode = (int)(data?.ExportMode ?? MaterialImportMode.FixedSize); + EditorGUI.BeginChangeCheck(); + int newMode = EditorGUILayout.Popup("Render Mode", mode, Enum.GetNames(typeof(MaterialImportMode)), EditorStyles.miniPullDown); + + if (EditorGUI.EndChangeCheck()) + { + foreach (Material mat in selectedMaterials) + { + mat.SetMaterialImportMode((MaterialImportMode)newMode); + } + } + } + + if (datas.Any(x => x.ExportMode == MaterialImportMode.Dynamic)) + { + EditorGUILayout.BeginHorizontal(); + { + EditorGUILayout.LabelField(new GUIContent + { + text = "Resolution", + tooltip = "Override this to force the texture to render at a certain resolution." + }, GUILayout.MaxWidth(82)); + + EditorGUI.BeginChangeCheck(); + + GUIStyle miniLabel = EditorStyles.centeredGreyMiniLabel; + miniLabel.alignment = TextAnchor.MiddleRight; + + EditorGUILayout.LabelField("Override", EditorStyles.centeredGreyMiniLabel); + + bool overrideRes = EditorGUILayout.Toggle(data?.IsResolutionOverridden ?? false, GUILayout.MinWidth(0)); + if (EditorGUI.EndChangeCheck()) + { + foreach (Material mat in selectedMaterials) + { + mat.SetMaterialResolutionOverridden(overrideRes); + } + } + + string[] resolutionLabels = MaterialExportSizeUtils.Names; + if (data?.IsResolutionOverridden ?? false) + { + MaterialExportSize sizeX = data?.ResolutionX ?? MaterialExportSizeUtils.GetDefault(); + MaterialExportSize sizeY = data?.ResolutionY ?? MaterialExportSizeUtils.GetDefault(); + + // X Resolution + EditorGUI.BeginChangeCheck(); + sizeX = (MaterialExportSize)EditorGUILayout.Popup((int)sizeX, resolutionLabels, EditorStyles.miniPullDown); + if (EditorGUI.EndChangeCheck()) + { + foreach (Material mat in selectedMaterials) + { + mat.SetMaterialResolutionX(sizeX); + } + } + + GUI.contentColor = Color.gray; + GUILayout.Label(" x "); + GUI.contentColor = Color.white; + + // Y Resolution + EditorGUI.BeginChangeCheck(); + sizeY = (MaterialExportSize)EditorGUILayout.Popup((int)sizeY, resolutionLabels, EditorStyles.miniPullDown); + if (EditorGUI.EndChangeCheck()) + { + foreach (Material mat in selectedMaterials) + { + mat.SetMaterialResolutionY(sizeY); + } + } + } + else + { + int[] widths = selectedMaterials.Select(m => m.mainTexture?.width ?? 0).Where(w => w > 0).Distinct().ToArray(); + int[] heights = selectedMaterials.Select(m => m.mainTexture?.height ?? 0).Where(h => h > 0).Distinct().ToArray(); + + string widthStr = widths.Length > 0 ? widths[0].ToString() : "(multiple)"; + string heightStr = heights.Length > 0 ? heights[0].ToString() : "(multiple)"; + + GUI.contentColor = Color.gray; + GUILayout.Label($"{widthStr} x {heightStr}"); + GUI.contentColor = Color.white; + } + } + EditorGUILayout.EndHorizontal(); + EditorGUI.indentLevel--; + } + } + EditorGUILayout.EndFoldoutHeaderGroup(); + } + + private static string GetMaterialGroupName(TrembleSyncSettings trembleSyncSettings, Material material) + { + foreach (MaterialGroup group in trembleSyncSettings.MaterialGroups) + { + if (group.Materials.Contains(material)) + return group.Name; + } + + return "(none)"; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Materials/MaterialInspectorGUI.cs.meta b/Assets/Tremble/Editor/EditorUI/Materials/MaterialInspectorGUI.cs.meta new file mode 100644 index 0000000..606d970 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Materials/MaterialInspectorGUI.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a398d54cc0ba4b90af4093ec13fa6bec +timeCreated: 1709455118 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/Materials/MaterialInspectorGUI.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/Materials/NewMaterialGroupWindow.cs b/Assets/Tremble/Editor/EditorUI/Materials/NewMaterialGroupWindow.cs new file mode 100644 index 0000000..d9e7ee8 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Materials/NewMaterialGroupWindow.cs @@ -0,0 +1,90 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + internal class NewMaterialGroupWindow : EditorWindow + { + private const string MAT_NAME_ID = "MatNameField"; + + private MaterialGroup[] m_ExistingGroups; + private Action m_OnAdded; + + private string m_Name; + + internal void Show(Rect fromRect, MaterialGroup[] existingGroups, Action onAdded) + { + position = fromRect; + + m_ExistingGroups = existingGroups; + m_OnAdded = onAdded; + + m_Name = "Group " + m_ExistingGroups.Length; + ShowModalUtility(); + } + + private void OnGUI() + { + GUI.SetNextControlName(MAT_NAME_ID); + m_Name = EditorGUILayout.TextField("Name", m_Name); + + GUI.FocusControl(MAT_NAME_ID); + + bool escaped = Event.current.keyCode == KeyCode.Escape; + bool entered = Event.current.keyCode == KeyCode.Return; + + GUILayout.BeginHorizontal(); + { + escaped |= GUILayout.Button("Cancel"); + entered |= GUILayout.Button("Create"); + } + GUILayout.EndHorizontal(); + + + if (Event.current.type is EventType.Repaint or EventType.Layout) + return; + + if (escaped) + { + Close(); + } + else if (entered) + { + TrembleSyncSettings trembleSyncSettings = TrembleSyncSettings.Get(); + if (trembleSyncSettings.MaterialGroups.Length == 0) + { + string text = "You are adding your first Material Group, which is a great idea to organise your materials. However, you will need to manually assign each material to a material group for it to be available in TrenchBroom. All good?"; + int selection = EditorUtility.DisplayDialogComplex("Material Groups", text, "Understood, Continue", "Oh, No Thanks!", "Okay but add all materials into a group"); + switch (selection) + { + case 0: //ok + { + break; + } + case 1: // cancel + { + return; + } + case 2: // ok but add + { + // Quickly add a "user" group with current mats, and then continue + MaterialGroup defaultGroup = MaterialGroup.CreateDefault(); + MaterialGroupUtil.MoveMaterialsToGroup(defaultGroup.Materials, defaultGroup.Name, createIfNotExist: true); + break; + } + } + } + + // Return new name back + m_OnAdded(m_Name); + Close(); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Materials/NewMaterialGroupWindow.cs.meta b/Assets/Tremble/Editor/EditorUI/Materials/NewMaterialGroupWindow.cs.meta new file mode 100644 index 0000000..520570b --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Materials/NewMaterialGroupWindow.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: be384b78cb984abd86673e4aca0d4ea2 +timeCreated: 1709543387 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/Materials/NewMaterialGroupWindow.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/Q3Map2OutputWindow.cs b/Assets/Tremble/Editor/EditorUI/Q3Map2OutputWindow.cs new file mode 100644 index 0000000..5a8f1fd --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Q3Map2OutputWindow.cs @@ -0,0 +1,142 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public class Q3Map2OutputWindow : EditorWindow + { + private IList m_Lines; + private Vector2 m_Scroll; + + private bool m_ShowErrors = true; + private bool m_ShowWarnings = true; + private bool m_ShowInfo = false; + + private string m_Filter = ""; + private bool m_HasErrors; + private bool m_HasWarnings; + + public static void Open(IList output, bool showAllInfo = false) + { + Q3Map2OutputWindow window = GetWindow(true, "Map Conversion Output", true); + Vector2 size = new(700f, 350f); + window.minSize = size; + window.position = new(EditorGUIUtility.GetMainWindowPosition().center - size / 2f, size); + window.m_Lines = output; + + if (showAllInfo) + { + window.m_ShowInfo = true; + } + + window.Show(); + } + + private bool IsWarning(string line) => line.ContainsInvariant("warning") && !line.ContainsInvariant("__TB_"); + private bool IsError(string line) => line.ContainsInvariant("error") && !line.ContainsInvariant("__TB_"); + + private void OnGUI() + { + if (m_Lines == null) + { + Close(); + return; + } + + if (m_HasErrors) + { + GUI.color = Color.red; + GUILayout.Label("Q3Map2 produced error(s)!", EditorStyles.largeLabel); + GUI.color = Color.white; + } + else if (m_HasWarnings) + { + GUI.color = Color.yellow; + GUILayout.Label("Q3Map2 produced warning(s)!", EditorStyles.largeLabel); + GUI.color = Color.white; + } + else + { + GUILayout.Label("Q3Map2 Output", EditorStyles.largeLabel); + + } + + GUILayout.Space(10f); + GUILayout.Box(" ", GUILayout.ExpandWidth(true), GUILayout.Height(2f)); + + using (EditorGUILayout.ScrollViewScope scroll = new(m_Scroll)) + { + foreach (string line in m_Lines) + { + if (m_Filter.Length > 0 && !line.ContainsInvariant(m_Filter)) + continue; + + if (IsError(line)) + { + if (!m_ShowErrors) + continue; + + GUI.color = Color.red; + m_HasErrors = true; + } + else if (IsWarning(line)) + { + if (!m_ShowWarnings) + continue; + + GUI.color = Color.yellow; + m_HasWarnings = true; + } + else + { + if (!m_ShowInfo) + continue; + + GUI.color = new Color(0.8f, 0.8f, 0.8f); + } + + GUILayout.Label(" " + line, EditorStyles.wordWrappedLabel); + } + + m_Scroll = scroll.scrollPosition; + } + + GUI.color = Color.white; + + GUILayout.Box(" ", GUILayout.ExpandWidth(true), GUILayout.Height(2f)); + + using (EditorGUILayout.HorizontalScope _ = new()) + { + GUILayout.Label("Show:"); + + GUI.color = Color.red; + m_ShowErrors = GUILayout.Toggle(m_ShowErrors, "Errors"); + GUI.color = Color.yellow; + m_ShowWarnings = GUILayout.Toggle(m_ShowWarnings, "Warnings"); + GUI.color = Color.white; + m_ShowInfo = GUILayout.Toggle(m_ShowInfo, "Info"); + + GUILayout.Label("\ud83d\udd0e", GUILayout.Width(40f)); + m_Filter = GUILayout.TextArea(m_Filter, GUILayout.Width(150f)); + + GUI.enabled = m_Filter.Length > 0; + + if (GUILayout.Button("x", GUILayout.Width(20f))) + { + m_Filter = ""; + } + + GUI.enabled = true; + } + + GUILayout.Space(10f); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Q3Map2OutputWindow.cs.meta b/Assets/Tremble/Editor/EditorUI/Q3Map2OutputWindow.cs.meta new file mode 100644 index 0000000..318c025 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Q3Map2OutputWindow.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: c6c93bcb039a346b586b77785874827f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/Q3Map2OutputWindow.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/Settings.meta b/Assets/Tremble/Editor/EditorUI/Settings.meta new file mode 100644 index 0000000..fbcc2bb --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Settings.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3399abca45114db19b7cb0a3de6cd661 +timeCreated: 1721666624 \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Settings/TrembleProjectSettingsProvider.cs b/Assets/Tremble/Editor/EditorUI/Settings/TrembleProjectSettingsProvider.cs new file mode 100644 index 0000000..7daea69 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Settings/TrembleProjectSettingsProvider.cs @@ -0,0 +1,126 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public static class TrembleProjectSettingsProvider + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Entry Points + // ----------------------------------------------------------------------------------------------------------------------------- + [SettingsProvider] public static SettingsProvider ProvideAboutGUI() + => ProvideTrembleTab(s => s.OnAboutGUI()); + + [SettingsProvider] public static SettingsProvider ProvideSettingsGUI() + => ProvideTrembleTab(order: 1, "Basic Settings", s => s.OnSettingsGUI(isEmbedded: true)); + + [SettingsProvider] public static SettingsProvider ProvideNamingConventionsGUI() + => ProvideTrembleTab(order: 2, "Naming Conventions", s => s.OnNamingConventionsGUI(isEmbedded: true)); + + [SettingsProvider] public static SettingsProvider ProvideMaterialsGUI() + => ProvideTrembleTab(order: 3, "Materials", s => s.OnMaterialsGUI(isEmbedded: true)); + + [SettingsProvider] public static SettingsProvider ProvidePipelineGUI() + => ProvideTrembleTab(order: 4, "Pipeline", s => s.OnPipelineGUI(isEmbedded: true)); + + [SettingsProvider] public static SettingsProvider ProvideAdvancedGUI() + => ProvideTrembleTab(order: 5, "Advanced", s => GUILayout.Label("Here be dragons! Most users should not need to change these options. But, if you're brave - select a subcategory on the left...", EditorStyles.wordWrappedLabel), dontCaptureKeywords: true); + + [SettingsProvider] public static SettingsProvider ProvideAdvancedGUI_Features() + => ProvideTrembleTab(order: 5, "Advanced", subOrder: 0, "Features", s => s.OnAdvancedGUI_Features()); + [SettingsProvider] public static SettingsProvider ProvideAdvancedGUI_Debugging() + => ProvideTrembleTab(order: 5, "Advanced", subOrder: 1, "Debugging", s => s.OnAdvancedGUI_Debugging()); + [SettingsProvider] public static SettingsProvider ProvideAdvancedGUI_SyncImport() + => ProvideTrembleTab(order: 5, "Advanced", subOrder: 2, "Sync & Import", s => s.OnAdvancedGUI_SyncImport()); + [SettingsProvider] public static SettingsProvider ProvideAdvancedGUI_Materials() + => ProvideTrembleTab(order: 5, "Advanced", subOrder: 3, "Materials", s => s.OnAdvancedGUI_Materials()); + [SettingsProvider] public static SettingsProvider ProvideAdvancedGUI_ImportScale() + => ProvideTrembleTab(order: 5, "Advanced", subOrder: 4, "Import Scale", s => s.OnAdvancedGUI_ImportScale()); + + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private static TrembleSyncSettingsEditor s_SettingsEditor; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Internals + // ----------------------------------------------------------------------------------------------------------------------------- + private static SettingsProvider ProvideTrembleTab(Action onGui, bool dontCaptureKeywords = false) + => ProvideTrembleTab(null, "Tremble", onGui, dontCaptureKeywords); + private static SettingsProvider ProvideTrembleTab(int order, string categoryName, Action onGui, bool dontCaptureKeywords = false) + => ProvideTrembleTab($"{order} {categoryName}", categoryName, onGui, dontCaptureKeywords); + + private static SettingsProvider ProvideTrembleTab(int order, string categoryName, int subOrder, string subCategoryName, Action onGui, bool dontCaptureKeywords = false) + => ProvideTrembleTab($"{order} {categoryName}/{subOrder} {subCategoryName}", subCategoryName, onGui, dontCaptureKeywords); + + private static SettingsProvider ProvideTrembleTab(string path, string label, Action onGui, bool dontCaptureKeywords = false) + { + // Create an editor (or used cached) + TrembleSyncSettings settings = TrembleSyncSettings.Get(); + + if (!s_SettingsEditor) + { + s_SettingsEditor = (TrembleSyncSettingsEditor)UnityEditor.Editor.CreateEditor(settings); + } + + // Prepend root to path + string fullPath = "Project/Tremble"; + if (path != null) + { + fullPath += $"/{path}"; + } + + // Capture keywords + List keywords = new(64) { "Tremble", label }; + + if (!dontCaptureKeywords) + { + s_SettingsEditor.EnsureInit(onlyKeywordsCapture: true); + + TrembleSettingsGUI.BeginKeywordCapture(); + { + try + { + onGui(s_SettingsEditor); + } + catch (Exception ex) + { + Debug.LogException(ex); + } + } + keywords.AddRange(TrembleSettingsGUI.EndKeywordCapture()); + } + + // Register path with order embedded :) + return new(path: fullPath, SettingsScope.Project) + { + label = label, + guiHandler = (searchContext) => + { + s_SettingsEditor.EnsureInit(); + EditorGUILayoutUtil.Pad(10f, () => + { + try + { + onGui(s_SettingsEditor); + } + catch (Exception ex) + { + Debug.LogException(ex); + GUILayout.Label($"An error occurred rendering this page: {ex.Message}", EditorStyles.wordWrappedLabel); + } + }); + s_SettingsEditor.ResetLabelWidth(); + }, + keywords = keywords + }; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Settings/TrembleProjectSettingsProvider.cs.meta b/Assets/Tremble/Editor/EditorUI/Settings/TrembleProjectSettingsProvider.cs.meta new file mode 100644 index 0000000..3d8578d --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Settings/TrembleProjectSettingsProvider.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 898680ff76b449889b5d52a2011c13e9 +timeCreated: 1721384604 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/Settings/TrembleProjectSettingsProvider.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/Settings/TrembleSyncSettingsEditor.cs b/Assets/Tremble/Editor/EditorUI/Settings/TrembleSyncSettingsEditor.cs new file mode 100644 index 0000000..c3fb68f --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Settings/TrembleSyncSettingsEditor.cs @@ -0,0 +1,1031 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using UnityEditor; +using UnityEngine; + +using static TinyGoose.Tremble.Editor.TrembleSettingsGUI; + +namespace TinyGoose.Tremble.Editor +{ + [CustomEditor(typeof(TrembleSyncSettings))] + public class TrembleSyncSettingsEditor : UnityEditor.Editor + { + private SerializedObject m_SettingsObject; + private SerializedObject m_DefaultObject; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Consts + // ----------------------------------------------------------------------------------------------------------------------------- + private readonly string[] m_Tabs = { "About", "Config", "Naming", "Materials", "Advanced" }; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Lookups + // ----------------------------------------------------------------------------------------------------------------------------- + private PrefabNameLookup m_PrefabNameLookup; + private MapTypeLookup m_MapTypeLookup; + private MaterialNameLookup m_MaterialNameLookup; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Getters + // ----------------------------------------------------------------------------------------------------------------------------- + public bool IsAnyPropDirty => m_IsAnyPropDirty; + + public SerializedObject DefaultObject + { + get + { + if (m_DefaultObject == null || !m_DefaultObject.targetObject) + { + m_DefaultObject = new(CreateInstance()); + } + + return m_DefaultObject; + } + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private int m_SelectedTab; + private bool m_IsAnyPropDirty; + + private Vector2 m_ScrollPosition; + + private GUIStyle m_TitleStyle; + private GUIStyle m_SubtitleStyle; + private GUIStyle m_PipelineTitleStyle; + private GUIStyle m_SmallTitleStyle; + private GUIStyle m_LeftAlignedSmallStyle; + private GUIStyle m_RightAlignedSmallStyle; + private float m_OriginalLabelWidth; + + private string m_OriginalIdentityProperty; + + private void OnEnable() + { + VersionCheck.FetchLatestVersionsInBackground(); + } + + public void EnsureInit(bool onlyKeywordsCapture = false) + { + if (m_SettingsObject == null) + { + if (target) + { + m_SettingsObject = new(target); + + m_PrefabNameLookup = new((TrembleSyncSettings)target); + m_MapTypeLookup = new((TrembleSyncSettings)target); + m_MaterialNameLookup = new((TrembleSyncSettings)target); + } + + if (m_SettingsObject == null) + { + Debug.LogError("Settings editor with no settings?"); + Label("Error..."); + return; + } + } + + m_SettingsObject.Update(); + + if (onlyKeywordsCapture) + return; + + m_TitleStyle ??= new(EditorStyles.boldLabel) { fontSize = EditorStyles.boldLabel.fontSize + 5 }; + m_SubtitleStyle ??= new(EditorStyles.boldLabel) { fontSize = EditorStyles.boldLabel.fontSize + 2 }; + m_PipelineTitleStyle ??= new(EditorStyles.boldLabel) { alignment = TextAnchor.MiddleCenter, fontSize = EditorStyles.boldLabel.fontSize + 2 }; + m_SmallTitleStyle ??= new(EditorStyles.boldLabel) { fontSize = EditorStyles.boldLabel.fontSize + 3 }; + m_LeftAlignedSmallStyle ??= new(EditorStyles.label) { fontSize = EditorStyles.label.fontSize - 2, alignment = TextAnchor.MiddleLeft }; + m_RightAlignedSmallStyle ??= new(EditorStyles.label) { fontSize = EditorStyles.label.fontSize - 2, alignment = TextAnchor.MiddleRight}; + + m_OriginalLabelWidth = EditorGUIUtility.labelWidth; + EditorGUIUtility.labelWidth = 275f; + } + + public void ResetLabelWidth(bool onlyKeywordsCapture = false) + { + if (onlyKeywordsCapture) + return; + + EditorGUIUtility.labelWidth = m_OriginalLabelWidth; + + m_SettingsObject?.ApplyModifiedProperties(); + } + + public override void OnInspectorGUI() + { + EnsureInit(); + + m_SelectedTab = GUILayout.Toolbar(m_SelectedTab, m_Tabs, "LargeButton"); + + using (EditorGUILayout.ScrollViewScope scroll = new(m_ScrollPosition)) + { + EditorGUILayoutUtil.Pad(10f, () => + { + switch (m_SelectedTab) + { + case 0: OnAboutGUI(); break; + case 1: OnSettingsGUI(); break; + case 2: OnNamingConventionsGUI(); break; + case 3: OnMaterialsGUI(); break; + case 4: OnAdvancedGUI(); break; + } + }); + m_ScrollPosition = scroll.scrollPosition; + } + + ResetLabelWidth(); + } + + public void OnAboutGUI() + { + Space(10f); + + Texture2D logoTexture = TrembleAssetLoader.LoadAssetByName("T_TrembleLogo"); + float width = Screen.width / EditorGUIUtility.pixelsPerPoint; + float useWidth = Mathf.Min(200f, width); + + // Logo + BeginHorizontal(); + { + Image(logoTexture, useWidth, useWidth); + BeginVertical(GUILayout.ExpandWidth(true)); + { + Space(20f); + + Label($"Tremble version {TrembleConsts.VERSION_STRING}", m_TitleStyle); + Label($"for {TrembleConsts.GAME_NAME}"); + + Space(10f); + + Label("(c) 2024-2025 Tiny Goose & contributors", EditorStyles.wordWrappedMiniLabel); + Label("Special thanks to our community members: Andicraft, bill1487, Tinog, xage & everyone from our Discord server!", EditorStyles.wordWrappedMiniLabel); + + Space(20f); + + if (VersionCheck.IsNewerVersionAvailable) + { + UseColour(Color.green, () => + { + Label($"A newer version of Tremble is available!!"); + Label($"Open Window > Package Manager to update to v{VersionCheck.NewestAvailableVersion.Version}."); + if (Button("Open Package Manager")) + { + EditorApplication.ExecuteMenuItem("Window/Package Manager"); + } + }); + } + } + EndVertical(); + } + EndHorizontal(); + + Space(80f); + + // Discord & other links + Label("Support Links", m_SmallTitleStyle); + Space(10f); + + LabelledHyperlink("Read the manual", "Open in Unity", () => TrembleEditorAPI.OpenManual()); + LabelledHyperlink("Visit our Discord server", "discord.gg/aUTmYxbVHZ", "https://discord.gg/aUTmYxbVHZ"); + LabelledHyperlink("Email support", "hello@tinygoose.com", "mailto:hello@tinygoose.com"); + + Space(40f); + + string sampleFolder = Path.Combine(TrembleConsts.EDITOR_GetTrembleInstallFolder(), "Sample"); + if (Directory.Exists(sampleFolder)) + { + Label("Sample Content", m_SmallTitleStyle); + Label("Your project contains Tremble sample contents (materials, prefabs, scripts, etc.)"); + Label("You may want to delete these when you are done with them!"); + + if (Button("Delete Sample Contents")) + { + Directory.Delete(sampleFolder, true); + File.Delete(sampleFolder + ".meta"); + + AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); + TrembleEditorAPI.SyncToTrenchBroom(); + } + } + + Space(40f); + + // Acknowledgements + Label("Acknowledgements", m_SmallTitleStyle); + string[] acknowledgements = + { + "Tremble would not be possible without Q3Map2, licensed under the GPL Licence. Original Q3Map software by id Software.", + "Tremble was originally built upon the BSP import and MD3 model export functionality found in 'UBSP Map Tools for Unity' by John Evans (evans3d512@gmail.com).", + "Tremble is not affiliated with, or sponsored by the authors of TrenchBroom or id Software.", + "", + "Thanks for buying Tremble!" + }; + Label(String.Join('\n', acknowledgements), EditorStyles.wordWrappedMiniLabel); + } + public void OnSettingsGUI(bool isEmbedded = false) + { + Title("Basic Settings", + helpText: "The default settings should be fine for most users.", + isEmbedded: isEmbedded); + + Group("Sync", () => + { + Property(nameof(TrembleSyncSettings.AutoSyncOnCompile), + overrideLabel: "Automatic Sync", + off: "Manual sync only (from toolbar button)", on: "Sync to TrenchBroom whenever C# code changes"); + +#if !ADDRESSABLES_INSTALLED + UseDisabled(true, () => + { +#endif + + Property(nameof(TrembleSyncSettings.AllowStandaloneImport), + overrideLabel: "User-Generated Content", + off: "Developer Only - Do not allow User-Generated Content", on: "Developer & Players - Allow import of User-Generated Content)", + + extraContents: () => + { +#if !ADDRESSABLES_INSTALLED + UseDisabled(false, () => { UseColour(Color.red, () => { HelpBox("You must install 'Addressables' from the Unity Package Manager to use this setting!", MessageType.Error); }); }); +#endif + } + ); + +#if !ADDRESSABLES_INSTALLED + }); +#endif + }); + + Group("Global Map Settings", () => + { + + Property(nameof(TrembleSyncSettings.TrenchBroomVersion), overrideLabel: "TrenchBroom Version"); + + // Validate template map + GameObject defaultMapObject = (GameObject)m_SettingsObject.FindBackedProperty(nameof(TrembleSyncSettings.TemplateMap)).objectReferenceValue; + if (defaultMapObject && !defaultMapObject.TryGetComponent(out MapDocument _)) + { + Property(nameof(TrembleSyncSettings.TemplateMap), + extraContents: () => { UseColour(new(1f, 0.4f, 0.4f), () => { HelpBox($"{defaultMapObject.name} is NOT a valid map and will not be used!", MessageType.Error); }); }); + } + else + { + Property(nameof(TrembleSyncSettings.TemplateMap)); + } + + Property(nameof(TrembleSyncSettings.WorldspawnScript), overrideLabel: "Worldspawn Script Class"); + }); + } + + public void OnNamingConventionsGUI(bool isEmbedded = false) + { + Title("Naming Conventions", + helpText: "Here you can set how Tremble maps Unity naming to TrenchBroom. " + + "Use this to follow a more standard Quake-style naming convention, " + + "or use a more Unity-style convention.", + isEmbedded: isEmbedded); + + Color[] pastelColours = { + new(1f, 0.6f, 0.6f), + new(1f, 1f, 0.6f), + new(0.6f, 1f, 0.6f), + new(0.6f, 0.8f, 1f), + }; + + string[] spawnflagsExamples = { "m_dangerousObject", "m_couldEatYou", "_scaryMode", "mightEmitSmoke" }; + string suffix = m_SettingsObject.FindBackedProperty(nameof(TrembleSyncSettings.SpawnFlagNamingConvention)).enumValueIndex == (int)NamingConvention.HumanFriendly + ? "?" + : ""; + + UseColour(pastelColours[0], () => + { + string[] classExamples = m_PrefabNameLookup.AllPrefabPaths + .Take(2) + .Select(Path.GetFileNameWithoutExtension) + .Concat(m_MapTypeLookup.AllTypes.Take(2).Select(t => t.Name)) + .ToArray(); + + Property(nameof(TrembleSyncSettings.TypeNamingConvention), overrideLabel: "Entity Class Names"); + RenderNamingExamples(classExamples, nameof(TrembleSyncSettings.TypeNamingConvention)); + }); + + Space(10f); + + UseColour(pastelColours[1], () => + { + string[] fieldsExamples = { "m_NumberOfEggs", "m_eggCount", "_eggs", "spawnEggs" }; + + Property(nameof(TrembleSyncSettings.FieldNamingConvention), overrideLabel: "Field Names"); + RenderNamingExamples(fieldsExamples, nameof(TrembleSyncSettings.FieldNamingConvention)); + }); + + Space(10f); + + UseColour(pastelColours[2], () => + { + Property(nameof(TrembleSyncSettings.SpawnFlagNamingConvention), overrideLabel: "Spawnflag Names", allowHumanFriendly: true); + RenderNamingExamples(spawnflagsExamples, nameof(TrembleSyncSettings.SpawnFlagNamingConvention), suffix: suffix); + }); + + Space(10f); + + UseColour(pastelColours[3], () => + { + string[] materialExamples = m_MaterialNameLookup.AllMaterialPaths + .Take(4) + .Select(Path.GetFileNameWithoutExtension) + .ToArray(); + + Property(nameof(TrembleSyncSettings.MaterialNamingConvention), overrideLabel: "Material Names", allowHumanFriendly: true); + RenderNamingExamples(materialExamples, nameof(TrembleSyncSettings.MaterialNamingConvention)); + }); + + if (TrembleSyncSettings.Get().IsTrenchBroomVersionAtLeast(TrenchBroomVersion.VersionNext)) + { + string identityProperty = m_SettingsObject.FindBackedProperty(nameof(TrembleSyncSettings.IdentityPropertyName)).stringValue; + m_OriginalIdentityProperty ??= identityProperty; + + bool isIdentityPropertyChanged = m_OriginalIdentityProperty != null && !identityProperty.Equals(m_OriginalIdentityProperty); + Property(nameof(TrembleSyncSettings.IdentityPropertyName), overrideTooltip: isIdentityPropertyChanged + ? $"The name of the property used to identify entities (NOTE: you will need to manually change any of your maps that are still using '{m_OriginalIdentityProperty}' to use '{identityProperty}'!)" + : null); + } + } + + + public void OnMaterialsGUI(bool isEmbedded = false) + { + SerializedProperty materialGroupsProp = m_SettingsObject.FindBackedProperty(nameof(TrembleSyncSettings.MaterialGroups)); + + MaterialGroup defaultMaterialGroup = MaterialGroup.CreateDefault(); + int numMaterials = defaultMaterialGroup.Materials.Length; + int numGroups = materialGroupsProp.arraySize; + + int totalGroupedMaterials = 0; + for (int i = 0; i < numGroups; i++) + { + SerializedProperty matGroup = materialGroupsProp.GetArrayElementAtIndex(i); + totalGroupedMaterials += matGroup.FindPropertyRelative("Materials").arraySize; + } + + Title("Material Settings", + helpText: $"Controls how your project's {numMaterials} materials are synced with TrenchBroom.", + isEmbedded: isEmbedded); + { + string helpBoxText = numGroups > 0 + ? $"{totalGroupedMaterials} of your project's {numMaterials} compatible materials will be exported to TrenchBroom, in {numGroups} folders named after your material groups." + : $"{numMaterials} compatible materials will be exported to TrenchBroom, in a single texture folder."; + + for (int i = 0; i < numGroups; i++) + { + SerializedProperty matGroup = materialGroupsProp.GetArrayElementAtIndex(i); + string groupName = matGroup.FindPropertyRelative("Name").stringValue; + int numGroupMaterials = matGroup.FindPropertyRelative("Materials").arraySize; + + helpBoxText += $"\n - Group '{groupName}' with {numGroupMaterials} material(s)"; + } + + HelpBox(helpBoxText, MessageType.Info); + Space(10f); + + Property + ( + nameof(TrembleSyncSettings.MaterialGroups), + displayVertically: true, + overrideTooltip: "" + ); + } + } + + public void OnPipelineGUI(bool isEmbedded = false) + { + Label("This page shows you how Tremble will import your map. You can turn off pipeline " + + "stages that you don't require to speed up map import.", EditorStyles.wordWrappedLabel); + + PipelineHeader("On Map Import"); + PipelineArrow(); + PipelineStage("Split Mesh", TrembleTimer.Context.SplitMesh, nameof(TrembleSyncSettings.PipelineSplitMesh)); + PipelineArrow(); + PipelineStage("Smooth Mesh Normals", TrembleTimer.Context.SmoothMeshNormals, nameof(TrembleSyncSettings.PipelineSmoothMeshNormals)); + PipelineArrow(); + PipelineStage("Simplify Collision Meshes", TrembleTimer.Context.SimplifyCollisionMeshes, nameof(TrembleSyncSettings.PipelineSimplifyCollisionMeshes)); + PipelineArrow(); + PipelineStage("Generate UV2 Lightmaps", TrembleTimer.Context.GenerateUV2, nameof(TrembleSyncSettings.PipelineUnwrapUV2)); + PipelineArrow(); + PipelineStage("Run Map Processors", TrembleTimer.Context.RunMapProcessors, nameof(TrembleSyncSettings.PipelineRunMapProcessors), extraContents: () => + { +#if UNITY_2022_1_OR_NEWER + SerializedProperty processorsArray = m_SettingsObject.FindBackedProperty(nameof(TrembleSyncSettings.MapProcessors)); + + TypeCache.TypeCollection allProcessorTypes = TypeCache.GetTypesDerivedFrom(); + HashSet typesInArray = new(allProcessorTypes.Count); + + // Show enabled types + for (int i = 0; i < processorsArray.arraySize; i++) + { + if (processorsArray.GetArrayElementAtIndex(i).boxedValue is not MapProcessorEntry entry || !entry.Class.IsValid) + { + // Broken or invalid - remove and roll back + processorsArray.DeleteArrayElementAtIndex(i); + i--; + + continue; + } + + PipelineMapProcessor(entry.Class.Class, processorsArray, entry.Enabled, i); + typesInArray.Add(entry.Class.Class); + } + + // Show enableable type + foreach (Type type in allProcessorTypes) + { + if (typesInArray.Contains(type)) + continue; + + PipelineMapProcessor(type, processorsArray, false); + } + + Label("Note: Map Processors are run concurrently as entities are discovered in the map, rather " + + "than one after the other. The order dictates which processor sees each entity first.", + style: EditorStyles.wordWrappedMiniLabel); +#else + // Unity 2021 and below can't do boxedValue :( - at least show the array! + Property(nameof(TrembleSyncSettings.MapProcessors)); +#endif + }); + + PipelineArrow(); + PipelineHeader("Done"); + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Pipeline stuff + // ----------------------------------------------------------------------------------------------------------------------------- + private void PipelineArrow() => Label("↓", EditorStyles.centeredGreyMiniLabel); + +#if UNITY_2022_1_OR_NEWER + private void PipelineMapProcessor(Type mapProcessorClass, SerializedProperty array, bool isEnabled, int currentIdx = -1) + { + string friendlyName = mapProcessorClass.Name; + if (friendlyName.EndsWithInvariant("MapProcessor", caseSensitive: true)) + { + friendlyName = friendlyName.Substring(0, friendlyName.Length - 12); + } + + string description = null; + try + { + PropertyInfo propertyInfo = mapProcessorClass.GetProperty("Description"); + description = (string)propertyInfo?.GetValue(mapProcessorClass, null); + } + catch (Exception) { /* ignored */ } + + long lastRuntime = TrembleTimer.GetLastTime(mapProcessorClass); + + if (currentIdx > -1) + { + // Existing processor + PipelineStageImpl(friendlyName.ToNamingConvention(NamingConvention.HumanFriendly), description, lastRuntime, isEnabled, + isMapProcessor: true, + onSetActive: newActive => + { + MapProcessorEntry entry = (MapProcessorEntry)array.GetArrayElementAtIndex(currentIdx).boxedValue; + entry.Enabled = newActive; + array.GetArrayElementAtIndex(currentIdx).boxedValue = entry; + + m_SettingsObject.ApplyModifiedProperties(); + }, + onReorder: offset => + { + int newIdx = currentIdx + offset; + if (newIdx < 0) + return; + + if (newIdx >= array.arraySize) + return; + + array.MoveArrayElement(currentIdx, newIdx); + m_SettingsObject.ApplyModifiedProperties(); + }); + } + else + { + PipelineStageImpl(friendlyName.ToNamingConvention(NamingConvention.HumanFriendly), description, lastRuntime, isEnabled, + isMapProcessor: true, + onSetActive: newActive => + { + if (newActive) + { + array.AppendArrayElement().boxedValue = new MapProcessorEntry() + { + Class = mapProcessorClass, + Enabled = true + }; + } + }); + } + } +#endif + + private void PipelineHeader(string header) => PipelineStageImpl(header, null, -1L, false, null); + + private void PipelineStage(string label, TrembleTimer.Context timerContext, string pipelinePropertyName, Action extraContents = null) + { + SerializedProperty prop = m_SettingsObject.FindBackedProperty(pipelinePropertyName); + PipelineStageImpl(label, prop.tooltip, TrembleTimer.GetLastTime(timerContext), prop.boolValue, v => + { + prop.boolValue = v; + m_SettingsObject.ApplyModifiedProperties(); + }, extraContents: extraContents); + } + + private void PipelineStageImpl(string label, string description, long lastRuntime, bool isActive, Action onSetActive, bool isMapProcessor = false, Action onReorder = null, Action extraContents = null) + { + if (onSetActive == null) + { + GUI.color = Color.white; + } + else + { + bool disableDueToMapProcessor = isMapProcessor && !TrembleSyncSettings.Get().PipelineRunMapProcessors; + GUI.color = isActive && !disableDueToMapProcessor ? Color.green : Color.grey; + } + + BeginVertical(EditorStyles.helpBox); + { + BeginHorizontal(); + { + if (onSetActive != null) + { + onSetActive(Toggle(isActive, GUIContent.none, GUILayout.Width(10f))); + } + + BeginVertical(GUILayout.ExpandWidth(true)); + { + StringBuilder finalLabel = new(); + if (!isActive && onSetActive != null) + { + finalLabel.Append("(skipped) "); + } + + finalLabel.Append(label); + + if (lastRuntime != -1L) + { + finalLabel.Append($" (last run: {lastRuntime}ms)"); + } + + Label(finalLabel.ToString(), m_PipelineTitleStyle, GUILayout.ExpandWidth(true)); + + if (description != null) + { + Label(description, EditorStyles.centeredGreyMiniLabel); + } + } + EndVertical(); + + if (onReorder != null) + { + BeginVertical(GUILayout.Width(20f)); + { +#if UNITY_2023_1_OR_NEWER + if (Button("⬆")) { onReorder(-1); } + if (Button("⬇")) { onReorder(+1); } +#else + if (Button("^")) { onReorder(-1); } + if (Button("v")) { onReorder(+1); } +#endif + } + EndVertical(); + } + } + EndHorizontal(); + + extraContents?.Invoke(); + } + EndVertical(); + + // Also allow clicks inside the entire block! + if (onSetActive != null) + { + MakeLastRectClickable(() => onSetActive(!isActive)); + } + + GUI.color = Color.white; + } + + public void OnAdvancedGUI() + { + Title("Advanced Settings", + helpText: "Here be dragons! These are way more advanced options, which " + + "most users will not need to care about!"); + + Foldout("Features", OnAdvancedGUI_Features); + Foldout("Debugging", OnAdvancedGUI_Debugging); + Foldout("Sync/Import", OnAdvancedGUI_SyncImport); + Foldout("Materials", OnAdvancedGUI_Materials); + Foldout("Import Scale", OnAdvancedGUI_ImportScale); + } + + public void OnAdvancedGUI_Features() + { + Property(nameof(TrembleSyncSettings.UseLiveUpdate), + overrideLabel: "Live Update", + off: "Don't update maps during playmode", on: "Update maps even during playmode (experimental!)", + extraContents: () => + { + int autoRefreshMode = EditorPrefs.GetInt("kAutoRefreshMode"); + if (autoRefreshMode != 1) + { + UseColour(Color.yellow, () => + { +#if UNITY_EDITOR_OSX + const string CTRL_TEXT = "Cmd"; +#else + const string CTRL_TEXT = "Ctrl"; +#endif + + HelpBox("Your project has Auto Refresh disabled. " + + "To see map changes during playmode, you will need " + + $"to press {CTRL_TEXT}+R to refresh the map. Alternatively, you " + + "can enable Auto Refresh in Editor Preferences > Asset Pipeline.", MessageType.Warning); + }); + } + } + ); + + Property(nameof(TrembleSyncSettings.AutomaticallyReimportWhenDependencyChanges), + overrideLabel: "Automatic Map Re-Import", + off: "Don't re-import, just show out of date icons", on: "Re-import maps when Prefabs or Materials inside are changed"); + + Property(nameof(TrembleSyncSettings.EntityIconStyle), overrideLabel: "Gizmos for Entities in Editor"); + + Property(nameof(TrembleSyncSettings.PrefabOverrideHandling), overrideLabel: "Handling of Prefab Overrides"); + } + public void OnAdvancedGUI_Debugging() + { + Property(nameof(TrembleSyncSettings.LogOnImportAndSync), + overrideLabel: "Log During Import/Sync", + off: "Don't log when importing or syncing", on: "Output timing messages when importing or syncing"); + + Property(nameof(TrembleSyncSettings.Q3Map2ResultDisplayType), + overrideLabel: "Show Q3Map2 Result"); + + Property(nameof(TrembleSyncSettings.FgdFormattingStyle)); + + Property(nameof(TrembleSyncSettings.SubdivideAllLeafs), + overrideLabel: "(Debug) Map Subdivision Mode", + off: "Standard", on: "Subdivide down to BSP leafs (inefficient)"); + } + public void OnAdvancedGUI_SyncImport() + { + Group("Fields", () => + { + Property(nameof(TrembleSyncSettings.AlwaysPackBoolsIntoSpawnFlags), + overrideLabel: "Boolean Fields", + off: "Expose bool fields as separate booleans", on: "Pack all bool fields into spawnflags"); + + Property(nameof(TrembleSyncSettings.SyncEnumsAsStringValue), + overrideLabel: "Enum Fields", + off: "Store enums as integers", on: "Store enums as strings"); + + Property(nameof(TrembleSyncSettings.SyncMaterialsAndPrefabs), + overrideLabel: "Material & Prefab Fields", + off: "Don't expose Material & Prefab fields", on: "Expose Material & Prefab fields"); + + Property(nameof(TrembleSyncSettings.SyncSerializedFields), + overrideLabel: "Other Serialised Fields", + off: "Only expose fields explicitly marked with [Tremble]", on: "Expose all [SerializedField] and public fields"); + }); + + Group("Layers/Groups", () => + { + Property(nameof(TrembleSyncSettings.DiscardMapGroups), + overrideLabel: "Map Groups", + off: "Preserve layers & groups from the map", on: "Flatten layers & groups"); + }); + + Group("Worldspawn Settings", () => + { + Property(nameof(TrembleSyncSettings.WorldspawnLayer), + displayAsLayerMask: true, + overrideLabel: "Worldspawn Layer"); + + Property(nameof(TrembleSyncSettings.MainMeshName), + overrideLabel: "Worldspawn GameObject Name"); + }); + + Group("Quake® Compatibility", () => + { + Property(nameof(TrembleSyncSettings.UseClassicQuakeCulling), + off: "Prevent entire map culling, even with no point entities (Tremble)", + on: "Cull areas inaccessible by point entities, including exteriors (Quake®) - Entire map is culled without point entities!"); + }); + + Group("Other Settings", () => + { + Property(nameof(TrembleSyncSettings.AutoDeleteMapBackups), + overrideLabel: "TrenchBroom Autosaves", + off: "Allow TrenchBroom to create autosave backup files inside your project", on: "Remove TrenchBroom's autosave backup files from your project"); + + Property(nameof(TrembleSyncSettings.ExtraCommandLineArgs), + overrideLabel: "Extra Command Line Args for Q3Map2"); + }); + } + public void OnAdvancedGUI_Materials() + { + Group("Texture Export", () => + { + Label("Use these sliders to control how Tremble renders your Unity materials " + + "into textures for TrenchBroom. This can fix 'blown-out' or dimly-lit " + + "texture appearance in TrenchBroom.", EditorStyles.wordWrappedLabel); + + Space(10f); + + Property(nameof(TrembleSyncSettings.MaterialCaptureLightIntensity), onChanged: TrembleEditorAPI.InvalidateMaterialAndPrefabCache); + Property(nameof(TrembleSyncSettings.MaterialCaptureLightAngle), onChanged: TrembleEditorAPI.InvalidateMaterialAndPrefabCache); + }); + + Group("Advanced Material Settings", () => + { + Property(nameof(TrembleSyncSettings.MaterialExportSize), onChanged: TrembleEditorAPI.InvalidateMaterialAndPrefabCache); + Property(nameof(TrembleSyncSettings.ExportClipSkipTextures)); + }); + } + public void OnAdvancedGUI_ImportScale() + { + Label("Change how TrenchBroom units map to Unity metres. By default, 1m = 64 map units.", EditorStyles.wordWrappedLabel); + Space(10f); + + SerializedProperty scale = m_SettingsObject.FindBackedProperty(nameof(TrembleSyncSettings.ImportScale)); + float oneMetre = 1f / scale.floatValue; + + BeginHorizontal(); + { + Label("1 metre", GUILayout.Width(80f)); + Label("=", GUILayout.Width(20f)); + oneMetre = FloatField(oneMetre); + Label("map unit(s)", GUILayout.Width(80f)); + } + EndHorizontal(); + + Label("or", EditorStyles.centeredGreyMiniLabel); + + BeginHorizontal(); + { + Label("64 map units", GUILayout.Width(80f)); + Label("=", GUILayout.Width(20f)); + oneMetre = FloatField(oneMetre / 64f) * 64f; + Label("metre(s)", GUILayout.Width(80f)); + } + EndHorizontal(); + + scale.floatValue = 1f / oneMetre; + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Internals + // ----------------------------------------------------------------------------------------------------------------------------- + private void Title(string title, string helpText = null, bool isEmbedded = false) + { + if (!isEmbedded) + { + Space(10f); + Label(title, m_TitleStyle); + } + + if (helpText != null) + { + Label(helpText, EditorStyles.wordWrappedLabel); + } + + Space(20f); + } + private void Subtitle(string title) + { + Space(10f); + Label(title, m_SubtitleStyle); + + Space(10f); + } + + private void Group(string title, Action inside) + { + Subtitle(title); + inside(); + Space(5f); + Separator(); + Space(5f); + } + + private void RenderNamingExamples(string[] examples, string namingConventionPropName, string suffix = "") + { + if (examples.Length == 0) + { + Label("No examples found in your project!"); + } + else + { + NamingConvention naming = (NamingConvention)m_SettingsObject.FindBackedProperty(namingConventionPropName).enumValueIndex; + + foreach (string example in examples) + { + string rawExample = naming == NamingConvention.PreserveExact + ? example + : RemovePrefixes(example, "M_", "P_", "m_", "_"); + + BeginHorizontal(GUILayout.ExpandWidth(true)); + { + Label($"(Unity) '{example}'", m_RightAlignedSmallStyle, GUILayout.Width(100f), GUILayout.ExpandWidth(true)); + Label("->", EditorStyles.centeredGreyMiniLabel, GUILayout.Width(40f)); + Label($"'{rawExample.ToNamingConvention(naming)}{suffix}' (TrenchBroom)", m_LeftAlignedSmallStyle, GUILayout.Width(100f), GUILayout.ExpandWidth(true)); + } + EndHorizontal(); + } + } + } + + private string RemovePrefix(string input, string prefix) => input.StartsWith(prefix) ? input.Substring(prefix.Length) : input; + private string RemovePrefixes(string input, params string[] prefixes) + { + foreach (string prefix in prefixes) + { + input = RemovePrefix(input, prefix); + } + + return input; + } + + private void Property(string propertyName, + string overrideLabel = null, string overrideTooltip = null, + Action extraContents = default, Action onChanged = default, + bool allowHumanFriendly = false, + string on = null, string off = null, + bool displayVertically = false, bool displayAsLayerMask = false) + { + SerializedProperty sp = m_SettingsObject.FindBackedProperty(propertyName); + SerializedProperty defaultProp = DefaultObject.FindBackedProperty(propertyName); + uint oldValueHash = sp.GetHashOfContent(); + string useTooltip = overrideTooltip ?? sp.tooltip; + + // Naming convention selection - show in human-friendly format + if (sp.propertyType == SerializedPropertyType.Enum && sp.name.ContainsInvariant("NamingConvention", caseSensitive: true)) + { + // Special-case: Show naming convention in actual naming convention + List names = new() { "snake_case", "UpperCamelCase", "lowerCamelCase", "(Preserve Exact Name)" }; + + if (allowHumanFriendly) + { + names.Add("Human Friendly"); + } + + BeginHorizontal(); + + PrefixLabel(overrideLabel ?? sp.displayName, useTooltip); + if (defaultProp != null) + { + AddResetButton(sp.enumValueIndex == defaultProp.intValue, () => sp.enumValueIndex = defaultProp.intValue); + } + + if (displayVertically) + { + EndHorizontal(); + } + + sp.enumValueIndex = Popup(sp.enumValueIndex, names.ToArray(), EditorStyles.popup); + + if (!displayVertically) + { + EndHorizontal(); + } + } + // Show booleans as dropdowns if we passed on/off labels + else if (sp.propertyType == SerializedPropertyType.Boolean && on != null && off != null) + { + BeginHorizontal(); + + bool wasDefaulted = false; + + PrefixLabel(overrideLabel ?? sp.displayName, useTooltip); + + if (defaultProp != null) + { + AddResetButton(sp.boolValue == defaultProp.boolValue, () => + { + sp.boolValue = defaultProp.boolValue; + wasDefaulted = true; + }); + } + + if (displayVertically) + { + EndHorizontal(); + } + + sp.boolValue = wasDefaulted ? defaultProp.boolValue : Popup(sp.boolValue ? 1 : 0, new[]{ off, on }) == 1; + + if (!displayVertically) + { + EndHorizontal(); + } + } + // Layermask dropdown, if needed + else if (displayAsLayerMask) + { + string[] layerNames = Enumerable.Range(0, 32).Select(LayerMask.LayerToName).ToArray(); + int currentLayer = LayerMask.NameToLayer(sp.stringValue); + + BeginHorizontal(); + + PrefixLabel(overrideLabel ?? sp.displayName, useTooltip); + + bool wasDefaulted = false; + + if (defaultProp != null) + { + AddResetButton(sp.stringValue == defaultProp.stringValue, () => + { + wasDefaulted = true; + sp.stringValue = defaultProp.stringValue; + }); + } + + if (displayVertically) + { + EndHorizontal(); + } + + int layerIndex = Popup(currentLayer, layerNames); + sp.stringValue = LayerMask.LayerToName(wasDefaulted ? 0 : layerIndex); + + if (!displayVertically) + { + EndHorizontal(); + } + } + // Nothing special: draw normal one + else + { + // All else: use normal property field + BeginHorizontal(); + + PrefixLabel(overrideLabel ?? sp.displayName, useTooltip); + if (defaultProp != null) + { + AddResetButton(sp.EqualByValue(defaultProp), () => sp.SetTo(defaultProp)); + } + + if (displayVertically) + { + EndHorizontal(); + } + + PropertyField(sp, GUILayout.ExpandWidth(true)); + + if (!displayVertically) + { + EndHorizontal(); + } + } + + // Extra contents, if any + extraContents?.Invoke(); + + // On changed, if set + if (sp.GetHashOfContent() != oldValueHash) + { + m_SettingsObject.ApplyModifiedProperties(); + onChanged?.Invoke(); + m_IsAnyPropDirty = true; + } + + // Spacing + Space(5f); + } + + private void AddResetButton(bool isDefault, Action setDefault) + { + GUIContent icon = isDefault ? new(" ") : EditorGUIUtility.IconContent("preAudioLoopOff"); + icon.tooltip = "Reset to default value"; + + UseColour(Color.yellow, () => + { + if (Button(icon, EditorStyles.label, GUILayout.Width(20f))) + { + setDefault(); + } + }); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Settings/TrembleSyncSettingsEditor.cs.meta b/Assets/Tremble/Editor/EditorUI/Settings/TrembleSyncSettingsEditor.cs.meta new file mode 100644 index 0000000..dd41f3a --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Settings/TrembleSyncSettingsEditor.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: c36699011d4c4cbda4b3dd2392a60bf6 +timeCreated: 1707738241 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/Settings/TrembleSyncSettingsEditor.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/TrembleIcons.cs b/Assets/Tremble/Editor/EditorUI/TrembleIcons.cs new file mode 100644 index 0000000..b8b6ba3 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/TrembleIcons.cs @@ -0,0 +1,226 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.IO; +using System.Text; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public class EditorTexture + { + public EditorTexture(string textureName, params byte[] data) + { + m_TextureName = textureName; + m_Data = data; + } + + private readonly string m_TextureName; + private readonly byte[] m_Data; + + public Texture2D Get() + { + // This sucks. On first import, we can't find the textures. So, to preserve the + // initial experience, we also supply the textures as byte arrays. + // If we can find the asset, use that. If not, create a texture on the fly from + // the byte data. + // Once the textures are available, the byte arrays also no longer work - hence the + // double data. Luckily they're only 20x20 PNGs so they're very small. + + Texture2D packedTexture = TrembleAssetLoader.LoadAssetByName(m_TextureName); + if (packedTexture) + { + return packedTexture; + } + + Texture2D texture = new(TrembleIcons.ICON_SIZE, TrembleIcons.ICON_SIZE); + texture.LoadImage(m_Data, true); + + return texture; + } + } + + public static class TrembleIcons + { + internal const int ICON_SIZE = 20; + + [MenuItem("Tools/Tremble/Advanced/Debug/Export TB Icon")] + private static void Export() + { + if (Selection.activeObject is not Texture2D tex) + { + Debug.LogError($"{Selection.activeObject?.name ?? "none"} is not a texture!"); + return; + } + + string path = AssetDatabase.GetAssetPath(Selection.activeObject); + string filename = Path.GetFileNameWithoutExtension(path); + string shoutName = filename.Split('_')[^1].ToUpperInvariant(); + + StringBuilder snippet = new(); + snippet.AppendLine($"public static readonly EditorTexture {shoutName}_PNG = new(\"{filename}\","); + + int rowCounter = 0; + foreach (byte b in File.ReadAllBytes(path)) + { + if (rowCounter > 0) + { + snippet.Append(", "); + } + + if (rowCounter > 16) + { + rowCounter = 0; + snippet.AppendLine(); + snippet.Append('\t'); + } + + snippet.Append($"0x{b:X2}"); + rowCounter++; + } + snippet.AppendLine(");"); + + EditorGUIUtility.systemCopyBuffer = snippet.ToString(); + + Debug.Log($"{Selection.activeObject.name} copied to clipboard!"); + } + + public static readonly EditorTexture IMPORT_PNG = new("T_TB_Import", + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x14, 0x08, 0x06, 0x00, 0x00, 0x00, 0x8D, 0x89, 0x1D, + 0x0D, 0x00, 0x00, 0x02, 0x05, 0x49, 0x44, 0x41, 0x54, 0x38, 0x11, 0x8D, 0x94, 0xBF, 0x6A, 0x55, + 0x41, 0x10, 0xC6, 0x73, 0x6E, 0x12, 0x0D, 0xF1, 0x0F, 0xA2, 0x95, 0xAD, 0x56, 0xD6, 0x76, 0x8A, + 0x96, 0x8A, 0x95, 0x8D, 0xA4, 0x14, 0x04, 0xDF, 0x23, 0x68, 0xA1, 0x36, 0x82, 0x08, 0x36, 0xFA, + 0x0C, 0xBE, 0x82, 0x8D, 0xAF, 0x60, 0x21, 0x01, 0x6D, 0x44, 0x5B, 0x0B, 0x41, 0xA3, 0xC9, 0xCD, + 0xF1, 0xF7, 0x9B, 0xBB, 0xDF, 0x65, 0x73, 0xEF, 0x45, 0xFC, 0xE0, 0x3B, 0x33, 0x3B, 0x33, 0x3B, + 0x3B, 0x3B, 0xBB, 0x7B, 0x86, 0x71, 0x1C, 0xD7, 0x82, 0x61, 0x18, 0xA2, 0xAE, 0xF5, 0xF6, 0x18, + 0xE3, 0xEF, 0x7C, 0x93, 0xE6, 0x3B, 0x52, 0xEA, 0x8F, 0xA1, 0xEC, 0x5D, 0x60, 0x8B, 0x9B, 0x89, + 0x15, 0x89, 0x74, 0x6C, 0x42, 0x13, 0xC9, 0x8B, 0xB0, 0xB0, 0x11, 0x45, 0x99, 0x89, 0xBD, 0x2D, + 0x7A, 0xE7, 0x73, 0x1B, 0xCE, 0x3B, 0x68, 0xBE, 0xB7, 0xC8, 0xEF, 0xF0, 0x21, 0x5C, 0xAF, 0xAD, + 0x51, 0xD9, 0x04, 0x0E, 0x56, 0xB8, 0x8A, 0x4E, 0x6C, 0xF6, 0xCD, 0xCE, 0x7F, 0x13, 0xFD, 0x1B, + 0x3C, 0x84, 0xE7, 0x9B, 0x7D, 0x62, 0x60, 0x12, 0xB9, 0xF2, 0xBC, 0x89, 0x06, 0x74, 0x30, 0x26, + 0xC9, 0x5C, 0xFC, 0x05, 0x0C, 0xEE, 0xA0, 0x98, 0xA7, 0xFC, 0x59, 0xF9, 0x92, 0xC6, 0x86, 0x4A, + 0xDA, 0x82, 0xF4, 0x6F, 0x74, 0xFA, 0x35, 0xF4, 0x3D, 0x18, 0xBC, 0x41, 0x39, 0x16, 0x93, 0x84, + 0xBB, 0x38, 0x5E, 0xEB, 0x04, 0xEB, 0xD0, 0x8A, 0xFA, 0xAA, 0x8C, 0x7B, 0x06, 0x7B, 0x7C, 0x61, + 0xB0, 0x0D, 0xF5, 0x59, 0x75, 0xE5, 0x4A, 0xC2, 0x07, 0x18, 0xC4, 0x23, 0xA8, 0xCD, 0xAA, 0x4C, + 0xA8, 0x7E, 0x15, 0x7E, 0x80, 0x62, 0x0A, 0x7F, 0x97, 0x36, 0x8E, 0xB7, 0x90, 0xFA, 0xD3, 0x8A, + 0xCA, 0x55, 0x1F, 0x8C, 0xF7, 0x5A, 0x90, 0xE2, 0x29, 0x8C, 0xDD, 0x05, 0x82, 0x3F, 0x28, 0xFB, + 0x6D, 0xF0, 0x0A, 0xB9, 0x94, 0x4C, 0x5B, 0x26, 0xDE, 0x6E, 0x81, 0x59, 0xFD, 0x25, 0xE3, 0x77, + 0xCD, 0x76, 0x84, 0x3C, 0x80, 0x9E, 0xA6, 0xF8, 0x04, 0x67, 0x07, 0xD0, 0x1D, 0xA2, 0xBD, 0xC2, + 0x3E, 0x4F, 0x78, 0xDD, 0x48, 0xE0, 0x96, 0x32, 0xD1, 0xB1, 0x55, 0x99, 0x50, 0xE8, 0x13, 0x37, + 0xA0, 0x93, 0xFB, 0xC3, 0x4A, 0x61, 0xF3, 0x97, 0xF2, 0xC3, 0x15, 0x80, 0x2F, 0x47, 0x1E, 0xC2, + 0x29, 0xF4, 0x35, 0x78, 0xEA, 0x5E, 0x62, 0xED, 0xCF, 0xE1, 0x7B, 0xA8, 0xDD, 0x98, 0x65, 0xB4, + 0xD5, 0x2E, 0x23, 0x53, 0x59, 0x2A, 0xC2, 0x54, 0x70, 0xBB, 0xE2, 0x23, 0xAC, 0x83, 0x22, 0xCB, + 0xFC, 0xBE, 0x2E, 0x66, 0xCC, 0xD3, 0xFB, 0x89, 0x63, 0x1F, 0x9E, 0x5A, 0x0C, 0x60, 0xEC, 0x35, + 0x12, 0x3B, 0xD0, 0x7B, 0x65, 0xFF, 0xF2, 0xEC, 0xB4, 0x1F, 0x43, 0x7E, 0x0E, 0x26, 0xFC, 0xD5, + 0x3C, 0x75, 0x19, 0xBB, 0xA8, 0x8C, 0xEF, 0x36, 0xDB, 0x94, 0x77, 0x2D, 0xEA, 0xED, 0x2F, 0xCA, + 0x34, 0x73, 0x8B, 0x55, 0x3F, 0x43, 0xE1, 0xD5, 0x70, 0x9B, 0x8B, 0xD4, 0x97, 0x7B, 0x6A, 0x21, + 0xAB, 0xB7, 0x4D, 0x90, 0x49, 0xED, 0xCD, 0x57, 0xF8, 0x3F, 0x78, 0x42, 0x50, 0x0A, 0xA9, 0x9E, + 0x66, 0xEC, 0x0E, 0xD2, 0x64, 0xF5, 0xFB, 0xF0, 0x0A, 0xDC, 0x82, 0xE7, 0xE0, 0xD9, 0xC6, 0x33, + 0xC8, 0xD3, 0xD0, 0xFE, 0x9E, 0x84, 0xFE, 0xFB, 0x76, 0xE1, 0x63, 0x68, 0xA5, 0xF5, 0x73, 0x45, + 0x16, 0xFA, 0x84, 0xB1, 0xCD, 0x1C, 0xF4, 0xC8, 0x95, 0xED, 0x51, 0xC3, 0x09, 0xC6, 0x26, 0xDC, + 0x86, 0x17, 0xE0, 0x1E, 0x5C, 0xBA, 0x3A, 0x7D, 0x42, 0x4F, 0xDC, 0xD9, 0x75, 0x08, 0x24, 0x62, + 0x3E, 0xBD, 0x40, 0xC6, 0xC6, 0x10, 0xF5, 0xDF, 0xF8, 0x0B, 0x1C, 0x07, 0xCE, 0xEF, 0xA8, 0x1B, + 0x38, 0x53, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82); + + public static readonly EditorTexture SYNC_PNG = new("T_TB_Sync", + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x14, 0x08, 0x06, 0x00, 0x00, 0x00, 0x8D, 0x89, 0x1D, + 0x0D, 0x00, 0x00, 0x01, 0xE8, 0x49, 0x44, 0x41, 0x54, 0x38, 0x11, 0x8D, 0x93, 0xBB, 0x6A, 0x54, + 0x51, 0x14, 0x86, 0xE7, 0xC4, 0x09, 0x24, 0x31, 0x20, 0xD8, 0xD9, 0x5A, 0xE8, 0x03, 0xD8, 0x29, + 0xA6, 0x0C, 0xD8, 0xE7, 0x05, 0x7C, 0x10, 0x91, 0x34, 0x2A, 0xD8, 0x08, 0x92, 0x46, 0x2D, 0xC4, + 0x32, 0x90, 0xC2, 0x27, 0xF0, 0x25, 0x02, 0x01, 0x0B, 0x1B, 0x51, 0x0B, 0x11, 0xC4, 0x1B, 0x89, + 0xB9, 0x9C, 0x7C, 0xDF, 0x9E, 0xFD, 0x0F, 0x7B, 0x8E, 0x47, 0x74, 0xC1, 0x3F, 0xEB, 0xFE, 0xEF, + 0xBD, 0xF6, 0x59, 0xD3, 0xF5, 0x7D, 0x3F, 0xF9, 0x97, 0x74, 0x5D, 0x97, 0x92, 0x8E, 0x7A, 0xDC, + 0xAE, 0xE8, 0x1A, 0x34, 0x29, 0xC9, 0x89, 0xFE, 0xD4, 0x9F, 0x11, 0x31, 0x7E, 0x0D, 0x7C, 0x01, + 0xBF, 0xC0, 0x11, 0xF8, 0x0D, 0x99, 0x8D, 0x55, 0x61, 0x8D, 0xC8, 0x18, 0xE1, 0x12, 0x75, 0x9E, + 0xB6, 0x05, 0xB6, 0xC1, 0x27, 0x18, 0x24, 0xFC, 0x09, 0x7E, 0x80, 0xEF, 0xE0, 0x5B, 0xC5, 0x57, + 0xF4, 0x21, 0x38, 0x00, 0xAF, 0xC0, 0x4C, 0x3C, 0xB8, 0x81, 0xE3, 0xC4, 0x7F, 0x80, 0xFD, 0x3F, + 0xF2, 0x81, 0xA2, 0xD2, 0x17, 0xCE, 0xA1, 0x36, 0xB9, 0x04, 0x24, 0xDE, 0x06, 0xCA, 0xF1, 0x08, + 0x0E, 0x4B, 0xA6, 0xEF, 0xDF, 0xA1, 0x57, 0xC0, 0x90, 0x67, 0xC1, 0x6F, 0x49, 0xEF, 0xD5, 0xC6, + 0xD3, 0xAA, 0xA3, 0xE2, 0x7F, 0x26, 0x70, 0x09, 0x4C, 0x72, 0x8B, 0x8C, 0xD8, 0x6A, 0x8F, 0xBB, + 0x50, 0x8F, 0x78, 0x5D, 0xF5, 0xFC, 0x73, 0x0F, 0xFC, 0x55, 0xFC, 0x35, 0x63, 0xD3, 0x66, 0x25, + 0x6A, 0xCD, 0x5C, 0xD9, 0xEC, 0x98, 0xEA, 0xDD, 0x1A, 0x3D, 0x45, 0x8F, 0x7D, 0xC8, 0x15, 0xE2, + 0x33, 0x42, 0xAF, 0xF9, 0x17, 0xB1, 0xF1, 0x18, 0x3C, 0x06, 0xD7, 0xAB, 0xBD, 0x8C, 0x56, 0x24, + 0x6E, 0x27, 0x70, 0x92, 0x8B, 0x26, 0xDA, 0x11, 0x5B, 0x7B, 0xEA, 0x41, 0xE0, 0x36, 0x50, 0xF2, + 0x56, 0x67, 0xD8, 0x65, 0x1F, 0x4B, 0xB4, 0xEF, 0x4F, 0x9A, 0xDC, 0x2D, 0xEC, 0x89, 0x3B, 0x37, + 0x71, 0xEC, 0x06, 0x98, 0x9D, 0x7B, 0xE8, 0x6D, 0x5E, 0x02, 0xC5, 0xDB, 0x94, 0x7F, 0x02, 0xDA, + 0xF8, 0x1B, 0xF0, 0x14, 0x78, 0xB3, 0xC4, 0xD7, 0xB1, 0x47, 0x6F, 0xB8, 0xEC, 0x49, 0x60, 0x07, + 0x28, 0xAE, 0x46, 0x7B, 0x2B, 0xD7, 0x28, 0xD3, 0x3C, 0xB4, 0xA0, 0xCA, 0x16, 0xFA, 0x0F, 0xC2, + 0x90, 0x6D, 0xD6, 0xA2, 0x23, 0x74, 0xC6, 0xDD, 0xC7, 0xBE, 0x61, 0x13, 0x70, 0xA5, 0xF2, 0x2C, + 0xD9, 0xD3, 0xBB, 0xE6, 0x72, 0x92, 0x3A, 0x2B, 0xB4, 0x86, 0xFD, 0x1E, 0xB4, 0xF2, 0x08, 0x27, + 0xB5, 0x1E, 0xEA, 0x97, 0x17, 0x65, 0xAD, 0xF0, 0x9F, 0x81, 0xFB, 0x60, 0x81, 0x30, 0x27, 0x3E, + 0x27, 0x11, 0x79, 0x8B, 0x71, 0x13, 0x84, 0x2C, 0x35, 0xBE, 0x96, 0x22, 0x69, 0x72, 0x57, 0xAD, + 0x8B, 0x93, 0x51, 0xEF, 0x84, 0x09, 0xFD, 0x04, 0xE4, 0xD6, 0x7E, 0x88, 0xD2, 0x1C, 0x02, 0x75, + 0x15, 0xC7, 0x17, 0x72, 0x75, 0xFE, 0xA4, 0xE9, 0x32, 0xB6, 0x6B, 0xF0, 0x11, 0x6C, 0x80, 0x85, + 0xC3, 0x6C, 0x6E, 0x62, 0x43, 0x5B, 0xC2, 0xC2, 0x63, 0x5D, 0xDE, 0xE1, 0x05, 0xC1, 0xBD, 0xA6, + 0x69, 0xE1, 0x56, 0x43, 0x42, 0xFD, 0x48, 0xD3, 0x33, 0x0B, 0xD5, 0xC0, 0x95, 0x26, 0x51, 0x9E, + 0xC0, 0x6C, 0x62, 0xAD, 0x6D, 0x2C, 0x92, 0x7C, 0xF4, 0xFC, 0x51, 0x6B, 0x41, 0x59, 0x74, 0xEC, + 0x33, 0x7D, 0x97, 0x5D, 0x69, 0x09, 0x4A, 0x80, 0x9F, 0xE4, 0x86, 0xF9, 0x73, 0x83, 0xE5, 0xF3, + 0x69, 0xCF, 0x05, 0x29, 0x55, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, + 0x82); + + public static readonly EditorTexture CONFIG_PNG = new("T_TB_Config", + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x14, 0x08, 0x06, 0x00, 0x00, 0x00, 0x8D, 0x89, 0x1D, + 0x0D, 0x00, 0x00, 0x01, 0xA8, 0x49, 0x44, 0x41, 0x54, 0x38, 0x11, 0xAD, 0x94, 0x3B, 0x2F, 0x04, + 0x51, 0x14, 0xC7, 0xC7, 0xAB, 0xB1, 0xBB, 0xB2, 0x44, 0xA2, 0x41, 0x48, 0x68, 0x49, 0x48, 0xF4, + 0x6C, 0x54, 0x3A, 0x89, 0x42, 0xC5, 0x37, 0x10, 0xA2, 0xF3, 0x31, 0x94, 0xE2, 0xD1, 0x53, 0x4A, + 0x24, 0x7A, 0xAD, 0x44, 0xEB, 0x55, 0xE8, 0xBC, 0xD6, 0x62, 0x45, 0xE1, 0xB1, 0x7E, 0xFF, 0x99, + 0x3B, 0xD7, 0xC9, 0x5D, 0x8F, 0x89, 0x38, 0xC9, 0x6F, 0xCF, 0x63, 0xEE, 0xFC, 0xE7, 0xDC, 0x7B, + 0x66, 0xB6, 0xA1, 0x56, 0xAB, 0x45, 0xFF, 0x69, 0x8D, 0x19, 0xC5, 0x4A, 0xAC, 0x5B, 0x82, 0xE1, + 0x5F, 0xD7, 0xAB, 0x43, 0x43, 0x13, 0xF1, 0x18, 0x8C, 0x98, 0x5A, 0x89, 0xF8, 0x00, 0x64, 0x3B, + 0x30, 0x0C, 0xBA, 0xA7, 0x03, 0xBA, 0xA0, 0xC5, 0xE5, 0xB1, 0x4E, 0x28, 0x36, 0xC1, 0x45, 0xD9, + 0x03, 0x48, 0x34, 0x07, 0x7B, 0x60, 0x6D, 0x81, 0x44, 0x62, 0x47, 0xAE, 0x38, 0x89, 0xF7, 0xA2, + 0x56, 0xB0, 0xE8, 0x16, 0xA4, 0xEE, 0x89, 0xE0, 0x36, 0x4D, 0x8C, 0xBF, 0x27, 0x3E, 0x37, 0xB9, + 0xC2, 0x51, 0x88, 0xB5, 0xEC, 0x19, 0xBE, 0x71, 0x3E, 0x87, 0xEE, 0x8C, 0x34, 0xA9, 0x56, 0xE8, + 0x70, 0xB9, 0x75, 0x6D, 0x24, 0xFD, 0xF0, 0xEE, 0x8A, 0x65, 0xFC, 0x8B, 0x8B, 0x23, 0xDB, 0xA1, + 0xE2, 0x02, 0x9C, 0x42, 0x56, 0xAB, 0xB0, 0x70, 0x08, 0xBC, 0x4E, 0xB3, 0x57, 0x8E, 0x22, 0xC5, + 0xEA, 0xB8, 0xDD, 0xD4, 0x14, 0x3E, 0xC2, 0xB6, 0xAB, 0xCD, 0xE0, 0x0B, 0x2E, 0x96, 0xD3, 0x4E, + 0xD4, 0x71, 0x11, 0x2A, 0xE0, 0x3B, 0xEC, 0x73, 0x2D, 0xDD, 0x04, 0xAD, 0x69, 0x38, 0x83, 0xA6, + 0x03, 0xC5, 0xAA, 0x85, 0xB6, 0x4C, 0x41, 0x33, 0x88, 0x05, 0x7B, 0xC2, 0xAB, 0x26, 0x5F, 0xD7, + 0xA2, 0x00, 0xD5, 0xBE, 0xB2, 0x69, 0x8A, 0xF1, 0x16, 0xD5, 0xF6, 0x6B, 0xDC, 0xEE, 0xDF, 0x7F, + 0xCE, 0xB8, 0xF5, 0x2E, 0xBE, 0x5D, 0xAA, 0xD0, 0x0D, 0x2F, 0x70, 0x09, 0xD6, 0xB2, 0x6C, 0x59, + 0x43, 0x1C, 0x87, 0x78, 0x27, 0x0D, 0x0A, 0x8C, 0xE5, 0x88, 0x2F, 0xC0, 0xBE, 0x2E, 0x3F, 0x0D, + 0x45, 0xAF, 0x4C, 0x2F, 0x3C, 0x41, 0x62, 0xA9, 0xB2, 0xF1, 0x8B, 0xC4, 0x59, 0x6D, 0x8B, 0x85, + 0x76, 0x68, 0x7E, 0xCA, 0xE9, 0xC1, 0x0F, 0xB0, 0x60, 0x37, 0xA3, 0xDA, 0xB5, 0x5B, 0xB7, 0x89, + 0xF7, 0xA2, 0xA9, 0x50, 0xEA, 0x37, 0x02, 0xB1, 0x6A, 0x90, 0x2B, 0x2D, 0xC3, 0x41, 0x50, 0x9F, + 0x25, 0x8F, 0x35, 0xEC, 0xA7, 0xA7, 0x33, 0xD0, 0xB4, 0xAE, 0x92, 0xC3, 0x88, 0x4E, 0xF1, 0x73, + 0xF0, 0xF9, 0x59, 0x25, 0x17, 0x06, 0x71, 0x6B, 0x70, 0x92, 0xA4, 0xD1, 0x3E, 0xFE, 0xD8, 0xC5, + 0x75, 0x5B, 0xD6, 0x53, 0x56, 0x5C, 0x07, 0x53, 0xEE, 0xA9, 0x79, 0xFC, 0x33, 0xC8, 0x3A, 0x21, + 0xDD, 0xCD, 0x3C, 0xF1, 0x2A, 0xF8, 0x3F, 0x06, 0x5D, 0x0B, 0xA7, 0xEC, 0x1F, 0x14, 0x04, 0x79, + 0x97, 0x57, 0x83, 0x7A, 0x5D, 0x9A, 0x55, 0xB0, 0xEE, 0xC6, 0xEF, 0x0A, 0x1F, 0x71, 0x03, 0x2D, + 0x56, 0xEC, 0x1B, 0x00, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, + 0x82); + + public static readonly EditorTexture MANUAL_PNG = new("T_TB_Manual", + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, + 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x14, 0x08, 0x04, 0x00, 0x00, 0x00, 0x27, 0x80, 0xD5, 0x86, 0x00, + 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xAE, 0xCE, 0x1C, 0xE9, 0x00, 0x00, 0x01, 0x4F, 0x49, + 0x44, 0x41, 0x54, 0x28, 0xCF, 0xBD, 0xD2, 0xBF, 0x4B, 0x95, 0x51, 0x1C, 0xC7, 0xF1, 0xAF, 0xBF, 0xA2, + 0xAE, 0x21, 0x14, 0x28, 0x2E, 0xD1, 0xE8, 0x10, 0x09, 0x85, 0x43, 0xD0, 0x10, 0x82, 0x58, 0x54, 0x44, + 0x0D, 0x49, 0x81, 0x6B, 0x4B, 0x8B, 0x43, 0xD0, 0x60, 0x08, 0x82, 0x70, 0xFF, 0x01, 0xF1, 0x1F, 0x68, + 0x6E, 0x6B, 0xCB, 0x4D, 0x5D, 0x6E, 0x54, 0x90, 0x8B, 0x38, 0x18, 0x21, 0xA1, 0x68, 0x6A, 0x57, 0xF3, + 0xDE, 0xD2, 0xE7, 0xDE, 0xFB, 0x72, 0x78, 0xD4, 0xFB, 0x18, 0x78, 0x71, 0xEA, 0x4C, 0xE7, 0xF0, 0x79, + 0x73, 0x0E, 0xDF, 0xF7, 0xE7, 0x44, 0xFC, 0x97, 0x25, 0x67, 0xCA, 0xBC, 0x82, 0x51, 0x6D, 0x8D, 0xB0, + 0xA7, 0x7E, 0xDB, 0x55, 0x50, 0x50, 0xB1, 0x73, 0x3A, 0xF6, 0x5A, 0xC5, 0xAC, 0x5C, 0x44, 0x84, 0x5B, + 0xAA, 0x3A, 0xB2, 0xE1, 0x88, 0x55, 0x45, 0xFB, 0x7E, 0x79, 0xA7, 0x2A, 0x1F, 0xA1, 0xCB, 0xA4, 0x09, + 0x1D, 0xF6, 0xBC, 0xAC, 0x63, 0x4F, 0x54, 0xCC, 0x79, 0x61, 0xC8, 0x5B, 0x89, 0x9F, 0x9A, 0x22, 0xAC, + 0xF8, 0x63, 0x4B, 0x9F, 0x05, 0x1F, 0xEA, 0xE0, 0x77, 0x33, 0xC7, 0xFB, 0x2B, 0x12, 0xFD, 0x6E, 0x4B, + 0xF4, 0x44, 0x44, 0x78, 0xA3, 0xE4, 0x62, 0x1A, 0xB5, 0x2A, 0x1B, 0x88, 0xF0, 0x4C, 0x51, 0x49, 0xCE, + 0xA2, 0x82, 0x2E, 0xF7, 0x5C, 0x36, 0x23, 0xEF, 0x9C, 0xB2, 0xF1, 0x14, 0xBC, 0xA3, 0xE6, 0xAA, 0x1B, + 0x6A, 0x3E, 0x7B, 0xA0, 0xD9, 0x98, 0xBF, 0xDA, 0x22, 0x7C, 0x53, 0xF6, 0x25, 0xC2, 0x27, 0xCB, 0x29, + 0xD8, 0xA9, 0xE8, 0xBD, 0x71, 0x8B, 0x87, 0x8F, 0xB7, 0x4B, 0xBC, 0x8A, 0x50, 0xD4, 0x1F, 0x11, 0xE1, + 0x91, 0xC4, 0xA5, 0x34, 0x7A, 0x6E, 0xDF, 0xF5, 0x08, 0xD7, 0xAC, 0xAB, 0x18, 0x34, 0x6B, 0xFE, 0x84, + 0xF6, 0x5D, 0xF7, 0x53, 0xB0, 0xC9, 0x82, 0xE5, 0x08, 0x5F, 0x6D, 0x78, 0xEC, 0x82, 0x41, 0x25, 0xB9, + 0x8C, 0xF6, 0x4D, 0xF9, 0xA3, 0x59, 0x7B, 0xEC, 0x19, 0xF6, 0xD0, 0xCD, 0xC3, 0xF3, 0x8E, 0xB9, 0x8C, + 0xF6, 0x56, 0x2D, 0x75, 0x45, 0xD3, 0x96, 0x32, 0xDA, 0xD7, 0x38, 0xBE, 0xE5, 0x9F, 0xE2, 0x7A, 0x55, + 0x4F, 0x68, 0xDF, 0x3E, 0xBD, 0xE3, 0x9A, 0x1F, 0x67, 0xF9, 0x58, 0x2D, 0x3E, 0x66, 0x5A, 0x6D, 0x00, + 0x76, 0xBB, 0xAB, 0xF9, 0x2C, 0xE0, 0x79, 0xED, 0x8D, 0x89, 0x03, 0xDB, 0x0E, 0x1A, 0x97, 0x4F, 0xCA, + 0x84, 0x01, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82); + + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/TrembleIcons.cs.meta b/Assets/Tremble/Editor/EditorUI/TrembleIcons.cs.meta new file mode 100644 index 0000000..ef69da0 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/TrembleIcons.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 4b6cd1e1a8fb4d328fbb09d76179a619 +timeCreated: 1711455760 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/TrembleIcons.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/TrembleSyncOverlay.cs b/Assets/Tremble/Editor/EditorUI/TrembleSyncOverlay.cs new file mode 100644 index 0000000..c953078 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/TrembleSyncOverlay.cs @@ -0,0 +1,79 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEditor; +using UnityEditor.Overlays; +using UnityEditor.Toolbars; + +namespace TinyGoose.Tremble.Editor +{ +#if UNITY_2022_1_OR_NEWER + [Overlay(typeof(SceneView), "Tremble Sync", true, id = ID)] +#else + [Overlay(typeof(SceneView), "Tremble Sync", true)] +#endif + public class TrembleSyncOverlay : ToolbarOverlay + { + private const string ID = "TrembleSync"; + + public TrembleSyncOverlay() : base(ReimportMapButton.ID, SyncButton.ID, ConfigButton.ID, ManualButton.ID) + { + } + + protected override Layout supportedLayouts => Layout.HorizontalToolbar | Layout.VerticalToolbar; + } + + [EditorToolbarElement(ID, typeof(SceneView))] + public class ReimportMapButton : EditorToolbarButton + { + public const string ID = "Tremble/Reimport"; + + public ReimportMapButton() + { + icon = TrembleIcons.IMPORT_PNG.Get(); + tooltip = "Reimport Current Map"; + clicked += TrembleEditorAPI.ReimportCurrentMap; + } + } + + [EditorToolbarElement(ID, typeof(SceneView))] + public class SyncButton : EditorToolbarButton + { + public const string ID = "Tremble/Sync"; + + public SyncButton() + { + icon = TrembleIcons.SYNC_PNG.Get(); + tooltip = "Sync to TrenchBroom"; + clicked += TrembleEditorAPI.SyncToTrenchBroom; + } + } + + [EditorToolbarElement(ID, typeof(SceneView))] + public class ConfigButton : EditorToolbarButton + { + public const string ID = "Tremble/Config"; + + public ConfigButton() + { + icon = TrembleIcons.CONFIG_PNG.Get(); + tooltip = "Tremble Settings"; + clicked += TrembleEditorAPI.OpenSettings; + } + } + + [EditorToolbarElement(ID, typeof(SceneView))] + public class ManualButton : EditorToolbarButton + { + public const string ID = "Tremble/Manual"; + + public ManualButton() + { + icon = TrembleIcons.MANUAL_PNG.Get(); + tooltip = "Tremble Manual"; + clicked += () => TrembleEditorAPI.OpenManual(); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/TrembleSyncOverlay.cs.meta b/Assets/Tremble/Editor/EditorUI/TrembleSyncOverlay.cs.meta new file mode 100644 index 0000000..9d7747e --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/TrembleSyncOverlay.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a930a79e3a324c35b20894fac9d8b4a2 +timeCreated: 1706013427 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/TrembleSyncOverlay.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/Utils.meta b/Assets/Tremble/Editor/EditorUI/Utils.meta new file mode 100644 index 0000000..97a836d --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Utils.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c63360b568474474a397794178a8f00a +timeCreated: 1721666903 \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Utils/EditorGUILayoutUtil.cs b/Assets/Tremble/Editor/EditorUI/Utils/EditorGUILayoutUtil.cs new file mode 100644 index 0000000..ba76ee4 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Utils/EditorGUILayoutUtil.cs @@ -0,0 +1,117 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using UnityEngine; +using System.Collections.Generic; +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + internal static class EditorGUILayoutUtil + { + internal static void Pad(float pad, Action content) => Pad(pad, pad, content); + internal static void Pad(float hPad, float vPad, Action content) + { + GUILayout.BeginHorizontal(); + { + GUILayout.Space(hPad); + GUILayout.BeginVertical(); + { + GUILayout.Space(vPad); + + try + { + content(); + } + catch (ExitGUIException) + { + // ignore + } + catch (Exception ex) + { + Debug.LogException(ex); + } + + GUILayout.Space(vPad); + } + GUILayout.EndVertical(); + GUILayout.Space(hPad); + } + GUILayout.EndHorizontal(); + } + + private static readonly Dictionary s_CollapsibleHeaderStates = new(); + + internal static void Indent(Action inside) + { + EditorGUI.indentLevel++; + inside(); + EditorGUI.indentLevel--; + } + + + internal static bool FoldoutArrow(bool isOpen) + { + bool toggle = GUILayout.Button(GUIContent.none, EditorStyles.label, GUILayout.Width(20f)); + + Rect buttonRect = GUILayoutUtility.GetLastRect(); + buttonRect.x += 5f; + + if (Event.current.type == EventType.Repaint) + { + EditorStyles.foldout.Draw(buttonRect, false, false, isOpen, false); + } + + return toggle; + } + + internal static bool CollapsibleHeader(string header, bool isOpen, Action inside) + { + GUILayout.BeginHorizontal(); + { + bool toggle = FoldoutArrow(isOpen); + toggle |= GUILayout.Button(header, EditorStyles.label); + + if (toggle) + { + isOpen = !isOpen; + } + } + GUILayout.EndHorizontal(); + + if (isOpen) + { + GUILayout.BeginHorizontal(); + { + GUILayout.Space(20f); + GUILayout.BeginVertical(); + { + inside(); + } + GUILayout.EndVertical(); + } + GUILayout.EndHorizontal(); + } + + return isOpen; + } + + internal static void CollapsibleHeader(string header, string id, bool defaultOpen, Action inside) + { + bool wasOpen = s_CollapsibleHeaderStates.GetValueOrDefault(id, defaultOpen); + s_CollapsibleHeaderStates[id] = CollapsibleHeader(header, wasOpen, inside); + } + + internal static void CollapsibleHeader(string header, string id, Action inside) + => CollapsibleHeader(header, id, defaultOpen: false, inside); + + internal static void SetHeaderOpen(string id, bool isOpened) + { + s_CollapsibleHeaderStates[id] = isOpened; + } + internal static bool IsHeaderOpen(string id) => s_CollapsibleHeaderStates.GetValueOrDefault(id, false); + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Utils/EditorGUILayoutUtil.cs.meta b/Assets/Tremble/Editor/EditorUI/Utils/EditorGUILayoutUtil.cs.meta new file mode 100644 index 0000000..2e2d165 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Utils/EditorGUILayoutUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 4c018a50074942338e9d90803f43545a +timeCreated: 1712049970 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/Utils/EditorGUILayoutUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/Utils/EditorGameObjectIconUtil.cs b/Assets/Tremble/Editor/EditorUI/Utils/EditorGameObjectIconUtil.cs new file mode 100644 index 0000000..94cd60b --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Utils/EditorGameObjectIconUtil.cs @@ -0,0 +1,81 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +// Adapted from Unity3D-IconManager by Thundernerd. +// This is only a tiny portion of the original code, but in the interest of attributing to his good work, +// I'll include his licence and a link to the original. + +// https://github.com/Thundernerd/Unity3D-IconManager/ + +// Original Licence follows: +// MIT License +// +// Copyright (c) [2020] [Christiaan Bloemendaal] +// +// 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 UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public static class EditorGameObjectIconUtil + { + public enum EditorIcon + { + GrayDiamond, + BlueDiamond, + TealDiamond, + GreenDiamond, + YellowDiamond, + OrangeDiamond, + RedDiamond, + PurpleDiamond, + + MAX + } + + public enum EditorLabel + { + Gray, + Blue, + Teal, + Green, + Yellow, + Orange, + Red, + Purple, + + MAX + } + + public static void SetEditorIcon(this GameObject go, EditorIcon icon) + { + //TODO(jwf): cache these! + Texture2D texture = EditorGUIUtility.FindTexture($"sv_icon_dot{(int)icon+8}_pix16_gizmo"); + EditorGUIUtility.SetIconForObject(go, texture); + } + + public static void SetEditorIcon(this GameObject go, EditorLabel label) + { + //TODO(jwf): cache these! + Texture2D texture = EditorGUIUtility.FindTexture($"sv_label_{(int)label}"); + EditorGUIUtility.SetIconForObject(go, texture); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Utils/EditorGameObjectIconUtil.cs.meta b/Assets/Tremble/Editor/EditorUI/Utils/EditorGameObjectIconUtil.cs.meta new file mode 100644 index 0000000..c14ae0d --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Utils/EditorGameObjectIconUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 053deb05101c4cf29d8d760aa74f619f +timeCreated: 1724832500 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/Utils/EditorGameObjectIconUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/Utils/MaterialGroupUtil.cs b/Assets/Tremble/Editor/EditorUI/Utils/MaterialGroupUtil.cs new file mode 100644 index 0000000..533c224 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Utils/MaterialGroupUtil.cs @@ -0,0 +1,154 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public static class MaterialGroupUtil + { + public static bool RemoveMaterialsFromGroups(Material[] materials) + => MoveMaterialsToGroupIdx(materials, -1); + + public static bool MoveMaterialsToGroup(Material[] materials, string groupName, bool createIfNotExist = false) + { + int index = GetMaterialGroupIndex(groupName); + if (index == -1 && !createIfNotExist) + { + Debug.LogError($"Could not move materials to non-existent group '{groupName}'!"); + return false; + } + + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + + // New group - create and add + if (index == -1) + { + syncSettings.Modify(so => + { + SerializedProperty materialGroupsArray = so.FindBackedProperty(nameof(TrembleSyncSettings.MaterialGroups)); + materialGroupsArray.AppendArrayElement(); + }); + + MaterialGroup[] mgs = syncSettings.MaterialGroups; + mgs[^1].Name = groupName; + mgs[^1].Materials = Array.Empty(); + + index = mgs.Length - 1; + } + + return MoveMaterialsToGroupIdx(materials, index); + } + + public static int GetMaterialGroupIndexForMaterial(Material material) + { + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + + for (int materialGroupIdx = 0; materialGroupIdx < syncSettings.MaterialGroups.Length; materialGroupIdx++) + { + MaterialGroup mg = syncSettings.MaterialGroups[materialGroupIdx]; + + foreach (Material m in mg.Materials) + { + if (material == m) + return materialGroupIdx; + } + } + + return -1; + } + + public static bool IsMaterialPartOfAnyMaterialGroup(Material material) + => GetMaterialGroupIndexForMaterial(material) != -1; + + private static bool MoveMaterialsToGroupIdx(Material[] materials, int index) + { + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + MaterialGroup[] mgs = syncSettings.MaterialGroups; + + for (int groupIdx = 0; groupIdx < mgs.Length; groupIdx++) + { + if (groupIdx == index) + { + // Our target group - remove these mats, and add to end + mgs[groupIdx].Materials = mgs[groupIdx].Materials + .Where(m => !materials.Contains(m)) + .Concat(materials) + .ToArray(); + } + else + { + // Not our target group - remove these mats + mgs[groupIdx].Materials = mgs[groupIdx].Materials + .Where(m => !materials.Contains(m)) + .ToArray(); + } + } + + CleanupMissingMaterials(mgs); + CleanupEmptyGroups(mgs); + + return true; + } + + private static void CleanupMissingMaterials(MaterialGroup[] mgs) + { + for (int groupIdx = 0; groupIdx < mgs.Length; groupIdx++) + { + mgs[groupIdx].Materials = mgs[groupIdx].Materials + .Where(m => m) + .ToArray(); + } + } + + private static void CleanupEmptyGroups(MaterialGroup[] mgs) + { + // Now check for empty groups + List removeIndexes = new(); + for (int groupIdx = 0; groupIdx < mgs.Length; groupIdx++) + { + if (mgs[groupIdx].Materials.Length != 0) + continue; + + bool remove = EditorUtility.DisplayDialog("Empty Material Group", $"Material Group '{mgs[groupIdx].Name}' is empty - delete it?", "Yup", "No - keep it!"); + if (!remove) + continue; + + removeIndexes.Add(groupIdx); + } + + int numRemoved = 0; + foreach (int idx in removeIndexes) + { + int removeIdx = idx - numRemoved; + numRemoved++; + + TrembleSyncSettings.Get().Modify(so => + { + SerializedProperty groupsProp = so.FindBackedProperty(nameof(TrembleSyncSettings.MaterialGroups)); + groupsProp.DeleteArrayElementAtIndex(removeIdx); + }); + } + } + + + private static int GetMaterialGroupIndex(string groupName) + { + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + + for (int mgIdx = 0; mgIdx < syncSettings.MaterialGroups.Length; mgIdx++) + { + if (syncSettings.MaterialGroups[mgIdx].Name.EqualsInvariant(groupName)) + return mgIdx; + } + + return -1; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Utils/MaterialGroupUtil.cs.meta b/Assets/Tremble/Editor/EditorUI/Utils/MaterialGroupUtil.cs.meta new file mode 100644 index 0000000..bbd5e7d --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Utils/MaterialGroupUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: bfca730eb4364517a3fa6aafb28dc837 +timeCreated: 1722943294 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/Utils/MaterialGroupUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/Utils/MaterialRenderDataUtil.cs b/Assets/Tremble/Editor/EditorUI/Utils/MaterialRenderDataUtil.cs new file mode 100644 index 0000000..6b7dbba --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Utils/MaterialRenderDataUtil.cs @@ -0,0 +1,31 @@ +using System; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public static class MaterialRenderDataUtil + { + public static void SetMaterialImportMode(this Material mat, MaterialImportMode mode) + => ModifyRenderData(mat, mrd => mrd.ExportMode = mode); + + public static void SetMaterialResolutionOverridden(this Material mat, bool overrideResolution) + => ModifyRenderData(mat, mrd => mrd.IsResolutionOverridden = overrideResolution); + + public static void SetMaterialResolutionX(this Material mat, MaterialExportSize size) + => ModifyRenderData(mat, mrd => mrd.ResolutionX = size); + + public static void SetMaterialResolutionY(this Material mat, MaterialExportSize size) + => ModifyRenderData(mat, mrd => mrd.ResolutionY = size); + + + private static void ModifyRenderData(Material mat, Action action) + { + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + MaterialRenderData renderData = TrembleSyncSettings.Get().GetMaterialRenderData(mat); + + action(renderData); + EditorUtility.SetDirty(syncSettings); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Utils/MaterialRenderDataUtil.cs.meta b/Assets/Tremble/Editor/EditorUI/Utils/MaterialRenderDataUtil.cs.meta new file mode 100644 index 0000000..b8cdbed --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Utils/MaterialRenderDataUtil.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 808c02ac921b9e4638fdb31dd490d61c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/Utils/MaterialRenderDataUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/EditorUI/Utils/TrembleSettingsGUI.cs b/Assets/Tremble/Editor/EditorUI/Utils/TrembleSettingsGUI.cs new file mode 100644 index 0000000..7246ca9 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Utils/TrembleSettingsGUI.cs @@ -0,0 +1,391 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + // This wraps EditorGUI, EditorGUILayout, GUI, and GUILayout calls. + // The purpose is that you can call them in "normal" mode, which forwards the calls on to Unity, + // or "keywords capture" mode, which performs no GUI work at all but captures a list of + // keywords to expose to the Project Settings window's search. + public static class TrembleSettingsGUI + { + private static readonly List s_Keywords = new(256); + private static bool s_IsCapturingKeywords = false; + + private static GUIStyle s_LineStyle; + + private static readonly Dictionary s_FoldoutStates = new(); + + public static void BeginKeywordCapture() + { + s_IsCapturingKeywords = true; + s_Keywords.Clear(); + } + + public static List EndKeywordCapture() + { + s_IsCapturingKeywords = false; + return s_Keywords; + } + + public static void Space(float size) + { + if (s_IsCapturingKeywords) + return; + + GUILayout.Space(size); + } + + public static void FlexibleSpace() + { + if (s_IsCapturingKeywords) + return; + + GUILayout.FlexibleSpace(); + } + + public static void LabelledHyperlink(string label, string buttonText, string url) + => LabelledHyperlink(label, buttonText, () => Application.OpenURL(url)); + + public static void LabelledHyperlink(string label, string buttonText, Action action) + { + if (s_IsCapturingKeywords) + { + s_Keywords.Add(label); + s_Keywords.Add(buttonText); + return; + } + + BeginHorizontal(); + { + Label(label + ":"); + if (Button(buttonText, GUILayout.Width(250f))) + { + action(); + } + } + EndHorizontal(); + } + + public static void BeginHorizontal(GUIStyle style, params GUILayoutOption[] options) + { + if (s_IsCapturingKeywords) + return; + + GUILayout.BeginHorizontal(style, options); + } + public static void BeginHorizontal(params GUILayoutOption[] options) + { + if (s_IsCapturingKeywords) + return; + + GUILayout.BeginHorizontal(options); + } + + public static void EndHorizontal() + { + if (s_IsCapturingKeywords) + return; + + GUILayout.EndHorizontal(); + } + + public static void BeginVertical(GUIStyle style, params GUILayoutOption[] options) + { + if (s_IsCapturingKeywords) + return; + + GUILayout.BeginVertical(style, options); + } + + public static void BeginVertical(params GUILayoutOption[] options) + { + if (s_IsCapturingKeywords) + return; + + GUILayout.BeginVertical(options); + } + + public static void EndVertical() + { + if (s_IsCapturingKeywords) + return; + + GUILayout.EndVertical(); + } + + public static void BeginScrollView(ref Vector2 scrollPosition, params GUILayoutOption[] options) + { + if (s_IsCapturingKeywords) + return; + + scrollPosition = GUILayout.BeginScrollView(scrollPosition, options); + } + + public static void EndScrollView() + { + if (s_IsCapturingKeywords) + return; + + GUILayout.EndScrollView(); + } + + public static void MakeLastRectClickable(Action onClick) + { + if (s_IsCapturingKeywords) + return; + + Rect verticalRect = GUILayoutUtility.GetLastRect(); + if (Event.current.type == EventType.MouseDown && verticalRect.Contains(Event.current.mousePosition)) + { + onClick(); + Event.current.Use(); // consume + } + } + + public static void HelpBox(string message, MessageType type) + { + if (s_IsCapturingKeywords) + { + s_Keywords.Add(message); + return; + } + + EditorGUILayout.HelpBox(message, type); + } + + public static void Separator(float height = 1f) + { + if (s_IsCapturingKeywords) + return; + + s_LineStyle ??= new() { normal = new() { background = Texture2D.grayTexture } }; + GUILayout.Box(Texture2D.grayTexture, s_LineStyle, GUILayout.ExpandWidth(true), GUILayout.Height(height)); + } + + public static void Label(string text, params GUILayoutOption[] options) + { + if (s_IsCapturingKeywords) + { + s_Keywords.Add(text); + return; + } + + GUILayout.Label(text, GUI.skin.label, options); + } + + public static void Label(string text, GUIStyle style, params GUILayoutOption[] options) + { + if (s_IsCapturingKeywords) + { + s_Keywords.Add(text); + return; + } + + GUILayout.Label(text, style, options); + } + + public static bool Button(string text, params GUILayoutOption[] options) + { + if (s_IsCapturingKeywords) + { + s_Keywords.Add(text); + return false; + } + + return GUILayout.Button(text, options); + } + + public static bool Button(GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + if (s_IsCapturingKeywords) + { + s_Keywords.Add(content.text); + return false; + } + + return GUILayout.Button(content, style, options); + } + + public static bool Toggle(bool value, GUIContent content) + { + if (s_IsCapturingKeywords) + { + s_Keywords.Add(content.text); + return value; + } + + return GUILayout.Toggle(value, content); + } + + public static bool Toggle(bool value, GUIContent content, params GUILayoutOption[] options) + { + if (s_IsCapturingKeywords) + { + s_Keywords.Add(content.text); + return value; + } + + return GUILayout.Toggle(value, content, options); + } + + public static float FloatField(float value) + { + if (s_IsCapturingKeywords) + return value; + + return EditorGUILayout.FloatField(value); + } + + + public static void PropertyField(SerializedProperty sp, params GUILayoutOption[] options) + { + if (s_IsCapturingKeywords) + return; + + EditorGUILayout.PropertyField(sp, GUIContent.none, options); + } + + public static void Image(Texture2D texture, float width, float height) + { + if (s_IsCapturingKeywords) + return; + + GUILayout.Box(texture, GUILayout.Width(width), GUILayout.Height(height)); + } + + public static bool Foldout(bool foldout, string content, bool toggleOnLabelClick) + => Foldout(foldout, content, toggleOnLabelClick, EditorStyles.foldout); + + public static bool Foldout(bool foldout, string content, bool toggleOnLabelClick, GUIStyle style) + { + if (s_IsCapturingKeywords) + return foldout; + + return EditorGUILayout.Foldout(foldout, content, toggleOnLabelClick, style); + } + + public static void Foldout(string title, Action contents) + => Foldout(title, contents, EditorStyles.foldout); + + public static void Foldout(string title, Action contents, GUIStyle style) + { + if (s_IsCapturingKeywords) + return; + + bool foldout = s_FoldoutStates.GetValueOrDefault(title, false); + foldout = Foldout(foldout, title, true, style); + + if (foldout) + { + Space(10f); + + BeginHorizontal(); + { + Space(20f); + + BeginVertical(); + { + contents(); + } + EndVertical(); + } + EndHorizontal(); + + Space(10f); + } + + s_FoldoutStates[title] = foldout; + } + + public static void PrefixLabel(string text, string tooltip) + { + if (s_IsCapturingKeywords) + { + s_Keywords.Add(text); + return; + } + + EditorGUILayout.PrefixLabel(new GUIContent(text, tooltip)); + } + + public static int Popup(int value, string[] options) + { + if (s_IsCapturingKeywords) + { + s_Keywords.AddRange(options); + return value; + } + + return EditorGUILayout.Popup(value, options); + } + public static int Popup(int value, string[] options, GUIStyle style) + { + if (s_IsCapturingKeywords) + { + s_Keywords.AddRange(options); + return value; + } + + return EditorGUILayout.Popup(value, options, style); + } + + public static void UseDisabled(bool disabled, Action inside) + { + bool prevDisabled = false; + + if (!s_IsCapturingKeywords) + { + prevDisabled = !GUI.enabled; + GUI.enabled = !disabled; + } + + inside(); + + if (!s_IsCapturingKeywords) + { + GUI.enabled = !prevDisabled; + } + } + + public static void UseColour(Color c, Action inside) + { + Color previousColour = Color.white; + + if (!s_IsCapturingKeywords) + { + previousColour = GUI.color; + GUI.color = c; + } + + inside(); + + if (!s_IsCapturingKeywords) + { + GUI.color = previousColour; + } + } + + public static void Indent(Action inside) + { + if (!s_IsCapturingKeywords) + { + EditorGUI.indentLevel++; + } + + inside(); + + if (!s_IsCapturingKeywords) + { + EditorGUI.indentLevel--; + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/EditorUI/Utils/TrembleSettingsGUI.cs.meta b/Assets/Tremble/Editor/EditorUI/Utils/TrembleSettingsGUI.cs.meta new file mode 100644 index 0000000..8be5b98 --- /dev/null +++ b/Assets/Tremble/Editor/EditorUI/Utils/TrembleSettingsGUI.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 4aa6428101b54401a08834d76320438b +timeCreated: 1721666909 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/EditorUI/Utils/TrembleSettingsGUI.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Icons.meta b/Assets/Tremble/Editor/Icons.meta new file mode 100644 index 0000000..b0fc48b --- /dev/null +++ b/Assets/Tremble/Editor/Icons.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f20e9f4a105af4a71a347271c79ea536 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tremble/Editor/Icons/T_TB_Config.png b/Assets/Tremble/Editor/Icons/T_TB_Config.png new file mode 100644 index 0000000..a81c7be --- /dev/null +++ b/Assets/Tremble/Editor/Icons/T_TB_Config.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d917c46608ebf206911b87664ce054cfa1b615e1063fe1fa4ce2b34ebfcbef2d +size 1593 diff --git a/Assets/Tremble/Editor/Icons/T_TB_Config.png.meta b/Assets/Tremble/Editor/Icons/T_TB_Config.png.meta new file mode 100644 index 0000000..ba4c0b1 --- /dev/null +++ b/Assets/Tremble/Editor/Icons/T_TB_Config.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: c459dc1c802f7437c980e9dd45061327 +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: 0 + 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: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iOS + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: WindowsStoreApps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: 5e97eb03825dee720800000000000000 + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Icons/T_TB_Config.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Icons/T_TB_Import.png b/Assets/Tremble/Editor/Icons/T_TB_Import.png new file mode 100644 index 0000000..f1ab83d --- /dev/null +++ b/Assets/Tremble/Editor/Icons/T_TB_Import.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:770a50efcb5b007da0a08873832fe640f26173c148367b725a04fc5967e6d7c0 +size 1630 diff --git a/Assets/Tremble/Editor/Icons/T_TB_Import.png.meta b/Assets/Tremble/Editor/Icons/T_TB_Import.png.meta new file mode 100644 index 0000000..d9e40cf --- /dev/null +++ b/Assets/Tremble/Editor/Icons/T_TB_Import.png.meta @@ -0,0 +1,160 @@ +fileFormatVersion: 2 +guid: e900b833b9fae460ea0bc74e646c43c8 +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + 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: 8192 + 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: 8192 + 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: 8192 + 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: 8192 + 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: Windows Store Apps + maxTextureSize: 8192 + 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: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Icons/T_TB_Import.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Icons/T_TB_Manual.png b/Assets/Tremble/Editor/Icons/T_TB_Manual.png new file mode 100644 index 0000000..0f7a84a --- /dev/null +++ b/Assets/Tremble/Editor/Icons/T_TB_Manual.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca6967f88c9b4522cd7c0c27a21ed3600fd5c91073666be39d6c9acbbbfb7105 +size 405 diff --git a/Assets/Tremble/Editor/Icons/T_TB_Manual.png.meta b/Assets/Tremble/Editor/Icons/T_TB_Manual.png.meta new file mode 100644 index 0000000..5cd933c --- /dev/null +++ b/Assets/Tremble/Editor/Icons/T_TB_Manual.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: d7da2c0fbbbc7469ca79b005587b60f3 +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: 0 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 2 + 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: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Icons/T_TB_Manual.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Icons/T_TB_Sync.png b/Assets/Tremble/Editor/Icons/T_TB_Sync.png new file mode 100644 index 0000000..731e155 --- /dev/null +++ b/Assets/Tremble/Editor/Icons/T_TB_Sync.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:897a3922d6b38992aa2bb66a8940153858e0faf790354911144d728b1e20eee2 +size 1632 diff --git a/Assets/Tremble/Editor/Icons/T_TB_Sync.png.meta b/Assets/Tremble/Editor/Icons/T_TB_Sync.png.meta new file mode 100644 index 0000000..0bb7ffa --- /dev/null +++ b/Assets/Tremble/Editor/Icons/T_TB_Sync.png.meta @@ -0,0 +1,160 @@ +fileFormatVersion: 2 +guid: 3f4bdc2c9cf994f2aa00e457583810e6 +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + 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: 8192 + 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: 8192 + 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: 8192 + 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: 8192 + 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: Windows Store Apps + maxTextureSize: 8192 + 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: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Icons/T_TB_Sync.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Icons/T_TrembleLogo.png b/Assets/Tremble/Editor/Icons/T_TrembleLogo.png new file mode 100644 index 0000000..d157e7a --- /dev/null +++ b/Assets/Tremble/Editor/Icons/T_TrembleLogo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:969a4d568dc9de0ec2d135916e018f6a736ff33b3c61fc862f7f4fd5ae8be6e2 +size 143896 diff --git a/Assets/Tremble/Editor/Icons/T_TrembleLogo.png.meta b/Assets/Tremble/Editor/Icons/T_TrembleLogo.png.meta new file mode 100644 index 0000000..1d9a851 --- /dev/null +++ b/Assets/Tremble/Editor/Icons/T_TrembleLogo.png.meta @@ -0,0 +1,164 @@ +fileFormatVersion: 2 +guid: 9d50f81f814a047cc85a0414111c84ea +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Icons/T_TrembleLogo.png + uploadId: 939664 +TextureImporter: + internalIDToNameTable: + - first: + 213: 7041757788322832993 + second: T_TrembleLogo_0 + 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: 0 + 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 + spriteTessellationMethod: 0 + spriteTessellationDetail: -1 + spriteGeometrySubdivision: -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: 4 + 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: 4 + 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: 4 + 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: + - serializedVersion: 2 + name: T_TrembleLogo_0 + rect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1024 + height: 1024 + alignment: 0 + pivot: {x: 0, y: 0} + border: {x: 0, y: 0, z: 0, w: 0} + customData: + outline: [] + physicsShape: [] + tessellationDetail: -1 + bones: [] + spriteID: 162a25f466959b160800000000000000 + internalID: 7041757788322832993 + vertices: [] + indices: + edges: [] + weights: [] + outline: [] + customData: + physicsShape: [] + bones: [] + spriteID: 5e97eb03825dee720800000000000000 + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tremble/Editor/Manual.meta b/Assets/Tremble/Editor/Manual.meta new file mode 100644 index 0000000..18b7d2f --- /dev/null +++ b/Assets/Tremble/Editor/Manual.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: cf92aea5ec3540bca20dc4d8428c93ba +timeCreated: 1722960124 \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/FNT_UbuntuMono.ttf b/Assets/Tremble/Editor/Manual/FNT_UbuntuMono.ttf new file mode 100644 index 0000000..fdd309d Binary files /dev/null and b/Assets/Tremble/Editor/Manual/FNT_UbuntuMono.ttf differ diff --git a/Assets/Tremble/Editor/Manual/FNT_UbuntuMono.ttf.meta b/Assets/Tremble/Editor/Manual/FNT_UbuntuMono.ttf.meta new file mode 100644 index 0000000..7d5a4cb --- /dev/null +++ b/Assets/Tremble/Editor/Manual/FNT_UbuntuMono.ttf.meta @@ -0,0 +1,28 @@ +fileFormatVersion: 2 +guid: fba6c5b92231f442a8364fdb83b3edad +TrueTypeFontImporter: + externalObjects: {} + serializedVersion: 4 + fontSize: 16 + forceTextureCase: -2 + characterSpacing: 0 + characterPadding: 1 + includeFontData: 1 + fontNames: + - Ubuntu Mono + fallbackFontReferences: [] + customCharacters: + fontRenderingMode: 0 + ascentCalculationMode: 1 + useLegacyBoundsCalculation: 0 + shouldRoundAdvanceValue: 1 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/FNT_UbuntuMono.ttf + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualEntry.cs b/Assets/Tremble/Editor/Manual/ManualEntry.cs new file mode 100644 index 0000000..667f98c --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualEntry.cs @@ -0,0 +1,34 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; + +namespace TinyGoose.Tremble.Editor +{ + public record ManualEntry + { + public string Title { get; init; } + public string PagePath { get; init; } + public bool ShowInTree { get; init; } = true; + + public List Children { get; } = new(); + + public ManualEntry FindEntryByPath_Recursive(string path) + { + if (PagePath != null && PagePath.EqualsInvariant(path)) + return this; + + foreach (ManualEntry child in Children) + { + ManualEntry result = child.FindEntryByPath_Recursive(path); + if (result != null) + return result; + } + + return null; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/ManualEntry.cs.meta b/Assets/Tremble/Editor/Manual/ManualEntry.cs.meta new file mode 100644 index 0000000..383cd36 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualEntry.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: e522cd7f114947df9cd7e4422f37ac92 +timeCreated: 1722961528 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualEntry.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages.meta b/Assets/Tremble/Editor/Manual/ManualImages.meta new file mode 100644 index 0000000..6d9986e --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: acb2d0790139b4bd0a99529ee3e28a22 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_BrushEntity.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_BrushEntity.png new file mode 100644 index 0000000..d2c8b93 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_BrushEntity.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0627eb0b31343c0bed652c560500db78383d0d547b305b242503c2f78044f71d +size 19960 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_BrushEntity.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_BrushEntity.png.meta new file mode 100644 index 0000000..b3e27ba --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_BrushEntity.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: edbd082dde0b24cee9dbe83b2399e40f +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: 2 + mipBias: 0 + wrapU: 0 + wrapV: 0 + wrapW: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_BrushEntity.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_CreateMap.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_CreateMap.png new file mode 100644 index 0000000..5ac4e6e --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_CreateMap.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d45b542d0a02045e78b7c55aef8147f1569846b9c4b7232b5da15f4307bb66e1 +size 41437 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_CreateMap.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_CreateMap.png.meta new file mode 100644 index 0000000..b10ed66 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_CreateMap.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 5204d1c0f162d4a589ca60d8c6f289c1 +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_CreateMap.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_LiveUpdate1.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_LiveUpdate1.png new file mode 100644 index 0000000..1e45199 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_LiveUpdate1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:63a858b7f2fa55ca3c3a13de9f894ecb0fca8df7a9829f577e184ab852d5f483 +size 35129 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_LiveUpdate1.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_LiveUpdate1.png.meta new file mode 100644 index 0000000..09e992f --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_LiveUpdate1.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 397a0f0f28f9f4e9eaca335b9b9479ce +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: 2 + mipBias: 0 + wrapU: 0 + wrapV: 0 + wrapW: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_LiveUpdate1.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_LiveUpdate2.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_LiveUpdate2.png new file mode 100644 index 0000000..0244ede --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_LiveUpdate2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:538d8d9b786c18859d32f3a58319933e575cddb2f61d8858dfd8fedca0d16d33 +size 61735 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_LiveUpdate2.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_LiveUpdate2.png.meta new file mode 100644 index 0000000..aa7e94f --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_LiveUpdate2.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 92ee6046b7c734acaa687b23061a1723 +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: 2 + mipBias: 0 + wrapU: 0 + wrapV: 0 + wrapW: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_LiveUpdate2.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapProcessor.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapProcessor.png new file mode 100644 index 0000000..e0a4273 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapProcessor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8fcb4e7093cff7a1dac5daa5ccc6736231455f72a2dcb325a101bb5003080087 +size 113661 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapProcessor.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapProcessor.png.meta new file mode 100644 index 0000000..845cb71 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapProcessor.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 1618957b737a3490c9d9ac3d8f5413da +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: 2 + mipBias: 0 + wrapU: 0 + wrapV: 0 + wrapW: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapProcessor.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair.png new file mode 100644 index 0000000..c8043eb --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:638323e2d856c8c803501723ef31dbd1e5d81a3eb482fcc7a8668c9c0e604f4d +size 81199 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair.png.meta new file mode 100644 index 0000000..a233ed2 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 7154fd07e64354cf59ae63b87206f05d +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Entities.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Entities.png new file mode 100644 index 0000000..fa6948a --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Entities.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9dac0570d2d95b5be2da62b33b79b5216171bc5a23cc0425c3279ff4edfaf20 +size 50677 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Entities.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Entities.png.meta new file mode 100644 index 0000000..023caad --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Entities.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 17f71c996af184292a24fe277d2f84b8 +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Entities.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_NoFGD.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_NoFGD.png new file mode 100644 index 0000000..22b6841 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_NoFGD.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03038b9e613788adaba253c8aff051257ba40898ccd397fc619f8cfe7250f95b +size 164540 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_NoFGD.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_NoFGD.png.meta new file mode 100644 index 0000000..9d2bf0e --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_NoFGD.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 0dd22f4c150c94b1a84aba479d697668 +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: 2 + mipBias: 0 + wrapU: 0 + wrapV: 0 + wrapW: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_NoFGD.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Required.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Required.png new file mode 100644 index 0000000..26238cc --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Required.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:293d079ca2db6720dee58589756cfefb41da3794f5360cf53e3eeb4bd169aa9c +size 72550 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Required.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Required.png.meta new file mode 100644 index 0000000..953f417 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Required.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 512558f9a81a84ea0983b1b0b7460e0c +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: 2 + mipBias: 0 + wrapU: 0 + wrapV: 0 + wrapW: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Required.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Textures.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Textures.png new file mode 100644 index 0000000..5256909 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Textures.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c14dbd9b377c276251ff75d10522cdbb329ab5969328a478f5d23b30e4df4db4 +size 54349 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Textures.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Textures.png.meta new file mode 100644 index 0000000..7a5b26f --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Textures.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 1a1ed8b8ca0684270bf22fa864bd1c4b +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_Textures.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_WithFGD.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_WithFGD.png new file mode 100644 index 0000000..fede3b5 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_WithFGD.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c5a7a8c28fb2fb2dcd6b13c4fa23cbeeece8fee6bbcbf1b377301501d31236a4 +size 197553 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_WithFGD.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_WithFGD.png.meta new file mode 100644 index 0000000..0f71f6f --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_WithFGD.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 860ecfae5d6d5468e85890e003668045 +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: 2 + mipBias: 0 + wrapU: 0 + wrapV: 0 + wrapW: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MapRepair_WithFGD.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MaterialGroups.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MaterialGroups.png new file mode 100644 index 0000000..2a94c0a --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MaterialGroups.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed56ddfba8e8df501c415af85ecf5bd5b459c156294c692e1f2630c51a4a866b +size 81644 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MaterialGroups.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MaterialGroups.png.meta new file mode 100644 index 0000000..715ccb2 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MaterialGroups.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: b02b0e10ead7244a39a3b23be4286e62 +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MaterialGroups.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_TB1.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_TB1.png new file mode 100644 index 0000000..bf5cc74 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_TB1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e54cdcbba883b20d48b6e97f60775eaea04c68234228a0077b730c2d2535f0c6 +size 3108938 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_TB1.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_TB1.png.meta new file mode 100644 index 0000000..365d124 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_TB1.png.meta @@ -0,0 +1,121 @@ +fileFormatVersion: 2 +guid: f9d23417eb63440518f17f98a84018bf +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 + 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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + 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 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_TB1.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_TB2.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_TB2.png new file mode 100644 index 0000000..1cd9e81 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_TB2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43f70c3705196118c2b2960ab38ef456d1dd1971939fe45ab8784307d00792d5 +size 3063330 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_TB2.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_TB2.png.meta new file mode 100644 index 0000000..5e6fc63 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_TB2.png.meta @@ -0,0 +1,121 @@ +fileFormatVersion: 2 +guid: 512b951d450244dc490de97c11f16400 +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 + 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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + 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 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_TB2.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_Unity1.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_Unity1.png new file mode 100644 index 0000000..d700498 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_Unity1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2849afe07eb6eaae576becc6179f719269d2c96c0bd090b7df36b736a458f926 +size 1040173 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_Unity1.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_Unity1.png.meta new file mode 100644 index 0000000..e996f6d --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_Unity1.png.meta @@ -0,0 +1,121 @@ +fileFormatVersion: 2 +guid: e7dc51b9f011b47118ad1f32472e6cfe +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 + 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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + 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 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_Unity1.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_Unity2.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_Unity2.png new file mode 100644 index 0000000..6bdf6cd --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_Unity2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fafeef077a607e3b3b127fbc133601c4166f9e1bcde178142cd4c6835cd6273e +size 2417162 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_Unity2.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_Unity2.png.meta new file mode 100644 index 0000000..125b3f7 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_Unity2.png.meta @@ -0,0 +1,121 @@ +fileFormatVersion: 2 +guid: b02a7c9a8c5da4731af31f805eb11804 +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 + 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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + 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 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_MissingGeo_Unity2.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Pipeline.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Pipeline.png new file mode 100644 index 0000000..da045e8 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Pipeline.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0fd4a6c11997e110e13e71319fc12245dbb82c42146801dbb71435daed51f01 +size 367790 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Pipeline.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Pipeline.png.meta new file mode 100644 index 0000000..d42c485 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Pipeline.png.meta @@ -0,0 +1,163 @@ +fileFormatVersion: 2 +guid: 50a31cab696ef4f1191339661e72fb5a +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Pipeline.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_PointEntity.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_PointEntity.png new file mode 100644 index 0000000..10272f6 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_PointEntity.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c29e9550ccebde31424f37e114a5b0c97cc9bf4b28f2349a6dafda803e109457 +size 19362 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_PointEntity.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_PointEntity.png.meta new file mode 100644 index 0000000..ab42771 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_PointEntity.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 37c91588401a94de1bad2135884efe70 +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: 2 + mipBias: 0 + wrapU: 0 + wrapV: 0 + wrapW: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_PointEntity.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_PrefabEntity.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_PrefabEntity.png new file mode 100644 index 0000000..7979471 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_PrefabEntity.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60b0cb3923e9c11ece8467cf768351e4f5815ea8133658acbbf5b145b4603158 +size 28537 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_PrefabEntity.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_PrefabEntity.png.meta new file mode 100644 index 0000000..bdec307 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_PrefabEntity.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 975dcbf6686ba43e18cbed841f05f6e8 +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_PrefabEntity.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_RenderSettings.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_RenderSettings.png new file mode 100644 index 0000000..af1d429 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_RenderSettings.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fbda8986477d3e1799947317755b966ef51c7e943766aceeeb1ce71301c70aa3 +size 20895 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_RenderSettings.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_RenderSettings.png.meta new file mode 100644 index 0000000..4611c90 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_RenderSettings.png.meta @@ -0,0 +1,137 @@ +fileFormatVersion: 2 +guid: 2fe327c4fae9e74d8bea648040eeed1b +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + 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: 4 + buildTarget: WebGL + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_RenderSettings.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_SpawnablePrefab.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_SpawnablePrefab.png new file mode 100644 index 0000000..f2dddd0 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_SpawnablePrefab.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43797c741c6755d52a780b342e1814061c4efd3fa5f4bceeefb93596990dd125 +size 110087 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_SpawnablePrefab.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_SpawnablePrefab.png.meta new file mode 100644 index 0000000..6a0e5f8 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_SpawnablePrefab.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 496dce75903ae44d0ace66d47a7e8d7a +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_SpawnablePrefab.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_DLL1.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_DLL1.png new file mode 100644 index 0000000..5c3b481 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_DLL1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f83172c852a461a6fb0a8597c66738e34b8d171cecb0a0e33188562bf612b5d +size 161746 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_DLL1.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_DLL1.png.meta new file mode 100644 index 0000000..99c2786 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_DLL1.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 8d4ed641ac16f4f9ea0ed0423383f198 +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_DLL1.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_DLL2.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_DLL2.png new file mode 100644 index 0000000..c4bf48b --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_DLL2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca1b068c8b69062532c48bc94ea8b72c341bac7d4a5c8b86e7268636cfce78a1 +size 30604 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_DLL2.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_DLL2.png.meta new file mode 100644 index 0000000..77a26a3 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_DLL2.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: ceb966372c8744d64a0b83a21dde66ee +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_DLL2.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_FixPinkMaterialsVideo.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_FixPinkMaterialsVideo.png new file mode 100644 index 0000000..f56d93d --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_FixPinkMaterialsVideo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e311af5feed30258dbd9589672b7223244a7761493ef88d72cd15618899bec7 +size 147949 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_FixPinkMaterialsVideo.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_FixPinkMaterialsVideo.png.meta new file mode 100644 index 0000000..6c85d7c --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_FixPinkMaterialsVideo.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 2daf6bf8d225141d18d9e6ee4787f07d +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_FixPinkMaterialsVideo.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_MaterialBrightness.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_MaterialBrightness.png new file mode 100644 index 0000000..a00ae50 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_MaterialBrightness.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4b5d51132710575af9927f37cee9f125c1e08079721e9d264f661bc7daf8bba +size 156208 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_MaterialBrightness.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_MaterialBrightness.png.meta new file mode 100644 index 0000000..d6d627c --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_MaterialBrightness.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 68dc678b14c754e0eb97bea3527e7f3e +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_MaterialBrightness.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_MaterialBrightnessSettings.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_MaterialBrightnessSettings.png new file mode 100644 index 0000000..deff542 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_MaterialBrightnessSettings.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c4ae8591b4cad52bbdde4a86d4693cf87a423c4b2b4e9d6f974446825557761 +size 38593 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_MaterialBrightnessSettings.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_MaterialBrightnessSettings.png.meta new file mode 100644 index 0000000..44eba85 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_MaterialBrightnessSettings.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: f9e3201bf80fd462297cab6a73cf1a8e +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_MaterialBrightnessSettings.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_PinkMaterials.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_PinkMaterials.png new file mode 100644 index 0000000..e4a7b76 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_PinkMaterials.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f663d51e94d747d86ef0f3e8cf44bf833256cc3f4b5bae145a1f7f45189f9dd +size 181760 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_PinkMaterials.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_PinkMaterials.png.meta new file mode 100644 index 0000000..555066e --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_PinkMaterials.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: fa99fe121e4274518ae28788c8942b85 +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_Trouble_PinkMaterials.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_WadImport2.png b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_WadImport2.png new file mode 100644 index 0000000..5ca3d74 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_WadImport2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef3708f0d3c53cf4b0abed2490f62641313bcebb17daad519e8a4a97682cfee1 +size 49907 diff --git a/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_WadImport2.png.meta b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_WadImport2.png.meta new file mode 100644 index 0000000..63e98c1 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualImages/T_Manual_WadImport2.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 48ad6b4636f5344b8a92818a4e9f5d28 +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iPhone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Windows Store Apps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualImages/T_Manual_WadImport2.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualPageAttribute.cs b/Assets/Tremble/Editor/Manual/ManualPageAttribute.cs new file mode 100644 index 0000000..e834a2f --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualPageAttribute.cs @@ -0,0 +1,32 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using UnityEngine.Scripting; + +namespace TinyGoose.Tremble.Editor +{ + [AttributeUsage(AttributeTargets.Class)] + public class ManualPageAttribute : PreserveAttribute + { + public ManualPageAttribute(string path, string title = null, bool showInTree = true, bool isHomePage = false) + { + m_Path = path; + m_Title = title ?? path.Split('/')[^1]; + m_ShowInTree = showInTree; + m_IsHomePage = isHomePage; + } + + private readonly string m_Title; + private readonly string m_Path; + private readonly bool m_ShowInTree; + private readonly bool m_IsHomePage; + + public string Title => m_Title; + public string Path => m_Path; + public bool ShowInTree => m_ShowInTree; + public bool IsHomePage => m_IsHomePage; + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/ManualPageAttribute.cs.meta b/Assets/Tremble/Editor/Manual/ManualPageAttribute.cs.meta new file mode 100644 index 0000000..189af7d --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualPageAttribute.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: eac801fb3ff2452cac86d6e01aa048e2 +timeCreated: 1722962036 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualPageAttribute.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualPageBase.cs b/Assets/Tremble/Editor/Manual/ManualPageBase.cs new file mode 100644 index 0000000..c5de698 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualPageBase.cs @@ -0,0 +1,389 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public abstract class ManualPageBase + { + private readonly Dictionary m_Images = new(); + private int m_NextNumber; + private ManualWindow m_ManualWindow; + + private readonly Dictionary m_FoldoutState = new(); + + protected float PageWidth => m_ManualWindow.PageWidth; + + protected void Repaint() => m_ManualWindow.Repaint(); + + internal void Init(ManualWindow window) + { + m_ManualWindow = window; + OnInit(); + } + + internal void DeInit() => OnDeInit(); + + internal void Render() + { + ResetNumbering(); + OnGUI(); + } + + protected virtual void OnInit() {} + protected virtual void OnDeInit() {} + protected abstract void OnGUI(); + + protected void GoToPage(Type type) + { + m_ManualWindow.GoToPage(type); + } + + protected void NYI() + { + GUI.color = Color.red; + Text("This page is not yet implemented!!!"); + GUI.color = Color.grey; + Text(GetType().Name.ToNamingConvention(NamingConvention.HumanFriendly)); + GUI.color = Color.white; + } + + protected int Tabs(ref int selectedIdx, string[] tabNames) + { + selectedIdx = GUILayout.Toolbar(selectedIdx, tabNames, "LargeButton"); + return selectedIdx; + } + protected int Tabs(ref int selectedIdx, string[] tabNames, float width) + { + selectedIdx = GUILayout.Toolbar(selectedIdx, tabNames, "LargeButton", GUILayout.Width(width * ManualStyles.Scale)); + return selectedIdx; + } + + + protected void Image(string name, float width = 400f, bool centred = true) + { + if (!m_Images.TryGetValue(name, out Texture2D texture)) + { + texture = TrembleAssetLoader.LoadAssetByName(name); + m_Images[name] = texture; + } + + width *= ManualStyles.Scale; + float height = texture ? texture.height * (width / texture.width) : width; + + var style = new GUIStyle("IN ThumbnailShadow"); + style.margin.bottom = 16; + style.margin.top = 16; + + void RawImage() + { + if (texture) + { + GUILayout.Box(texture, style, GUILayout.Width(width), GUILayout.Height(height)); + } + else + { + GUI.color = Color.red; + GUILayout.Box($"", style, GUILayout.Width(width), GUILayout.Height(height)); + GUI.color = Color.white; + } + } + + if (centred) + { + Centre(RawImage); + } + else + { + RawImage(); + } + } + + protected void Title(string text) => TextAndSpace(text, ManualStyles.Styles.Title); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Text + // ----------------------------------------------------------------------------------------------------------------------------- + protected void Text(string text) => TextAndSpace(text, ManualStyles.Styles.Text); + protected void Text(params string[] text) => Text(String.Join(' ', text)); + protected void TextMultiline(params string[] text) => Text(String.Join('\n', text)); + protected void Text(string text, float width) => TextAndSpace(text, ManualStyles.Styles.Text, width); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Bold + // ----------------------------------------------------------------------------------------------------------------------------- + protected void Bold(string text) => TextAndSpace(text, ManualStyles.Styles.B); + protected void Bold(params string[] text) => Bold(String.Join(' ', text)); + protected void BoldMultiline(params string[] text) => Bold(String.Join('\n', text)); + protected void Bold(string text, float width) => TextAndSpace(text, ManualStyles.Styles.B, width); + + protected void CheckListItem(string text, bool isChecked, string action = null, Action doIt = null) + { + Color oldColour = GUI.color; + GUI.color = isChecked ? Color.green : Color.red; + + GUILayout.BeginHorizontal(EditorStyles.helpBox); + { + bool wasTicked = GUILayout.Toggle(isChecked, text, ManualStyles.Styles.Toggle, GUILayout.ExpandWidth(true)); + + if (!isChecked && !action.IsNullOrEmpty() && doIt != null) + { + GUI.color = Color.green; + if (GUILayout.Button(action, ManualStyles.Styles.Button, GUILayout.Width(200f))) + { + doIt(); + } + } + + if (!isChecked && wasTicked && doIt != null) + { + doIt(); + } + } + GUILayout.EndHorizontal(); + + GUI.color = oldColour; + } + + protected void Foldout(string title, Action inside) + { + bool foldout = m_FoldoutState.GetValueOrDefault(title, false); + foldout = EditorGUILayout.Foldout(foldout, title, true, ManualStyles.Styles.Foldout); + + SmallSpace(); + + if (foldout) + { + Indent(inside); + } + + SmallSpace(); + + m_FoldoutState[title] = foldout; + } + + + protected void Indent(Action inside) => Indent(1, inside); + protected void Indent(int amount, Action inside) + { + GUILayout.BeginHorizontal(); + { + GUILayout.Space(20f * amount); + + GUILayout.BeginVertical(); + { + inside(); + } + GUILayout.EndVertical(); + } + GUILayout.EndHorizontal(); + } + + protected void Code(params string[] text) => CodeInternal(null, false, text); + protected void CodeNoCopy(params string[] text) => CodeInternal(null, true, text); + protected void CodeWithHeader(string header, params string[] text) => CodeInternal(header, false, text); + protected void CodeWithHeaderNoCopy(string header, params string[] text) => CodeInternal(header, true, text); + + private void CodeInternal(string header, bool noCopy, params string[] text) + { + GUILayout.BeginVertical(EditorStyles.helpBox); + { + string textJoined = String.Join('\n', text); + int numLines = textJoined.Count(c => c == '\n') + 1; + + GUILayout.BeginHorizontal(); + { + header ??= "C# Source Code"; + + GUI.color = Color.grey; + GUILayout.Label($"{header}, {numLines} line(s)"); + GUI.color = Color.white; + GUILayout.FlexibleSpace(); + + if (!noCopy && GUILayout.Button("Copy to clipboard")) + { + GUIUtility.systemCopyBuffer = textJoined; + } + } + GUILayout.EndHorizontal(); + + GUILayout.Label(textJoined, ManualStyles.Styles.Code); + } + GUILayout.EndVertical(); + } + + protected void Button(string label, Action action, float width = 0f) + { + bool pressed = width > 0f + ? GUILayout.Button(label, GUILayout.Width(width)) + : GUILayout.Button(label); + + if (pressed) + action(); + } + + protected void LargeButton(string label, Action action) => SizedButton(label, ManualStyles.Styles.VeryLargeButton, action); + + private void SizedButton(string label, GUIStyle style, Action action) + { + GUILayout.BeginHorizontal(); + { + GUILayout.FlexibleSpace(); + + if (GUILayout.Button(label, style, GUILayout.ExpandWidth(false), GUILayout.Height(80f))) + action(); + + GUILayout.FlexibleSpace(); + } + GUILayout.EndHorizontal(); + } + + protected void Bullet(params string[] text) => BulletInternal("•", text); + + protected void ResetNumbering() => m_NextNumber = 1; + protected void Number(params string[] text) => BulletInternal($"{m_NextNumber++})", text); + + private void BulletInternal(string bullet, params string[] text) + { + GUILayout.BeginHorizontal(); + { + GUILayout.Label(bullet, ManualStyles.Styles.B, GUILayout.Width(20f)); + GUILayout.Label(String.Join(' ', text), ManualStyles.Styles.Text); + } + GUILayout.EndHorizontal(); + } + + protected void PropertyDescription(string property, params string[] text) + => PropertyDescription(property, EditorGUIUtility.labelWidth, text); + protected void PropertyDescription(string property, float labelWidth, params string[] text) + => CustomPropertyDescription(property, labelWidth, () => GUILayout.Label(String.Join(' ', text), ManualStyles.Styles.Text)); + + protected void CustomPropertyDescription(string property, Action inside) + => CustomPropertyDescription(property, EditorGUIUtility.labelWidth, inside); + protected void CustomPropertyDescription(string property, float labelWidth, Action inside) + { + GUILayout.BeginHorizontal(); + { + GUILayout.Label(property, ManualStyles.Styles.B, GUILayout.Width(labelWidth)); + inside(); + } + GUILayout.EndHorizontal(); + } + + protected void Experimental() => Callout("This feature is experimental and may not work in all cases!"); + + protected void Callout(params string[] text) + { + SmallSpace(); + + GUIContent helpContent = new(String.Join('\n', text), EditorGUIUtility.IconContent("console.infoicon").image); + GUILayout.Label(helpContent, ManualStyles.Styles.HelpBox); + } + + + protected void H1(string text) => TextAndSpace(text, ManualStyles.Styles.H1); + + protected void H2(string text) => TextAndSpace(text, ManualStyles.Styles.H2); + + protected void H3(string text) => TextAndSpace(text, ManualStyles.Styles.H3); + + //protected void H4(string text) => TextAndSpace(text, ManualStyles.Styles.H4); + + protected void B(string text) => GUILayout.Label(text, ManualStyles.Styles.B); + + private void TextAndSpace(string text, GUIStyle style) + { + GUILayout.Space(style.fontSize * ManualStyles.Scale); + GUILayout.Label(text, style); + SmallSpace(); + } + + private void TextAndSpace(string text, GUIStyle style, float width) + { + GUILayout.BeginVertical(); + { + GUILayout.Space(style.fontSize * ManualStyles.Scale); + GUILayout.Label(text, style, GUILayout.Width(width * ManualStyles.Scale)); + SmallSpace(); + } + GUILayout.EndVertical(); + } + + protected void SmallSpace() => Space(0.25f); + protected void LargeSpace() => Space(2.5f); + protected void Space(float scale = 1f) => GUILayout.Space(ManualStyles.SPACE * scale * ManualStyles.Scale); + + protected void HorizontalLine(float height = 2f) + { + GUILayout.Space(5f); + GUILayout.Box(Texture2D.whiteTexture, GUILayout.ExpandWidth(true), GUILayout.Height(height)); + } + + protected void Centre(Action inside) + { + GUILayout.BeginHorizontal(); + { + GUILayout.FlexibleSpace(); + { + inside(); + } + GUILayout.FlexibleSpace(); + } + GUILayout.EndHorizontal(); + } + protected void RAlign(Action inside) + { + GUILayout.BeginHorizontal(); + { + GUILayout.FlexibleSpace(); + inside(); + } + GUILayout.EndHorizontal(); + } + + protected void ActionBar(Action inside) + { + Color oldColour = GUI.color; + GUI.color = Color.yellow; + + GUILayout.BeginHorizontal(EditorStyles.helpBox); + { + GUILayout.Label("Try it:", ManualStyles.Styles.B, GUILayout.ExpandWidth(false)); + GUILayout.FlexibleSpace(); + inside(); + } + GUILayout.EndHorizontal(); + + SmallSpace(); + + GUI.color = oldColour; + } + + protected void Action(string action, Action inside) + { + if (GUILayout.Button(action, ManualStyles.Styles.Button, GUILayout.ExpandWidth(false))) + { + inside(); + } + } + + protected void ActionBar_SingleAction(string action, Action inside) + => ActionBar(() => Action(action, inside)); + + protected static string FormatAttributeName(Type attributeType) + { + string name = attributeType.Name; + int attrIdx = name.LastIndexOfInvariant("Attribute", caseSensitive: true); + + return attrIdx == -1 ? name : name.Substring(0, attrIdx); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/ManualPageBase.cs.meta b/Assets/Tremble/Editor/Manual/ManualPageBase.cs.meta new file mode 100644 index 0000000..e9ea4bb --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualPageBase.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: dc264e8de3f14d22bb1937514ee4c126 +timeCreated: 1722960151 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualPageBase.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualStyles.cs b/Assets/Tremble/Editor/Manual/ManualStyles.cs new file mode 100644 index 0000000..c03beec --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualStyles.cs @@ -0,0 +1,112 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public class ManualStyles + { + private ManualStyles() + { + string manualPath = Path.Combine(TrembleConsts.EDITOR_GetTrembleInstallFolder(), "Editor", "Manual"); + string fontPath = Path.Combine(manualPath, "FNT_UbuntuMono.ttf"); + Font ubuntuMonoFont = AssetDatabase.LoadAssetAtPath(fontPath); + + string bookmarkOnPath = Path.Combine(manualPath, "T_Bookmark_On.png"); + m_BookmarkIconOn = AssetDatabase.LoadAssetAtPath(bookmarkOnPath); + string bookmarkOffPath = Path.Combine(manualPath, "T_Bookmark_Off.png"); + m_BookmarkIconOff = AssetDatabase.LoadAssetAtPath(bookmarkOffPath); + + m_Text = new(EditorStyles.wordWrappedLabel) { fontSize = Mathf.FloorToInt(13 * s_Scale) }; + m_Code = new(EditorStyles.wordWrappedLabel) { font = ubuntuMonoFont, fontSize = Mathf.FloorToInt(13 * s_Scale)}; + m_CenteredGreyMiniLabel = new(EditorStyles.centeredGreyMiniLabel) { fontSize = Mathf.FloorToInt(9 * s_Scale)}; + + m_Toggle = new(EditorStyles.toggle) { fontSize = Mathf.FloorToInt(13 * s_Scale) }; + m_Foldout = new(EditorStyles.foldout) { fontSize = Mathf.FloorToInt(13 * s_Scale) }; + + m_Button = new("Button") { fontSize = Mathf.FloorToInt(13 * s_Scale) }; + m_VeryLargeButton = new(m_Button) { padding = new(30, 30, 30, 30), fontSize = Mathf.FloorToInt(20 * s_Scale) }; + m_B = new(m_Text) { fontStyle = FontStyle.Bold, fontSize = Mathf.FloorToInt(13 * s_Scale) }; + + m_HelpBox = new(EditorStyles.helpBox) { fontSize = Mathf.FloorToInt(13 * s_Scale) }; + + m_Title = new(m_B) { fontStyle = FontStyle.Bold, fontSize = Mathf.FloorToInt(24 * s_Scale) }; + + m_H1 = new(m_B) { fontSize = Mathf.FloorToInt(20 * s_Scale) }; + m_H2 = new(m_B) { fontSize = Mathf.FloorToInt(18 * s_Scale) }; + m_H3 = new(m_B) { fontSize = Mathf.FloorToInt(16 * s_Scale) }; + } + + private static ManualStyles s_ManualStyles; + private static float s_Scale = 1f; + + public static ManualStyles Styles + { + get + { + s_ManualStyles ??= new(); + return s_ManualStyles; + } + } + + public static float Scale + { + get => s_Scale; + set + { + s_Scale = value; + s_ManualStyles = new(); + } + } + + private readonly Texture2D m_BookmarkIconOn; + private readonly Texture2D m_BookmarkIconOff; + + private readonly GUIStyle m_Text; + private readonly GUIStyle m_Code; + private readonly GUIStyle m_CenteredGreyMiniLabel; + + private readonly GUIStyle m_Button; + private readonly GUIStyle m_VeryLargeButton; + private readonly GUIStyle m_Toggle; + private readonly GUIStyle m_Foldout; + private readonly GUIStyle m_B; + + private readonly GUIStyle m_HelpBox; + + private readonly GUIStyle m_Title; + private readonly GUIStyle m_H1; + private readonly GUIStyle m_H2; + private readonly GUIStyle m_H3; + + public const float SPACE = 20f; + + + public Texture2D BookmarkIconOn => m_BookmarkIconOn; + public Texture2D BookmarkIconOff => m_BookmarkIconOff; + + public GUIStyle Text => m_Text; + public GUIStyle Code => m_Code; + public GUIStyle CenteredGreyMiniLabel => m_CenteredGreyMiniLabel; + + + public GUIStyle Button => m_Button; + public GUIStyle VeryLargeButton => m_VeryLargeButton; + public GUIStyle Toggle => m_Toggle; + public GUIStyle Foldout => m_Foldout; + public GUIStyle B => m_B; + + public GUIStyle HelpBox => m_HelpBox; + + public GUIStyle Title => m_Title; + + public GUIStyle H1 => m_H1; + public GUIStyle H2 => m_H2; + public GUIStyle H3 => m_H3; + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/ManualStyles.cs.meta b/Assets/Tremble/Editor/Manual/ManualStyles.cs.meta new file mode 100644 index 0000000..d8c45c1 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualStyles.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 689cba6a005c4398b5e076898317b92c +timeCreated: 1723118191 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualStyles.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/ManualWindow.cs b/Assets/Tremble/Editor/Manual/ManualWindow.cs new file mode 100644 index 0000000..2abda52 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualWindow.cs @@ -0,0 +1,558 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public class ManualWindow : EditorWindow + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Statics - for storing state between reloads + // ----------------------------------------------------------------------------------------------------------------------------- + private const string MANUAL_PREFIX = "Manual_"; + private const int MAX_BOOKMARKS = 5; + + private static readonly EditorPrefsBackedString s_Path = new(MANUAL_PREFIX + nameof(s_Path)); + private static readonly EditorPrefsBackedString s_HomePath = new(MANUAL_PREFIX + nameof(s_HomePath)); + private static readonly EditorPrefsBackedString s_SortOrderFirst = new(MANUAL_PREFIX + nameof(s_SortOrderFirst)); + private static readonly EditorPrefsBackedString s_SortOrderLast = new(MANUAL_PREFIX + nameof(s_SortOrderLast)); + private static readonly EditorPrefsBackedString s_Bookmarks = new(MANUAL_PREFIX + nameof(s_Bookmarks)); + + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private Vector2 m_ListScrollPos; + private Vector2 m_PageScrollPos; + + private ManualEntry m_CurrentNode; + private ManualPageBase m_CurrentPage; + + private ManualEntry m_TreeRoot; + private readonly Dictionary m_PageClasses = new(); + + private GUIStyle m_SelectedItemStyle; + + private float m_TreeViewWidth = 235f; + private bool m_IsResizing; + private readonly List m_History = new(); + private int m_HistoryPtr = -1; + + public float PageWidth => position.width - m_TreeViewWidth - 20f; + + public static void OpenManual(string windowTitle, Type startPage = null, string[] sortOrderFirst = null, string[] sortOrderLast = null) + { + string startPath = null; + + if (startPage != null) + { + startPage.GetCustomAttributes(out ManualPageAttribute pageInfo); + if (pageInfo == null) + { + Debug.LogWarning($"Tried to open manual to page: {startPage.Name} - which is not a valid page - going home..."); + } + else + { + startPath = pageInfo.Path; + } + } + + OpenManual(windowTitle, startPath, sortOrderFirst, sortOrderLast); + } + + public static void OpenManual(string windowTitle, string startPath = null, string[] sortOrderFirst = null, string[] sortOrderLast = null) + { + s_Path.Value = startPath; + s_SortOrderFirst.Values = sortOrderFirst ?? Array.Empty(); + s_SortOrderLast.Values = sortOrderLast ?? Array.Empty(); + + ManualWindow window = GetWindow(true, windowTitle, true); + + Vector2 size = new(1200f, 640f); + window.minSize = new(800f, 400f); + window.position = new(EditorGUIUtility.GetMainWindowPosition().center - size / 2f, size); + window.Show(); + } + + private void OnEnable() + { + s_HomePath.Value = null; + m_TreeRoot = new() { Title = "" }; + + TypeCache.TypeCollection pages = TypeCache.GetTypesWithAttribute(); + foreach (Type pageClass in pages) + { + pageClass.GetCustomAttributes(out ManualPageAttribute pageInfo); + + if (pageInfo.IsHomePage) + { + if (s_HomePath.Value != null) + { + Debug.LogError($"Multiple home pages in manual! Was: {s_HomePath.Values}, now using: {pageInfo.Path}!"); + } + s_HomePath.Value = pageInfo.Path; + } + + m_PageClasses[pageInfo.Path] = pageClass; + + List pathList = pageInfo.Path.Split("/", StringSplitOptions.RemoveEmptyEntries).ToList(); + CreateHierarchy_Recursive(m_TreeRoot, pathList, pageInfo); + } + + SortHierarchy_Recursive(m_TreeRoot, s_HomePath.Value); + GoToPage(s_Path.Value ?? s_HomePath.Value); + } + + public void GoToPage(Type type, bool noUpdateHistory = false) + { + type.GetCustomAttributes(out ManualPageAttribute manualPageAttribute); + if (manualPageAttribute == null) + { + Debug.LogError($"Type {type.Name} is not a [ManualPage]"); + return; + } + + GoToPage(manualPageAttribute.Path, noUpdateHistory); + } + public void GoToPage(string path, bool noUpdateHistory = false) + { + if (!noUpdateHistory) + { + if (m_History.Count > 0 && m_HistoryPtr > -1 && m_HistoryPtr != m_History.Count - 1) + { + m_History.RemoveRange(m_HistoryPtr + 1, m_History.Count - m_HistoryPtr - 1); + } + + m_History.Add(path); + m_HistoryPtr = m_History.Count - 1; + } + + if (!m_PageClasses.TryGetValue(path, out Type pageType)) + { + EditorUtility.DisplayDialog("Invalid Page", $"Could not go to page with path '{path}' - maybe it was removed or moved?", "Oh no!"); + RemoveBookmark(path); + return; + } + + m_CurrentPage?.DeInit(); + { + m_CurrentNode = m_TreeRoot.FindEntryByPath_Recursive(path); + m_CurrentPage = (ManualPageBase)Activator.CreateInstance(pageType); + } + m_CurrentPage.Init(this); + + s_Path.Value = path; + m_PageScrollPos = Vector2.zero; + + ExpandHierarchy(path); + } + + private void OnGUI() + { + if (m_SelectedItemStyle == null) + { + Color lightBlue = new(0f, 0.6f, 1f); + m_SelectedItemStyle = new(EditorStyles.wordWrappedLabel) + { + fontStyle = FontStyle.Bold, + normal = { textColor = lightBlue }, + focused = { textColor = lightBlue }, + hover = { textColor = lightBlue } + }; + } + + DrawToolbar(); + + // Horizontal separator + GUILayout.Box(GUIContent.none, GUILayout.ExpandWidth(true), GUILayout.Height(2f)); + + GUILayout.BeginHorizontal(GUILayout.ExpandHeight(true)); + { + DrawTreeView(m_TreeViewWidth); + DrawDraggableSeparator(); + DrawContent(); + + DrawBookmarkOverlayButton(); + } + GUILayout.EndHorizontal(); + } + + private void DrawToolbar() + { + GUILayout.BeginHorizontal(); + { + EditorGUI.BeginDisabledGroup(m_HistoryPtr < 1); + { + if (GUILayout.Button("<", GUILayout.Width(20f))) + { + m_HistoryPtr--; + GoToPage(m_History[m_HistoryPtr], noUpdateHistory: true); + } + } + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(m_HistoryPtr >= m_History.Count - 1); + { + if (GUILayout.Button(">", GUILayout.Width(20f))) + { + m_HistoryPtr++; + GoToPage(m_History[m_HistoryPtr], noUpdateHistory: true); + } + } + EditorGUI.EndDisabledGroup(); + + EditorGUI.BeginDisabledGroup(m_CurrentNode?.PagePath.EqualsInvariant(s_HomePath.Value) ?? false); + { + if (GUILayout.Button("Home", GUILayout.Width(50f))) + { + m_History.Clear(); + m_HistoryPtr = -1; + + GoToPage(s_HomePath.Value); + } + } + EditorGUI.EndDisabledGroup(); + + // Bookmarks + GUILayout.Space(5f); + + string[] bookmarks = s_Bookmarks.Values; + Array.Sort(bookmarks, String.CompareOrdinal); + + if (bookmarks.Length > MAX_BOOKMARKS) + { + if (EditorGUILayout.DropdownButton(new("Bookmarks"), FocusType.Passive)) + { + GenericMenu menu = new(); + foreach (string bookmark in bookmarks) + { + menu.AddItem(new(bookmark), false, () => GoToPage(bookmark)); + } + + menu.ShowAsContext(); + } + } + else + { + foreach (string bookmark in bookmarks) + { + EditorGUI.BeginDisabledGroup(s_Path.Value.EqualsInvariant(bookmark)); + { + if (GUILayout.Button(new GUIContent(Path.GetFileName(bookmark)), EditorStyles.miniButton)) + { + GoToPage(bookmark); + } + } + EditorGUI.EndDisabledGroup(); + } + } + + // GUI.color = Color.gray; + // GUILayout.Label($"Path: {m_CurrentNode?.PagePath ?? ""}"); + // GUI.color = Color.white; + + + + GUILayout.FlexibleSpace(); + + GUILayout.Label($"Scale: {ManualStyles.Scale*100f:F0}%"); + + float rawValue = GUILayout.HorizontalSlider(ManualStyles.Scale, 0.7f, 1.3f, GUILayout.Width(200f)); + ManualStyles.Scale = Mathf.FloorToInt(rawValue * 10f) / 10f; + + EditorGUI.BeginDisabledGroup(ManualStyles.Scale == 1f); + { + if (GUILayout.Button(new GUIContent("x", "Reset Zoom"))) + { + ManualStyles.Scale = 1f; + } + } + EditorGUI.EndDisabledGroup(); + } + GUILayout.EndHorizontal(); + } + + private void DrawTreeView(float width) + { + // Tree view + m_ListScrollPos = GUILayout.BeginScrollView(m_ListScrollPos, GUILayout.Width(width)); + { + DrawHierarchy_Recursive(m_TreeRoot, isRoot: true); + } + GUILayout.EndScrollView(); + } + + private void DrawDraggableSeparator() + { + GUILayout.Box(GUIContent.none, GUILayout.Width(4f), GUILayout.ExpandHeight(true)); + + Rect resizeHandleRect = GUILayoutUtility.GetLastRect(); + EditorGUIUtility.AddCursorRect(resizeHandleRect, MouseCursor.ResizeHorizontal); + + if (resizeHandleRect.Contains(Event.current.mousePosition)) + { + // Mouse down while over - start resizing + if (Event.current.type == EventType.MouseDown) + { + m_IsResizing = true; + Event.current.Use(); + } + } + + // Mouse up - no resizing + if (Event.current.type == EventType.MouseUp) + { + m_IsResizing = false; + } + + // If currently resizing, update the m_TreeViewWidth based on mouse movement + if (m_IsResizing && Event.current.type != EventType.Layout && Event.current.type != EventType.Repaint) + { + m_TreeViewWidth += Event.current.delta.x; + m_TreeViewWidth = Mathf.Clamp(m_TreeViewWidth, 10f, 500f); + + Event.current.Use(); + } + } + + private void DrawContent() + { + if (m_CurrentPage != null) + { + EditorGUILayoutUtil.Pad(10f, () => + { + m_PageScrollPos = GUILayout.BeginScrollView(m_PageScrollPos); + { + GUILayout.Label(m_CurrentNode.Title, ManualStyles.Styles.Title); + m_CurrentPage.Render(); + } + GUILayout.EndScrollView(); + }); + } + else + { + GUILayout.Label("Please select an item on the left!", EditorStyles.centeredGreyMiniLabel, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); + } + } + + private void DrawBookmarkOverlayButton() + { + // Bookmark overlay button + bool wasBookmarked = s_Bookmarks.Values.Contains(s_Path.Value); + + Rect buttonPosition = position; + buttonPosition.x = position.width - 32f - 30f; + buttonPosition.y = 26f; + buttonPosition.width = 32f; + buttonPosition.height = 32f; + + GUIContent bookmarkButton = wasBookmarked + ? new(ManualStyles.Styles.BookmarkIconOn, "Remove bookmark from this page") + : new(ManualStyles.Styles.BookmarkIconOff, "Bookmark this page"); + + if (GUI.Button(buttonPosition, bookmarkButton, ManualStyles.Styles.Text)) + { + SetBookmark(s_Path.Value, !wasBookmarked); + } + } + + private void ExpandHierarchy(string path) + { + int endSlice = path.Length; + + // While the path still has '/' in it... + while (endSlice != -1) + { + // Chop off after last slash (no-op on first run) + path = path.Substring(0, endSlice); + + // Open the child, find the parent for further chopping + EditorGUILayoutUtil.SetHeaderOpen(path, true); + endSlice = path.LastIndexOf('/'); + } + } + + private void SetBookmark(string path, bool on) + { + if (on) + { + AddBookmark(path); + } + else + { + RemoveBookmark(path); + } + } + private void AddBookmark(string path) + { + s_Bookmarks.Values = s_Bookmarks.Values.Append(path).ToArray(); + ShowNotification(new("Page bookmarked!")); + } + + private void RemoveBookmark(string path) + { + s_Bookmarks.Values = s_Bookmarks.Values.Where(p => p != path).ToArray(); + ShowNotification(new("Bookmark removed!")); + } + + + private void CreateHierarchy_Recursive(ManualEntry node, List path, ManualPageAttribute pageInfo) + { + if (path.Count == 0) + return; + + string newNodeTitle = path[0]; + path.RemoveAt(0); + + // Find existing parent, and go down that route + foreach (ManualEntry existingChild in node.Children) + { + if (existingChild.Title.EqualsInvariant(newNodeTitle)) + { + CreateHierarchy_Recursive(existingChild, path, pageInfo); + return; + } + } + + // Or... create a new one, and go down that route! + bool isLeaf = path.Count == 0; + + string newPagePath = isLeaf + ? pageInfo.Path + : (node.PagePath.IsNullOrEmpty() ? newNodeTitle : $"{node.PagePath}/{newNodeTitle}"); + + ManualEntry entry = new() + { + Title = isLeaf ? pageInfo.Title : newNodeTitle, + PagePath = newPagePath, + ShowInTree = pageInfo.ShowInTree + }; + node.Children.Add(entry); + + CreateHierarchy_Recursive(entry, path, pageInfo); + } + + private void SortHierarchy_Recursive(ManualEntry node, string homePath) + { + string[] sortOrderFirst = s_SortOrderFirst.Values; + string[] sortOrderLast = s_SortOrderLast.Values; + + node.Children.Sort((c1, c2) => + { + // Home path ALWAYS TOP + if (c1.PagePath != null && c1.PagePath.EqualsInvariant(homePath)) + return -1; + if (c2.PagePath != null && c2.PagePath.EqualsInvariant(homePath)) + return +1; + + // Specific FIRST sort order first? + int c1FirstSort = Array.IndexOf(sortOrderFirst, c1.Title); + int c2FirstSort = Array.IndexOf(sortOrderFirst, c2.Title); + + if (c1FirstSort != -1 || c2FirstSort != -1) + { + // One sorted, the other not - put sorted below + if (c1FirstSort == -1) + return +1; + + if (c2FirstSort == -1) + return -1; + + // Both last-sorted! + return c1FirstSort.CompareTo(c2FirstSort); + } + + // Specific LAST sort order first? + int c1LastSort = Array.IndexOf(sortOrderLast, c1.Title); + int c2LastSort = Array.IndexOf(sortOrderLast, c2.Title); + + if (c1LastSort != -1 || c2LastSort != -1) + { + // One sorted, the other not - put sorted below + if (c1LastSort == -1) + return -1; + + if (c2LastSort == -1) + return +1; + + // Both last-sorted! + return c1LastSort.CompareTo(c2LastSort); + } + + // Both no specific sort at all - check titles + return String.Compare(c1.Title, c2.Title, StringComparison.Ordinal); + + }); + + foreach (ManualEntry child in node.Children) + { + SortHierarchy_Recursive(child, homePath); + } + } + + private void DrawHierarchy_Recursive(ManualEntry entry, bool isRoot = false) + { + if (entry == null) + return; + + // It's a leaf! + if (entry.Children.Count == 0) + { + if (!entry.ShowInTree) + return; + + bool isCurrentPage = entry == m_CurrentNode; + + GUILayout.BeginHorizontal(); + + GUILayout.Space(26f); + + bool wasPressed = isCurrentPage + ? GUILayout.Button(entry.Title, m_SelectedItemStyle) + : GUILayout.Button(entry.Title, EditorStyles.wordWrappedLabel); + + GUILayout.EndHorizontal(); + + if (wasPressed) + { + GoToPage(entry.PagePath); + } + + GUILayout.Space(5f); + + return; + } + + if (isRoot) + { + foreach (ManualEntry child in entry.Children) + { + DrawHierarchy_Recursive(child); + } + } + else + { + EditorGUILayoutUtil.CollapsibleHeader(entry.Title, entry.PagePath, () => + { + GUILayout.Space(5f); + + foreach (ManualEntry child in entry.Children) + { + DrawHierarchy_Recursive(child); + } + }); + + if (!EditorGUILayoutUtil.IsHeaderOpen(entry.PagePath)) + { + GUILayout.Space(5f); + } + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/ManualWindow.cs.meta b/Assets/Tremble/Editor/Manual/ManualWindow.cs.meta new file mode 100644 index 0000000..aace8df --- /dev/null +++ b/Assets/Tremble/Editor/Manual/ManualWindow.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a65db7c4cc9e4ebc9badc668b140ddba +timeCreated: 1722960129 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/ManualWindow.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages.meta b/Assets/Tremble/Editor/Manual/Pages.meta new file mode 100644 index 0000000..6211e93 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b7fbbf7261684aa2b0a07ca9e9ec9ee1 +timeCreated: 1722960145 \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Advanced.meta b/Assets/Tremble/Editor/Manual/Pages/Advanced.meta new file mode 100644 index 0000000..9ad6d63 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Advanced.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4a10d864747e4870a69b944b49fb0f57 +timeCreated: 1723448980 \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Advanced/BaseClassesPage.cs b/Assets/Tremble/Editor/Manual/Pages/Advanced/BaseClassesPage.cs new file mode 100644 index 0000000..8777cac --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Advanced/BaseClassesPage.cs @@ -0,0 +1,90 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Advanced/Base Classes")] + public class BaseClassesPage : ManualPageBase + { + protected override void OnGUI() + { + Text( + "Sometimes, you want to use a field (or a set of fields) across multiple", + "prefabs, point entities, and brush entities. For example, imagine you have a 'team' system,", + "whereby different entities might be on a player 'team' or the enemy 'team'. Entities that", + "you may wish to give a 'team' in this case could be the player prefab, some enemy prefabs,", + "and some doors which can only be interacted with by things on the same 'team'." + ); + + Text( + $"In this case, you can create a C# interface derived from {nameof(ITrembleBaseClass)}, which", + "those entities or prefabs implement, in order to attach fields to all of", + "them at once." + ); + + Text("Here's how this might look for our 'teams' example:"); + + Code( + $"using {nameof(TinyGoose)}.{nameof(Tremble)};", + "", + "// Simple enum to denote which team an entity is on (or for).", + "public enum TeamType", + "{", + " Neutral,", + " Players,", + " Enemies,", + "}", + "", + "// Inherit your interface from ITrembleBaseClass in order to expose it to", + "// Tremble.", + $"public interface ITeam : {nameof(ITrembleBaseClass)}", + "{", + " public TeamType Team => TeamType.Neutral; //you must provide a default!", + "}" + ); + + Text("Now, attach the interface to your entities, like this:"); + + Code( + $"using {nameof(TinyGoose)}.{nameof(Tremble)};", + "", + $"[{FormatAttributeName(typeof(PrefabEntityAttribute))}]", + "public class Door : MonoBehaviour, ITeam", + "{", + "", + "}" + ); + + Text( + "In order to read the data set from this base class, you will need to implement", + "OnImportFromMapEntity. You can then store this data in a variable, or do whatever", + "else you need with it." + ); + + Code( + $"using {nameof(TinyGoose)}.{nameof(Tremble)};", + "", + $"[{FormatAttributeName(typeof(PrefabEntityAttribute))}]", + $"public class Door : MonoBehaviour, ITeam, {nameof(IOnImportFromMapEntity)}", + "{", + " // [SerializeField] so that Unity stores the result", + " [SerializeField] private TeamType m_Team; ", + " ", + " // We must implement this method and pull the data out manually", + $" public void OnImportFromMapEntity({nameof(MapBsp)} mapBsp, {nameof(BspEntity)} entity)", + " {", + " // Interestingly, because this is named `m_Team`, and our", + " // interface has `Team`, this would have been set", + " // automagically anyway. But it's better to be explicit!", + " m_Team = entity.GetBaseClassData(this, nameof(ITeam.Team));", + " Debug.Log($\"This door is usable by the {m_Team} team!\");", + " }", + "}" + ); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Advanced/BaseClassesPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Advanced/BaseClassesPage.cs.meta new file mode 100644 index 0000000..5e201f1 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Advanced/BaseClassesPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: c25e8e2e7f7a4efdbc9985c7232a2ed0 +timeCreated: 1723449065 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Advanced/BaseClassesPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Advanced/CustomTypesPage.cs b/Assets/Tremble/Editor/Manual/Pages/Advanced/CustomTypesPage.cs new file mode 100644 index 0000000..f94ec36 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Advanced/CustomTypesPage.cs @@ -0,0 +1,120 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Advanced/Custom Types")] + public class CustomTypesPage : ManualPageBase + { + protected override void OnGUI() + { + Text("Tremble also supports syncing custom data types from your maps."); + + Text("For example, imagine you have an enemy that has a random amount of", + "health, chosen between two values that you want to set in a map. You could of course add", + "two fields, like this:" + ); + CodeWithHeader("Individual fields sample", + "[SerializeField] private int m_MinHealth = 10;", + "[SerializeField] private int m_MaxHealth = 50;" + ); + + Text("However, you might prefer a single field of a custom type, something like this:"); + CodeWithHeader("Custom type sample", + "[SerializeField] private IntInRange m_HealthRange = new(10, 50);"); + + Text("To do this, first you need a custom type of course (well, you might already have one!)", + "- in our example something like this:"); + CodeWithHeader("IntInRange.cs", + "[Serializable]", + "public struct IntInRange", + "{", + " [SerializeField] public int Min;", + " [SerializeField] public int Max;", + "", + " public override string ToString() => $\"{Min}-{Max}\";", + "}"); + + Text("Now we have our class to store our data, we just need to tell Tremble how to read/write", + "this data from our map."); + + Text("To do this, we create a new class extending TrembleFieldConverter,", + "and add the [TrembleFieldConverter] attribute to it."); + + CodeWithHeader("IntInRangeFieldConverter.cs", + "[TrembleFieldConverter(typeof(IntInRange))]", + "public class IntInRangeFieldConverter : TrembleFieldConverter", + "{", + " ...", + "}"); + + Text("Next, you need to implement the AddFieldToFgd method which tells TrenchBroom how to", + "display your data. This can be as a string, an integer, a list of values, and more."); + + CodeWithHeader("AddFieldToFgd Method", + $"protected override void AddFieldToFgd({nameof(FgdClass)} entityClass, string fieldName, IntInRange defaultValue, MemberInfo target)", + "{", + " // Add a hint to the end of the description to show the format", + " string extraDescription = \" (format: \\\"2-4\\\")\";", + "", + " // Get the [Tooltip] attribute for this field, if it exists", + " target.GetCustomAttributes(out TooltipAttribute existingTooltip);", + " ", + " // Add a \"string\" field to the FGD class (it's not a float or boolean, for example)", + $" entityClass.AddField(new {nameof(FgdStringField)}", + " {", + " Name = fieldName,", + " DefaultValue = defaultValue.ToString(),", + " Description = (existingTooltip?.tooltip ?? $\"IntInRange {target.Name}\") + extraDescription", + " });", + "}"); + + Text("Finally, you need to implement the TryGetValueFromMap method which reads your custom data", + "from an entity in map. This is used when a map is parsed during import. You can read any data", + "from the 'entity' passed in, in any format. This example reads a string value, but you can", + "also read integers, floats, and others."); + + CodeWithHeader("TryGetValueFromMap Method", + "protected override bool TryGetValueFromMap(BspEntity entity, string key, MapProcessorBase mapProcessor, MemberInfo target, out IntInRange value)", + "{", + " // Try to read string value for our field", + " if (!entity.TryGetString(key, out string rangeIntValue))", + " {", + " value = default;", + " return false; // we could not convert the data", + " }", + "", + " // Now parse our range from the string value in the map.", + " // !! NOTE !!: This sample code performs no bounds checking and is", + " thus very unsafe. See IntInRangeFieldConverter.cs", + " in the Tremble Sample for a much better implementation!", + "", + " value.Min = int.Parse(rangeIntValue.Split(\"-\")[0]);", + " value.Max = int.Parse(rangeIntValue.Split(\"-\")[1]);", + " return true; // we succesfully converted the data", + "", + "}"); + + Text("And that's it! Now Tremble will be able to tell TrenchBroom how to display your custom", + "type, and it will be able to import it from maps without issue."); + + Text("Feel free to check out the real 'IntInRange.cs' and 'IntInRangeFieldConverter.cs' classes", + "in the Tremble Sample folder, or look in Tremble's FieldConverters folder to see all the", + "built-in field converters for things like Vector3s, strings, Materials, and more!"); + } + + private void Test(out MinMax mm) + { + mm.Min = 2; + mm.Max = 2; + } + } + + struct MinMax + { + public int Min; + public int Max; + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Advanced/CustomTypesPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Advanced/CustomTypesPage.cs.meta new file mode 100644 index 0000000..9cff57f --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Advanced/CustomTypesPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 88bb368f84f84983aa5e46dd6b28b70e +timeCreated: 1725216144 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Advanced/CustomTypesPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Advanced/MapProcessorPage.cs b/Assets/Tremble/Editor/Manual/Pages/Advanced/MapProcessorPage.cs new file mode 100644 index 0000000..ff13bbb --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Advanced/MapProcessorPage.cs @@ -0,0 +1,97 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Advanced/Map Processors")] + public class MapProcessorPage : ManualPageBase + { + protected override void OnGUI() + { + Text( + $"While {nameof(IOnImportFromMapEntity)} can cover a lot of bases for custom import logic,", + "sometimes you need to either:" + ); + + Bullet( + "look at the map as a whole - for example, to capture all", + "entities of a certain class into a list, and pass this to some system" + ); + + Bullet( + "or, you might want to use Editor-only functionality, which can be tricky", + "to write inside an OnImportFromMapEntity callback." + ); + + Text( + $"For this, you can create your own {nameof(MapProcessorBase)} subclass, and override the", + "functions you need." + ); + + Text( + "An example of this is provided in SampleMapProcessor.cs. The example finds all", + "the Sheep Spawners in the map, and logs their position. However in a real game", + "you might, for example, take the positions of these and write them into a", + "ScriptableObject which could be later used by a minimap system." + ); + + Text( + "Map Processors can either be set per-Map or in the Tremble Pipeline settings to affect every", + "map in your project."); + + Number("To set a per-Map processor, click your map file in the", + "Project tab, and ensure your map processor class(es) are set, like this:" + ); + + Image("T_Manual_MapProcessor"); + + Number("To set Map processors globally for your project, open the Pipeline settings."); + ActionBar_SingleAction("Open Pipeline Settings", () => + { + const string TREMBLE_PIPELINE_PATH = "Project/Tremble/4 Pipeline"; + SettingsService.OpenProjectSettings(TREMBLE_PIPELINE_PATH); + }); + + H1("Sample Map Processor"); + Foldout("Show Code", () => + { + Code( + $"using {nameof(TinyGoose)}.{nameof(Tremble)};", + "", + $"public class MyCoolMapProcessor : {nameof(MapProcessorBase)}", + "{", + $" public override void OnProcessingStarted({nameof(TrembleMapImportSettings)} context, GameObject root, {nameof(MapBsp)} mapBsp)", + " {", + " Debug.Log($\"Map processing started for {mapBsp.MapName}\");", + " }", + $" public override void OnProcessingCompleted({nameof(TrembleMapImportSettings)} context, GameObject root, {nameof(MapBsp)} mapBsp)", + " {", + " Debug.Log($\"Map processing completed for {mapBsp.MapName} - all entities spawned\");", + " }", + " ", + $" public override void ProcessWorldSpawnProperties({nameof(TrembleMapImportSettings)} context, {nameof(MapBsp)} mapBsp, {nameof(BspEntity)} entity, GameObject rootGameObject)", + " {", + " Debug.Log($\"Worldspawn created for {mapBsp.MapName} - map-wide properties can be read from 'entity'\");", + " }", + " ", + $" public override void ProcessPrefabEntity({nameof(TrembleMapImportSettings)} context, {nameof(MapBsp)} mapBsp, {nameof(BspEntity)} entity, GameObject prefab)", + " {", + " Debug.Log(\"Found a prefab!\");", + " }", + $" public override void ProcessBrushEntity({nameof(TrembleMapImportSettings)} context, {nameof(MapBsp)} mapBsp, {nameof(BspEntity)} entity, GameObject brush)", + " {", + " Debug.Log(\"Found a brush!\");", + " }", + $" public override void ProcessPointEntity({nameof(TrembleMapImportSettings)} context, {nameof(MapBsp)} mapBsp, {nameof(BspEntity)} entity, GameObject point)", + " {", + " Debug.Log(\"Found a point!\");", + " }", + "}"); + }); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Advanced/MapProcessorPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Advanced/MapProcessorPage.cs.meta new file mode 100644 index 0000000..334257a --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Advanced/MapProcessorPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 1a71f6a787fc471cbaabca9141e578fe +timeCreated: 1723449126 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Advanced/MapProcessorPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Advanced/OnImportFromMapEntityPage.cs b/Assets/Tremble/Editor/Manual/Pages/Advanced/OnImportFromMapEntityPage.cs new file mode 100644 index 0000000..a6e19ce --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Advanced/OnImportFromMapEntityPage.cs @@ -0,0 +1,58 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Advanced/Custom Logic with IOnImportFromMapEntity")] + public class OnImportFromMapEntityPage : ManualPageBase + { + protected override void OnGUI() + { + Text( + "Sometimes, the automated import which takes entity properties from TrenchBroom cannot", + "convert the entity fully, or you need to add custom processing logic to translate the", + "data afterwards." + ); + + Text( + "You can see an example of this in SheepSpawner.cs in the sample project.", + "In this case, we are importing a Point Entity with various properties,", + "but at runtime we set up a reference to a default prefab to spawn, if not set in TrenchBroom.", + $"So, by using this interface and handling OnImportFromMapEntity({nameof(MapBsp)} mapBsp, {nameof(BspEntity)} entity),", + "we can wire this up before the GameObject is saved into the imported map." + ); + + Text( + "You might also want to add extra components to a Brush entity - for example,", + "adding a Rigidbody:" + ); + + H1("Code sample"); + Code( + $"[{FormatAttributeName(typeof(BrushEntityAttribute))}(\"rigidbody\", category: \"misc\")]", + $"public class RigidbodyEntity : MonoBehaviour, {nameof(IOnImportFromMapEntity)}", + "{", + " // Customisable mass for the rigidbody - but 1kg by default", + " [SerializeField] private float m_Mass = 1f;", + " ", + " // Called after importing this entity into the map.", + $" public void OnImportFromMapEntity({nameof(MapBsp)} mapBsp, {nameof(BspEntity)} entity)", + " {", + " // Turn all colliders for this mesh convex (required for Rigidbodies)", + " foreach (MeshCollider meshCollider in gameObject.GetComponentsInChildren())", + " {", + " meshCollider.convex = true;", + " }", + " ", + " // Finally add the rigidbody to the entity, and set its mass.", + " Rigidbody rb = gameObject.AddComponent();", + " rb.mass = m_Mass;", + " }", +"}"); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Advanced/OnImportFromMapEntityPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Advanced/OnImportFromMapEntityPage.cs.meta new file mode 100644 index 0000000..dadb930 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Advanced/OnImportFromMapEntityPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 1e143c387f9646d18f3ac2ddbc84093d +timeCreated: 1723449090 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Advanced/OnImportFromMapEntityPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Advanced/PipelinePage.cs b/Assets/Tremble/Editor/Manual/Pages/Advanced/PipelinePage.cs new file mode 100644 index 0000000..c14faca --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Advanced/PipelinePage.cs @@ -0,0 +1,40 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Advanced/Pipeline")] + public class PipelinePage : ManualPageBase + { + protected override void OnGUI() + { + Text("When Tremble imports a map, it performs a number of processing steps on it."); + + Text( + "From the Pipeline settings, you can choose which steps to perform, and which", + "custom map processors (if any) you want to run. You can speed up import", + "by disabling any steps which your game does not use." + ); + + Text("The settings looks like this:"); + + Image("T_Manual_Pipeline"); + + Callout( + "Note that each step shows how long it took to run, the last time", + "a map was imported." + ); + + ActionBar_SingleAction("Open Pipeline Settings", () => + { + const string TREMBLE_PIPELINE_PATH = "Project/Tremble/4 Pipeline"; + SettingsService.OpenProjectSettings(TREMBLE_PIPELINE_PATH); + }); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Advanced/PipelinePage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Advanced/PipelinePage.cs.meta new file mode 100644 index 0000000..6d87c14 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Advanced/PipelinePage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 4185f010c3e840a9bff636ae5998e587 +timeCreated: 1728887902 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Advanced/PipelinePage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Advanced/RuntimeQueryingPage.cs b/Assets/Tremble/Editor/Manual/Pages/Advanced/RuntimeQueryingPage.cs new file mode 100644 index 0000000..b66e502 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Advanced/RuntimeQueryingPage.cs @@ -0,0 +1,73 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Advanced/Runtime Querying")] + public class RuntimeQueryingPage : ManualPageBase + { + protected override void OnGUI() + { + Text( + "At runtime, Tremble does not perform any logic and has zero overhead by design.", + "Almost all Tremble functionality only runs in the Editor. However, you may need to query", + "a loaded map to find certain objects at runtime." + ); + + Text( + "Of course, since entities are just MonoBehaviours, you can use Unity's functionality", + "(such as gameObject.GetComponentsInChildren()) to find all objects of a given type." + ); + + Text( + "However, if you want to find a specific instance of an entity in the map,", + "you can do the following:" + ); + + Number( + "Ensure the entity you want to find is marked with a unique", + $"{TrembleSyncSettings.Get().IdentityPropertyName} property in TrenchBroom. You can also have multiple", + $"objects with the same {TrembleSyncSettings.Get().IdentityPropertyName}, but when you query the map", + "you will then get a list of entities back." + ); + Indent(() => + { + Bullet( + "For example, in the worldspawn entity you could have a start_spawn field", + "which names a spawn point to start from. We'll set it to 'my_cool_spawnpoint'.", + $"Then, you give your spawn point entity in the world a {TrembleSyncSettings.Get().IdentityPropertyName}" + ,"field, with the value 'my_cool_spawnpoint'." + ); + }); + + Number( + $"Now, given a reference to the {nameof(MapDocument)} for your map (which is added to the root", + $"GameObject), you can query for your {TrembleSyncSettings.Get().IdentityPropertyName} with the Q() method." + ); + + Code( + "// Get the map document - assumes one map in the scene.", + "// You might store a reference somewhere to this instead.", + "", + $"{nameof(MapDocument)} map = GameObject.FindAnyObjectByType<{nameof(MapDocument)}>();", + "", + $"// 1. Find a single entity with this {TrembleSyncSettings.Get().IdentityPropertyName}", + "if (map.Q(\"my_cool_spawnpoint\", out SpawnPoint spawnPoint))", + "{", + " spawnPoint.DoAThing();", + "}", + "", + $"// 2. Find many entities with this {TrembleSyncSettings.Get().IdentityPropertyName}", + "if (map.Q(\"my_cool_spawnpoint\", out SpawnPoint[] spawnPoints))", + "{", + " foreach (SpawnPoint spawnPoint in spawnPoints)", + " {", + " spawnPoint.DoAThing();", + " }", + "}" + ); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Advanced/RuntimeQueryingPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Advanced/RuntimeQueryingPage.cs.meta new file mode 100644 index 0000000..16f99d4 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Advanced/RuntimeQueryingPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 7d23c1b332fc42a98456960d6ee4e7de +timeCreated: 1723448990 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Advanced/RuntimeQueryingPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Basics.meta b/Assets/Tremble/Editor/Manual/Pages/Basics.meta new file mode 100644 index 0000000..8b85e83 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Basics.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: cbb8db30e0c04bceaa04fcd01ce6d5c1 +timeCreated: 1723137362 \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Basics/CreateMapPage.cs b/Assets/Tremble/Editor/Manual/Pages/Basics/CreateMapPage.cs new file mode 100644 index 0000000..9615777 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Basics/CreateMapPage.cs @@ -0,0 +1,49 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Basics/Create Map", "Create your first map")] + public class CreateMapPage : ManualPageBase + { + protected override void OnGUI() + { + Number( + "In the project window, right-click and select 'Create' > 'Tremble Map'. Give your map a name,", + "then hit enter." + ); + + ActionBar_SingleAction("Create new map called 'Test' in Assets", () => + { + MapFileAsset mapFileAsset = MapFileAsset.CreateInstance(); + + AssetDatabase.CreateAsset(mapFileAsset, "Assets/MAP_Test.asset"); + AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); + }); + + Number( + "TrenchBroom will open the new map for you to edit, with your project's materials", + "available to use." + ); + + Number( + "Since you have not yet marked any Unity scripts as entities, you will not see any", + "in TrenchBroom yet and can only create worldspawn brushes for now. See", + "the 'Entities' section to get started!" + ); + ActionBar_SingleAction("Read about Entities", () => GoToPage(typeof(EntitiesOverviewPage))); + + Number("When you're ready, save the map and return to Unity."); + Number("You should see a prompt - click 'Yep!'. Your new map is added to your current Unity scene."); + + Image("T_Manual_CreateMap", width: 300f); + + Callout("If the prompt doesn't show, or you want to add it to another scene, manually drag your", + "new map file into the scene."); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Basics/CreateMapPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Basics/CreateMapPage.cs.meta new file mode 100644 index 0000000..d0975e7 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Basics/CreateMapPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 43b737fff371496b807982db7eb1e9ad +timeCreated: 1723137369 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Basics/CreateMapPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Basics/LiveUpdatePage.cs b/Assets/Tremble/Editor/Manual/Pages/Basics/LiveUpdatePage.cs new file mode 100644 index 0000000..129600c --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Basics/LiveUpdatePage.cs @@ -0,0 +1,105 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Basics/Live Update", "Using Live Update")] + public class LiveUpdatePage : ManualPageBase + { + private static readonly string[] REFRESH_MODES = { "Disabled", "Enabled", "Enabled Outside Playmode" }; + + protected override void OnGUI() + { + Experimental(); + + int autoRefreshMode = EditorPrefs.GetInt("kAutoRefreshMode"); + if (autoRefreshMode != 1) + { + Callout($"Your project uses Auto Refresh Mode: {REFRESH_MODES[autoRefreshMode]}. This", + $"will mean that Live Update will not function. Change it to {REFRESH_MODES[1]} to", + "use Live Update!"); + ActionBar_SingleAction("Enable Auto Refresh during playmode", () => EditorPrefs.SetInt("kAutoRefreshMode", 1)); + } + + Text( + "Tremble supports Live Editing - the act of editing a map while in Unity Editor's playmode.", + "All you need to do is save changes to your map file while the game is running in editor playmode.", + "The map is imported as normal, and then Tremble will try to 'reinstance' the map in memory." + ); + + Foldout("Wait, what's reinstancing?", () => + { + Text("What this means is, Tremble will:"); + + Bullet("Destroy all worldspawn geometry, and copy the new geometry from the new map"); + Bullet("For entities:"); + Indent(() => + { + Bullet( + "If an entity is not present in the running game, spawn it (note: this may mean, for example,", + "that if you kill an enemy and then save the map, the enemy may get respawned)." + ); + Bullet( + "If an entity is present in the running game, but not in the map, it is removed", + "(this does not work in all cases!)" + ); + Bullet( + "If any entity properties have changed, and are simple properties", + "(floats, ints, Vector3s), these are updated." + ); + }); + }); + + H1("Handling Live Update logic"); + { + H2("General Usage"); + + Text( + "If you need to re-run some logic in an entity after it is LiveUpdated, you can implement", + $"the {nameof(IOnLiveUpdate)} interface, and override the OnLiveUpdate() method to perform any custom", + "logic." + ); + + Text( + "For example, finding the list of entities of a certain type (as these may have", + "changed as a result of the map changing)." + ); + + Image("T_Manual_LiveUpdate1"); + + H2("Simpler Usage"); + + Text( + "If this logic is identical to what would usually happen in your Start or Awake methods,", + $"you can instead implement the {nameof(IOnLiveUpdate_Simple)} interface." + ); + + Text( + "This will signal to Tremble that after a LiveUpdate occurs, it should call OnDestroy,", + "followed by Awake and Start (in that order) on your entity. That way, as long as your", + "Awake/Start methods set your entity up, and OnDestroy removes any state, it will 'just work'!" + ); + + Image("T_Manual_LiveUpdate2"); + } + + H2("Warnings!"); + { + Text( + "If LiveUpdate goes wrong or breaks, your game may be left in a broken state.", + "To recover from this, you'll need to stop playmode, and start it again." + ); + + Callout( + "Known bug: Sometimes, after LiveUpdate has failed, the map is left in a broken state", + "outside of playmode too. This is a rare bug that I've only seen a handful of times.", + "Of course, if this occurs, simply re-import your map again after exiting playmode to fix it." + ); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Basics/LiveUpdatePage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Basics/LiveUpdatePage.cs.meta new file mode 100644 index 0000000..53a2f1e --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Basics/LiveUpdatePage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 5da16a3f20f7452f92a7f6ca768bb67b +timeCreated: 1723449031 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Basics/LiveUpdatePage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Basics/SettingsPage.cs b/Assets/Tremble/Editor/Manual/Pages/Basics/SettingsPage.cs new file mode 100644 index 0000000..2380664 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Basics/SettingsPage.cs @@ -0,0 +1,27 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Basics/Settings", "Tremble's Settings")] + public class SettingsPage : ManualPageBase + { + protected override void OnGUI() + { + Text( + "Tremble's default settings are designed to be suitable for most users, and most games.", + "If you're a bit more advanced, or just want to tweak various things - click ''Tools'' > ", + "''Tremble'' > ''Open Settings...'' in the Unity menu." + ); + + Text( + "Each tab shows settings for a different aspect of Tremble.", + "Help text is provided for each option." + ); + + ActionBar_SingleAction("Open Settings for me", TrembleEditorAPI.OpenSettings); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Basics/SettingsPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Basics/SettingsPage.cs.meta new file mode 100644 index 0000000..37e0551 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Basics/SettingsPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 00222940e88a45a3ac88a8fa87192328 +timeCreated: 1723137185 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Basics/SettingsPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Basics/SyncOverlayPage.cs b/Assets/Tremble/Editor/Manual/Pages/Basics/SyncOverlayPage.cs new file mode 100644 index 0000000..c5a8653 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Basics/SyncOverlayPage.cs @@ -0,0 +1,71 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Basics/Sync Toolbar")] + public class SyncOverlayPage : ManualPageBase + { + private bool m_ShowAlreadyHere; + + protected override void OnGUI() + { + Text( + "By default, Tremble adds a toolbar to your scene view to quickly sync settings to", + "TrenchBroom, or to (re)import your map." + ); + + Text( + "You can reopen it with \"Tools\" > \"Tremble\" > \"Show Sync Toolbar\" (Unity 2022+)", + "if you lose it, or by right-clicking on your scene tab and clicking \"Overlay Menu\"", + "(or hitting [`] on your keyboard) and selecting \"Tremble Sync\"."); + +#if UNITY_2022_1_OR_NEWER + ActionBar_SingleAction("Open the Sync Toolbar for me", () => SceneView.AddOverlayToActiveView(new TrembleSyncOverlay())); +#endif + + H1("Toolbar Buttons"); + Text("The sync toolbar looks like this:"); + ToolbarButtonDescription("T_TB_Import", "Re-import map(s) in current scene from TrenchBroom"); + ToolbarButtonDescription("T_TB_Sync", "Sync Unity prefabs and materials to TrenchBroom"); + ToolbarButtonDescription("T_TB_Config", "Open Tremble's Settings"); + ToolbarButtonDescription("T_TB_Manual", "Open the Tremble Manual (this!)"); + + ActionBar(() => + { + Action("Import", TrembleEditorAPI.ReimportCurrentMap); + Action("Sync", TrembleEditorAPI.SyncToTrenchBroom); + Action("Settings", TrembleEditorAPI.OpenSettings); + Action("Manual", () => m_ShowAlreadyHere = true); + }); + + if (m_ShowAlreadyHere) + { + Text("You silly! You're already in the manual!"); + } + } + + private void ToolbarButtonDescription(string textureName, string description) + { + GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); + { + Image(textureName, 30f, centred: false); + GUILayout.BeginVertical(); + { + GUILayout.Space(10f * ManualStyles.Scale); + GUILayout.Label(description, ManualStyles.Styles.Text); + } + GUILayout.EndVertical(); + GUILayout.FlexibleSpace(); + } + GUILayout.EndHorizontal(); + + SmallSpace(); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Basics/SyncOverlayPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Basics/SyncOverlayPage.cs.meta new file mode 100644 index 0000000..417862b --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Basics/SyncOverlayPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: b7dbe33a0d0446e381e8d0316f066317 +timeCreated: 1723117770 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Basics/SyncOverlayPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Debug.meta b/Assets/Tremble/Editor/Manual/Pages/Debug.meta new file mode 100644 index 0000000..c577d94 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Debug.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9d822fe9fde64471bed45f0c6381719e +timeCreated: 1726388519 \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Debug/DebugSanityCheckPage.cs b/Assets/Tremble/Editor/Manual/Pages/Debug/DebugSanityCheckPage.cs new file mode 100644 index 0000000..cce4ea5 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Debug/DebugSanityCheckPage.cs @@ -0,0 +1,181 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Debug/Sanity Check")] + public class DebugSanityCheckPage : ManualPageBase + { + private PrefabNameLookup m_PrefabNameLookup; + private MapTypeLookup m_MapTypeLookup; + + private readonly Dictionary m_TypeToMonoScript = new(); + + private int m_SelectedTabIdx = 0; + private readonly string[] m_TabNames = new[] { "Basics", "Entities" }; + + protected override void OnInit() + { + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + m_PrefabNameLookup = new(syncSettings); + m_MapTypeLookup = new(syncSettings); + } + + protected override void OnGUI() + { + Tabs(ref m_SelectedTabIdx, m_TabNames); + + switch (m_SelectedTabIdx) + { + case 0: + OnBasicsGUI(); + break; + case 1: + OnEntitiesGUI(); + break; + } + } + + private void OnBasicsGUI() + { + Text("This page will verify that Tremble is installed and working correctly!"); + + // TB? + bool trenchBroomInstalled = !TrenchBroomUtil.TrenchBroomPath.IsNullOrEmpty(); + CheckListItem("TrenchBroom installed and detected?", trenchBroomInstalled); + + if (!trenchBroomInstalled) + { + Callout("If TrenchBroom is installed, but not detected here, open it", + "and Tremble should detect its location!"); + } + + // Installed game into TB? + bool gameFolderExists = Directory.Exists(TrenchBroomUtil.GetGameFolder()); + CheckListItem("TrenchBroom game folder exists?", gameFolderExists, "Sync to create it!", TrembleEditorAPI.SyncToTrenchBroom); + + bool gameInstalledInTBPrefs = TrenchBroomUtil.DoesEnginePathExistInTrenchBroomPrefs(); + CheckListItem("TrenchBroom knows game location?", gameInstalledInTBPrefs, "Sync to create it!", TrembleEditorAPI.SyncToTrenchBroom); + + // BaseQ3 folder + bool baseQ3FolderExists = Directory.Exists(TrembleConsts.BASEQ3_PATH); + CheckListItem("BaseQ3 folder exists in Library?", baseQ3FolderExists, "Sync to create it!", TrembleEditorAPI.SyncToTrenchBroom); + + // DLL loaded? + bool dllIsLoaded = Q3Map2Dll.IsLoaded; + CheckListItem("Q3Map2 DLL loaded successfully?", dllIsLoaded); + } + + private void OnEntitiesGUI() + { + Foldout("Prefab Entities", () => + { + Text("The following are the prefabs that Tremble knows about:"); + + EditorGUI.BeginDisabledGroup(true); + { + foreach (string prefabPath in m_PrefabNameLookup.AllPrefabPaths) + { + GameObject prefab = AssetDatabase.LoadAssetAtPath(prefabPath); + + m_PrefabNameLookup.TryGetMapNameFromPrefabPath(prefabPath, out string mapName); + + GUILayout.BeginHorizontal(); + { + EditorGUILayout.PrefixLabel(mapName); + EditorGUILayout.ObjectField(prefab, typeof(GameObject), false); + } + GUILayout.EndHorizontal(); + } + } + EditorGUI.EndDisabledGroup(); + }); + + Foldout("Point Entities", () => + { + Text("The following are the [PointEntity] MonoBehaviours that Tremble knows about:"); + + bool wasAnyPresent = false; + + foreach (Type type in m_MapTypeLookup.AllTypes) + { + if (!m_MapTypeLookup.TryGetMapNameFromClass(type, out string mapName)) + { + Text($"Invalid: '{type.Name}' - no map name known!"); + continue; + } + + if (!m_MapTypeLookup.TryGetEntityTypeFromMapName(mapName, out EntityType entityType) || entityType != EntityType.Point) + continue; + + DisabledTypeField(type, mapName); + wasAnyPresent = true; + } + + if (!wasAnyPresent) + { + Text("There are none (which might be fine)!"); + } + }); + + Foldout("Brush Entities", () => + { + Text("The following are the [BrushEntity] MonoBehaviours that Tremble knows about:"); + bool wasAnyPresent = false; + + foreach (Type type in m_MapTypeLookup.AllTypes) + { + if (!m_MapTypeLookup.TryGetMapNameFromClass(type, out string mapName)) + { + Text($"Invalid: '{type.Name}' - no map name known!"); + continue; + } + + if (!m_MapTypeLookup.TryGetEntityTypeFromMapName(mapName, out EntityType entityType) || entityType != EntityType.Brush) + continue; + + DisabledTypeField(type, mapName); + wasAnyPresent = true; + } + + if (!wasAnyPresent) + { + Text("There are none (which might be fine)!"); + } + }); + } + + private void DisabledTypeField(Type type, string label) + { + EditorGUI.BeginDisabledGroup(true); + { + if (!m_TypeToMonoScript.TryGetValue(type, out MonoScript monoScript)) + { + GameObject go = new("Tester"); + MonoBehaviour mb = (MonoBehaviour)go.AddComponent(type); + monoScript = MonoScript.FromMonoBehaviour(mb); + m_TypeToMonoScript[type] = monoScript; + + GameObject.DestroyImmediate(go); + } + + GUILayout.BeginHorizontal(); + { + EditorGUILayout.PrefixLabel(label); + EditorGUILayout.ObjectField(monoScript, typeof(MonoScript), false); + } + GUILayout.EndHorizontal(); + } + EditorGUI.EndDisabledGroup(); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Debug/DebugSanityCheckPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Debug/DebugSanityCheckPage.cs.meta new file mode 100644 index 0000000..b9ba7e6 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Debug/DebugSanityCheckPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a7c8885112604038b963d644ebbb4ead +timeCreated: 1726483054 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Debug/DebugSanityCheckPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Debug/DebugShowEntitiesPage.cs b/Assets/Tremble/Editor/Manual/Pages/Debug/DebugShowEntitiesPage.cs new file mode 100644 index 0000000..08b3ede --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Debug/DebugShowEntitiesPage.cs @@ -0,0 +1,68 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; +using System.Linq; +using System.Text; +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Debug/Entity Explorer")] + public class DebugShowEntitiesPage : ManualPageBase + { + private FgdWriter m_FgdWriter; + + private string[] m_ClassList; + private int m_SelectedClassIdx = 0; + + protected override void OnInit() + { + m_FgdWriter = TrembleSync.GatherEntities(); + + m_ClassList = m_FgdWriter.BaseClasses + .Select(bc => $"@BaseClass {bc.Name}") + .Concat(m_FgdWriter.Classes.Select(c => $"@{c.Type}Class {c.Name}")) + .Prepend("(select a class...)") + .ToArray(); + } + + protected override void OnGUI() + { + m_SelectedClassIdx = EditorGUILayout.Popup(m_SelectedClassIdx, m_ClassList); + + int selectedClassIdx = m_SelectedClassIdx - 1; + if (selectedClassIdx < 0) + { + Text("Select a class above to see its entity definition!"); + return; + } + + FgdClass entityClass = (selectedClassIdx < m_FgdWriter.BaseClasses.Count) + ? m_FgdWriter.BaseClasses[selectedClassIdx] + : m_FgdWriter.Classes[selectedClassIdx - m_FgdWriter.BaseClasses.Count]; + + MemoryStream memoryStream = new(); + + // Write to memory + using StreamWriter writer = new(memoryStream, Encoding.ASCII); + entityClass.WriteFgd(writer, TrembleSyncSettings.Get().ImportScale); + writer.Flush(); + + // Rewind and read + memoryStream.Position = 0; + using StreamReader reader = new(memoryStream, Encoding.ASCII); + string snippet = reader.ReadToEnd().Replace("\t", " "); + + CodeWithHeader($"[{entityClass.Type}] {entityClass.Name}", snippet); + + Text("Above is how the entity is passed to TrenchBroom. If you're familiar with FGD files,", + "this will look very familiar! If not, you basically are looking to make sure the name", + "is what you would expect, and any fields that you wish to edit on entities of that", + "class are present."); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Debug/DebugShowEntitiesPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Debug/DebugShowEntitiesPage.cs.meta new file mode 100644 index 0000000..9cc4533 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Debug/DebugShowEntitiesPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 2dc49cc1fab340b8a6d97e6fbff9fe66 +timeCreated: 1726387089 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Debug/DebugShowEntitiesPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Debug/DebugShowMaterialsPage.cs b/Assets/Tremble/Editor/Manual/Pages/Debug/DebugShowMaterialsPage.cs new file mode 100644 index 0000000..d79d428 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Debug/DebugShowMaterialsPage.cs @@ -0,0 +1,112 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Debug/Material Explorer")] + public class DebugShowMaterialsPage : ManualPageBase + { + private readonly Dictionary> m_Textures = new(); + + protected override void OnInit() + { + int texSize = TrembleSyncSettings.Get().MaterialExportSize.ToIntSize(); + + string texturesPath = TrembleConsts.BASE_MATERIALS_PATH; + foreach (string dir in Directory.GetDirectories(texturesPath)) + { + string[] pngFiles = Directory.GetFiles(dir, "*.png"); + if (pngFiles.Length == 0) + continue; + + List textures = new(pngFiles.Length); + + foreach (string textureFile in pngFiles) + { + byte[] textureBytes = File.ReadAllBytes(textureFile); + + Texture2D texture = new(texSize, texSize); + texture.name = Path.GetFileNameWithoutExtension(textureFile); + texture.LoadImage(textureBytes); + + textures.Add(texture); + } + + m_Textures[Path.GetFileName(dir)] = textures; + } + } + + protected override void OnDeInit() + { + foreach (List textures in m_Textures.Values) + { + foreach (Texture texture in textures) + { + Texture.DestroyImmediate(texture); + } + } + + m_Textures.Clear(); + } + + protected override void OnGUI() + { + float thumbnailSize = 64f * ManualStyles.Scale; + float labelSize = thumbnailSize + 40f * ManualStyles.Scale; + int numWide = Mathf.Max(1, Mathf.FloorToInt(PageWidth / labelSize) - 2); + + foreach (string textureFolder in m_Textures.Keys) + { + H1(textureFolder); + { + int cell = 0; + GUILayout.BeginHorizontal(); + { + foreach (Texture texture in m_Textures[textureFolder]) + { + GUILayout.BeginVertical(); + { + GUILayout.BeginHorizontal(GUILayout.Width(labelSize)); + { + GUILayout.Space((labelSize - thumbnailSize) / 2f); + GUIContent content = new(texture, texture.name); + GUILayout.Box(content, GUILayout.Width(thumbnailSize), GUILayout.Height(thumbnailSize)); + } + GUILayout.EndHorizontal(); + + GUILayout.Label(texture.name, ManualStyles.Styles.CenteredGreyMiniLabel, GUILayout.Width(labelSize)); + } + GUILayout.EndVertical(); + + // New row? + if (++cell >= numWide) + { + cell = 0; + GUILayout.FlexibleSpace(); + + GUILayout.EndHorizontal(); + GUILayout.Space(1f); + GUILayout.BeginHorizontal(); + } + } + + if (cell <= numWide) + { + GUILayout.FlexibleSpace(); + } + } + GUILayout.EndHorizontal(); + } + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Debug/DebugShowMaterialsPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Debug/DebugShowMaterialsPage.cs.meta new file mode 100644 index 0000000..3a0326f --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Debug/DebugShowMaterialsPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: d1d737f97a4f45c193f15ac0551af98e +timeCreated: 1726390246 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Debug/DebugShowMaterialsPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities.meta b/Assets/Tremble/Editor/Manual/Pages/Entities.meta new file mode 100644 index 0000000..bce3d3b --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: efd666aa9a5c4579a55f666673349d69 +timeCreated: 1723201715 \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/BrushEntitiesPage.cs b/Assets/Tremble/Editor/Manual/Pages/Entities/BrushEntitiesPage.cs new file mode 100644 index 0000000..62c19b6 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/BrushEntitiesPage.cs @@ -0,0 +1,62 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Entities/Brush Entities")] + public class BrushEntitiesPage : ManualPageBase + { + protected override void OnGUI() + { + Text( + "Brush Entities are brushes (models/shapes) in the map, which you want to apply a", + "MonoBehaviour script to. For example, a moving platform whose shape you design in", + "your TrenchBroom. Or, a trigger box which kills players on entry (see below)."); + + Image("T_Manual_BrushEntity"); + + Text("The following properties are available:"); + + PropertyDescription("name", + "The name of the entity in TrenchBroom.", + "If omitted, we convert your MonoBehaviour name according to your Naming Convention in settings." + ); + + PropertyDescription("category", + "The menu category to show the entity under, for example 'solid'.", + $"If omitted, we use the default prefix, '{FgdConsts.BRUSH_PREFIX}'." + ); + + PropertyDescription("type", + "Which brush type to use, which defines how the brush appears and how its collision", + "functions." + ); + + Foldout("Available Brush Types", () => + { + PropertyDescription("Solid", + "A Solid brush with a texture.", + "Example: a moving platform."); + PropertyDescription("Liquid", + "A brush with a texture, but with a trigger collision instead of a solid one.", + "Example: a volume of water/lava, which damages players when entering."); + PropertyDescription("Trigger", + "A completely invisible brush which has a trigger collision.", + "Example: a volume which triggers an event when players walk into the area."); + PropertyDescription("Invisible", + "A completely invisible brush which has solid collision.", + "Example: an invisible wall to stop players going out of bounds."); + }); + + H1("Brush Entity Wizard"); + Text( + "Tremble can guide you through creating the correct attribute code for your entity,", + "to help you get up and running quickly." + ); + + ActionBar_SingleAction("Build Brush Entity", () => GoToPage(typeof(BrushBuilderPage))); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/BrushEntitiesPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Entities/BrushEntitiesPage.cs.meta new file mode 100644 index 0000000..f5c632c --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/BrushEntitiesPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 468269cf35e449789a6062b8bcf8066f +timeCreated: 1723201757 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Entities/BrushEntitiesPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/BuilderPageBase.cs b/Assets/Tremble/Editor/Manual/Pages/Entities/BuilderPageBase.cs new file mode 100644 index 0000000..4f626f1 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/BuilderPageBase.cs @@ -0,0 +1,94 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Diagnostics.Eventing.Reader; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public abstract class BuilderPageBase : ManualPageBase + where TDataClass : ScriptableObject + { + private TDataClass m_Sample; + private SerializedObject m_SampleSO; + private TrembleSyncSettings m_SyncSettings; + + protected virtual bool HasInitialQuestions { get; } = false; + + private bool m_DoneInitialQuestions = false; + + protected TDataClass Sample => m_Sample; + protected SerializedObject SampleSO => m_SampleSO; + protected TrembleSyncSettings SyncSettings => m_SyncSettings; + + protected override void OnInit() + { + m_Sample = ScriptableObject.CreateInstance(); + m_SampleSO = new(m_Sample); + + m_SyncSettings = TrembleSyncSettings.Get(); + } + + protected sealed override void OnGUI() + { + if (HasInitialQuestions && !m_DoneInitialQuestions) + { + OnInitialQuestionsGUI(); + return; + } + + OnPrePropertiesGUI(); + m_SampleSO.Update(); + { + OnPropertiesGUI(); + } + m_SampleSO.ApplyModifiedPropertiesWithoutUndo(); + OnPostPropertiesGUI(); + } + + protected virtual void OnInitialQuestionsGUI() { } + protected virtual void OnPrePropertiesGUI() { } + protected virtual void OnPropertiesGUI() { } + protected virtual void OnPostPropertiesGUI() { } + + protected void MarkInitialQuestionsDone() => m_DoneInitialQuestions = true; + + protected bool RenderProperty(string propName, string title, string description, Type objectReferenceType = null, Action extraContent = null) + { + SerializedProperty prop = m_SampleSO.FindProperty(propName); + uint hash = prop.GetHashOfContent(); + + GUILayout.BeginVertical(EditorStyles.helpBox); + { + if (prop.propertyType == SerializedPropertyType.ObjectReference) + { + GUILayout.BeginHorizontal(); + { + EditorGUILayout.PrefixLabel(new GUIContent(title)); + prop.objectReferenceValue = EditorGUILayout.ObjectField(prop.objectReferenceValue, objectReferenceType ?? typeof(GameObject), allowSceneObjects: false); + } + GUILayout.EndVertical(); + + m_SampleSO.ApplyModifiedProperties(); + } + else + { + EditorGUILayout.PropertyField(prop, new GUIContent(title)); + } + + GUILayout.Label(description, ManualStyles.Styles.Text); + + extraContent?.Invoke(); + } + GUILayout.EndVertical(); + + GUILayout.Space(5f); + + return hash != prop.GetHashOfContent(); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/BuilderPageBase.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Entities/BuilderPageBase.cs.meta new file mode 100644 index 0000000..7e1468c --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/BuilderPageBase.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 41ce3b3d48ed40cbbf56dd2e637d5e9e +timeCreated: 1723225850 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Entities/BuilderPageBase.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/Builders.meta b/Assets/Tremble/Editor/Manual/Pages/Entities/Builders.meta new file mode 100644 index 0000000..923e0cc --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/Builders.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3f14b29b54b344b7b0aa40f206a78b41 +timeCreated: 1723226299 \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/BrushBuilderPage.cs b/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/BrushBuilderPage.cs new file mode 100644 index 0000000..b6a760f --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/BrushBuilderPage.cs @@ -0,0 +1,158 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Entities/Brush Entity Builder", showInTree: false)] + public class BrushBuilderPage : BuilderPageBase + { + public class SampleData : ScriptableObject + { + [SerializeField] internal string m_UnityName = "MyCoolBrush"; + [SerializeField] internal string m_MapName = ""; + [SerializeField] internal string m_Category = ""; + [SerializeField] internal BrushType m_Type = BrushType.Solid; + } + + protected override void OnPropertiesGUI() + { + RenderProperty(nameof(SampleData.m_UnityName), + title: "MonoBehaviour Name", + description: "The name of the main MonoBehaviour script for your brush entity."); + + RenderProperty(nameof(SampleData.m_MapName), + title: "TrenchBroom name", + description: "(optional) The entity name to use in TrenchBroom. Leave this blank to use the default."); + + RenderProperty(nameof(SampleData.m_Category), + title: "Category Name", + description: "(optional) The category/group name to use in TrenchBroom. Leave this blank to use the default."); + + RenderProperty(nameof(SampleData.m_Type), + title: "Brush Type", + description: "The brush type to use. Defaults to 'Solid'.", + extraContent: () => + { + Foldout("Available Brush Types", () => + { + PropertyDescription("Solid", + "A Solid brush with a texture.", + "Example: a moving platform."); + PropertyDescription("Liquid", + "A brush with a texture, but with a trigger collision instead of a solid one.", + "Example: a volume of water/lava, which damages players when entering."); + PropertyDescription("Trigger", + "A completely invisible brush which has a trigger collision.", + "Example: a volume which triggers an event when players walk into the area."); + PropertyDescription("Invisible", + "A completely invisible brush which has solid collision.", + "Example: an invisible wall to stop players going out of bounds."); + }); + }); + } + + protected override void OnPostPropertiesGUI() + { + List attributeParts = new(16); + + if (!Sample.m_MapName.IsNullOrEmpty()) + { + attributeParts.Add($"\"{Sample.m_MapName}\""); + } + + if (!Sample.m_Category.IsNullOrEmpty()) + { + attributeParts.Add($"category: \"{Sample.m_Category}\""); + } + + if (Sample.m_Type != BrushType.Solid) + { + attributeParts.Add($"type: {nameof(BrushType)}.{Sample.m_Type}"); + } + + string attrName = FormatAttributeName(typeof(BrushEntityAttribute)); + string attributeLine = attributeParts.Count == 0 + ? $"[{attrName}]" + : $"[{attrName}({String.Join(", ", attributeParts)})]"; + + string unityName = Sample.m_UnityName.IsNullOrEmpty() + ? "" + : Sample.m_UnityName; + + string catName = Sample.m_Category.IsNullOrEmpty() ? FgdConsts.BRUSH_PREFIX : Sample.m_Category; + string entName = Sample.m_MapName.IsNullOrEmpty() ? Sample.m_UnityName.ToNamingConvention(SyncSettings.TypeNamingConvention) : Sample.m_MapName; + + HorizontalLine(); + + GUILayout.BeginHorizontal(); + { + GUILayout.BeginVertical(); + { + H3("Create New Entity"); + + string code = + "// Generated by Tremble v1.7.0\n" + + $"// Brush entity '{catName}_{entName}'\n" + + "\n" + + "using UnityEngine;\n" + + $"using {nameof(TinyGoose)}.{nameof(Tremble)};\n" + + "\n" + + attributeLine + "\n" + + $"public class {unityName} : MonoBehaviour\n" + + "{\n" + + " // Your cool class here ;)\n" + + "}"; + + CodeWithHeaderNoCopy($"Full source for {unityName}.cs", code); + + ActionBar_SingleAction("Save to new MonoBehaviour class", () => + { + string assetsFolder = Path.Combine(Directory.GetCurrentDirectory(), "Assets"); + + string filename = EditorUtility.SaveFilePanel($"Choose where to save {unityName}", assetsFolder, $"{unityName}.cs", "cs"); + if (!filename.IsNullOrEmpty()) + { + File.WriteAllText(filename, code); + EditorCompileUtil.CompileThen(typeof(BrushBuilderPage), nameof(OnPostCompile)); + } + }); + } + GUILayout.EndVertical(); + + GUILayout.Label("-or-", EditorStyles.centeredGreyMiniLabel, GUILayout.ExpandHeight(true)); + + GUILayout.BeginVertical(); + { + H3("Add to existing MonoBehaviour"); + CodeWithHeaderNoCopy("Attribute line only (for existing MonoBehaviour)", attributeLine); + ActionBar_SingleAction("Copy to clipboard", () => EditorGUIUtility.systemCopyBuffer = attributeLine); + } + GUILayout.EndVertical(); + + } + GUILayout.EndHorizontal(); + } + + private static void OnPostCompile() + { + string message = TrenchBroomUtil.IsTrenchBroomRunning + ? "Be sure to press F6 in TrenchBroom to reload entity definitions, so that your new entity appears!" + : "All done!"; + EditorUtility.DisplayDialog("MonoBehaviour created!", message, "Great!"); + + ManualWindow mw = EditorWindow.GetWindow(); + if (mw) + { + mw.GoToPage(typeof(BrushEntitiesPage)); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/BrushBuilderPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/BrushBuilderPage.cs.meta new file mode 100644 index 0000000..d37de9e --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/BrushBuilderPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a19bc95fc7d74231b15345de8d617a86 +timeCreated: 1723368005 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Entities/Builders/BrushBuilderPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/PointBuilderPage.cs b/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/PointBuilderPage.cs new file mode 100644 index 0000000..991f1e6 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/PointBuilderPage.cs @@ -0,0 +1,163 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Entities/Point Entity Builder", showInTree: false)] + public class PointBuilderPage : BuilderPageBase + { + public class SampleData : ScriptableObject + { + [SerializeField] internal string m_UnityName = "MyCoolPoint"; + [SerializeField] internal string m_MapName = ""; + [SerializeField] internal string m_Category = ""; + [SerializeField] internal Color m_Colour = Color.white; + [SerializeField] internal float m_Size = 0.25f; + [SerializeField] internal Texture2D m_Sprite; + } + + protected override void OnPropertiesGUI() + { + RenderProperty(nameof(SampleData.m_UnityName), + title: "MonoBehaviour Name", + description: "The name of the main MonoBehaviour script of your point entity."); + + RenderProperty(nameof(SampleData.m_MapName), + title: "TrenchBroom name", + description: "(optional) The entity name to use in TrenchBroom. Leave this blank to use the default."); + + RenderProperty(nameof(SampleData.m_Category), + title: "Category Name", + description: "(optional) The category/group name to use in TrenchBroom. Leave this blank to use the default."); + + RenderProperty(nameof(SampleData.m_Colour), + title: "Preview Colour", + description: "The colour of preview cube to represent this Point entity in TrenchBroom."); + + RenderProperty(nameof(SampleData.m_Size), + title: "Preview Size", + description: "The size of preview cube to represent this Point entity in TrenchBroom."); + + RenderProperty(nameof(SampleData.m_Sprite), + title: "Preview Sprite", + description: "(optional) A sprite to use to represent this Point entity in TrenchBroom.", + objectReferenceType: typeof(Texture2D)); + } + + protected override void OnPostPropertiesGUI() + { + List attributeParts = new(16); + + if (!Sample.m_MapName.IsNullOrEmpty()) + { + attributeParts.Add($"\"{Sample.m_MapName}\""); + } + + if (!Sample.m_Category.IsNullOrEmpty()) + { + attributeParts.Add($"category: \"{Sample.m_Category}\""); + } + + if (Sample.m_Sprite) + { + attributeParts.Add($"sprite: \"{Sample.m_Sprite.name}\""); + } + else + { + if (Sample.m_Colour != Color.white) + { + attributeParts.Add($"colour: \"{Sample.m_Colour.ToStringInvariant()}\""); + } + + if (Sample.m_Size != 0.25f) + { + attributeParts.Add($"size: {Sample.m_Size}"); + } + } + + string attrName = FormatAttributeName(typeof(PointEntityAttribute)); + + string attributeLine = attributeParts.Count == 0 + ? $"[{attrName}]" + : $"[{attrName}({String.Join(", ", attributeParts)})]"; + + string unityName = Sample.m_UnityName.IsNullOrEmpty() + ? "" + : Sample.m_UnityName; + + string catName = Sample.m_Category.IsNullOrEmpty() ? FgdConsts.POINT_PREFIX : Sample.m_Category; + string entName = Sample.m_MapName.IsNullOrEmpty() ? Sample.m_UnityName.ToNamingConvention(SyncSettings.TypeNamingConvention) : Sample.m_MapName; + HorizontalLine(); + + GUILayout.BeginHorizontal(); + { + GUILayout.BeginVertical(); + { + H3("Create New Entity"); + + string code = + "// Generated by Tremble v1.7.0\n" + + $"// Point entity '{catName}_{entName}'\n" + + "\n" + + "using UnityEngine;\n" + + $"using {nameof(TinyGoose)}.{nameof(Tremble)};\n" + + "\n" + + attributeLine + "\n" + + $"public class {unityName} : MonoBehaviour\n" + + "{\n" + + " // Your cool class here ;)\n" + + "}"; + + CodeWithHeaderNoCopy($"Full source for {unityName}.cs", code); + + ActionBar_SingleAction("Save to new MonoBehaviour class", () => + { + string assetsFolder = Path.Combine(Directory.GetCurrentDirectory(), "Assets"); + + string filename = EditorUtility.SaveFilePanel($"Choose where to save {unityName}", assetsFolder, $"{unityName}.cs", "cs"); + if (!filename.IsNullOrEmpty()) + { + File.WriteAllText(filename, code); + EditorCompileUtil.CompileThen(typeof(PointBuilderPage), nameof(OnPostCompile)); + } + }); + } + GUILayout.EndVertical(); + + GUILayout.Label("-or-", EditorStyles.centeredGreyMiniLabel, GUILayout.ExpandHeight(true)); + + GUILayout.BeginVertical(); + { + H3("Add to existing MonoBehaviour"); + CodeWithHeaderNoCopy("Attribute line only (for existing MonoBehaviour)", attributeLine); + ActionBar_SingleAction("Copy to clipboard", () => EditorGUIUtility.systemCopyBuffer = attributeLine); + } + GUILayout.EndVertical(); + + } + GUILayout.EndHorizontal(); + } + + private static void OnPostCompile() + { + string message = TrenchBroomUtil.IsTrenchBroomRunning + ? "Be sure to press F6 in TrenchBroom to reload entity definitions, so that your new entity appears!" + : "All done!"; + EditorUtility.DisplayDialog("MonoBehaviour created!", message, "Great!"); + + ManualWindow mw = EditorWindow.GetWindow(); + if (mw) + { + mw.GoToPage(typeof(PointEntitiesPage)); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/PointBuilderPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/PointBuilderPage.cs.meta new file mode 100644 index 0000000..a1bc276 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/PointBuilderPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: d7c600b3e6a34d8a86cdaab529cef411 +timeCreated: 1723368625 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Entities/Builders/PointBuilderPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/PrefabBuilderPage.cs b/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/PrefabBuilderPage.cs new file mode 100644 index 0000000..248631f --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/PrefabBuilderPage.cs @@ -0,0 +1,592 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Entities/Prefab Entity Builder", showInTree: false)] + public class PrefabBuilderPage : BuilderPageBase + { + private static readonly Dictionary s_ScriptFileLookup = new(); + + protected override bool HasInitialQuestions => true; + + private bool m_MonoBehaviourListDirty = false; + private readonly List m_CandidateTypes = new(); + + private readonly TrembleFieldConverterCollection m_FieldConverterCollection = new(); + + private Type m_UnityScriptType; + private string m_NewUnityScriptName; + private Action m_ResolutionAction; + + private bool m_IsOnlyAddingSpawnablePrefab = false; + + private bool m_IsAlreadyTrembleSpawnable = false; + private bool m_IsAlreadyPrefabEntity = false; + private bool m_IsMap = false; + + private bool IsNewScript => !m_NewUnityScriptName.IsNullOrEmpty(); + private string ScriptName => m_UnityScriptType?.Name ?? m_NewUnityScriptName; + + public class SampleData : ScriptableObject + { + [SerializeField] internal GameObject m_BasePrefab; + [SerializeField] internal bool m_WantsData; + + [SerializeField] internal string m_Category = ""; + [SerializeField] internal GameObject[] m_ExcludedPrefabs = Array.Empty(); + [SerializeField] internal GameObject[] m_IncludedPrefabs = Array.Empty(); + [SerializeField] internal bool m_OnlyVariants = false; + } + + protected override void OnInitialQuestionsGUI() + { + Text("Please select a prefab that you want to use in Tremble!"); + + m_MonoBehaviourListDirty = RenderProperty(nameof(SampleData.m_BasePrefab), + title: "Target Prefab", + description: "The prefab to use"); + + RenderProperty(nameof(SampleData.m_WantsData), + title: "I want to add data", + description: "Whether to allow setting fields on the prefab from TrenchBroom. e.g. "+ + "variables such as Health, Colour, etc?"); + + if (Sample.m_BasePrefab) + { + if (m_MonoBehaviourListDirty) + { + Type[] monoBehaviours = Sample.m_BasePrefab + .GetComponents() + .Select(m => m.GetType()) + .ToArray(); + + m_CandidateTypes.Clear(); + m_CandidateTypes.AddRange(monoBehaviours + .Where(t => t != typeof(TrembleSpawnablePrefab))); + + m_IsAlreadyTrembleSpawnable = monoBehaviours.Contains(typeof(TrembleSpawnablePrefab)); + m_IsMap = monoBehaviours.Contains(typeof(MapDocument)); + m_IsAlreadyPrefabEntity = !m_IsAlreadyTrembleSpawnable && monoBehaviours.Any(t => t.HasCustomAttribute()); + } + + if (m_IsMap) + { + Text("Ha! No, that's a map prefab. We better not."); + } + else if (m_IsAlreadyPrefabEntity) + { + Text("Well, that's already spawnable in TrenchBroom. Try another prefab!"); + } + else if (m_CandidateTypes.Count == 0) + { + if (m_IsAlreadyTrembleSpawnable) + { + Callout("Note, this prefab already has a TrembleSpawnablePrefab component", + "allowing it to be spawned from TrenchBroom - but without field support.", + "Converting this to a PrefabEntity will remove the TrembleSpawnablePrefab component!"); + } + + if (m_IsAlreadyTrembleSpawnable) + { + if (Sample.m_WantsData) + { + Resolution("Create a new MonoBehaviour to use - this allows", + "you to add fields which can be set in TrenchBroom", + "- in order to be able to set data (i.e. Health, Type, etc)."); + ActionBar_SingleAction("Create New MonoBehaviour", () => + { + m_NewUnityScriptName = GetScriptNameFromPrefab(Sample.m_BasePrefab); + + if (Sample.m_BasePrefab.TryGetComponent(out TrembleSpawnablePrefab tsp)) + { + Sample.m_Category = tsp.Category; + Sample.m_OnlyVariants = tsp.OnlyVariants; + } + + SetResolution(Resolve_CreateNewClassAndAdd); + }); + } + else + { + Text("Well, that's already spawnable in TrenchBroom. Tick the box above", + "to add data using a [PrefabEntity]."); + } + } + else + { + if (Sample.m_WantsData) + { + Resolution("Create a new MonoBehaviour to use - this allows", + "you to add fields which can be set in TrenchBroom", + "- in order to be able to set data (i.e. Health, Type, etc)."); + ActionBar_SingleAction("Create New MonoBehaviour", () => + { + m_NewUnityScriptName = GetScriptNameFromPrefab(Sample.m_BasePrefab); + + if (Sample.m_BasePrefab.TryGetComponent(out TrembleSpawnablePrefab tsp)) + { + Sample.m_Category = tsp.Category; + Sample.m_OnlyVariants = tsp.OnlyVariants; + } + + SetResolution(Resolve_CreateNewClassAndAdd); + }); + } + else + { + Resolution("Add a 'TrembleSpawnablePrefab' component - this", + "only allows you to spawn this prefab without being able to", + "set any data on it."); + + ActionBar_SingleAction("Add TrembleSpawnablePrefab component", () => + { + m_IsOnlyAddingSpawnablePrefab = true; + SetResolution(Resolve_AddTrembleSpawnablePrefab); + }); + } + } + } + else if (m_IsAlreadyTrembleSpawnable) + { + // Already spawnable, but no candidates for [PrefabEntity] - make a new code class + if (Sample.m_WantsData) + { + Resolution("Upgrade to a [PrefabEntity] - this allows", + "you to add fields which can be set in TrenchBroom", + "- in order to be able to set data (i.e. Health, Type, etc)."); + + foreach (Type type in m_CandidateTypes) + { + Bullet(type.Name); + ActionBar_SingleAction($"Add [PrefabEntity] to {type.Name}", () => + { + m_UnityScriptType = type; + + if (Sample.m_BasePrefab.TryGetComponent(out TrembleSpawnablePrefab tsp)) + { + Sample.m_Category = tsp.Category; + Sample.m_OnlyVariants = tsp.OnlyVariants; + } + + SetResolution(Resolve_AddPrefabEntityAttribute); + }); + } + } + else + { + Text("This is already a TrembleSpawnablePrefab. Unless you want to add data,", + "you don't need to do anything!"); + } + } + else + { + if (Sample.m_WantsData) + { + if (m_CandidateTypes.Count == 1) + { + Type type = m_CandidateTypes[0]; + + Resolution($"You can add a [PrefabEntity] attribute to {type.Name} on this", + "prefab. This will enable setting the following fields:"); + + Indent(() => + { + foreach (string fieldName in GetFieldNames(type)) + { + Bullet(fieldName); + } + }); + + ActionBar_SingleAction($"Add [PrefabEntity]", () => + { + m_UnityScriptType = type; + SetResolution(Resolve_AddPrefabEntityAttribute); + }); + } + else + { + Resolution("This prefab has MonoBehaviours which can be set to be a", + "[PrefabEntity]. Select which one to add this attribute to."); + + foreach (Type type in m_CandidateTypes) + { + string[] fieldNames = GetFieldNames(type); + + string fields = (fieldNames is { Length: > 0 }) ? String.Join(", ", fieldNames) : "no fields"; + Bullet($"{type.Name} ({fields})"); + + ActionBar_SingleAction($"Add [PrefabEntity] to {type.Name}", () => + { + m_UnityScriptType = type; + SetResolution(Resolve_AddPrefabEntityAttribute); + }); + } + } + } + else + { + Resolution("Simply add a TrembleSpawnablePrefab component to it, which will", + "allow you to spawn the prefab in TrenchBroom, but not allow you to set any", + "data on it."); + ActionBar_SingleAction("Add TrembleSpawnablePrefab component", () => + { + m_IsOnlyAddingSpawnablePrefab = true; + SetResolution(Resolve_AddTrembleSpawnablePrefab); + }); + } + } + } + } + + private string[] GetFieldNames(Type type) + { + List soTypes= new(); + FgdClass dummyClass = new(FgdClassType.Point, type.Name, type.Name); + TrembleSync.AddExposedFieldsToEntity(type, dummyClass, m_FieldConverterCollection, soTypes); + + // Gather spawnflags + NamingConvention spawnFlagNaming = TrembleSyncSettings.Get().SpawnFlagNamingConvention; + + IEnumerable spawnFlagNames = dummyClass.AllSpawnFlags + .Select(f => + { + string name = f.FieldName.ToNamingConvention(spawnFlagNaming); + if (spawnFlagNaming == NamingConvention.HumanFriendly) + { + name += "?"; + } + + return $"{name} (Boolean)"; + }); + + return dummyClass.AllFields + .Select(f => $"{f.FieldName} ({f.FriendlyTypeName})") + .Concat(spawnFlagNames) + .ToArray(); + } + + protected override void OnPropertiesGUI() + { + H2("Optional Extras"); + + RenderProperty(nameof(SampleData.m_Category), + title: "Category Name", + description: "(optional) The category/group name to use in TrenchBroom. Leave this blank to use the default."); + + Foldout("(optional) Include/Exclude specific Prefabs?", () => + { + if (!m_IsOnlyAddingSpawnablePrefab) + { + Text("By default, any other prefabs containing your MonoBehaviour will be exported."); + Text("Instead, you can choose to explicitly whitelist prefab(s) here."); + Text("Or, you can choose to blacklist certain prefab(s) here."); + + RenderProperty(nameof(SampleData.m_IncludedPrefabs), + title: "Included Prefabs", + description: $"A whitelist of the ONLY prefab(s) to include, even though others may include your {ScriptName} MonoBehaviour?"); + + RenderProperty(nameof(SampleData.m_ExcludedPrefabs), + title: "Excluded Prefabs", + description: $"A blacklist of any prefab(s) to ignore, even though they include your {ScriptName} MonoBehaviour?"); + } + + RenderProperty(nameof(SampleData.m_OnlyVariants), + title: "Only Prefab Variants?", + description: "Whether to only export VARIANTS of the prefab(s) found?"); + }); + } + + protected override void OnPostPropertiesGUI() + { + string catName = Sample.m_Category.IsNullOrEmpty() ? FgdConsts.PREFAB_PREFIX : Sample.m_Category; + //string entName = Sample.m_UnityName.ToNamingConvention(SyncSettings.TypeNamingConvention); + string fullEntName = $"{catName}_{Sample.m_BasePrefab.name}"; + + if (m_IsOnlyAddingSpawnablePrefab) + { + H2("Tremble Spawnable Prefab Details"); + PropertyDescription("Prefab Name", labelWidth: 250f, Sample.m_BasePrefab.name); + PropertyDescription("Exported TrenchBroom Name", labelWidth: 250f, fullEntName); + } + else + { + H2("C# Code"); + Text($"This is the code that will be used for {Sample.m_BasePrefab.name} if you click Apply below. You don't need to copy", + "it manually (unless you want to!)"); + CodeWithHeader($"C# Script: {ScriptName}.cs (for TrenchBroom Prefab entity '{fullEntName}')", GenerateFullCodeSnippet()); + } + + Space(); + + GUI.color = Color.green; + LargeButton("Apply & Finish!", Resolve); + GUI.color = Color.white; + } + + private void Resolution(params string[] resolution) + { + HorizontalLine(); + + H1("Action to take"); + Text(resolution); + } + + private string GetAttributeLine() + { + List attributeParts = new(16); + + if (!Sample.m_Category.IsNullOrEmpty()) + { + attributeParts.Add($"category: \"{Sample.m_Category}\""); + } + + if (TryFormatPrefabNames("excludePrefab", Sample.m_ExcludedPrefabs, out string excludePart)) + { + attributeParts.Add(excludePart); + } + + if (TryFormatPrefabNames("includePrefab", Sample.m_IncludedPrefabs, out string includePart)) + { + attributeParts.Add(includePart); + } + + if (Sample.m_OnlyVariants) + { + attributeParts.Add("onlyVariants: true"); + } + + string attrName = FormatAttributeName(typeof(PrefabEntityAttribute)); + + return attributeParts.Count == 0 + ? $"[{attrName}]" + : $"[{attrName}({String.Join(", ", attributeParts)})]"; + } + + private string GenerateFullCodeSnippet() + { + return + "using UnityEngine;\n" + + $"using {nameof(TinyGoose)}.{nameof(Tremble)};\n" + + "\n" + + GetAttributeLine() + "\n" + + $"public class {ScriptName} : MonoBehaviour\n" + + "{\n" + + (IsNewScript ? $" // Your new {ScriptName} class contents ;)" : $" // (your existing {ScriptName} code)") + "\n" + + "}"; + } + + private bool TryFormatPrefabNames(string propertyName, GameObject[] prefabs, out string formatted) + { + GameObject[] filteredPrefabs = prefabs.Where(p => p).ToArray(); + + switch (filteredPrefabs.Length) + { + case 1: + formatted = $"{propertyName}: \"{filteredPrefabs[0].name}\""; + return true; + case > 1: + { + string prefabList = String.Join("\", \"", filteredPrefabs.Select(p => p.name)); + formatted = $"{propertyName}s: \"{prefabList}\""; + return true; + } + } + + formatted = default; + return false; + } + + private void SetResolution(Action resolutionAction) + { + m_ResolutionAction = resolutionAction; + MarkInitialQuestionsDone(); + } + + private void Resolve() + { + m_ResolutionAction.Invoke(); + GoToPage(typeof(PrefabEntitiesPage)); + } + + private void Resolve_AddTrembleSpawnablePrefab() + { + Sample.m_BasePrefab.AddComponent().Modify(so => + { + so.FindBackedProperty(nameof(TrembleSpawnablePrefab.OnlyVariants)).boolValue = Sample.m_OnlyVariants; + so.FindBackedProperty(nameof(TrembleSpawnablePrefab.Category)).stringValue = Sample.m_Category; + }); + + EditorUtility.SetDirty(Sample.m_BasePrefab); + AssetDatabase.SaveAssets(); + + EditorApplication.delayCall += TrembleEditorAPI.SyncToTrenchBroom; + + ShowCompleteDialog( + title: "TrembleSpawnablePrefab component added!", + message: $"{Sample.m_BasePrefab.name} now has a Tremble Spawnable Prefab component and should be available from TrenchBroom."); + } + + private void Resolve_CreateNewClassAndAdd() + { + // Write code and compile + string assetsFolder = Path.Combine(Directory.GetCurrentDirectory(), "Assets"); + + string scriptFilePath = EditorUtility.SaveFilePanel($"Choose where to save {ScriptName}", assetsFolder, $"{ScriptName}.cs", "cs"); + if (scriptFilePath.IsNullOrEmpty()) + return; + + File.WriteAllText(scriptFilePath, GenerateFullCodeSnippet()); + + EditorCompileUtil.CompileThen(typeof(PrefabBuilderPage), nameof(OnPostCompile_AddNewScript), + ScriptName, AssetDatabase.GetAssetPath(Sample.m_BasePrefab)); + } + + private void Resolve_AddPrefabEntityAttribute() + { + string scriptFileName = GetScriptFilename(m_UnityScriptType); + if (scriptFileName.IsNullOrEmpty()) + { + EditorUtility.DisplayDialog( + title: "Uh-oh!", + message: $"Tremble could not find the source file for {ScriptName}.", + "Oh no!"); + return; + } + + bool prefabEntityWasAdded = false; + bool usingWasAdded = false; + + string[] lines = File.ReadAllLines(scriptFileName); + List outLines = new(lines.Length+2); + foreach (string line in lines) + { + if (!usingWasAdded && !line.ContainsInvariant("using", caseSensitive: true)) + { + outLines.Add("using TinyGoose.Tremble;"); + usingWasAdded = true; + } + + if (line.ContainsInvariant($"class {ScriptName}", caseSensitive: true)) + { + prefabEntityWasAdded = true; + outLines.Add($"\t{GetAttributeLine()}"); + } + + outLines.Add(line); + } + + if (!prefabEntityWasAdded) + { + EditorUtility.DisplayDialog( + title: "Uh-oh!", + message: $"Tremble could not find the class {ScriptName} in the source file {Path.GetFileName(scriptFileName)}.", + "Oh no!"); + return; + } + + File.WriteAllLines(scriptFileName, outLines); + + EditorCompileUtil.CompileThen(typeof(PrefabBuilderPage), nameof(OnPostCompile_AddAttribute), ScriptName); + } + + private static string GetScriptNameFromPrefab(GameObject prefab) + { + string newName = prefab.name; + if (newName.StartsWithInvariant("P_", caseSensitive: true)) + return newName.Substring(2); + + StringBuilder finalName = new(newName.Length); + foreach (char c in newName) + { + if (c is '-') + { + // Swap characters + finalName.Append('_'); + } + else if (c is ' ') + { + // Omit characters + } + else + { + // Allowed characters + finalName.Append(c); + } + } + + return finalName.ToString(); + } + + private static string GetScriptFilename(Type monoBehaviourType) + { + if (s_ScriptFileLookup.TryGetValue(monoBehaviourType, out string existingPath)) + return existingPath; + + foreach (string path in AssetDatabase.GetAllAssetPaths()) + { + // Check if the file name matches exactly (without the full path) + if (Path.GetFileNameWithoutExtension(path).EqualsInvariant(monoBehaviourType.Name)) + { + s_ScriptFileLookup[monoBehaviourType] = path; + return path; + } + } + + return null; + } + + private static void ShowCompleteDialog(string title, string message) + { + if (TrenchBroomUtil.IsTrenchBroomRunning) + { + message += "\n\n Note: Press F6 inside TrenchBroom to refresh Entity Definitions for it to appear!"; + } + + EditorUtility.DisplayDialog(title, message, "Great!"); + } + + private static void OnPostCompile_AddAttribute(string scriptName) + { + TrembleEditorAPI.SyncToTrenchBroom(); + + ShowCompleteDialog( + title: "[PrefabEntity] attribute added!", + message: $"{scriptName} now has a [PrefabEntity] attribute and should be available from TrenchBroom."); + } + + private static void OnPostCompile_AddNewScript(string scriptName, string prefabPath) + { + GameObject prefab = AssetDatabase.LoadAssetAtPath(prefabPath); + + Type newComponentType = Unsupported.GetTypeFromFullName(scriptName); + prefab.AddComponent(newComponentType); + + foreach (TrembleSpawnablePrefab tsp in prefab.GetComponents()) + { + Component.DestroyImmediate(tsp, true); + } + + EditorUtility.SetDirty(prefab); + AssetDatabase.SaveAssets(); + + // Now sync + EditorApplication.delayCall += TrembleEditorAPI.SyncToTrenchBroom; + + // And tell the user! + ShowCompleteDialog( + title: "New Prefab Entity Created!", + message: $"{scriptName}.cs was created and attached to {prefab.name}, and should be available from TrenchBroom."); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/PrefabBuilderPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/PrefabBuilderPage.cs.meta new file mode 100644 index 0000000..ff2959f --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/Builders/PrefabBuilderPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 76e837b79b44474bb99e6e62f09d2af6 +timeCreated: 1723206660 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Entities/Builders/PrefabBuilderPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/EntitiesOverviewPage.cs b/Assets/Tremble/Editor/Manual/Pages/Entities/EntitiesOverviewPage.cs new file mode 100644 index 0000000..3da84e3 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/EntitiesOverviewPage.cs @@ -0,0 +1,49 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Entities/Overview")] + public class EntitiesOverviewPage : ManualPageBase + { + protected override void OnGUI() + { + Text( + "Entities are used to place objects (for example prefabs, trigger volumes, etc.)", + "into your map to make them more interactive." + ); + + Text("Tremble supports 3 kinds of Entities:"); + + Space(); + + PropertyDescription("Prefab Entities", + "These are 1:1 representations of your Unity prefabs, which can be dropped into a map.", + $"You can either use a '{nameof(TrembleSpawnablePrefab)}' component in your prefab to allow it to", + "be simply spawned from your map, or you can mark your scripts up with", + $"'[{FormatAttributeName(typeof(PrefabEntityAttribute))}]' to synchronise properties and more!"); + ActionBar(() => + { + Action("More about Spawnable Prefabs", () => GoToPage(typeof(SpawnablePrefabEntitiesPage))); + Action("More about Prefab Entities", () => GoToPage(typeof(PrefabEntitiesPage))); + }); + + Space(); + + PropertyDescription("Brush Entities", + "These are brushes (shapes/meshes) in the map, which you want to apply a MonoBehaviour script to.", + "These can be Solids - for example, a moving platform whose shape you design in TrenchBroom,", + "Triggers - for example an area which triggers an event, and more!"); + ActionBar_SingleAction("More about Brush Entities", () => GoToPage(typeof(BrushEntitiesPage))); + + Space(); + + PropertyDescription("Point Entities", + "These are points in space which contain data - for example a target location for spawning enemies,", + "or a goal location for a player to go to."); + ActionBar_SingleAction("More about Point Entities", () => GoToPage(typeof(PointEntitiesPage))); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/EntitiesOverviewPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Entities/EntitiesOverviewPage.cs.meta new file mode 100644 index 0000000..f6119c8 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/EntitiesOverviewPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 62b4b35600af4819baf0389a9252be03 +timeCreated: 1723278285 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Entities/EntitiesOverviewPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/PointEntitiesPage.cs b/Assets/Tremble/Editor/Manual/Pages/Entities/PointEntitiesPage.cs new file mode 100644 index 0000000..00abeb3 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/PointEntitiesPage.cs @@ -0,0 +1,51 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Entities/Point Entities")] + public class PointEntitiesPage : ManualPageBase + { + protected override void OnGUI() + { + Text( + "Point Entities are points/positions in space in the map, which you want to apply a", + "MonoBehaviour script to. They do not have a visual representation (mesh).", + "For example, a target position that an enemy should move to. Or, a position in space", + "in which to spawn the player (see below)."); + + Image("T_Manual_PointEntity"); + + Text("The following properties are available:"); + + PropertyDescription("name", + "The name of the entity in TrenchBroom.", + "If omitted, we convert your MonoBehaviour name according to your Naming Convention in settings." + ); + + PropertyDescription("category", + "The menu category to show the entity under, for example 'solid'.", + $"If omitted, we use the default prefix, '{FgdConsts.BRUSH_PREFIX}'." + ); + + PropertyDescription("colour, size", + "Colour and Size define how to display this Point entity's preview cube in TrenchBroom." + ); + + PropertyDescription("sprite", + "(optional) A sprite to show, instead of a coloured cube for this Point entity in TrenchBroom.", + "This should be the name of a texture in your project, e.g. 'T_MyTexture'." + ); + + H1("Point Entity Wizard"); + Text( + "Tremble can guide you through creating the correct attribute code for your entity,", + "to help you get up and running quickly." + ); + + ActionBar_SingleAction("Build Point Entity", () => GoToPage(typeof(PointBuilderPage))); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/PointEntitiesPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Entities/PointEntitiesPage.cs.meta new file mode 100644 index 0000000..a107cce --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/PointEntitiesPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: d1a1a3ae162244f1819732c6cb04f4a8 +timeCreated: 1723201769 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Entities/PointEntitiesPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs.meta b/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs.meta new file mode 100644 index 0000000..b9b0dc5 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5dbfda69803f4f39ac23255094985859 +timeCreated: 1723206454 \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs/PrefabEntitiesPage.cs b/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs/PrefabEntitiesPage.cs new file mode 100644 index 0000000..0ef3eae --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs/PrefabEntitiesPage.cs @@ -0,0 +1,54 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Entities/Prefabs/Prefab Entities")] + public class PrefabEntitiesPage : ManualPageBase + { + protected override void OnGUI() + { + Text( + "Prefab Entities are 1:1 representations of your Unity prefabs, which can be dropped into a map.", + $"All you have to do is mark up your scripts with '[{FormatAttributeName(typeof(PrefabEntityAttribute))}]' to synchronise properties and more!"); + + Image("T_Manual_PrefabEntity"); + + Text("The following properties are available:"); + + PropertyDescription("category", + "The menu category to show the entity under, for example 'player'.", + $"If omitted, we use the default prefix, '{FgdConsts.PREFAB_PREFIX}'." + ); + + PropertyDescription("excludePrefab(s)", + "Exclude prefabs with the given name. For example, if your", + "script appears on multiple prefabs 'P_Coin' and 'P_CoinSpecial', and you only", + " want to show 'P_Coin' in TrenchBroom, you can pass 'P_CoinSpecial' in here." + ); + + PropertyDescription("includePrefab(s)", + "Only include prefabs with the given name. For example, if your", + "script appears on multiple prefabs 'P_Coin' and 'P_CoinSpecial', and you only", + " want to show 'P_Coin' in TrenchBroom, you can pass 'P_Coin' in here." + ); + + PropertyDescription("onlyVariants", + "Only include variants of this prefab, not the base prefab itself.", + "For example, imagine your game has a 'P_Sign' prefab, which is an empty signpost,", + "but also has Prefab Variants 'P_Sign_Info' and 'P_Sign_QuestionMark' - ticking", + "this box will export those variants but not the base 'P_Sign'." + ); + + H1("Prefab Entity Wizard"); + Text( + "Tremble can guide you through creating the correct attribute code for your entity,", + "to help you get up and running quickly." + ); + + ActionBar_SingleAction("Build Prefab Entity", () => GoToPage(typeof(PrefabBuilderPage))); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs/PrefabEntitiesPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs/PrefabEntitiesPage.cs.meta new file mode 100644 index 0000000..61e4df1 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs/PrefabEntitiesPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: fdcea6d257154068a23f70d1bdb72b0a +timeCreated: 1723201724 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs/PrefabEntitiesPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs/SpawnablePrefabsPage.cs b/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs/SpawnablePrefabsPage.cs new file mode 100644 index 0000000..7fffa83 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs/SpawnablePrefabsPage.cs @@ -0,0 +1,40 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Entities/Prefabs/Spawnable Prefabs")] + public class SpawnablePrefabEntitiesPage : ManualPageBase + { + protected override void OnGUI() + { + Text( + "Spawnable Prefabs are a quick way to add a single script to ANY prefab in editor, to", + "allow your prefab to be instantiated from TrenchBroom without any code changes.", + "Note that this method does not allow you to set variables on those prefabs!" + ); + + Image("T_Manual_SpawnablePrefab"); + + Text( + $"Add a '{nameof(TrembleSpawnablePrefab)}' component to your prefab. This gives you the following", + "options:" + ); + + PropertyDescription("Category", + "You can supply the 'Category' of prefab here, too - the menu category to", + "show the entity under, for example 'player'. If omitted, we use the prefix defined in", + "the settings (default: 'p')" + ); + + PropertyDescription("Only Variants", + "Only Variants: Tremble will ignore the base prefab and only export Prefab Variants of", + "the prefab. See the above explanation about 'onlyVariants' for more information." + ); + + ActionBar_SingleAction("Build Prefab Entity", () => GoToPage(typeof(PrefabBuilderPage))); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs/SpawnablePrefabsPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs/SpawnablePrefabsPage.cs.meta new file mode 100644 index 0000000..30d745e --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs/SpawnablePrefabsPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 7a0a012f06324a7e962feefd29e85628 +timeCreated: 1723206473 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Entities/Prefabs/SpawnablePrefabsPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/MapRepairPage.cs b/Assets/Tremble/Editor/Manual/Pages/MapRepairPage.cs new file mode 100644 index 0000000..dd4dc05 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/MapRepairPage.cs @@ -0,0 +1,37 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Map Repair")] + public class MapRepairOverviewPage : ManualPageBase + { + protected override void OnGUI() + { + Text( + "Sometimes, after renaming entities or materials, your map might import in a broken state,", + "missing materials or functionality. In this case, you can right click the map in Unity,", + "and select 'Repair Map' (or, go to Tools > Tremble > Repair Map)." + ); + + Image("T_Manual_MapRepair"); + + ActionBar_SingleAction("Open Map Repair", MapRepairWindow.OpenMapRepair); + + Callout("Note, that you should ensure TrenchBroom does not have your map open while it is repaired."); + + H2("Other uses for map repair"); + Bullet( + "Swap materials around, or reassign entities in the map wholesale - which can", + "be far quicker than manually editing them." + ); + Bullet( + "Import maps from Quake®, or another game using .map files" + ); + + ActionBar_SingleAction("Show me how to import maps from other games", () => GoToPage(typeof(MapRepairForeignPage))); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/MapRepairPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/MapRepairPage.cs.meta new file mode 100644 index 0000000..1177901 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/MapRepairPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 235e96de3d244c26bdf4c5c2e8b833dc +timeCreated: 1723448743 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/MapRepairPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Materials.meta b/Assets/Tremble/Editor/Manual/Pages/Materials.meta new file mode 100644 index 0000000..4c64d44 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Materials.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 966bf55c023a42aa9b1ee89f32290315 +timeCreated: 1724656265 \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialGroupsPage.cs b/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialGroupsPage.cs new file mode 100644 index 0000000..66ed6f5 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialGroupsPage.cs @@ -0,0 +1,138 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Materials/Material Groups")] + public class MaterialGroupsPage : ManualPageBase + { + private TrembleSyncSettings m_SyncSettings; + private MaterialGroup m_DefaultMaterialGroup; + private Material[] m_UnexposedMaterials; + + protected override void OnInit() + { + m_SyncSettings = TrembleSyncSettings.Get(); + + Material[] allMaterials = AssetDatabase + .FindAssets("t:material", new[] { "Assets" }) + .Select(AssetDatabase.GUIDToAssetPath) + .Select(AssetDatabase.LoadAssetAtPath) + .ToArray(); + + m_DefaultMaterialGroup = MaterialGroup.CreateDefault(); + + m_UnexposedMaterials = allMaterials + .Where(m => !MaterialGroupUtil.IsMaterialPartOfAnyMaterialGroup(m)) + .ToArray(); + } + + protected override void OnGUI() + { + Text( + "By default, Tremble will export all of the materials in your project into TrenchBroom.", + "If your project has a lot of materials though, this can take some time,", + "and there may be materials that you never want to use in TrenchBroom at all." + ); + + Text( + "By using material groups, you can decide which materials to export to TrenchBroom,", + "and even organise them into groups!" + ); + + H1("Assigning material groups"); + Text("There are 2 ways to set up material groups:"); + Bullet( + "Click an individual material (or a group of materials) in Unity's Project window,", + "and select a group from the dropdown at the top of the Inspector view." + ); + Image("T_Manual_MaterialGroups"); + Bullet( + "or, go into Tremble's settings (see Basics > Tremble's Settings), click 'Materials',", + "and add one or more groups. Now you can assign materials to each group." + ); + + H1("How is my project set up?"); + + if (m_SyncSettings.MaterialGroups is { Length: > 0 }) + { + Text( + $"Your project is using material groups, and you have {m_SyncSettings.MaterialGroups.Length}", + "of them:" + ); + + foreach (MaterialGroup matGroup in m_SyncSettings.MaterialGroups) + { + Indent(() => + { + Foldout($"{matGroup.Name}, {matGroup.Materials.Length} material(s)", () => + { + foreach (Material mat in matGroup.Materials) + { + GUILayout.BeginHorizontal(); + { + Bullet(mat.name); + Button($"select {mat.name}", width: 200f, action: () => Selection.activeObject = mat); + } + GUILayout.EndHorizontal(); + } + }); + }); + } + + if (m_UnexposedMaterials.Length == 0) + { + Text("...and that's all your materials!"); + } + else + { + Text($"There are {m_UnexposedMaterials.Length} materials that are not exposed to TrenchBroom:"); + Indent(() => + { + Foldout($"Unavailable material(s)", () => + { + foreach (Material mat in m_UnexposedMaterials) + { + GUILayout.BeginHorizontal(); + { + Bullet(mat.name); + Button($"select {mat.name}", width: 200f, action: () => Selection.activeObject = mat); + } + GUILayout.EndHorizontal(); + } + + Text("To make a Material available for use, select it and use the Inspector to add it", + "to a Material Group."); + }); + }); + } + } + else + { + Text( + $"Your project is not using material groups, and you have {m_DefaultMaterialGroup.Materials.Length}", + "compatible material(s) in your project:" + ); + Indent(() => + { + Foldout("Show materials", () => + { + foreach (Material material in m_DefaultMaterialGroup.Materials) + { + Bullet(material.name); + } + }); + }); + } + + string trembleMaterialsPath = "Project/Tremble/3 Materials"; + ActionBar_SingleAction("Edit Material Groups", () => SettingsService.OpenProjectSettings(trembleMaterialsPath)); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialGroupsPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialGroupsPage.cs.meta new file mode 100644 index 0000000..9c6fb69 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialGroupsPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: fcdaf93099d84ea28783d12928ca5055 +timeCreated: 1723448806 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Materials/MaterialGroupsPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialRenderDataPage.cs b/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialRenderDataPage.cs new file mode 100644 index 0000000..1610130 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialRenderDataPage.cs @@ -0,0 +1,71 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Materials/Render Settings")] + public class MaterialRenderDataPage : ManualPageBase + { + private TrembleSyncSettings m_SyncSettings; + private MaterialGroup m_DefaultMaterialGroup; + private Material[] m_UnexposedMaterials; + + protected override void OnInit() + { + m_SyncSettings = TrembleSyncSettings.Get(); + } + + protected override void OnGUI() + { + Text( + "When Tremble exports materials, it can convert your materials in a few different ways.", + "You can choose a material's render settings by finding that material in the editor,", + "and changing the following settings:" + ); + + Image("T_Manual_RenderSettings"); + + H1("Render Mode"); + + Bold("Dynamic Mode (\"MainTex\")"); + Bullet( + "Uses the main texture of the material as the texture exported to Trenchbroom.", + "This will work fine for most materials. Directly copies the texture to the export folder", + "if the resolution is unmodified." + ); + Bullet( + "If you're using a custom shader, make sure your material either has a texture named _MainTex,", + "or a texture marked as Main Texture. This can be done through ShaderLab markup with [MainTexture]", + "for code shaders, or by marking the texture as a Main Texture in Shader Graph shaders."); + Bullet( + "If the renderer fails to find a matching main texture, it will try a few other texture names", + "like _Color, _BaseColor, or other misspellings of _MainTex (just in case)."); + Bullet( + "If that also fails, the renderer will switch to Fixed Size Mode." + ); + + Bold("Fixed-Size Mode (\"Legacy\")"); + Bullet( + "Renders the material using a camera system. ", + "This is useful for procedural materials, or any other material that doesn't have", + "a main texture parameter." + ); + Bullet( + "Will be automatically used if MainTex mode fails." + ); + + H1("Resolution"); + Text( + "You can use these settings to set the resolution of a texture.", + "This is useful for textures that don't have the same resolution on the X and Y axis.", + "Note that the resolution affects UV mapping - in Trenchbroom, one pixel is one unit by default." + ); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialRenderDataPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialRenderDataPage.cs.meta new file mode 100644 index 0000000..43fbd11 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialRenderDataPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: b87f0fb523a94356827025cd020dd8d3 +timeCreated: 1752489026 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Materials/MaterialRenderDataPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialsAboutPage.cs b/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialsAboutPage.cs new file mode 100644 index 0000000..bff8d88 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialsAboutPage.cs @@ -0,0 +1,57 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Materials/About")] + public class MaterialsAboutPage : ManualPageBase + { + protected override void OnGUI() + { + Text( + "Tremble uses a novel approach compared to other map import tools.", + "Many map import tools will allow users to create their own Textures folder for use", + "with TrenchBroom, and will try to create materials based on those on import." + ); + + Text( + "This results in materials in your project which use the built-in 'Standard'", + "(or URP/HDRP 'Lit') shader." + ); + + Text( + "Tremble does NOT work in this way. Tremble takes your existing Unity materials,", + "and generates a Textures folder for you with an accurate representation of each", + "Unity material as a texture." + ); + + H1("Why?!"); + Text( + "Well, we believe that users don't want to spend time curating textures for", + "TrenchBroom when ultimately what they care about is the Material looking good", + "in Unity (where your players will see it). It's the same reason Tremble does", + "not support Quake®'s lightmapping tech. Your game will use Unity's lighting,", + "so this is where you should apply your scene's lighting setup." + ); + + H1("But really, what benefits does it give me?"); + Bullet("Your materials and shaders appear exactly how you set them up in Unity, in your game!"); + Bullet( + "You are not restricted to using Standard/Lit shaders for your map materials! You", + "can use custom shaders/Shader Graphs, including Unlit, bumpmapped, or entirely HLSL-driven", + "materials." + ); + Bullet( + "There's no need to worry about how TrenchBroom handles textures - Tremble", + "keeps everything in sync automagically!" + ); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialsAboutPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialsAboutPage.cs.meta new file mode 100644 index 0000000..510f427 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Materials/MaterialsAboutPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 0eedd4cad37c4fdca5801d345f060473 +timeCreated: 1724656293 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Materials/MaterialsAboutPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/OtherGames.meta b/Assets/Tremble/Editor/Manual/Pages/OtherGames.meta new file mode 100644 index 0000000..05fbb43 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/OtherGames.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9168ecc737624c8899cf1cb3474b0b9f +timeCreated: 1723449331 \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/OtherGames/ImportFgdPage.cs b/Assets/Tremble/Editor/Manual/Pages/OtherGames/ImportFgdPage.cs new file mode 100644 index 0000000..5335ebf --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/OtherGames/ImportFgdPage.cs @@ -0,0 +1,43 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Import from Other Games/Texture FGDs from other games")] + public class ImportFgdPage : ManualPageBase + { + protected override void OnGUI() + { + Text("When importing maps from other games, Tremble might encounter entities which it does not recognise."); + + Text("For example, if you import a map from Quake®, it will contain (among others) an", + "'info_player_start' entity to define where the player should spawn."); + + Text("If you import the map and use Map Repair, you can either:"); + + Number("Map an existing MonoBehaviour from your game to this unknown entity, or"); + Number("Have Tremble generate a new MonoBehaviour, by making assumptions based on what's in the map."); + + Text("However, this can be problematic. If the map doesn't contain data for a given field,", + "Tremble will have no knowledge of it and won't generate complete C# script for it."); + + Text("Tremble will never generate anything invalid, but you may be missing functionality."); + + Text("This is where importing an FGD file can help!"); + + Foldout("What's an FGD file?", () => + { + Text("A Forge Game Data file. It contains a list of all entities in a game, and what", + "fields they support."); + + Text("It can also contain helpful tooltips and hints as to how each field is used."); + }); + + H1("Importing an FGD file"); + Text("To import an FGD file, simply drag it into your project."); + Text("Tremble will extract the FGD classes into a folder of the same name."); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/OtherGames/ImportFgdPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/OtherGames/ImportFgdPage.cs.meta new file mode 100644 index 0000000..5cf8574 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/OtherGames/ImportFgdPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: e85c2df6351a493aaeea88ae4c9fdae4 +timeCreated: 1724661376 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/OtherGames/ImportFgdPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/OtherGames/ImportWadPage.cs b/Assets/Tremble/Editor/Manual/Pages/OtherGames/ImportWadPage.cs new file mode 100644 index 0000000..251b00c --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/OtherGames/ImportWadPage.cs @@ -0,0 +1,28 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Import from Other Games/Texture WADs from other games")] + public class ImportWadPage : ManualPageBase + { + protected override void OnGUI() + { + Text("Unfortunately, you cannot supply a WAD file in your TrenchBroom map files for Tremble to use."); + + Text("However, Tremble does support extracting WAD files into your Unity project, which in turn", + "makes them available to TrenchBroom."); + + Callout("Note: Only WAD2 (Quake) format WAD files are supported at the moment.", + "WAD3 (Valve) are not supported (yet?)"); + + Text("To get started, simply drop a WAD file into your Unity project."); + + Text("This process can take a while for a large WAD file - up to a minute or two.", + "It only needs to be done once."); + Image("T_Manual_WadImport2"); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/OtherGames/ImportWadPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/OtherGames/ImportWadPage.cs.meta new file mode 100644 index 0000000..d61c897 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/OtherGames/ImportWadPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 418c0e37fc314aa489c2459b11529dbf +timeCreated: 1723449354 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/OtherGames/ImportWadPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/OtherGames/MapRepairFgdComparisonPage.cs b/Assets/Tremble/Editor/Manual/Pages/OtherGames/MapRepairFgdComparisonPage.cs new file mode 100644 index 0000000..8b5095a --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/OtherGames/MapRepairFgdComparisonPage.cs @@ -0,0 +1,30 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Import from Other Games/FGD Comparison", title: "The difference made by importing an FGD file", showInTree: false)] + public class MapRepairFgdComparisonPage : ManualPageBase + { + protected override void OnGUI() + { + Text("With an FGD file imported, you'll see that Tremble has the proper names and", + "descriptions of all the fields of the map classes - rather than just the ones", + "that happened to be set in the map."); + + Text("It's recommended to import the FGD whenever importing 'foreign' maps to make", + "them easier to work with."); + + CustomPropertyDescription("No FGD File", () => + { + Image("T_Manual_MapRepair_NoFGD", width: 700f, centred: false); + }); + CustomPropertyDescription("With FGD File", () => + { + Image("T_Manual_MapRepair_WithFGD", width: 700f, centred: false); + }); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/OtherGames/MapRepairFgdComparisonPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/OtherGames/MapRepairFgdComparisonPage.cs.meta new file mode 100644 index 0000000..2c6fc3f --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/OtherGames/MapRepairFgdComparisonPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 937a21eaecb54e83a8e4180905259474 +timeCreated: 1723549012 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/OtherGames/MapRepairFgdComparisonPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/OtherGames/MapRepairForeignPage.cs b/Assets/Tremble/Editor/Manual/Pages/OtherGames/MapRepairForeignPage.cs new file mode 100644 index 0000000..fe3670d --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/OtherGames/MapRepairForeignPage.cs @@ -0,0 +1,82 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Import from Other Games/Maps from other games")] + public class MapRepairForeignPage : ManualPageBase + { + private static readonly string[] TAB_NAMES = new[] + { + "Materials/Textures", "Entities" + }; + + private int m_SelectedTabIdx; + + protected override void OnGUI() + { + Image("T_Manual_MapRepair_Required", width: 220f); + + Text("You can also use Map Repair to patch up what Tremble terms 'foreign maps' (maps", + "from other games) to work with your Tremble/Unity project. This also allows you to", + "import/export maps between your own projects, or even import maps from other games", + "(such as Quake®!)."); + + Text("For any unrecognised entities in maps, Map Repair will generate new MonoBehaviour classes", + "to match them. This saves time creating C# classes for brand new entities you've", + "added to the map."); + + Text("These generated classes will allow Tremble to import these new entities and will", + "bring any values from the map into Unity - but of course, it won't provide any game", + "logic such as movement or AI - you'd have to code that yourself."); + + + H2("Available Tabs"); + { + switch (Tabs(ref m_SelectedTabIdx, TAB_NAMES, width: 420f)) + { + case 0: // Textures + GUILayout.BeginHorizontal(); + { + Image("T_Manual_MapRepair_Textures", width: 400f); + GUILayout.BeginVertical(); + { + Text("This tab shows a list of all of the map's textures, and Tremble’s best guess", + "at which project Materials match those textures."); + Bullet("You can then change which material each texture maps to manually, if you desire."); + Bullet("You can click the small '!' button to apply a given material to all missing materials", + "(for example, if you want to apply a single material to all unknown materials in a map)"); + } + GUILayout.EndVertical(); + } + GUILayout.EndHorizontal(); + break; + + case 1: // Entities + GUILayout.BeginHorizontal(); + { + Image("T_Manual_MapRepair_Entities", width: 400f); + GUILayout.BeginVertical(); + { + Text("This tab shows a list of all the map's point and brush entities, and Tremble’s best guess", + "at which MonoBehaviour classes match those entities."); + Bullet("You can then change which class each entity maps to manually, if you desire."); + Bullet("Leave an unknown entity class as 'Generate new class' to ask Tremble to generate", + "a new MonoBehaviour class that matches the entity. This may need manual tweaking", + "afterwards, but will be valid and able to parse the map supplied."); + Bullet("At the bottom of this tab, you are able to designate where new classes", + "are generated and an optional namespace to use for them."); + } + GUILayout.EndVertical(); + } + GUILayout.EndHorizontal(); + break; + } + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/OtherGames/MapRepairForeignPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/OtherGames/MapRepairForeignPage.cs.meta new file mode 100644 index 0000000..c16682a --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/OtherGames/MapRepairForeignPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: e510aaa0a33f4bceb10e55cb90bbedd1 +timeCreated: 1723448767 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/OtherGames/MapRepairForeignPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/OverviewPage.cs b/Assets/Tremble/Editor/Manual/Pages/OverviewPage.cs new file mode 100644 index 0000000..034c987 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/OverviewPage.cs @@ -0,0 +1,125 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Overview", isHomePage: true)] + public class OverviewPage : ManualPageBase + { + private bool m_GotLatestVersions = false; + + protected override void OnInit() + { + VersionCheck.FetchLatestVersionsInBackground(() => + { + m_GotLatestVersions = true; + Repaint(); + }); + } + + protected override void OnGUI() + { + GUILayout.BeginHorizontal(); + { + Image("T_TrembleLogo", width: 200f, centred: false); + + GUILayout.BeginVertical(); + { + H1("Welcome to the Tremble manual!"); + Text( + "Please click an item on the left to navigate. There are also buttons in the top", + "toolbar for navigating back/forwards, and returning here (Home)." + ); + + + PropertyDescription("Your version of Tremble", labelWidth: 200f, $"Version {TrembleConsts.VERSION_STRING}"); + + if (!m_GotLatestVersions) + { + GUI.color = Color.yellow; + PropertyDescription("Latest version of Tremble", "... checking if there's a newer version ..."); + GUI.color = Color.white; + } + else + { + if (VersionCheck.IsNewerVersionAvailable) + { + GUILayout.BeginVertical(EditorStyles.helpBox); + { + PropertyDescription("Latest version of Tremble", labelWidth: 200f, $"There's a newer version available, v{VersionCheck.NewestAvailableVersion.Version}", + $"({VersionCheck.NumVersionsBehind} versions behind)!"); + + ActionBar_SingleAction("Upgrade in Package Manager!", () => EditorApplication.ExecuteMenuItem("Window/Package Manager")); + } + GUILayout.EndVertical(); + } + else + { + PropertyDescription("Latest version of Tremble", labelWidth: 200f, $"Version {VersionCheck.CurrentInstalledVersion.Version} - you're already on the latest and greatest!"); + } + } + + if (TrenchBroomUtil.TrenchBroomPath == null) + { + PropertyDescription("TrenchBroom", labelWidth: 200f, "(unknown location!)"); + + GUI.color = Color.yellow; + Text( + "Is TrenchBroom installed? Tremble is unsure where to find it. Try", + "opening TrenchBroom now - I'll keep checking for it :)" + ); + GUI.color = Color.white; + } + else + { + string path = TrenchBroomUtil.TrenchBroomPath; + +#if UNITY_EDITOR_OSX + // Under macOS, remove /Contents/MacOS/TrenchBroom + int suffix = path.IndexOfInvariant("/Contents", caseSensitive: true); + if (suffix != -1) + { + path = path.Substring(0, suffix); + } +#endif + + string running = TrenchBroomUtil.IsTrenchBroomRunning ? " (running)" : ""; + PropertyDescription("TrenchBroom", labelWidth: 200f, $"TrenchBroom was discovered at: {path}{running}"); + } + } + GUILayout.EndVertical(); + } + GUILayout.EndHorizontal(); + + LargeSpace(); + + if (TrenchBroomUtil.TrenchBroomPath == null) + { + ActionBar_SingleAction("Download TrenchBroom", () => { Application.OpenURL("https://github.com/TrenchBroom/TrenchBroom/releases");}); + } + + H2("Getting Started"); + ActionBar(() => + { + Action("Create your first map", () => GoToPage(typeof(CreateMapPage))); + Action("Set Tremble up for User Generated Content", () => GoToPage(typeof(UgcSetupPage))); + Action("Get support!", () => GoToPage(typeof(TroubleshootingGetHelpPage))); + }); + + H2("Quick Create Entity"); + ActionBar(() => + { + Action("Create a POINT entity", () => GoToPage(typeof(PointEntitiesPage))); + Action("Create a BRUSH entity", () => GoToPage(typeof(BrushEntitiesPage))); + Action("Create a PREFAB entity", () => GoToPage(typeof(PrefabEntitiesPage))); + }); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/OverviewPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/OverviewPage.cs.meta new file mode 100644 index 0000000..a645d36 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/OverviewPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 7901a6be0c0b40a6bae863067e7c1470 +timeCreated: 1722961223 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/OverviewPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Troubleshooting.meta b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting.meta new file mode 100644 index 0000000..d23d75a --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 273698197de74f00b452be8efe988040 +timeCreated: 1723448826 \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingDLLPage.cs b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingDLLPage.cs new file mode 100644 index 0000000..884ef92 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingDLLPage.cs @@ -0,0 +1,50 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Troubleshooting/'dylib can't be opened' (macOS only)")] + public class TroubleshootingDLLPage : ManualPageBase + { + protected override void OnGUI() + { + Image("T_Manual_Trouble_DLL1", width: 200f); + + Text( + "This can sometimes occur because Q3Map2, the converter which transforms your .map", + "file into something Tremble can understand, is not currently signed.", + "(this may change in future!)" + ); + + Text( + "It's a warning from macOS that you may not wish to trust the Q3Map2 binary." + ); + + Foldout("Why should I trust it?", () => + { + Bullet("Q3Map2 is distributed with Tremble from the Asset Store and is safe to use"); + Bullet("You can verify the source code OR build your own Q3Map2 library, if you prefer"); + + ActionBar_SingleAction("Verify Q3Map2 source on Github", () => Application.OpenURL("https://github.com/tinygooseuk/q3map2/tree/libq3map2")); + }); + + H1("To fix the error, do the following:"); + + Number("Click 'Done' to close the 'can't be opened' dialogue"); + Number("Open 'System Settings' on your Mac, and scroll down to 'Privacy & Security' in the left sidebar"); + Number("Scroll down to 'Security', and click 'Allow Anyway'"); + + Image("T_Manual_Trouble_DLL2"); + + Number("You may be prompted to enter your password or use Touch ID. Do so"); + Number("Close System Settings and return to Unity"); + Number("Try to import the map again. You will see the same error, but this time there will be an 'Open' button. Click 'Open'"); + + Text("This should now work!"); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingDLLPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingDLLPage.cs.meta new file mode 100644 index 0000000..221e0a9 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingDLLPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 4dcb872d73a04f568fdea7a559b18319 +timeCreated: 1723448843 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingDLLPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingGetHelpPage.cs b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingGetHelpPage.cs new file mode 100644 index 0000000..3bd2193 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingGetHelpPage.cs @@ -0,0 +1,32 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Troubleshooting/Get Help & Support")] + public class TroubleshootingGetHelpPage : ManualPageBase + { + protected override void OnGUI() + { + H1("Discord"); + Text( + "If you need help, please first join us on our Discord server:", + "https://discord.gg/aUTmYxbVHZ." + ); + + ActionBar_SingleAction("Open Discord", () => Application.OpenURL("https://discord.gg/aUTmYxbVHZ")); + + H1("Email Support"); + Text( + "For further assistance, or if you do not have access to Discord, do", + "not hesitate to contact us at: hello@tinygoose.com." + ); + + ActionBar_SingleAction("Send Email", () => Application.OpenURL("mailto:hello@tinygoose.com")); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingGetHelpPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingGetHelpPage.cs.meta new file mode 100644 index 0000000..941e22d --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingGetHelpPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ce80159b60eb429c822dbbab4c39d44b +timeCreated: 1723448946 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingGetHelpPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingMaterialBrightnessPage.cs b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingMaterialBrightnessPage.cs new file mode 100644 index 0000000..5e7e6e3 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingMaterialBrightnessPage.cs @@ -0,0 +1,56 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Troubleshooting/Too dark or too bright materials")] + public class TroubleshootingMaterialBrightnessPage : ManualPageBase + { + protected override void OnGUI() + { + Image("T_Manual_Trouble_MaterialBrightness"); + + Text("Some users experience issues with materials exporting too bright or too dark when", + "viewed in TrenchBroom. This can be due to the way Tremble captures Unity Materials to", + "texture PNGs - which uses specific lighting, but can sometimes take on the environment", + "from your scene."); + + Text("Please note that this does NOT affect how your materials will appear in Unity/your game!"); + + Text("As a workaround, you can adjust how Tremble lights your materials in Tremble's Settings,", + "under Advanced/Materials."); + + Callout("When changing these settings or force-resyncing below, note that you should", + "Refresh Texture Collections (F5) and Refresh Entity Definitions (F6) in TrenchBroom", + "to update to the latest data."); + + Image("T_Manual_Trouble_MaterialBrightnessSettings"); + + ActionBar_SingleAction("Open in Settings", () + => SettingsService.OpenProjectSettings("Project/Tremble/4 Advanced/3 Materials")); + + Text("As a last resort, you can also try force-syncing your project to TrenchBroom. You can do this", + "by clearing the cache and then re-syncing, from Tools > Tremble > Sync Project to TrenchBroom (Clean, Slow)", + "- or by pressing the button below."); + + ActionBar_SingleAction("Force-resync for me", ()=> + { + TrembleEditorAPI.InvalidateMaterialAndPrefabCache(silent: true); + TrembleEditorAPI.SyncToTrenchBroom(); + + if (TrenchBroomUtil.IsTrenchBroomRunning) + { + EditorUtility.DisplayDialog( + title: "TrenchBroom is running", + message: "You may need to refresh Textures and Entities in TrenchBroom (press F5, then F6 in TrenchBroom)!", + + "Oh, okay!"); + } + }); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingMaterialBrightnessPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingMaterialBrightnessPage.cs.meta new file mode 100644 index 0000000..13ef985 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingMaterialBrightnessPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ef8cfc4d6b7b43baa6078bbb722dca8f +timeCreated: 1723448882 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingMaterialBrightnessPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingMissingGeoPage.cs b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingMissingGeoPage.cs new file mode 100644 index 0000000..9531bd9 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingMissingGeoPage.cs @@ -0,0 +1,57 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Troubleshooting/Missing Geometry")] + public class TroubleshootingMissingGeoPage : ManualPageBase + { + private const float IMAGE_WIDTH = 300f; + + protected override void OnGUI() + { + Text("If you create an area in a map that is completely enclosed (known in the mapping", + "community as being 'sealed'), you might find that Tremble culls the", + "inside of these areas entirely!"); + + GUILayout.BeginHorizontal(); + { + Bold("TrenchBroom (before):", width: IMAGE_WIDTH); + Bold("Unity (before):", width: IMAGE_WIDTH); + } + GUILayout.EndHorizontal(); + + GUILayout.BeginHorizontal(); + { + Image("T_Manual_MissingGeo_TB1", width: IMAGE_WIDTH, centred: false); + Image("T_Manual_MissingGeo_Unity1", width: IMAGE_WIDTH, centred: false); + } + GUILayout.EndHorizontal(); + + Text("This is because Q3Map2 (the map compiler) determines that these areas can never", + "be reached, and thus is unnecessary geometry."); + + Text("In order to keep this geometry around, you need to place a Point or Brush entity", + "(or a prefab) inside this area. Tremble will no longer cull the area, as it", + "determines that there are gameplay elements inside the area and thus it is important."); + + GUILayout.BeginHorizontal(); + { + Bold("TrenchBroom (after):", width: IMAGE_WIDTH); + Bold("Unity (after):", width: IMAGE_WIDTH); + } + GUILayout.EndHorizontal(); + + GUILayout.BeginHorizontal(); + { + Image("T_Manual_MissingGeo_TB2", width: IMAGE_WIDTH, centred: false); + Image("T_Manual_MissingGeo_Unity2", width: IMAGE_WIDTH, centred: false); + } + GUILayout.EndHorizontal(); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingMissingGeoPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingMissingGeoPage.cs.meta new file mode 100644 index 0000000..220b84a --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingMissingGeoPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 2319b986770f4d8c9ddcbb9b6d37ba62 +timeCreated: 1724754283 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingMissingGeoPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingPinkMaterialsPage.cs b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingPinkMaterialsPage.cs new file mode 100644 index 0000000..82c47bb --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingPinkMaterialsPage.cs @@ -0,0 +1,34 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("Troubleshooting/Pink materials in TrenchBroom")] + public class TroubleshootingPinkMaterialsPage : ManualPageBase + { + protected override void OnGUI() + { + Text("Pink materials can appear in either Unity or TrenchBroom, and they indicate that", + "a Material or Shader could not be found."); + + Image("T_Manual_Trouble_PinkMaterials"); + + H1("For your own materials/textures not rendering"); + Text("Try to run Map Repair on the map with pink materials. You will be able to swap the", + "missing materials for valid ones."); + ActionBar_SingleAction("Open Map Repair", MapRepairWindow.OpenMapRepair); + + H1("For Tremble sample materials not rendering, under URP or HDRP"); + Text("Tremble's sample project materials are built for the Built-In Render Pipeline.", + "This means, if you're using URP or HDRP, you should manually upgrade them to your pipeline."); + + Text("There's a great tutorial for this by SpawnCampGames on YouTube:"); + Image("T_Manual_Trouble_FixPinkMaterialsVideo"); + ActionBar_SingleAction("Open Video", () => Application.OpenURL("https://www.youtube.com/watch?v=V_EGF1M3fgY")); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingPinkMaterialsPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingPinkMaterialsPage.cs.meta new file mode 100644 index 0000000..b1edee9 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingPinkMaterialsPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 8a86dbcdd6714f008d781a4d19f04b82 +timeCreated: 1723453626 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/Troubleshooting/TroubleshootingPinkMaterialsPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent.meta b/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent.meta new file mode 100644 index 0000000..8320b6a --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ed2fb86e7fa34acc930cb86907b49812 +timeCreated: 1723536800 \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent/UgcPlayerHintsPage.cs b/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent/UgcPlayerHintsPage.cs new file mode 100644 index 0000000..9c8a56d --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent/UgcPlayerHintsPage.cs @@ -0,0 +1,61 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("User Generated Content/For Players")] + public class UgcPlayerHintsPage : ManualPageBase + { + protected override void OnGUI() + { + Experimental(); + + Text("This page gives a bit more detail on what players need, in order to import maps"); + + H2("How do players get the FGD file/textures/etc?"); + Text( + "These are installed onto the user's computer when you call", + $"{nameof(TrembleRuntimeAPI)}.{nameof(TrembleRuntimeAPI.Initialise)},", + "so there is no need to distribute these yourself." + ); + + H2("Do players need a copy of my Unity project to import maps?"); + Text( + "Absolutely not! Just a copy of your game with Tremble installed and configured." + ); + + H2("Do players need to purchase a licence for Tremble, on the Asset Store?"); + Text( + "Again - absolutely not! Just a copy of your game with Tremble installed and configured." + ); + + H2("What if players want to use their own textures?"); + Text( + "Generally this is discouraged, especially when distributing user-generated maps.", + "However - it is possible! Users should place their textures (PNG only!) into your game's", + "Library/baseq3/Textures folder (this will be created on first run). When Tremble", + "finds these unexpected textures referenced in a map, it will create Unity", + "materials on-the-fly to display them." + ); + Text( + "Note, that you will need to distribute these textures with the maps, and place", + "them into the correct folder at runtime for this to work when sharing maps between", + "players." + ); + + H2("What about if these textures should be PBR materials?"); + Text( + "Yup - you might want to change the metallic and smoothness parameters when", + "importing a user's custom texture. To do that, Tremble uses a naming convention." + ); + PropertyDescription("s[0-100]", "Smoothness percent"); + PropertyDescription("m[0-100]", "Metallic/metalness percent"); + Text( + "For example, a texture which should be 60% smooth and 100% metal could be named: ", + "'MyCoolTexture_s60_m100.png'." + ); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent/UgcPlayerHintsPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent/UgcPlayerHintsPage.cs.meta new file mode 100644 index 0000000..7c7f848 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent/UgcPlayerHintsPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 56855e58ea5a449082f0be2069093e76 +timeCreated: 1723536946 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent/UgcPlayerHintsPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent/UgcSetupPage.cs b/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent/UgcSetupPage.cs new file mode 100644 index 0000000..9eee78e --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent/UgcSetupPage.cs @@ -0,0 +1,100 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + [ManualPage("User Generated Content/Setup", title: "UGC Setup")] + public class UgcSetupPage : ManualPageBase + { + private TrembleSyncSettings m_SyncSettings; + + private bool IsAddressablesInstalled => +#if ADDRESSABLES_INSTALLED + true; +#else + false; +#endif + + private bool m_IsInstalling; + + protected override void OnInit() + { + m_SyncSettings = TrembleSyncSettings.Get(); + } + + protected override void OnGUI() + { + Experimental(); + + Text( + "Tremble now supports importing maps at runtime, which allows players to create their", + "own maps in TrenchBroom, and import it into your game themselves." + ); + + Text( + "You could use something like Unity's UGC package, or Steam Workshop to distribute", + "maps to players (which is up to you to implement). Tremble just needs the map file", + "to load on disk somewhere, and it will import it at runtime." + ); + + H1("Setup"); + Text( + "There are a few things to set up first, before you can use this feature. This page", + "will help you do that." + ); + + CheckListItem("Install the Addressables package from Unity", m_IsInstalling || IsAddressablesInstalled, "Install", () => + { + m_IsInstalling = true; + UnityEditor.PackageManager.Client.Add("com.unity.addressables"); + }); + + CheckListItem("Enable the Tremble setting for UGC", m_SyncSettings.AllowStandaloneImport, "Enable", () => + { + SerializedObject so = new(m_SyncSettings); + so.FindBackedProperty(nameof(m_SyncSettings.AllowStandaloneImport)).boolValue = true; + so.ApplyModifiedPropertiesWithoutUndo(); + + TrembleEditorAPI.SyncToTrenchBroom(); + }); + + H1("Initialising the system"); + { + Text( + "This step will prepare Tremble for loading maps at runtime.", + "Unfortunately, it can lock your game up for about 200ms - so the idea is to do", + "this during your game's startup code, to allow Tremble to initialise", + "without causing your game to hitch during gameplay." + ); + Code("await TrembleRuntimeAPI.Initialise();"); + } + + H1("Loading a map at runtime"); + { + Text("Loading a map at runtime couldn't be simpler - simply call the following function:"); + + Code( + $"{nameof(MapDocument)} map = await {nameof(TrembleRuntimeAPI)}.{nameof(TrembleRuntimeAPI.LoadMapAsync)}(\"C:\\somemap.map\");", + "", + "// Your map is now in the current scene, if loading succeeded.", + "// Check `map.Result` to see if it worked, and the `map.gameObject` is the root", + "// of your new map!", + "Debug.Log($\"Result: {map.Result}\");", + "Debug.Log($\"Loaded map: {map.BspName}\");" + ); + + H2("Notes"); + { + Bullet("You can also provide additional arguments, such as subdivision parameters and smoothing angles."); + Bullet("Tremble respects Application.backgroundLoadingPriority, which you can use to signal how", + "much time you want Unity to dedicate per frame to async loading. Higher priorities will load", + "your map faster, but at the expense of dropping more frames during the load."); + } + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent/UgcSetupPage.cs.meta b/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent/UgcSetupPage.cs.meta new file mode 100644 index 0000000..f98f62f --- /dev/null +++ b/Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent/UgcSetupPage.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: f5ecfa2702b44c4b9f03bbacef113cfc +timeCreated: 1723448499 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/Pages/UserGeneratedContent/UgcSetupPage.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/T_Bookmark_Off.png b/Assets/Tremble/Editor/Manual/T_Bookmark_Off.png new file mode 100644 index 0000000..3c9fc64 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/T_Bookmark_Off.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3174d8e1c8bb5ca39eefa82d002481f1cfda59662c3c36501258c451e4700b73 +size 281 diff --git a/Assets/Tremble/Editor/Manual/T_Bookmark_Off.png.meta b/Assets/Tremble/Editor/Manual/T_Bookmark_Off.png.meta new file mode 100644 index 0000000..c1b1bb0 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/T_Bookmark_Off.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: 3c81fd60e49ff4b3193926b7ce3bb7b5 +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: 0 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 2 + 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: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iOS + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: WindowsStoreApps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/T_Bookmark_Off.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Manual/T_Bookmark_On.png b/Assets/Tremble/Editor/Manual/T_Bookmark_On.png new file mode 100644 index 0000000..abbcc76 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/T_Bookmark_On.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3028b015d012d27a53733fced630a79d81c341a8e8767bbe014d34602d9db4bc +size 380 diff --git a/Assets/Tremble/Editor/Manual/T_Bookmark_On.png.meta b/Assets/Tremble/Editor/Manual/T_Bookmark_On.png.meta new file mode 100644 index 0000000..4a75ce2 --- /dev/null +++ b/Assets/Tremble/Editor/Manual/T_Bookmark_On.png.meta @@ -0,0 +1,176 @@ +fileFormatVersion: 2 +guid: ff9800bae80224e7e9b9f70120e833e0 +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: 0 + nPOTScale: 0 + 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: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 4 + buildTarget: DefaultTexturePlatform + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Standalone + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: iOS + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: Android + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: WindowsStoreApps + maxTextureSize: 8192 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 4 + buildTarget: tvOS + maxTextureSize: 8192 + 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: [] + customData: + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spriteCustomMetadata: + entries: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Manual/T_Bookmark_On.png + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Templates.meta b/Assets/Tremble/Editor/Templates.meta new file mode 100644 index 0000000..0f3f93d --- /dev/null +++ b/Assets/Tremble/Editor/Templates.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6eaff3223d60b4db58e4d8d36fb6a8f0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tremble/Editor/Templates/gameconfig-4.cfg b/Assets/Tremble/Editor/Templates/gameconfig-4.cfg new file mode 100644 index 0000000..58e65e5 --- /dev/null +++ b/Assets/Tremble/Editor/Templates/gameconfig-4.cfg @@ -0,0 +1,45 @@ +{ + "version": 4, + "name": "$GAME_NAME", + "icon": "Icon.png", + "fileformats": [ + { "format": "Quake3 (Valve)" } + ], + "filesystem": { + "searchpath": "Library/baseq3", + "packageformat": { "extension": "pk3", "format": "zip" } + }, + "textures": { + "root": "textures", + "package": { "type": "directory", "root": "textures" }, + "format": { "extensions": [ "" ], "format": "q3shader" }, + "shaderSearchPath": "scripts", // this will likely change when we get a material system + "attribute": "_tb_textures" + }, + "entities": { + "definitions": [ "entities.fgd" ], + "defaultcolor": "0.6 0.6 0.6 1.0", + "modelformats": [ "md3" ] + }, + "tags": { + "brush": [ + $BRUSHES + ], + "brushface": [ + { + "name": "Clip", + "attribs": [ "transparent" ], + "match": "texture", + "pattern": "special/*clip" + } + ] + }, + "faceattribs": { + "defaults": { + "scale": [1.0, 1.0] + }, + "surfaceflags": [], + "contentflags": [] + }, + "softMapBounds":"-65536 -65536 -65536 65536 65536 65536" +} diff --git a/Assets/Tremble/Editor/Templates/gameconfig-4.cfg.meta b/Assets/Tremble/Editor/Templates/gameconfig-4.cfg.meta new file mode 100644 index 0000000..f9695bd --- /dev/null +++ b/Assets/Tremble/Editor/Templates/gameconfig-4.cfg.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: f63b0415b29894b9692931252d93fee7 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Templates/gameconfig-4.cfg + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Templates/gameconfig-8.cfg b/Assets/Tremble/Editor/Templates/gameconfig-8.cfg new file mode 100644 index 0000000..5726718 --- /dev/null +++ b/Assets/Tremble/Editor/Templates/gameconfig-8.cfg @@ -0,0 +1,45 @@ +{ + "version": 8, + "name": "$GAME_NAME", + "icon": "Icon.png", + "fileformats": [ + { "format": "Quake3 (Valve)" } + ], + "filesystem": { + "searchpath": "Library/baseq3", + "packageformat": { "extension": "pk3", "format": "zip" } + }, + "textures": { + "root": "textures", + "package": { "type": "directory", "root": "textures" }, + "format": { "extensions": [ "" ], "format": "q3shader" }, + "shaderSearchPath": "scripts", // this will likely change when we get a material system + "attribute": "_tb_textures" + }, + "entities": { + "definitions": [ "entities.fgd" ], + "defaultcolor": "0.6 0.6 0.6 1.0", + "modelformats": [ "md3" ] + }, + "tags": { + "brush": [ + $BRUSHES + ], + "brushface": [ + { + "name": "Clip", + "attribs": [ "transparent" ], + "match": "texture", + "pattern": "special/*clip" + } + ] + }, + "faceattribs": { + "defaults": { + "scale": [1.0, 1.0] + }, + "surfaceflags": [], + "contentflags": [] + }, + "softMapBounds":"-65536 -65536 -65536 65536 65536 65536" +} diff --git a/Assets/Tremble/Editor/Templates/gameconfig-8.cfg.meta b/Assets/Tremble/Editor/Templates/gameconfig-8.cfg.meta new file mode 100644 index 0000000..0abe6d0 --- /dev/null +++ b/Assets/Tremble/Editor/Templates/gameconfig-8.cfg.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: ef54f2ac0fc354740b3b2dcc56549180 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Templates/gameconfig-8.cfg + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Templates/gameconfig-9.cfg b/Assets/Tremble/Editor/Templates/gameconfig-9.cfg new file mode 100644 index 0000000..3baf001 --- /dev/null +++ b/Assets/Tremble/Editor/Templates/gameconfig-9.cfg @@ -0,0 +1,42 @@ +{ + "version": 9, + "name": "$GAME_NAME", + "icon": "Icon.png", + "fileformats": [ + { "format": "Quake3 (Valve)" } + ], + "filesystem": { + "searchpath": "Library/baseq3", + "packageformat": { "extension": "pk3", "format": "zip" } + }, + "materials": { + "root": "textures", + "format": { "extensions": [".png"], "format": "image" } + }, + "entities": { + "definitions": [ "entities.fgd" ], + "defaultcolor": "0.6 0.6 0.6 1.0", + "modelformats": [ "md3" ] + }, + "tags": { + "brush": [ + $BRUSHES + ], + "brushface": [ + { + "name": "Clip", + "attribs": [ "transparent" ], + "match": "material", + "pattern": "special/*clip" + } + ] + }, + "faceattribs": { + "defaults": { + "scale": [1.0, 1.0] + }, + "surfaceflags": [], + "contentflags": [] + }, + "softMapBounds":"-65536 -65536 -65536 65536 65536 65536" +} diff --git a/Assets/Tremble/Editor/Templates/gameconfig-9.cfg.meta b/Assets/Tremble/Editor/Templates/gameconfig-9.cfg.meta new file mode 100644 index 0000000..78d3bc9 --- /dev/null +++ b/Assets/Tremble/Editor/Templates/gameconfig-9.cfg.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: b221a3b342c714e93a5ced490d049184 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Templates/gameconfig-9.cfg + uploadId: 939664 diff --git a/Assets/Tremble/Editor/TinyGoose.Tremble.Editor.asmdef b/Assets/Tremble/Editor/TinyGoose.Tremble.Editor.asmdef new file mode 100644 index 0000000..f9421e1 --- /dev/null +++ b/Assets/Tremble/Editor/TinyGoose.Tremble.Editor.asmdef @@ -0,0 +1,25 @@ +{ + "name": "TinyGoose.Tremble.Editor", + "rootNamespace": "TinyGoose.Tremble.Editor", + "references": [ + "TinyGoose.Tremble", + "Unity.Addressables.Editor" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [ + { + "name": "com.unity.addressables", + "expression": "0.0.0", + "define": "ADDRESSABLES_INSTALLED" + } + ], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/TinyGoose.Tremble.Editor.asmdef.meta b/Assets/Tremble/Editor/TinyGoose.Tremble.Editor.asmdef.meta new file mode 100644 index 0000000..fa3b5f4 --- /dev/null +++ b/Assets/Tremble/Editor/TinyGoose.Tremble.Editor.asmdef.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 737bbd6b6175d4d3ebf6128db488a086 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/TinyGoose.Tremble.Editor.asmdef + uploadId: 939664 diff --git a/Assets/Tremble/Editor/TrembleEditorAPI.cs b/Assets/Tremble/Editor/TrembleEditorAPI.cs new file mode 100644 index 0000000..5f212da --- /dev/null +++ b/Assets/Tremble/Editor/TrembleEditorAPI.cs @@ -0,0 +1,96 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public static class TrembleEditorAPI + { + /// + /// Sync GameConfig, materials and entities to TrenchBroom + /// + public static void SyncToTrenchBroom() => _ = TrembleSync.PerformSync(); + + /// + /// Reimport the currently open map (if any) + /// + public static void ReimportCurrentMap() => TrembleMenu.PerformCurrentMapReimport(); + + /// + /// Reimport all maps in the project (slow!) + /// + public static void ReimportAllMaps(bool silent = false) => TrembleMenu.PerformAllMapsReimport(silent); + + /// + /// Open the settings window + /// + public static void OpenSettings() => SettingsService.OpenProjectSettings("Project/Tremble"); + + /// + /// Open the manual window + /// + public static void OpenManual(Type page = null) + { + // Find page to start on + if (page != null) + { + page.GetCustomAttributes(out ManualPageAttribute manualPage); + if (manualPage == null) + { + Debug.LogError($"{page.Name} is not a valid manual page!"); + page = null; + } + } + + // Create list of sortings + string[] sortOrderFirst = + { + // Main sections + "Basics", + "Entities", + "Advanced", + "User Generated Content", + + // Misc. important pages + "Overview", + "Setup", + "UGC Setup", + "Get Help & Support" + }; + + string[] sortOrderLast = + { + "Troubleshooting", + "Debug" + }; + + ManualWindow.OpenManual($"Tremble Manual v{TrembleConsts.VERSION_STRING}", page ?? typeof(OverviewPage), + sortOrderFirst, sortOrderLast); + } + + /// + /// Invalidate the materials and prefabs cache + /// + public static void InvalidateMaterialAndPrefabCache() => InvalidateMaterialAndPrefabCache(silent: false); + public static void InvalidateMaterialAndPrefabCache(bool silent) + { + string baseq3Path = Path.Combine(Directory.GetCurrentDirectory(), "Library", "baseq3"); + + if (Directory.Exists(baseq3Path)) + { + Directory.Delete(baseq3Path, true); + + if (!silent) + { + Debug.Log("Note: Cache was invalidated. Next sync will be a little slower!"); + } + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/TrembleEditorAPI.cs.meta b/Assets/Tremble/Editor/TrembleEditorAPI.cs.meta new file mode 100644 index 0000000..b357c11 --- /dev/null +++ b/Assets/Tremble/Editor/TrembleEditorAPI.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: f92ba3911ced4f5b80c39cd5828d20c6 +timeCreated: 1707844007 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/TrembleEditorAPI.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/TrembleEditorUtility.cs b/Assets/Tremble/Editor/TrembleEditorUtility.cs new file mode 100644 index 0000000..7515221 --- /dev/null +++ b/Assets/Tremble/Editor/TrembleEditorUtility.cs @@ -0,0 +1,38 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public static class TrembleEditorUtility + { + public delegate void OnHierarchyItemCallback(GameObject gameObject, Rect selectionRect); + + public static void RegisterOnHierarchyItem(OnHierarchyItemCallback callback) + { +#if UNITY_6000_5_OR_NEWER + EditorApplication.hierarchyWindowItemByEntityIdOnGUI += (id, rect) => + { + GameObject go = EditorUtility.EntityIdToObject(id) as GameObject; + if (!go) + return; + + callback(go, rect); + }; +#else + EditorApplication.hierarchyWindowItemOnGUI += (id, rect) => + { + GameObject go = EditorUtility.InstanceIDToObject(id) as GameObject; + if (!go) + return; + + callback(go, rect); + }; +#endif + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/TrembleEditorUtility.cs.meta b/Assets/Tremble/Editor/TrembleEditorUtility.cs.meta new file mode 100644 index 0000000..620fe70 --- /dev/null +++ b/Assets/Tremble/Editor/TrembleEditorUtility.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 2ae90077c25b4c5c9c04faa475c9e781 +timeCreated: 1781801352 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/TrembleEditorUtility.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/TrembleMenu.cs b/Assets/Tremble/Editor/TrembleMenu.cs new file mode 100644 index 0000000..285197d --- /dev/null +++ b/Assets/Tremble/Editor/TrembleMenu.cs @@ -0,0 +1,181 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEditor.SceneManagement; +using UnityEngine; +using UnityEngine.SceneManagement; + +namespace TinyGoose.Tremble.Editor +{ + public static class TrembleMenu + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Main options + // ----------------------------------------------------------------------------------------------------------------------------- + [MenuItem("Tools/Tremble/Open Settings...", priority = +20)] + public static void OpenSettings() => TrembleEditorAPI.OpenSettings(); + +#if UNITY_2022_1_OR_NEWER + [MenuItem("Tools/Tremble/Show Sync Toolbar")] + private static void ShowToolbar() + { + SceneView.AddOverlayToActiveView(new TrembleSyncOverlay()); + } +#endif + + [MenuItem("Tools/Tremble/Open Manual...", priority = +20)] + private static void ShowManual() => TrembleEditorAPI.OpenManual(); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Import + // ----------------------------------------------------------------------------------------------------------------------------- + [MenuItem("Tools/Tremble/Re-Import Current Map", priority = -10)] + private static void DoMenu_PerformCurrentMapReimport() => PerformCurrentMapReimport(); + + + // ----------------------------------------------------------------------------------------------------------------------------- + // Sync + // ----------------------------------------------------------------------------------------------------------------------------- + [MenuItem("Tools/Tremble/Sync Project to TrenchBroom", priority = -12)] + private static void DoMenu_PerformQuickSync() => TrembleEditorAPI.SyncToTrenchBroom(); + + [MenuItem("Tools/Tremble/Sync Project to TrenchBroom (Clean, Slow)", priority = -11)] + private static void DoMenu_PerformFullSync() + { + TrembleEditorAPI.InvalidateMaterialAndPrefabCache(silent: true); + TrembleEditorAPI.SyncToTrenchBroom(); + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Advanced + // ----------------------------------------------------------------------------------------------------------------------------- + [MenuItem("Tools/Tremble/Advanced/Re-Import ALL Maps", priority = 9)] + private static void DoMenu_PerformAllMapsReimport() => PerformAllMapsReimport(); + + [MenuItem("Tools/Tremble/Advanced/Delete all autosaves", priority = 9)] + private static void DoMenu_DeleteAutosaves() => DeleteAutosaves(); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Debug + // ----------------------------------------------------------------------------------------------------------------------------- + [MenuItem("Tools/Tremble/Advanced/Debug/Open TB Game folder", priority = 9)] + private static void DoMenu_OpenGameFolder() => EditorUtility.OpenWithDefaultApp(TrenchBroomUtil.GetGameFolder()); + + [MenuItem("Tools/Tremble/Advanced/Debug/Open Project baseq3 folder", priority = 9)] + private static void DoMenu_OpenBaseQ3() => EditorUtility.OpenWithDefaultApp(TrembleConsts.BASEQ3_PATH); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Helpers + // ----------------------------------------------------------------------------------------------------------------------------- + // Support for syncing after compile + [UnityEditor.Callbacks.DidReloadScripts] + private static void MaybePerformSyncAfterCompile() + { + // Because this is called when the Library folder is recreated (but before + // AssetDatabase is truly ready!), we need to be careful accessing the Sync + // settings. This fixes the bug where your material groups get lost, which + // was because a new Sync settings asset was being created! + TrembleSyncSettings tss = TrembleSyncSettings.Get(createIfNotExists: false); + if (!tss || !tss.AutoSyncOnCompile) + return; + + EditorApplication.delayCall += TrembleEditorAPI.SyncToTrenchBroom; + } + + internal static void PerformCurrentMapReimport() + { + for (int sceneIdx = 0; sceneIdx < EditorSceneManager.sceneCount; sceneIdx++) + { + Scene scene = EditorSceneManager.GetSceneAt(sceneIdx); + + foreach (GameObject go in scene.GetRootGameObjects()) + { + PrefabAssetType prefabType = PrefabUtility.GetPrefabAssetType(go); + + if (prefabType == PrefabAssetType.Model) + { + // Model intact, reimport + string path = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(go); + if (path.IsNullOrEmpty()) + continue; + + if (!AssetDatabaseUtil.IsTrembleMapFile(path)) + continue; + + AssetDatabase.ImportAsset(path); + } + else if (prefabType == PrefabAssetType.MissingAsset) + { + // Broken (failed import before) - try to find one + string path = TrembleAssetLoader.FindAssetPath(go.name); + + if (path == null || !AssetDatabaseUtil.IsTrembleMapFile(path)) + continue; + + AssetDatabase.ImportAsset(path); + } + } + } + } + + + internal static void PerformAllMapsReimport(bool silent = false) + { + List mapsToReimport = AssetDatabaseUtil.GetAllTrembleMapPaths(); + + if (!Application.isBatchMode && !silent && !EditorUtility.DisplayDialog("Map Reimport", $"Are you sure you want to reimport {mapsToReimport.Count} maps?", "Sure!", "No")) + return; + + int task = Progress.Start("Tremble Import", options: Progress.Options.Synchronous | Progress.Options.Managed); + + try + { + for (int i = 0; i < mapsToReimport.Count; i++) + { + string filename = Path.GetFileName(mapsToReimport[i]); + + Progress.Report(task, i + 1, mapsToReimport.Count, $"Importing {filename}... ({i + 1}/{mapsToReimport.Count})"); + AssetDatabase.ImportAsset(mapsToReimport[i], ImportAssetOptions.ForceUpdate); + } + } + finally + { + Progress.Finish(task); + } + } + + + internal static void DeleteAutosaves() + { + List maps = new(); + + foreach (string assetPath in AssetDatabase.GetAllAssetPaths()) + { + if (!AssetDatabaseUtil.IsTrembleMapFile(assetPath)) + continue; + + if (!assetPath.Contains("autosave/")) + continue; + + maps.Add(assetPath); + } + + IEnumerable autosaveFolders = maps + .Select(map => Directory.GetParent(map)?.FullName) + .Select(absDir => Path.GetRelativePath(Directory.GetCurrentDirectory(), absDir)) + .Distinct(); + + foreach (string autosaveFolder in autosaveFolders) + { + AssetDatabase.DeleteAsset(autosaveFolder); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/TrembleMenu.cs.meta b/Assets/Tremble/Editor/TrembleMenu.cs.meta new file mode 100644 index 0000000..b29c404 --- /dev/null +++ b/Assets/Tremble/Editor/TrembleMenu.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 3cccc0a27612452193b12e5c7e3c0e24 +timeCreated: 1709808883 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/TrembleMenu.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/TrembleSync.cs b/Assets/Tremble/Editor/TrembleSync.cs new file mode 100644 index 0000000..34bbee7 --- /dev/null +++ b/Assets/Tremble/Editor/TrembleSync.cs @@ -0,0 +1,1031 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using UnityEditor; +using UnityEditor.Build; +using UnityEngine; +using Color = UnityEngine.Color; +using Debug = UnityEngine.Debug; +using FileMode = System.IO.FileMode; + +namespace TinyGoose.Tremble.Editor +{ + public static class TrembleSync + { + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private static readonly List s_BackgroundTasks = new(256); + private static int s_ProgressTask; + + private static TrembleSyncSettings SyncSettings => TrembleSyncSettings.Get(); + + + internal static async Task PerformSync() + { + // Check for upgrades! + VersionCheck.FetchLatestVersionsInBackground(() => VersionCheck.PromptToUpgradeIfAvailable()); + + // Upgrade - check material export size is sane + UpgradeMaterialExportSettingsIfRequired(); + + TrembleTimer.BeginSession("Tremble Sync"); + + try + { + // Clear cached asset lists + UnityObjectFieldConverterStatics.s_CachedAssetLists.Clear(); + + // Calculate working folders + s_ProgressTask = ProgressUtil.Start("Trembling..."); + + // Create lookups + string baseq3 = TrembleConsts.BASEQ3_PATH; + string baseq3Old = TrembleConsts.BASEQ3_PATH_OLD; + string modelsFolder = TrembleConsts.BASE_MODELS_PATH; + string baseMaterialsFolder = TrembleConsts.BASE_MATERIALS_PATH; + + TrembleTimerScope createLookupTimer = new(TrembleTimer.Context.CreateTypeLookups); + + PrefabNameLookup prefabNameLookup = new(SyncSettings); + MaterialNameLookup materialNameLookup = new(SyncSettings); + MapTypeLookup typeLookup = new(SyncSettings); + ModTimeDB modTimeDB = new(TrembleConsts.MODTIME_DB_PATH); + + createLookupTimer.Dispose(); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Gather lists of resources + // ----------------------------------------------------------------------------------------------------------------------------- + TrembleTimerScope exportEntitiesTimer = new(TrembleTimer.Context.ExportEntities); + + List allPrefabPaths = prefabNameLookup.AllPrefabPaths; + List allBrushTypes = TypeDatabase.GetTypesWithAttribute().ToList(); + List allPointTypes = TypeDatabase.GetTypesWithAttribute().ToList(); + List allScriptableObjectTypes = new(128); + + // User supplied a list of materials - use that! + List allMaterialGroups = SyncSettings.GetMaterialGroupsOrDefault(); + int numMaterials = allMaterialGroups.Sum(mg => mg.Materials.Length); + + // Collect prefab materials and transparent brushes + List prefabMaterialPaths = new(allPrefabPaths.Count * 2); + List transparentBrushes = new(allBrushTypes.Count); + + // Collect assets + List assets = new(allPrefabPaths.Count + numMaterials); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Work out steps, create folders + // ----------------------------------------------------------------------------------------------------------------------------- + int numSteps = numMaterials + allPrefabPaths.Count + allPointTypes.Count + allBrushTypes.Count; + + if (Directory.Exists(baseq3Old)) + { + Directory.Delete(baseq3Old, true); + } + + if (Directory.Exists(baseq3)) + { + Directory.Move(baseq3, baseq3Old); + } + + DirectoryUtil.EmptyAndCreateDirectory(baseq3); + DirectoryUtil.CreateAllDirectories(modelsFolder); + DirectoryUtil.CreateAllDirectories(baseMaterialsFolder); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Export Prefabs + // ----------------------------------------------------------------------------------------------------------------------------- + int step = 0; + + FgdWriter fgdWriter = GatherEntities(ref step, numSteps, + prefabNameLookup, materialNameLookup, typeLookup, modTimeDB, + modelsFolder, baseMaterialsFolder, + prefabMaterialPaths, transparentBrushes, + allBrushTypes, allPointTypes, allScriptableObjectTypes, + assets); + exportEntitiesTimer.Dispose(); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Data Assets + // ----------------------------------------------------------------------------------------------------------------------------- + using (TrembleTimerScope _ = new(TrembleTimer.Context.GatherDataAssets)) + { + numSteps += allScriptableObjectTypes.Count; // Add discovered data assets + foreach (Type scriptableObjectType in allScriptableObjectTypes) + { + string[] paths = AssetDatabase + .FindAssets($"t:{scriptableObjectType.Name}", new[] { "Assets" }) + .Select(AssetDatabase.GUIDToAssetPath) + .ToArray(); + + foreach (string path in paths) + { + string mapName = Path.GetFileNameWithoutExtension(path); + + ReportProgress(ref step, numSteps, mapName); + assets.Add(new() + { + MapName = mapName, + Path = path, + +#if ADDRESSABLES_INSTALLED + AddressableName = TrembleSyncAddressables.GetExistingEntryForPath(path)?.address ?? mapName, +#endif + + FullTypeName = scriptableObjectType.FullName + }); + } + } + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Materials + // ----------------------------------------------------------------------------------------------------------------------------- + List allMaterialPaths = allMaterialGroups + .SelectMany(mg => mg.Materials + .Select(AssetDatabase.GetAssetPath) + .Where(path => !path.Contains("M_Clip")) + ) + .ToList(); + + using (TrembleTimerScope _ = new(TrembleTimer.Context.ExportMaterials)) + { + + MapTextureSnapshotter textureSnapshotter = new(); + textureSnapshotter.Init(SyncSettings); + + try + { + numSteps += prefabMaterialPaths.Count; + + // Material groups + foreach (string materialPath in allMaterialPaths) + { + // Look up material name with group + if (!materialNameLookup.TryGetMapNameFromMaterialPath(materialPath, out string mapName)) + { + mapName = Path.GetFileNameWithoutExtension(materialPath); + } + + string outputPath = Path.Combine(baseMaterialsFolder, mapName + ".png"); + string description = Path.GetFileName(materialPath); + + ReportProgress(ref step, numSteps, description); + ProcessMaterial(textureSnapshotter, materialPath, mapName, outputPath, modTimeDB, assets); + } + + // Prefab materials + foreach (string materialPath in prefabMaterialPaths) + { + string mapName = materialNameLookup.GetPrefabNameFromMaterialPath(materialPath); + + string outputPath = Path.Combine(modelsFolder, mapName + ".png"); + string description = Path.GetFileName(materialPath); + + ReportProgress(ref step, numSteps, description); + ProcessMaterial(textureSnapshotter, materialPath, mapName, outputPath, modTimeDB, assets); + } + } + finally + { + textureSnapshotter.DeInit(); + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // "clip" texture + // ----------------------------------------------------------------------------------------------------------------------------- + if (SyncSettings.ExportClipSkipTextures) + { + string clipPath = Path.Combine(baseMaterialsFolder, "special", "clip.png"); + DirectoryUtil.CreateAllDirectories(clipPath); + + Texture2D clipTexture = TextureUtil.GenerateClipTexture(Color.white, Color.grey, Color.red); + await File.WriteAllBytesAsync(clipPath, clipTexture.EncodeToPNG()); + + string skipPath = Path.Combine(baseMaterialsFolder, "special", "skip.png"); + DirectoryUtil.CreateAllDirectories(clipPath); + + Texture2D skipTexture = TextureUtil.GenerateSkipTexture(Color.white, Color.grey, Color.blue); + await File.WriteAllBytesAsync(skipPath, skipTexture.EncodeToPNG()); + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Missing texture texture + // ----------------------------------------------------------------------------------------------------------------------------- + { + string emptyPath = Path.Combine(baseMaterialsFolder, "__TB_empty.png"); + DirectoryUtil.CreateAllDirectories(emptyPath); + + Texture2D emptyTexture = TextureUtil.GenerateColourTexture(Color.magenta); + await File.WriteAllBytesAsync(emptyPath, emptyTexture.EncodeToPNG()); + } + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Write configs + // ----------------------------------------------------------------------------------------------------------------------------- + bool wasNewInstall = false; + + using (TrembleTimerScope _ = new(TrembleTimer.Context.WriteEntitiesFgdAndGameConfig)) + { + WriteAllConfigFiles(fgdWriter, transparentBrushes); + wasNewInstall = await TrenchBroomUtil.WriteEnginePathIntoTrenchBroomPrefs(); + modTimeDB.WriteToFile(); + + if (assets != null && SyncSettings) + { + SyncSettings.AssetMetadatas = assets.ToArray(); + EditorUtility.SetDirty(SyncSettings); + AssetDatabase.SaveAssetIfDirty(SyncSettings); + } + } + + + // ----------------------------------------------------------------------------------------------------------------------------- + // Cleanup backups, if wanted + // ----------------------------------------------------------------------------------------------------------------------------- + using (TrembleTimerScope _ = new(TrembleTimer.Context.Cleanup)) + { + if (SyncSettings.AutoDeleteMapBackups) + { + TrembleMenu.DeleteAutosaves(); + } + } + + + // ----------------------------------------------------------------------------------------------------------------------------- + // Write Addressables data + // ----------------------------------------------------------------------------------------------------------------------------- +#if ADDRESSABLES_INSTALLED + if (SyncSettings.AllowStandaloneImport) + { + await TrembleSyncAddressables.SetupAddressables( + SyncSettings, + materialNameLookup, allMaterialPaths, + prefabNameLookup, allPrefabPaths, + allScriptableObjectTypes); + } +#endif + + // ----------------------------------------------------------------------------------------------------------------------------- + // Wait for any background tasks + // ----------------------------------------------------------------------------------------------------------------------------- + await Task.WhenAll(s_BackgroundTasks); + s_BackgroundTasks.Clear(); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Open settings if newly installed + // ----------------------------------------------------------------------------------------------------------------------------- + if (wasNewInstall) + { + if (TrenchBroomUtil.IsTrenchBroomRunning) + { + EditorUtility.DisplayDialog( + title: "TrenchBroom running!", + message: "Hey, your new Tremble game was just installed, but TrenchBroom was running. " + + "You will need to quit TrenchBroom and re-open it before editing any maps!", + "Oh, Okay!"); + } + + EditorApplication.delayCall += () => + { + TrembleEditorAPI.SyncToTrenchBroom(); + TrembleEditorAPI.ReimportAllMaps(silent: true); + + try + { + Assembly assembly = Assembly.GetAssembly(typeof(UnityEditor.Editor)); + Type type = assembly.GetType("UnityEditor.LogEntries"); + MethodInfo method = type.GetMethod("Clear"); + method?.Invoke(new object(), null); + } + finally + { + Debug.ClearDeveloperConsole(); + } + }; + } + } + catch (Exception ex) + { + Debug.LogError("Project Sync failed!"); + Debug.LogException(ex); + + ProgressUtil.Fail(s_ProgressTask); + } + finally + { + ProgressUtil.Succeed(s_ProgressTask); + + string baseq3Old = Path.Combine(Directory.GetCurrentDirectory(), "Library", "baseq3_old"); + if (Directory.Exists(baseq3Old)) + { + Directory.Delete(baseq3Old, true); + } + + TrembleTimer.EndSession(); + } + } + + private static void ReportProgress(ref int step, int numSteps, string assetName) + { + ProgressUtil.Report(s_ProgressTask, step++, numSteps, $"{assetName} ({step + 1}/{numSteps})"); + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Entity + // ----------------------------------------------------------------------------------------------------------------------------- + internal static FgdWriter GatherEntities() + { + List allBrushTypes = TypeDatabase.GetTypesWithAttribute().ToList(); + List allPointTypes = TypeDatabase.GetTypesWithAttribute().ToList(); + List allScriptableObjectTypes = new(128); + + int step = 0; + int numSteps = allBrushTypes.Count + allPointTypes.Count + allScriptableObjectTypes.Count; + + // These are not duplicates - they're only used from the entities manual page! + MapTypeLookup mapTypeLookup = new(SyncSettings); + PrefabNameLookup prefabNameLookup = new(SyncSettings); + MaterialNameLookup materialNameLookup = new(SyncSettings); + ModTimeDB modTimeDB = new(TrembleConsts.MODTIME_DB_PATH); + + List prefabMaterialPaths = new(prefabNameLookup.AllPrefabPaths.Count * 2); + List transparentBrushes = new(allBrushTypes.Count); + List assets = new(prefabNameLookup.AllPrefabPaths.Count * 2); + + return GatherEntities(ref step, numSteps, + prefabNameLookup, materialNameLookup, mapTypeLookup, modTimeDB, + TrembleConsts.BASE_MODELS_PATH, TrembleConsts.BASE_MATERIALS_PATH, + prefabMaterialPaths, transparentBrushes, + allBrushTypes, allPointTypes, allScriptableObjectTypes, + assets); + } + private static FgdWriter GatherEntities(ref int step, int numSteps, + PrefabNameLookup prefabNameLookup, MaterialNameLookup materialNameLookup, MapTypeLookup typeLookup, ModTimeDB modTimeDB, + string modelsFolder, string baseMaterialsFolder, + List prefabMaterialPaths, List transparentBrushes, + List allBrushTypes, List allPointTypes, List allScriptableObjectTypes, + List assets) + { + TrembleFieldConverterCollection fieldConverter = new(); + + FgdWriter fgdWriter = new(TrembleConsts.VERSION_STRING, SyncSettings); + + DiscoverAndAddBaseClasses(fgdWriter, fieldConverter, allScriptableObjectTypes); + { + // Prefabs + foreach (string prefabPath in prefabNameLookup.AllPrefabPaths) + { + string rawPrefabName = Path.GetFileNameWithoutExtension(prefabPath); + prefabNameLookup.TryGetMapNameFromPrefabPath(prefabPath, out string prefabName); + + ReportProgress(ref step, numSteps, prefabName); + ProcessPrefab(prefabName, rawPrefabName, prefabPath, prefabMaterialPaths, modelsFolder, fgdWriter, fieldConverter, materialNameLookup, modTimeDB, allScriptableObjectTypes, assets); + } + + // Point MonoBehaviours + foreach (Type pointType in allPointTypes) + { + ReportProgress(ref step, numSteps, pointType.Name); + ProcessPointEntity(pointType, modelsFolder, fgdWriter, fieldConverter, typeLookup, allScriptableObjectTypes); + } + + // Brush MonoBehaviours + foreach (Type brushType in allBrushTypes) + { + ReportProgress(ref step, numSteps, brushType.Name); + ProcessBrushEntity(brushType, transparentBrushes, baseMaterialsFolder, fgdWriter, fieldConverter, typeLookup, allScriptableObjectTypes); + } + } + + // Export worldspawn data + Type worldspawnScriptType = SyncSettings.WorldspawnScript?.Class ?? typeof(Worldspawn); + + FgdClass worldspawn = new(FgdClassType.Brush, "worldspawn", "The root Worldspawn entity class"); + { + AddExposedFieldsToEntity(worldspawnScriptType, worldspawn, fieldConverter, allScriptableObjectTypes); + } + fgdWriter.WorldspawnClass = worldspawn; + + return fgdWriter; + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Processing + // ----------------------------------------------------------------------------------------------------------------------------- + private static bool ProcessMaterial(MapTextureSnapshotter snapshotter, string materialPath, string mapName, string outputPath, ModTimeDB modTimeDB, List assets) + { + if (materialPath.IsNullOrEmpty()) + return false; + + Material material = AssetDatabase.LoadAssetAtPath(materialPath); + if (!material) + { + //Debug.LogError($"Material {materialPath} not found!"); + return false; + } + + try + { + ulong lastModified = modTimeDB.GetFileModifiedTime(material); + ulong nowModified = ModTimeDB.CalcMaterialModifiedTime(material); + modTimeDB.SetFileModifiedTime(material, nowModified); + + // Store metadata about material + assets.Add(new() + { + MapName = mapName, + Path = materialPath, + FullTypeName = typeof(Material).FullName, + +#if ADDRESSABLES_INSTALLED + AddressableName = TrembleSyncAddressables.GetExistingEntryForPath(materialPath)?.address ?? material.name, +#endif + }); + + MaterialRenderData data = SyncSettings.GetMaterialRenderData(material); + + if (nowModified <= lastModified && !data.IsDirty && TryCopyLastVersion(outputPath)) + { + // No modifications, old value copied! + return true; + } + + DirectoryUtil.CreateAllDirectories(outputPath); + snapshotter.SnapshotMaterial(material, outputPath); + + if (data != null) + { + data.ClearDirty(); + EditorUtility.SetDirty(SyncSettings); + } + } + catch (Exception ex) + { + Debug.LogError(ex); + return false; + } + + return true; + } + + + private static bool ProcessPrefab(string prefabName, string unityPrefabName, string prefabPath, List materialsList, string modelsFolder, FgdWriter fgdWriter, TrembleFieldConverterCollection fieldConverter, MaterialNameLookup materialNameLookup, ModTimeDB modTimeDB, List scriptableObjectTypes, List assets) + { + GameObject prefab = AssetDatabase.LoadAssetAtPath(prefabPath); + string modelPath = Path.Combine(modelsFolder, $"{prefabName}.md3"); + + // Check if we have an up-to-date MD3 for this prefab already + bool dontCreateMD3 = false; + + ulong lastModified = modTimeDB.GetFileModifiedTime(prefab); + ulong nowModified = ModTimeDB.CalcModelModifiedTime(prefab); + modTimeDB.SetFileModifiedTime(prefab, nowModified); + + if (nowModified <= lastModified && TryCopyLastVersion(modelPath)) + { + dontCreateMD3 = true; + } + + foreach (MonoBehaviour mb in prefab.GetComponents()) + { + if (!mb) + { + Debug.LogWarning($"Prefab {prefab.name} has a broken/missing MonoBehaviour!"); + continue; + } + + Type prefabType = mb.GetType(); + + if (!prefabType.TryGetCustomAttribute(out PrefabEntityAttribute pea)) + continue; + + if (!pea.IsPrefabIncluded(unityPrefabName)) + continue; + + // Sanity check position + rotation + if (prefab.transform.position.sqrMagnitude > 1f) + { + Debug.LogWarning($"WARNING: Prefab {prefab.name} has an position offset of {prefab.transform.position}. This is probably unintended and will affect how your prefab appears in TrenchBroom! Set the prefab's position to (0, 0, 0) for best results.", prefab); + } + + if (prefab.transform.rotation.eulerAngles.magnitude > 1f) + { + Debug.LogWarning($"WARNING: Prefab {prefab.name} has a rotation of {prefab.transform.rotation.eulerAngles}. This is probably unintended and will affect how your prefab appears in TrenchBroom! Set the prefab's rotation to (0, 0, 0) for best results.", prefab); + } + + // Write materials used by prefab into material list + FindAndAddMaterialsUsedByPrefab(prefab, materialsList); + + // Write MD3 or use existing metadata + bool hasModel = dontCreateMD3 + ? MD3Util.HasModel(prefab, out Bounds modelBounds) + : MD3Util.SaveMD3(prefab, modelPath, materialNameLookup, SyncSettings.ImportScale, out modelBounds); + + string overrideSprite = pea.OverrideSprite; + if (mb is TrembleSpawnablePrefab tsp && tsp.OverrideSprite != null) + { + overrideSprite = Path.GetFileNameWithoutExtension(AssetDatabase.GetAssetPath(tsp.OverrideSprite)); + } + + if (overrideSprite != null) + { + hasModel = false; + + string srcPngPath = TrembleAssetLoader.FindAssetPath(overrideSprite); + string destPngPath = Path.Combine(modelsFolder, $"{overrideSprite}.png"); + File.Copy(srcPngPath, destPngPath, true); + } + + string prefabTypeDescription = prefabType == typeof(TrembleSpawnablePrefab) + ? $"Tremble Spawnable Prefab '{unityPrefabName}'" + : $"[PrefabEntity] class {prefabType.Name}, from prefab '{Path.GetFileNameWithoutExtension(prefabPath)}'"; + + FgdClass entityClass = new(FgdClassType.Point, prefabName, prefabTypeDescription) + { + HasModel = hasModel, + Sprite = overrideSprite, + Box = hasModel ? modelBounds : null, + }; + + entityClass.AddBaseClass(FgdConsts.CLASS_MAP_BASE); + entityClass.AddBaseClass(FgdConsts.CLASS_MAP_PREFAB_BASE); + entityClass.AddBaseClassInterfaces(prefabType); + AddExposedFieldsToEntity(prefabType, entityClass, fieldConverter, scriptableObjectTypes, prefab.GetComponent(prefabType)); + + fgdWriter.AddClass(entityClass); + + // Store metadata about prefab + assets.Add(new() + { + MapName = prefabName, + Path = prefabPath, + FullTypeName = typeof(GameObject).FullName, + +#if ADDRESSABLES_INSTALLED + AddressableName = TrembleSyncAddressables.GetExistingEntryForPath(prefabPath)?.address ?? unityPrefabName, +#endif + + SpawnOffset = MD3Util.GetPrefabUnitySpawnOffset(prefab, SyncSettings.ImportScale) + }); + + return true; + } + + return false; + } + + private static bool TryCopyLastVersion(string outputFile) + { + string oldVersion = outputFile.Replace("baseq3", "baseq3_old"); + if (!File.Exists(oldVersion)) + return false; + + ContinueInBackground(() => + { + DirectoryUtil.CreateAllDirectories(outputFile); + try + { + File.Copy(oldVersion, outputFile, true); + } + catch (IOException) + { + Debug.LogError($"Failed to copy old version of '{Path.GetFileName(outputFile)}'"); + } + }); + + return true; + } + + private static bool ProcessPointEntity(Type pointType, string modelsFolder, FgdWriter fgdWriter, TrembleFieldConverterCollection fieldConverter, MapTypeLookup typeLookup, List scriptableObjectTypes) + { + if (!pointType.IsSubclassOf(typeof(MonoBehaviour))) + { + Debug.LogError($"[PointEntity] {pointType.Name} is NOT a MonoBehaviour or derived from a type that is a MonoBehaviour. This won't work! Your class should appear as e.g. public class {pointType.Name} : MonoBehaviour"); + return false; + } + + typeLookup.TryGetMapNameFromClass(pointType, out string name); + pointType.TryGetCustomAttribute(out PointEntityAttribute pea); + + float size = pea.Size; + + // Write sprite, if any + if (!pea.Sprite.IsNullOrEmpty()) + { + string spritePath = TrembleAssetLoader.FindAssetPath(pea.Sprite); + if (spritePath.IsNullOrEmpty()) + { + Debug.LogWarning($"Couldn't find sprite '{pea.Sprite}' for Point Entity '{pointType.Name}'!"); + } + else + { + Texture2D texture = AssetDatabase.LoadAssetAtPath(spritePath); + if (texture) + { + size = (texture.width * SyncSettings.ImportScale) + 0.2f; + } + + string spriteFilename = Path.GetFileName(spritePath); + string outputPath = Path.Combine(modelsFolder, spriteFilename); + + ContinueInBackground(() => File.Copy(spritePath, outputPath, true)); + } + } + + FgdClass entityClass = new(FgdClassType.Point, name, $"[PointEntity] class {pointType.Name} ('{name}')") + { + Colour = pea.Colour, + Box = new Bounds(Vector3.zero, Vector3.one * size), + Sprite = pea.Sprite + }; + + entityClass.AddBaseClass(FgdConsts.CLASS_MAP_BASE); + entityClass.AddBaseClass(FgdConsts.CLASS_MAP_POINT_BASE); + entityClass.AddBaseClassInterfaces(pointType); + AddExposedFieldsToEntity(pointType, entityClass, fieldConverter, scriptableObjectTypes); + fgdWriter.AddClass(entityClass); + + return true; + } + + private static bool ProcessBrushEntity(Type brushType, List transparentBrushes, string baseMaterialsFolder, FgdWriter fgdWriter, TrembleFieldConverterCollection fieldConverter, MapTypeLookup typeLookup, List scriptableObjectTypes) + { + if (!brushType.IsSubclassOf(typeof(MonoBehaviour))) + { + Debug.LogError($"[BrushEntity] {brushType.Name} is NOT a MonoBehaviour or derived from a type that is a MonoBehaviour. This won't work! Your class should appear as e.g. public class {brushType.Name} : MonoBehaviour"); + return false; + } + + typeLookup.TryGetMapNameFromClass(brushType, out string name); + brushType.TryGetCustomAttribute(out BrushEntityAttribute bea); + + // Add to transparent brushes if needed + if (bea.BrushType is BrushType.Invisible or BrushType.Trigger) + { + transparentBrushes.Add(name); + } + + // Write texture, if present + if (bea.Colour != null) + { + string specialPath = Path.Combine(baseMaterialsFolder, "special", $"{name}.png"); + DirectoryUtil.CreateAllDirectories(specialPath); + + if (bea.CheckerStyle == CheckerboardStyle.None) + { + Texture2D specialTexture = TextureUtil.GenerateColourTexture(bea.Colour.Value); + File.WriteAllBytes(specialPath, specialTexture.EncodeToPNG()); + } + else + { + bool useDarkCheckerboard = bea.CheckerStyle == CheckerboardStyle.Dark; + Color checkerColour = useDarkCheckerboard ? Color.black : Color.white; + + Texture2D specialTexture = TextureUtil.GenerateCheckerTexture(bea.Colour.Value, checkerColour); + File.WriteAllBytes(specialPath, specialTexture.EncodeToPNG()); + } + } + + FgdClass entityClass = new(FgdClassType.Brush, name, $"[BrushEntity] class {brushType.Name} ('{name}')"); + entityClass.AddBaseClass(FgdConsts.CLASS_MAP_BASE); + entityClass.AddBaseClassInterfaces(brushType); + AddExposedFieldsToEntity(brushType, entityClass, fieldConverter, scriptableObjectTypes); + fgdWriter.AddClass(entityClass); + + return true; + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Helpers + // ----------------------------------------------------------------------------------------------------------------------------- + private static void FindAndAddMaterialsUsedByPrefab(GameObject prefab, List intoList) + { + foreach (Renderer renderer in prefab.GetComponentsInChildren()) + { + if (renderer is not MeshRenderer and not SkinnedMeshRenderer) + continue; + + IEnumerable usedMaterials = renderer.sharedMaterials + .Select(AssetDatabase.GetAssetPath) + .Where(p => !p.IsNullOrEmpty()); + + foreach (string usedMaterial in usedMaterials) + { + if (intoList.Contains(usedMaterial)) + continue; + + intoList.Add(usedMaterial); + + } + } + } + + private static Component CreateComponentOnTesterObject(Type scriptType) + { + GameObject tester = new("Tester"); + + foreach (RequireComponent requiredComponent in scriptType.GetCustomAttributes()) + { + MaybeAddComponent(requiredComponent.m_Type0); + MaybeAddComponent(requiredComponent.m_Type1); + MaybeAddComponent(requiredComponent.m_Type2); + } + + Component testerScript = tester.AddComponent(scriptType); + return testerScript; + + void MaybeAddComponent(Type type) + { + // Null, no need to add! + if (type == null) + return; + + // Collider - add a box collider + if (type == typeof(Collider)) + type = typeof(BoxCollider); + + tester.AddComponent(type); + } + } + + internal static void AddExposedFieldsToEntity(Type scriptType, FgdClass entityClass, TrembleFieldConverterCollection fieldConverter, List scriptableObjectTypes, Component testerComponent = null) + { + bool addComments = SyncSettings.FgdFormattingStyle == FgdFormattingStyle.VeryVerbose; + bool alsoHandleSerializedFields = SyncSettings.SyncSerializedFields; + + // Create a "tester" - an instance to read the default values, add any pre-requisites + Component testerScript = testerComponent ?? CreateComponentOnTesterObject(scriptType); + + foreach (FieldInfo target in scriptType.GetAllInstanceFieldsIncludingPrivateAndBaseClasses()) + { + target.GetCustomAttributes(out TrembleAttribute ta, out NoTrembleAttribute nta, out SerializeField sfa); + + string overrideName = ta?.OverrideName; + + if (ta == null && !(sfa != null && alsoHandleSerializedFields) && !target.IsPublic) + { + // If not public, and not [MapSerialized], skip! + if (addComments) + { + entityClass.AddComment($"Skipped {target.FieldType.Name} {target.Name} - missing [Tremble] or [SerializedField]!"); + } + continue; + } + + if (nta != null) + { + // Specifically NOT serialised in maps - skip! + if (addComments) + { + entityClass.AddComment($"Skipped {target.FieldType.Name} {target.Name} - saw [NoTremble]."); + } + continue; + } + + // Special case: Prefabs and Materials + bool isMaterialOrPrefabField = target.FieldType == typeof(Material) || target.FieldType == typeof(GameObject); + if (isMaterialOrPrefabField && ta == null && !SyncSettings.SyncMaterialsAndPrefabs) + { + // This is a Material or Prefab but we've turned off the setting + if (addComments) + { + entityClass.AddComment($"Skipped {target.FieldType.Name} {target.Name} - Material or Prefab, but the SyncMaterialsAndPrefabs setting is off."); + } + continue; + } + + string fieldName = overrideName ?? target.Name.GetFieldNameInMap(SyncSettings.FieldNamingConvention); + TrembleFieldConverter converter = fieldConverter.GetConverterForType(target.FieldType); + + if (target.FieldType.IsSubclassOf(typeof(ScriptableObject))) + { + scriptableObjectTypes.Add(target.FieldType); + } + + if (converter != null) + { + // Use a converter + object defaultValue = target.GetValue(testerScript); + if (defaultValue is Array defaultArray) + { + defaultValue = defaultArray.Length > 0 ? defaultArray.GetValue(0) : null; + } + converter.AddFieldToFgd(entityClass, fieldName, defaultValue, target); + } + else if (ta != null) + { + // Nothing worked - warning! + if (addComments) + { + entityClass.AddComment($"Skipped {target.FieldType.Name} {target.Name} - no field converter for a {target.FieldType}!"); + } + + Debug.LogWarning($"Saw field '{target.Name}' of type {target.FieldType}, which is not yet supported. Consider creating a TrembleFieldConverter for it!"); + } + } + + if (testerScript != testerComponent) + { + GameObject.DestroyImmediate(testerScript.gameObject); + } + } + + private static void DiscoverAndAddBaseClasses(FgdWriter fgd, TrembleFieldConverterCollection fieldConverter, List scriptableObjectTypes) + { + TypeCache.TypeCollection types = TypeCache.GetTypesDerivedFrom(); + foreach (Type baseType in types) + { + if (!baseType.IsInterface) + continue; + + string baseClassName = baseType.Name.Substring(1); // Remove 'I' + string baseClassDesc = $"Base Class from C# Interface '{baseType.Name}'"; + FgdClass baseClass = new(FgdClassType.Base, baseClassName, baseClassDesc); + + foreach (PropertyInfo target in baseType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + target.GetCustomAttributes(out TrembleAttribute ta, out NoTrembleAttribute nta); + + string overrideName = ta?.OverrideName; + + if (nta != null) + { + // Specifically NOT serialised in maps - skip! + continue; + } + + // Special case: Prefabs and Materials + bool isMaterialOrPrefabField = target.PropertyType == typeof(Material) || target.PropertyType == typeof(GameObject); + if (isMaterialOrPrefabField && ta == null && !SyncSettings.SyncMaterialsAndPrefabs) + { + // This is a Material or Prefab but we've turned off the setting + continue; + } + + ITrembleBaseClass defaultBaseType = TrembleBaseClassDefault.CreateDefault(baseType); + string fieldName = overrideName ?? target.Name.GetFieldNameInMap(SyncSettings.FieldNamingConvention); + TrembleFieldConverter converter = fieldConverter.GetConverterForType(target.PropertyType); + + if (target.PropertyType.IsSubclassOf(typeof(ScriptableObject))) + { + scriptableObjectTypes.Add(target.PropertyType); + } + + if (converter != null) + { + // Use a converter + converter.AddFieldToFgd(baseClass, fieldName, target.GetValue(defaultBaseType), target); + } + else if (ta != null) + { + // Nothing worked - warning! + Debug.LogWarning($"Saw field '{target.Name}' of type {target.PropertyType}, which is not yet supported. Consider creating a TrembleFieldConverter for it!"); + } + } + + fgd.AddClass(baseClass); + } + } + + // Continue a task on a worker thread. Don't touch Unity API in these callbacks!! + // These are awaited right at the end of the process. + private static void ContinueInBackground(Action action) + { + s_BackgroundTasks.Add(Task.Run(action)); + } + + private static void WriteAllConfigFiles(FgdWriter fgd, List invisibleBrushes) + { + // Write Files + string gameFolder = TrenchBroomUtil.GetGameFolder(); + DirectoryUtil.EmptyAndCreateDirectory(gameFolder); + + string gameConfigPath = Path.Combine(gameFolder, "gameconfig.cfg"); + string entitiesPath = Path.Combine(gameFolder, "entities.fgd"); + string iconPath = Path.Combine(gameFolder, "Icon.png"); + + // Write entities.fgd + using FileStream entityFile = new(entitiesPath, FileMode.Create, FileAccess.Write); + using StreamWriter sw = new(entityFile); + fgd.WriteFgd(sw, SyncSettings.FgdFormattingStyle is FgdFormattingStyle.HumanReadable or FgdFormattingStyle.VeryVerbose); + + // Write gameconfig.cfg + string version = SyncSettings.TrenchBroomGameConfigVersion; + + StringBuilder brushes = new(); + for (int brushIdx = 0; brushIdx < invisibleBrushes.Count; brushIdx++) + { + string invisibleBrush = invisibleBrushes[brushIdx]; + + if (brushIdx > 0) + { + brushes.AppendLine(","); + brushes.Append("\t\t\t"); + } + + brushes.AppendLine("{"); + brushes.AppendLine($"\t\t\t\t\"name\": \"{invisibleBrush}\","); + brushes.AppendLine($"\t\t\t\t\"attribs\": [ \"transparent\" ],"); + brushes.AppendLine($"\t\t\t\t\"match\": \"classname\","); + brushes.AppendLine($"\t\t\t\t\"pattern\": \"{invisibleBrush}\","); + brushes.AppendLine($"\t\t\t\t\"texture\": \"special/{invisibleBrush}\""); + brushes.Append("\t\t\t}"); + } + + string gameConfigFilename = $"gameconfig-{SyncSettings.TrenchBroomGameConfigVersion}.cfg"; + string gameConfigTemplatePath = Path.Combine(TrembleConsts.EDITOR_GetTrembleInstallFolder(), "Editor", "Templates", gameConfigFilename); + string gameConfigTemplate = File.ReadAllText(gameConfigTemplatePath); + string gameConfig = gameConfigTemplate + .Replace("$GAME_NAME", TrembleConsts.GAME_NAME) + .Replace("$BRUSHES", brushes.ToString()); + File.WriteAllText(gameConfigPath, gameConfig); + + // Copy Icon.png + bool copiedIcon = false; + Texture2D[] icons = PlayerSettings.GetIcons(NamedBuildTarget.Standalone, IconKind.Any); + for (int iconIdx = icons.Length - 1; iconIdx >= 0; iconIdx--) + { + if (!icons[iconIdx]) + continue; + + string sourceIconPath = Path.GetFullPath(AssetDatabase.GetAssetPath(icons[iconIdx])); + + ContinueInBackground(() => + { + File.Copy(sourceIconPath, iconPath, true); + File.SetAttributes(iconPath, FileAttributes.Normal); + }); + + copiedIcon = true; + break; + } + + if (!copiedIcon) + { + // No Icon! + } + } + + private static void UpgradeMaterialExportSettingsIfRequired() + { + // Older versions of Tremble encode this as an int, so we need to check that first + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + MaterialExportSize mes = syncSettings.MaterialExportSize; + + if ((int)mes <= 8) + return; + + int oldSize = (int)mes; + + bool hasResolvedSize = false; + for (int sizeIdx = 0; sizeIdx < MaterialExportSizeUtils.Names.Length; sizeIdx++) + { + int newSize = int.Parse(MaterialExportSizeUtils.Names[sizeIdx]); + + if (oldSize > newSize) + continue; + + mes = (MaterialExportSize)sizeIdx; + hasResolvedSize = true; + break; + } + + if (!hasResolvedSize) + { + // No matching size found - use default + mes = MaterialExportSizeUtils.GetDefault(); + } + + EditorUtility.DisplayDialog( + title: "Tremble Material Upgrade", + message: $"This new version of Tremble handles texture sizes differently. Your old size of {oldSize} has " + + $"been mapped to {mes}. Please verify this size is what you were expecting.", + ok: "Thanks!"); + + SerializedObject settingsObj = new(syncSettings); + SerializedProperty sizeProp = settingsObj.FindBackedProperty(nameof(syncSettings.MaterialExportSize)); + sizeProp.enumValueIndex = (int)mes; + settingsObj.ApplyModifiedPropertiesWithoutUndo(); + + EditorUtility.SetDirty(syncSettings); + AssetDatabase.SaveAssets(); + + TrembleEditorAPI.InvalidateMaterialAndPrefabCache(silent: true); + TrembleEditorAPI.SyncToTrenchBroom(); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/TrembleSync.cs.meta b/Assets/Tremble/Editor/TrembleSync.cs.meta new file mode 100644 index 0000000..48883f2 --- /dev/null +++ b/Assets/Tremble/Editor/TrembleSync.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: e9917c419f9e44e39a9696fc0cedfbc0 +timeCreated: 1698148085 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/TrembleSync.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/TrembleSyncAddressables.cs b/Assets/Tremble/Editor/TrembleSyncAddressables.cs new file mode 100644 index 0000000..0332f05 --- /dev/null +++ b/Assets/Tremble/Editor/TrembleSyncAddressables.cs @@ -0,0 +1,160 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +#if ADDRESSABLES_INSTALLED + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using UnityEditor; + +using UnityEditor.AddressableAssets; +using UnityEditor.AddressableAssets.Settings; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace TinyGoose.Tremble.Editor +{ + public static class TrembleSyncAddressables + { + private const string GROUP_TREMBLE_DATA = "Tremble Data"; + private const string GROUP_TREMBLE_PREFABS = "Tremble Prefabs"; + private const string GROUP_TREMBLE_MATERIALS = "Tremble Materials"; + + public static async Task SetupAddressables(TrembleSyncSettings settings, MaterialNameLookup materialNameLookup, List allMaterialPaths, PrefabNameLookup prefabNameLookup, List allPrefabPaths, List allAssetTypes) + { + using TrembleTimerScope _ = new(TrembleTimer.Context.ExportAddressableDataForStandalone); + + AddressableAssetSettings addressables = AddressableAssetSettingsDefaultObject.GetSettings(true); + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + + // Data/scriptable objects + AddressableAssetGroup dataGroup = addressables.FindOrCreateGroup(GROUP_TREMBLE_DATA); + addressables.AddEntryIfNotExist(dataGroup, settings, TrembleSyncSettings.ADDRESSABLE_KEY); + + foreach (string assetPath in allAssetTypes.SelectMany(t => TrembleAssetLoader.FindAssetPaths(t))) + { + addressables.AddEntryIfNotExist(dataGroup, assetPath); + } + + // Prefabs + AddressableAssetGroup prefabsGroup = addressables.FindOrCreateGroup(GROUP_TREMBLE_PREFABS); + foreach (string prefabPath in allPrefabPaths) + { + string prefabName = Path.GetFileNameWithoutExtension(prefabPath); + addressables.AddEntryIfNotExist(prefabsGroup, prefabPath, prefabName); + } + + // Materials + AddressableAssetGroup materialsGroup = addressables.FindOrCreateGroup(GROUP_TREMBLE_MATERIALS); + addressables.AddEntryIfNotExist(materialsGroup, TrembleAssetLoader.LoadAssetByName("M_Clip")); + foreach (string materialPath in allMaterialPaths) + { + if (!materialNameLookup.TryGetMapNameFromMaterialPath(materialPath, out string mapName)) + continue; + + addressables.AddEntryIfNotExist(materialsGroup, materialPath, mapName); + } + + // Add in any unexpected addressables + List assets = new(syncSettings.AssetMetadatas); + + List trembleEntries = new(1024); + addressables.GetAllAssets(trembleEntries, false, entryFilter: (e) => e.labels.Contains("Tremble")); + + foreach (AddressableAssetEntry entry in trembleEntries) + { + if (syncSettings.AssetMetadatas.Any(am => am.AddressableName == entry.address)) + continue; + + if (entry.MainAssetType == typeof(TrembleSyncSettings)) + continue; + + assets.Add(new() + { + AddressableName = entry.address, + MapName = entry.address, + Path = entry.AssetPath, + + FullTypeName = entry.MainAssetType.FullName, + }); + } + + // Write out resources + syncSettings.AssetMetadatas = assets.ToArray(); + EditorUtility.SetDirty(syncSettings); + AssetDatabase.SaveAssetIfDirty(syncSettings); + + await PackedResourceUtil.PackFolderIntoResource(TrembleConsts.BASEQ3_PATH, TrembleRuntimeAPI.TREMBLE_BASEQ3_RESOURCE); + await PackedResourceUtil.PackFolderIntoResource(TrenchBroomUtil.GetGameFolder(), TrembleRuntimeAPI.TREMBLE_GAME_RESOURCE); + + AssetDatabase.Refresh(); + } + + public static AddressableAssetEntry GetExistingEntryForPath(string assetPath) + { + AddressableAssetSettings addressables = AddressableAssetSettingsDefaultObject.GetSettings(true); + + string assetGuid = AssetDatabase.GUIDFromAssetPath(assetPath).ToString(); + return addressables.FindAssetEntry(assetGuid, true); + } + + private static AddressableAssetGroup FindOrCreateGroup(this AddressableAssetSettings settings, string name, bool clear = false) + { + AddressableAssetGroup matchingGroup = settings.FindGroup(name); + if (matchingGroup) + { + if (clear) + { + List entries = new(matchingGroup.entries); + foreach (AddressableAssetEntry entry in entries) + { + matchingGroup.RemoveAssetEntry(entry); + } + } + + return matchingGroup; + } + + return settings.CreateGroup(name, false, false, true, settings.DefaultGroup.Schemas, settings.DefaultGroup.SchemaTypes.ToArray()); + } + + private static AddressableAssetEntry AddEntryIfNotExist(this AddressableAssetSettings settings, AddressableAssetGroup group, string newObjectPath, string address = null) + => AddEntryIfNotExist(settings, group, AssetDatabase.LoadAssetAtPath(newObjectPath), address); + + private static AddressableAssetEntry AddEntryIfNotExist(this AddressableAssetSettings settings, AddressableAssetGroup group, Object newObject, string address = null) + { + if (!newObject) + { + Debug.LogWarning("Could not add an Addressable entry for a NULL object!"); + return null; + } + + string assetPath = AssetDatabase.GetAssetPath(newObject); + string guid = AssetDatabase.GUIDFromAssetPath(assetPath).ToString(); + + if (assetPath.IsNullOrEmpty()) + { + Debug.LogWarning($"Could not add an Addressable entry for {newObject.name} - could not find path!"); + return null; + } + + AddressableAssetEntry entry = GetExistingEntryForPath(assetPath); + + if (entry == null) + { + entry = settings.CreateOrMoveEntry(guid, group); + entry.SetAddress(address != null ? address.Sanitise(new() { '[', ']' }) : newObject.name); + } + + entry.SetLabel("Tremble", true, force: true); + + return entry; + } + } +} +#endif \ No newline at end of file diff --git a/Assets/Tremble/Editor/TrembleSyncAddressables.cs.meta b/Assets/Tremble/Editor/TrembleSyncAddressables.cs.meta new file mode 100644 index 0000000..3fdf171 --- /dev/null +++ b/Assets/Tremble/Editor/TrembleSyncAddressables.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: cb4b1464324e476d91169feef4ff231e +timeCreated: 1715707371 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/TrembleSyncAddressables.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Utils.meta b/Assets/Tremble/Editor/Utils.meta new file mode 100644 index 0000000..954f835 --- /dev/null +++ b/Assets/Tremble/Editor/Utils.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 8dda8c2e03a34342b4341df80bdd5138 +timeCreated: 1698306074 \ No newline at end of file diff --git a/Assets/Tremble/Editor/Utils/AssetDatabaseUtil.cs b/Assets/Tremble/Editor/Utils/AssetDatabaseUtil.cs new file mode 100644 index 0000000..b546e0e --- /dev/null +++ b/Assets/Tremble/Editor/Utils/AssetDatabaseUtil.cs @@ -0,0 +1,37 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + internal static class AssetDatabaseUtil + { + internal static List GetAllTrembleMapPaths() + { + List allMaps = new(); + + string[] assetPaths = AssetDatabase.GetAllAssetPaths(); + foreach (string assetPath in assetPaths) + { + if (!IsTrembleMapFile(assetPath)) + continue; + + if (assetPath.Contains("autosave/")) + continue; + + allMaps.Add(assetPath); + } + + return allMaps; + } + + internal static bool IsTrembleMapFile(string assetPath) + => Path.GetExtension(assetPath).EqualsInvariant(".map"); + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Utils/AssetDatabaseUtil.cs.meta b/Assets/Tremble/Editor/Utils/AssetDatabaseUtil.cs.meta new file mode 100644 index 0000000..0f4ac4b --- /dev/null +++ b/Assets/Tremble/Editor/Utils/AssetDatabaseUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ee00bb59f3db43ceb0674202088a8b91 +timeCreated: 1707729646 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Utils/AssetDatabaseUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Utils/EditorCompileUtil.cs b/Assets/Tremble/Editor/Utils/EditorCompileUtil.cs new file mode 100644 index 0000000..56d75a5 --- /dev/null +++ b/Assets/Tremble/Editor/Utils/EditorCompileUtil.cs @@ -0,0 +1,113 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public static class EditorCompileUtil + { + private static readonly EditorPrefsBackedString s_CompileList = new("Tremble_PostCompileActions"); + + /// + /// Compile scripts, then call a static method. + /// Method MUST be static. + /// Method can be private or public. + /// Method must take 0 args, or any number of STRING args only. + /// + /// Type containing method + /// Method name (use nameof) + /// Optional list of STRING only args to pass (must not contain ',') + public static void CompileThen(Type type, string staticFunctionName, params string[] stringArgs) + { + foreach (string stringArg in stringArgs) + { + if (stringArg.Contains(',')) + { + Debug.LogError($"Cannot schedule call to {type.Name}.{staticFunctionName} - arg contains ',' :("); + return; + } + } + + // Add to compile list, backed by editor prefs + string[] existing = s_CompileList.Values; + string[] newList = new string[existing.Length + 1]; + + if (existing.Length > 0) + { + Array.Copy(existing, newList, existing.Length); + } + + newList[^1] = $"{type.FullName}.{staticFunctionName}({String.Join(',', stringArgs)})"; + s_CompileList.Values = newList; + + // Now recompile + AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate); + } + + [UnityEditor.Callbacks.DidReloadScripts] + private static void PostCompile() + { + try + { + // Get list of calls and call each one + string[] calls = s_CompileList.Values; + foreach (string call in calls) + { + RunCall(call); + } + } + finally + { + // Finally clear! + s_CompileList.Values = null; + } + } + + private static void RunCall(string call) + { + Match match = Regex.Match(call, @"(.+)\.(.+?)\((.+?)?\)"); + if (match.Groups.Count < 4) + { + Debug.LogError($"Call '{call}' was not in the correct format :("); + return; + } + + string className = match.Groups[1].Captures[0].Value; + string methodName = match.Groups[2].Captures[0].Value; + + string argString = match.Groups[3].Captures.Count > 0 ? match.Groups[3].Captures[0].Value : null; + string[] args = argString.IsNullOrEmpty() ? Array.Empty() : argString.Split(','); + + Type finalType = Unsupported.GetTypeFromFullName(className); + if (finalType == null) + { + Debug.LogError($"Couldn't find type {className}!"); + return; + } + + MethodInfo method = finalType.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if (method == null) + { + Debug.LogError($"Couldn't find static method {finalType.Name}.{methodName}!"); + return; + } + + int numDeclaringParams = method.GetParameters().Length; + if (numDeclaringParams != args.Length) + { + Debug.LogError($"Couldn't call static method {finalType.Name}.{methodName} with {args.Length} args (expected: {numDeclaringParams}!"); + return; + } + + method.Invoke(null, args.Select(s => (object)s).ToArray()); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Utils/EditorCompileUtil.cs.meta b/Assets/Tremble/Editor/Utils/EditorCompileUtil.cs.meta new file mode 100644 index 0000000..4530d7c --- /dev/null +++ b/Assets/Tremble/Editor/Utils/EditorCompileUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 024f8fc5df2a44c288a85b38e4688027 +timeCreated: 1725008201 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Utils/EditorCompileUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Utils/EditorPrefsBackedString.cs b/Assets/Tremble/Editor/Utils/EditorPrefsBackedString.cs new file mode 100644 index 0000000..9d6451f --- /dev/null +++ b/Assets/Tremble/Editor/Utils/EditorPrefsBackedString.cs @@ -0,0 +1,81 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using UnityEditor; + +namespace TinyGoose.Tremble.Editor +{ + public class EditorPrefsBackedString + { + private readonly string m_Key; + private string m_Value; + + public EditorPrefsBackedString(string key) + { + m_Key = key; + } + + public string Value + { + get + { + if (m_Value == null) + { + if (!EditorPrefs.HasKey(m_Key)) + return null; + + m_Value = EditorPrefs.GetString(m_Key); + } + + return m_Value; + } + + set + { + m_Value = value; + + if (value == null) + { + EditorPrefs.DeleteKey(m_Key); + return; + } + + EditorPrefs.SetString(m_Key, value); + } + } + + public string[] Values + { + get + { + if (m_Value == null) + { + if (!EditorPrefs.HasKey(m_Key)) + return Array.Empty(); + + m_Value = EditorPrefs.GetString(m_Key); + } + + return m_Value.IsNullOrEmpty() ? Array.Empty() : m_Value.Split(';'); + } + + set + { + if (value == null) + { + m_Value = null; + EditorPrefs.DeleteKey(m_Key); + return; + } + + string joinedValue = String.Join(';', value); + m_Value = joinedValue; + + EditorPrefs.SetString(m_Key, joinedValue); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Utils/EditorPrefsBackedString.cs.meta b/Assets/Tremble/Editor/Utils/EditorPrefsBackedString.cs.meta new file mode 100644 index 0000000..1f67668 --- /dev/null +++ b/Assets/Tremble/Editor/Utils/EditorPrefsBackedString.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: c91b5487d0aa4bd1ab8350151bb0e544 +timeCreated: 1724773115 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Utils/EditorPrefsBackedString.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Utils/ModTimeDB.cs b/Assets/Tremble/Editor/Utils/ModTimeDB.cs new file mode 100644 index 0000000..e1bfb0f --- /dev/null +++ b/Assets/Tremble/Editor/Utils/ModTimeDB.cs @@ -0,0 +1,158 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace TinyGoose.Tremble.Editor +{ + public class ModTimeDB + { + private readonly string m_DbFile; + private readonly Dictionary m_Data = new(); + + public ModTimeDB(string dbFile) + { + m_DbFile = dbFile; + ReadFromFile(); + } + + public ulong GetFileModifiedTime(Object asset) + { + string assetDatabasePath = AssetDatabase.GetAssetPath(asset); + if (assetDatabasePath.IsNullOrEmpty() || !m_Data.TryGetValue(assetDatabasePath, out ulong time)) + return 0ul; + + return time; + } + + public void SetFileModifiedTime(Object asset, ulong time) + { + string assetDatabasePath = AssetDatabase.GetAssetPath(asset); + if (assetDatabasePath.IsNullOrEmpty()) + return; + + m_Data[assetDatabasePath] = time; + } + + public static ulong CalcModelModifiedTime(GameObject gameObject) + { + ulong time = 0ul; + + // Prefab time + AppendObjectModifiedTime(gameObject, ref time); + + // Materials + foreach (Renderer renderer in gameObject.GetComponentsInChildren()) + { + foreach (Material material in renderer.sharedMaterials) + { + if (!material) + continue; + + ulong matTime = CalcMaterialModifiedTime(material); + if (matTime > time) + { + time = matTime; + } + } + } + + // Meshes + foreach (MeshFilter filter in gameObject.GetComponentsInChildren()) + { + if (!filter.sharedMesh) + continue; + + AppendObjectModifiedTime(filter.sharedMesh, ref time); + } + + return time; + } + + public static ulong CalcMaterialModifiedTime(Material material) + { + ulong time = 0ul; + + // Material time + AppendObjectModifiedTime(material, ref time); + + if (material.shader) + { + // Shader time + AppendObjectModifiedTime(material.shader, ref time); + + foreach (string texName in material.GetTexturePropertyNames()) + { + // Texture times + Texture texture = material.GetTexture(texName); + if (!texture) + continue; + + AppendObjectModifiedTime(texture, ref time); + } + } + + return time; + } + + + private void ReadFromFile() + { + if (!File.Exists(m_DbFile)) + return; + + string data = File.ReadAllText(m_DbFile); + + TokenParser tp = new(data); + while (!tp.IsAtEnd) + { + ReadOnlySpan file = tp.ReadToken(supportCommentsAndQuotes: true); + ulong time = tp.ReadUlong(); + + m_Data[file.ToString()] = time; + } + } + + public void WriteToFile() + { + using FileStream stream = new(m_DbFile, FileMode.Create, FileAccess.Write); + using StreamWriter writer = new(stream); + + foreach ((string file, ulong time) in m_Data) + { + writer.WriteLine($"\"{file}\" {time}"); + } + } + + public static ulong GetObjectModifiedTime(Object unityObject) + { + string objectPath = AssetDatabase.GetAssetPath(unityObject); + + if (objectPath.IsNullOrEmpty()) + return 0ul; + + AssetImporter importer = AssetImporter.GetAtPath(objectPath); + if (!importer) + return 0ul; + + return importer.assetTimeStamp; + } + + private static void AppendObjectModifiedTime(Object unityObject, ref ulong time) + { + ulong thisTime = GetObjectModifiedTime(unityObject); + + if (thisTime > time) + { + time = thisTime; + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Utils/ModTimeDB.cs.meta b/Assets/Tremble/Editor/Utils/ModTimeDB.cs.meta new file mode 100644 index 0000000..e0ea431 --- /dev/null +++ b/Assets/Tremble/Editor/Utils/ModTimeDB.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 9ad6c3317444439e821b6999629b97e0 +timeCreated: 1711965846 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Utils/ModTimeDB.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Utils/SerializedObjectUtil.cs b/Assets/Tremble/Editor/Utils/SerializedObjectUtil.cs new file mode 100644 index 0000000..6c03dac --- /dev/null +++ b/Assets/Tremble/Editor/Utils/SerializedObjectUtil.cs @@ -0,0 +1,169 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using UnityEditor; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace TinyGoose.Tremble.Editor +{ + internal static class SerializedObjectUtil + { + internal static void Modify(this Component component, Action actions) => Modify(new SerializedObject(component), actions); + + internal static void Modify(this Object obj, Action actions) => Modify(new SerializedObject(obj), actions); + + + private static void Modify(SerializedObject so, Action actions) + { + actions?.Invoke(so); + so.ApplyModifiedPropertiesWithoutUndo(); + } + + internal static SerializedProperty FindBackedProperty(this SerializedObject obj, string name) => obj.FindProperty("m_" + name); + internal static SerializedProperty FindBackedRelativeProperty(this SerializedProperty obj, string name) => obj.FindPropertyRelative("m_" + name); + + internal static SerializedProperty AppendArrayElement(this SerializedProperty prop) + { + int elemIdx = prop.arraySize; + prop.InsertArrayElementAtIndex(elemIdx); + return prop.GetArrayElementAtIndex(elemIdx); + } + + internal static uint GetHashOfContent(this SerializedProperty prop) + { +#if UNITY_2022_1_OR_NEWER + if (prop.propertyType == SerializedPropertyType.Generic && !prop.isArray) + return (uint)prop.boxedValue.GetHashCode(); + + return prop.contentHash; +#else + switch (prop.propertyType) + { + case SerializedPropertyType.Integer: + return (uint)prop.intValue.GetHashCode(); + case SerializedPropertyType.Boolean: + return (uint)prop.boolValue.GetHashCode(); + case SerializedPropertyType.Float: + return (uint)prop.floatValue.GetHashCode(); + case SerializedPropertyType.String: + return (uint)prop.stringValue.GetHashCode(); + case SerializedPropertyType.Color: + return (uint)prop.colorValue.GetHashCode(); + case SerializedPropertyType.ObjectReference: + return (uint)(prop.objectReferenceValue ? prop.objectReferenceValue.GetHashCode() : 0); + case SerializedPropertyType.LayerMask: + return (uint)prop.intValue.GetHashCode(); + case SerializedPropertyType.Enum: + return (uint)prop.enumValueIndex.GetHashCode(); + case SerializedPropertyType.Vector2: + return (uint)prop.vector2Value.GetHashCode(); + case SerializedPropertyType.Vector3: + return (uint)prop.vector3Value.GetHashCode(); + case SerializedPropertyType.Vector4: + return (uint)prop.vector4Value.GetHashCode(); + case SerializedPropertyType.Rect: + return (uint)prop.rectValue.GetHashCode(); + case SerializedPropertyType.Character: + return (uint)prop.intValue.GetHashCode(); + case SerializedPropertyType.AnimationCurve: + return (uint)prop.animationCurveValue.GetHashCode(); + case SerializedPropertyType.Bounds: + return (uint)prop.boundsValue.GetHashCode(); + + case SerializedPropertyType.Generic: + return (uint)(prop.isArray ? prop.arraySize : 0); + + default: + Debug.LogWarning("Unsupported property type: " + prop.propertyType + $" '{prop.name}'"); + return 0u; + } +#endif + } + + internal static void SetTo(this SerializedProperty prop, SerializedProperty other) + { + switch (other.propertyType) + { + case SerializedPropertyType.Integer: + prop.intValue = other.intValue; + break; + case SerializedPropertyType.Boolean: + prop.boolValue = other.boolValue; + break; + case SerializedPropertyType.Float: + prop.floatValue = other.floatValue; + break; + case SerializedPropertyType.String: + prop.stringValue = other.stringValue; + break; + case SerializedPropertyType.Color: + prop.colorValue = other.colorValue; + break; + case SerializedPropertyType.ObjectReference: + prop.objectReferenceValue = other.objectReferenceValue; + break; + case SerializedPropertyType.LayerMask: + prop.intValue = other.intValue; + break; + case SerializedPropertyType.Enum: + prop.enumValueIndex = other.enumValueIndex; + break; + case SerializedPropertyType.Vector2: + prop.vector2Value = other.vector2Value; + break; + case SerializedPropertyType.Vector3: + prop.vector3Value = other.vector3Value; + break; + case SerializedPropertyType.Vector4: + prop.vector4Value = other.vector4Value; + break; + case SerializedPropertyType.Rect: + prop.rectValue = other.rectValue; + break; + case SerializedPropertyType.Character: + prop.intValue = other.intValue; + break; + case SerializedPropertyType.AnimationCurve: + prop.animationCurveValue = other.animationCurveValue; + break; + case SerializedPropertyType.Bounds: + prop.boundsValue = other.boundsValue; + break; + case SerializedPropertyType.Generic: + if (prop.isArray) + { + prop.ClearArray(); + for (int i = 0; i < other.arraySize; i++) + { + prop.AppendArrayElement().SetTo(prop.GetArrayElementAtIndex(i)); + } + } + else + { +#if UNITY_2022_1_OR_NEWER + prop.boxedValue = other.boxedValue; +#endif + } + + break; + +#if UNITY_2022_1_OR_NEWER + case SerializedPropertyType.Gradient: + prop.gradientValue = other.gradientValue; + break; +#endif + + default: + Debug.LogWarning("Unsupported property type: " + prop.propertyType + $" '{prop.name}'"); + break; + } + } + + internal static bool EqualByValue(this SerializedProperty prop, SerializedProperty other) + => prop.GetHashOfContent() == other.GetHashOfContent(); + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Utils/SerializedObjectUtil.cs.meta b/Assets/Tremble/Editor/Utils/SerializedObjectUtil.cs.meta new file mode 100644 index 0000000..d702528 --- /dev/null +++ b/Assets/Tremble/Editor/Utils/SerializedObjectUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 3865af53ccaf4f119a7f26638a8a9234 +timeCreated: 1707730421 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Utils/SerializedObjectUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Editor/Utils/VersionCheck.cs b/Assets/Tremble/Editor/Utils/VersionCheck.cs new file mode 100644 index 0000000..650c8e5 --- /dev/null +++ b/Assets/Tremble/Editor/Utils/VersionCheck.cs @@ -0,0 +1,152 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Linq; +using UnityEditor; +using UnityEngine; +using UnityEngine.Networking; +using UnityEngine.Serialization; + +namespace TinyGoose.Tremble.Editor +{ + [Serializable] + public record Changeset + { + public string Version; + public string[] Changes; + } + + [Serializable] + public record VersionsFile + { + public Changeset[] Changes; + } + + public static class VersionCheck + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Consts + // ----------------------------------------------------------------------------------------------------------------------------- + private const string VERSION_CHECK_URL = "https://tinygoose.com/data/tremble_version.json"; + + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private static VersionsFile s_Versions; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Public API + // ----------------------------------------------------------------------------------------------------------------------------- + public static bool HasData => s_Versions?.Changes is { Length: > 0 }; + private static Changeset LatestChange => s_Versions.Changes[0]; + + public static Changeset CurrentInstalledVersion + { + get + { + int currentVersion = GetVersion(TrembleConsts.VERSION_STRING); + if (HasData) + { + Changeset versionInfo = s_Versions.Changes.FirstOrDefault(c => GetVersion(c.Version) == currentVersion); + if (versionInfo != null) + return versionInfo; + } + + // Make an empty version info + return new() + { + Changes = new[] { "Development Version"}, + Version = TrembleConsts.VERSION_STRING, + }; + } + } + public static Changeset NewestAvailableVersion => HasData ? LatestChange : default; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Checking and prompting + // ----------------------------------------------------------------------------------------------------------------------------- + public static void FetchLatestVersionsInBackground(Action thenMainThread = null) + { + // Start web request on main thread + UnityWebRequest request = UnityWebRequest.Get(VERSION_CHECK_URL); + UnityWebRequestAsyncOperation async = request.SendWebRequest(); + async.completed += operation => + { + if (request.responseCode != 200) + return; + + s_Versions = JsonUtility.FromJson(request.downloadHandler.text); + + thenMainThread?.Invoke(); + }; + } + + public static bool IsNewerVersionAvailable + { + get + { + if (!HasData) + return false; + + int latestVersion = GetVersion(s_Versions.Changes[0].Version); + int currentVersion = GetVersion(TrembleConsts.VERSION_STRING); + + return latestVersion > currentVersion; + } + } + + public static void PromptToUpgradeIfAvailable(bool showEvenIfDeclined = false) + { + // First prompt to upgrade Tremble itself + bool showMainVersionUpgrade = IsNewerVersionAvailable && (showEvenIfDeclined || !HasPromptedForVersion(LatestChange.Version)); + if (showMainVersionUpgrade) + { + SetHasPromptedForVersion(LatestChange.Version); + EditorUtility.DisplayDialog( + title: "New Tremble Version", + message: $"A newer version of Tremble (v{LatestChange.Version}) is available! " + + "Open Window > Package Manager to update. You won't be reminded about this version again.", + ok: "Cool!"); + } + } + + public static string[] ChangesSinceCurrentVersion => HasData + ? s_Versions.Changes + .Where(c => GetVersion(c.Version) > GetVersion(TrembleConsts.VERSION_STRING)) + .SelectMany(c => c.Changes) + .ToArray() + : Array.Empty(); + + public static int NumVersionsBehind => HasData + ? s_Versions.Changes.Count(c => GetVersion(c.Version) > GetVersion(TrembleConsts.VERSION_STRING)) + : 0; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Editor prefs + // ----------------------------------------------------------------------------------------------------------------------------- + private static string GetPromptKey(string version) => $"Tremble_{Application.productName}_PromptedFor_{version}"; + private static bool HasPromptedForVersion(string version) => EditorPrefs.HasKey(GetPromptKey(version)); + private static void SetHasPromptedForVersion(string version) => EditorPrefs.SetBool(GetPromptKey(version), true); + + + // ----------------------------------------------------------------------------------------------------------------------------- + // Utils + // ----------------------------------------------------------------------------------------------------------------------------- + private static int GetVersion(string versionString) + { + if (versionString.IsNullOrEmpty()) + return 0; + + string[] parts = versionString.Split("."); + if (parts.Length != 3) + return 0; + + int[] intParts = parts.Select(p => int.TryParse(p, out int intPart) ? intPart : 0).ToArray(); + + return intParts[0] * 1000000 + intParts[1] * 1000 + intParts[2]; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Editor/Utils/VersionCheck.cs.meta b/Assets/Tremble/Editor/Utils/VersionCheck.cs.meta new file mode 100644 index 0000000..a696e7b --- /dev/null +++ b/Assets/Tremble/Editor/Utils/VersionCheck.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ff8e7fdbe35c46b1a9b0d0dc4b4757ac +timeCreated: 1720202784 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Editor/Utils/VersionCheck.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters.meta b/Assets/Tremble/FieldConverters.meta new file mode 100644 index 0000000..5918ade --- /dev/null +++ b/Assets/Tremble/FieldConverters.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f0a53ac27547247cabdbe0b303c23594 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tremble/FieldConverters/BaseClasses.meta b/Assets/Tremble/FieldConverters/BaseClasses.meta new file mode 100644 index 0000000..687db1b --- /dev/null +++ b/Assets/Tremble/FieldConverters/BaseClasses.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5d85820039b34dbdad142e9e57d62b6e +timeCreated: 1710147886 \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/BaseClasses/UnityAssetFieldConverter.cs b/Assets/Tremble/FieldConverters/BaseClasses/UnityAssetFieldConverter.cs new file mode 100644 index 0000000..11bb42c --- /dev/null +++ b/Assets/Tremble/FieldConverters/BaseClasses/UnityAssetFieldConverter.cs @@ -0,0 +1,120 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace TinyGoose.Tremble +{ + public static class UnityObjectFieldConverterStatics + { + public static readonly Dictionary s_CachedAssetLists = new(); + } + + public abstract class UnityAssetFieldConverter : TrembleFieldConverter + where TObjectType : Object + { + protected override bool TryGetValueFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out Object value) + { + if (!entity.TryGetString(key, out string objectName)) + { + value = null; + return false; + } + + return TryLoadObjectWithName(objectName, target.GetFieldOrPropertyTypeOrElementType(), key, entity, target, out value); + } + + protected override bool TryGetValuesFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out Object[] values) + { + if (!entity.TryGetString(key, out string objectNameString)) + { + values = default; + return false; + } + + string[] objectNames = objectNameString.Split(',').ToArray(); + values = new Object[objectNames.Length]; + + for (int objIdx = 0; objIdx < objectNames.Length; objIdx++) + { + if (!TryLoadObjectWithName(objectNames[objIdx], target.GetFieldOrPropertyTypeOrElementType(), key, entity, target, out Object foundObject)) + continue; + + values[objIdx] = foundObject; + } + + return true; + } + + private bool TryLoadObjectWithName(string name, Type objectType, string key, BspEntity entity, MemberInfo target, out Object obj) + { + string[] assetPaths = GetCachedAssetsPaths(objectType) + .Where(p => Path.GetFileNameWithoutExtension(p).EqualsInvariant(name)) + .ToArray(); + + if (assetPaths.Length > 1) + { + Debug.LogWarning($"Warning - importing {objectType.Name} value '{name}' for field '{key}', but multiple {objectType.Name}s match that name. Ensure your {target.GetFieldOrPropertyType().Name}s are named uniquely. Selecting the first available one!"); + + foreach (string assetPath in assetPaths) + { + Debug.LogWarning($"Could be: {assetPath}?", TrembleAssetLoader.LoadAssetByPath(assetPath)); + } + } + + if (assetPaths.Length == 0 || assetPaths[0].IsNullOrEmpty()) + { + string entityName = entity.GetID().IsNullOrEmpty() ? entity.GetClassname() : $"'{entity.GetID()}' ({entity.GetClassname()})"; + + Debug.LogWarning($"Couldn't find a {objectType.Name} asset named '{name}' in the project! Using default for entity {entityName}."); + + obj = null; + return false; + } + + obj = TrembleAssetLoader.LoadAssetByPath(assetPaths[0]); + return true; + } + + protected override void AddFieldToFgd(FgdClass entityClass, string fieldName, Object defaultValue, MemberInfo target) + { + target.GetCustomAttributes(out TooltipAttribute tooltip); + + string[] choices = GetCachedAssetsPaths(target.GetFieldOrPropertyTypeOrElementType()) + .Select(Path.GetFileNameWithoutExtension) + .ToArray(); + + string defaultString = Path.GetFileNameWithoutExtension(TrembleAssetLoader.GetPath(defaultValue)); + + entityClass.AddField(new FgdChoicesStringField + { + Name = fieldName, + Choices = choices, + Description = tooltip?.tooltip ?? $"{target.GetFieldOrPropertyType()} {target.Name}", + DefaultValue = defaultString + }); + } + + private string[] GetCachedAssetsPaths(Type actualType) + { + if (!UnityObjectFieldConverterStatics.s_CachedAssetLists.TryGetValue(actualType, out string[] assetPaths)) + { + List assetPathList = TrembleAssetLoader.FindAssetPaths(actualType).ToList(); + assetPathList.Insert(0, ""); + + assetPaths = assetPathList.ToArray(); + UnityObjectFieldConverterStatics.s_CachedAssetLists[actualType] = assetPaths; + } + + return assetPaths; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/BaseClasses/UnityAssetFieldConverter.cs.meta b/Assets/Tremble/FieldConverters/BaseClasses/UnityAssetFieldConverter.cs.meta new file mode 100644 index 0000000..db57139 --- /dev/null +++ b/Assets/Tremble/FieldConverters/BaseClasses/UnityAssetFieldConverter.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 7d223aafbe7449fa87a27768d5809659 +timeCreated: 1710147897 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/BaseClasses/UnityAssetFieldConverter.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters/BoolFieldConverter.cs b/Assets/Tremble/FieldConverters/BoolFieldConverter.cs new file mode 100644 index 0000000..c628270 --- /dev/null +++ b/Assets/Tremble/FieldConverters/BoolFieldConverter.cs @@ -0,0 +1,99 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Linq; +using System.Reflection; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [TrembleFieldConverter(typeof(bool))] + public class BoolFieldConverter : TrembleFieldConverter + { + protected override bool TryGetValueFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out bool value) + { + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + + target.GetCustomAttributes( + out SpawnFlagsAttribute sfa, + out NoSpawnFlagsAttribute noSfa + ); + + bool useSpawnFlag = sfa != null || syncSettings.AlwaysPackBoolsIntoSpawnFlags; + if (noSfa != null) + { + useSpawnFlag = false; + } + + // No spawn flag - easy! + if (!useSpawnFlag) + return entity.TryGetBoolean(key, out value); + + // Spawn flag + int bit = sfa.GetBitForSpawnFlagsField(syncSettings, target); + return entity.TryGetSpawnFlag(bit, out value); + } + + protected override bool TryGetValuesFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out bool[] values) + { + if (!entity.TryGetString(key, out string stringValues)) + { + values = default; + return false; + } + + values = stringValues + .Split(',') + .Select(s => int.TryParse(s, out int result) ? result == 1 : default) + .ToArray(); + return true; + } + + protected override void AddFieldToFgd(FgdClass entityClass, string fieldName, bool defaultValue, MemberInfo target) + { + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + + target.GetCustomAttributes( + out SpawnFlagsAttribute sfa, + out NoSpawnFlagsAttribute noSfa, + out TooltipAttribute tooltip + ); + + bool useSpawnFlag = sfa != null || syncSettings.AlwaysPackBoolsIntoSpawnFlags; + if (noSfa != null) + { + useSpawnFlag = false; + } + + if (useSpawnFlag) + { + string spawnFlagName = target.Name.GetFieldNameInMap(syncSettings.SpawnFlagNamingConvention); + if (syncSettings.SpawnFlagNamingConvention == NamingConvention.HumanFriendly) + { + spawnFlagName += "?"; + } + + int bit = sfa.GetBitForSpawnFlagsField(syncSettings, target); + entityClass.AddField(new FgdSpawnFlagField + { + Description = spawnFlagName, + Bit = bit, + DefaultValue = defaultValue + }); + } + else + { + string friendlyName = target.Name.GetFieldNameInMap(NamingConvention.HumanFriendly) + "?"; + + entityClass.AddField(new FgdBooleanField + { + Name = fieldName, + Description = tooltip?.tooltip ?? friendlyName, + DefaultValue = defaultValue + }); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/BoolFieldConverter.cs.meta b/Assets/Tremble/FieldConverters/BoolFieldConverter.cs.meta new file mode 100644 index 0000000..4a37a5b --- /dev/null +++ b/Assets/Tremble/FieldConverters/BoolFieldConverter.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: b803c9e49f18b441a9c42c5bbbc96d24 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/BoolFieldConverter.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters/ColourFieldConverter.cs b/Assets/Tremble/FieldConverters/ColourFieldConverter.cs new file mode 100644 index 0000000..afdfe37 --- /dev/null +++ b/Assets/Tremble/FieldConverters/ColourFieldConverter.cs @@ -0,0 +1,48 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Linq; +using System.Reflection; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [TrembleFieldConverter(typeof(Color))] + public class ColourFieldConverter : TrembleFieldConverter + { + protected override bool TryGetValueFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out Color value) + { + return entity.TryGetColour(key, out value); + } + + protected override bool TryGetValuesFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out Color[] values) + { + if (!entity.TryGetString(key, out string stringValues)) + { + values = default; + return false; + } + + values = stringValues + .Split(',') + .Select(s => s.TryParseQ3Colour(out Color result) ? result : Color.white) + .ToArray(); + return true; + } + + protected override void AddFieldToFgd(FgdClass entityClass, string fieldName, Color defaultValue, MemberInfo target) + { + string tooltip = target.GetCustomAttribute()?.tooltip; + + entityClass.AddField(new FgdColourField + { + Name = fieldName, + Description = tooltip ?? $"{target.GetFieldOrPropertyType().Name} {target.Name}", + DefaultColour = defaultValue + }); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/ColourFieldConverter.cs.meta b/Assets/Tremble/FieldConverters/ColourFieldConverter.cs.meta new file mode 100644 index 0000000..aaadadf --- /dev/null +++ b/Assets/Tremble/FieldConverters/ColourFieldConverter.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 5ddf531949ddd48c9b45c5bc4b79515a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/ColourFieldConverter.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters/ComponentReferenceFieldConverter.cs b/Assets/Tremble/FieldConverters/ComponentReferenceFieldConverter.cs new file mode 100644 index 0000000..d2c1ac7 --- /dev/null +++ b/Assets/Tremble/FieldConverters/ComponentReferenceFieldConverter.cs @@ -0,0 +1,74 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Collections.Generic; +using System.Reflection; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [TrembleFieldConverter(typeof(Component))] + public class ComponentReferenceFieldConverter : TrembleFieldConverter + { + protected override bool TryGetValueFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out Component value) + { + if (entity.TryGetString(key, out string id)) + { + if (TrembleMapImportSettings.Current.TryGetGameObjectsForID(id, out List objs) && objs.Count > 0) + { + value = objs[0].GetComponent(target.GetFieldOrPropertyTypeOrElementType()); + if (!value) + { + Debug.LogWarning($"Entity '{objs[0].name}' reference '{id}' is of unexpected type. (expected: {target.GetFieldOrPropertyTypeOrElementType().Name}). Check the targeted entity in the map is of the correct type."); + } + + return value; + } + } + + value = default; + return false; + } + + protected override bool TryGetValuesFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out Component[] values) + { + if (entity.TryGetString(key, out string id) && TrembleMapImportSettings.Current.TryGetGameObjectsForID(id, out List objs)) + { + values = new Component[objs.Count]; + for (int objIdx = 0; objIdx < objs.Count; objIdx++) + { + Component component = objs[objIdx].GetComponent(target.GetFieldOrPropertyTypeOrElementType()); + if (!component) + { + Debug.LogWarning($"Entity '{objs[objIdx].name}' reference '{id}' is of unexpected type. (expected: {target.GetFieldOrPropertyTypeOrElementType().Name}). Check the targeted entity in the map is of the correct type."); + + continue; + } + + values[objIdx] = component; + } + + return true; + } + + values = default; + return false; + } + + protected override void AddFieldToFgd(FgdClass entityClass, string fieldName, Component defaultValue, MemberInfo target) + { + target.GetCustomAttributes( + out TooltipAttribute tooltip + ); + + entityClass.AddField(new FgdTargetDestinationField + { + Name = fieldName, + Description = tooltip?.tooltip ?? $"{target.GetFieldOrPropertyType().Name} {target.Name}", + DefaultValue = default + }); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/ComponentReferenceFieldConverter.cs.meta b/Assets/Tremble/FieldConverters/ComponentReferenceFieldConverter.cs.meta new file mode 100644 index 0000000..778e7bc --- /dev/null +++ b/Assets/Tremble/FieldConverters/ComponentReferenceFieldConverter.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: e3f0373df73804108ada11dc71de54ad +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/ComponentReferenceFieldConverter.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters/EnumFieldConverter.cs b/Assets/Tremble/FieldConverters/EnumFieldConverter.cs new file mode 100644 index 0000000..f45d04e --- /dev/null +++ b/Assets/Tremble/FieldConverters/EnumFieldConverter.cs @@ -0,0 +1,98 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Reflection; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public class EnumFieldConverter : TrembleFieldConverter + { + public override bool TryGetValueFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out object value) + { + // Enum special case - parse as int or string + if (entity.TryGetInt(key, out int enumIntValue)) + { + value = enumIntValue; + return true; + } + + if (entity.TryGetString(key, out string enumStringValue)) + { + if (Enum.TryParse(target.GetFieldOrPropertyTypeOrElementType(), enumStringValue, true, out object enumObjValue)) + { + value = (int)enumObjValue; + return true; + } + + string entityName = entity.GetID().IsNullOrEmpty() ? entity.GetClassname() : $"'{entity.GetID()}' ({entity.GetClassname()})"; + Debug.LogWarning($"Failed to parse value '{enumStringValue}' for enum {target.GetFieldOrPropertyTypeOrElementType()} in entity {entityName}. Using default."); + } + + value = null; + return false; + } + + public override bool TryGetValuesFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out object[] values) + { + if (!entity.TryGetString(key, out string commaDelimitedValue)) + { + values = Array.Empty(); + return false; + } + + string[] parts = commaDelimitedValue.Split(','); + + values = new object[parts.Length]; + for (int i = 0; i < parts.Length; i++) + { + // Enum special case - parse as int or string + if (int.TryParse(parts[i], out int enumIntValue)) + { + values[i] = Enum.GetValues(target.GetFieldOrPropertyTypeOrElementType()).GetValue(enumIntValue); + } + else if (Enum.TryParse(target.GetFieldOrPropertyTypeOrElementType(), parts[i], true, out object enumObjValue)) + { + values[i] = enumObjValue; + } + else + { + string entityName = entity.GetID().IsNullOrEmpty() ? entity.GetClassname() : $"'{entity.GetID()}' ({entity.GetClassname()})"; + Debug.LogWarning($"Failed to parse value '{parts[i]}' for enum {target.GetFieldOrPropertyTypeOrElementType()} in entity {entityName}. Using default."); + } + } + + return true; + } + + public override void AddFieldToFgd(FgdClass entityClass, string fieldName, object defaultValue, MemberInfo target) + { + string tooltip = target.GetCustomAttribute()?.tooltip; + + bool isFlags = target.GetFieldOrPropertyTypeOrElementType().GetCustomAttribute() != null; + + if (isFlags) + { + entityClass.AddField(new FgdFlagsField + { + EnumClassName = target.GetFieldOrPropertyTypeOrElementType().FullName, + Name = fieldName, + Description = tooltip ?? $"{target.GetFieldOrPropertyTypeOrElementType()} {target.Name}", + }); + } + else + { + entityClass.AddField(new FgdEnumField + { + EnumClassName = target.GetFieldOrPropertyTypeOrElementType().FullName, + Name = fieldName, + Description = tooltip ?? $"{target.GetFieldOrPropertyTypeOrElementType()} {target.Name}", + DefaultValue = defaultValue == null ? 0 : (int)defaultValue + }); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/EnumFieldConverter.cs.meta b/Assets/Tremble/FieldConverters/EnumFieldConverter.cs.meta new file mode 100644 index 0000000..0dce395 --- /dev/null +++ b/Assets/Tremble/FieldConverters/EnumFieldConverter.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: d027622fcb2143c28cb9bd4ed8b74bd2 +timeCreated: 1710930324 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/EnumFieldConverter.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters/FloatFieldConverter.cs b/Assets/Tremble/FieldConverters/FloatFieldConverter.cs new file mode 100644 index 0000000..047d35b --- /dev/null +++ b/Assets/Tremble/FieldConverters/FloatFieldConverter.cs @@ -0,0 +1,58 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Globalization; +using System.Linq; +using System.Reflection; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [TrembleFieldConverter(typeof(float))] + public class FloatFieldConverter : TrembleFieldConverter + { + protected override bool TryGetValueFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out float value) + { + return entity.TryGetFloat(key, out value); + } + + protected override bool TryGetValuesFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out float[] values) + { + if (!entity.TryGetString(key, out string stringValues)) + { + values = default; + return false; + } + + values = stringValues + .Split(',') + .Select(s => s.TryParseFloat(out float result) ? result : default) + .ToArray(); + return true; + } + + protected override void AddFieldToFgd(FgdClass entityClass, string fieldName, float defaultValue, MemberInfo target) + { + target.GetCustomAttributes( + out TooltipAttribute tooltip, + out RangeAttribute range + ); + + // Read range hint, if available + string rangeHint = ""; + if (range != null) + { + rangeHint = $" (valid range: {range.min} - {range.max})"; + } + + entityClass.AddField(new FgdFloatField + { + Name = fieldName, + Description = (tooltip?.tooltip ?? $"{target.GetFieldOrPropertyType().Name} {target.Name}") + rangeHint, + DefaultValue = defaultValue + }); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/FloatFieldConverter.cs.meta b/Assets/Tremble/FieldConverters/FloatFieldConverter.cs.meta new file mode 100644 index 0000000..7aca8af --- /dev/null +++ b/Assets/Tremble/FieldConverters/FloatFieldConverter.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 8bd2fdf6f450b4c9abf17350308678c6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/FloatFieldConverter.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters/IntFieldConverter.cs b/Assets/Tremble/FieldConverters/IntFieldConverter.cs new file mode 100644 index 0000000..1e2b31f --- /dev/null +++ b/Assets/Tremble/FieldConverters/IntFieldConverter.cs @@ -0,0 +1,57 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Linq; +using System.Reflection; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [TrembleFieldConverter(typeof(int))] + public class IntFieldConverter : TrembleFieldConverter + { + protected override bool TryGetValueFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out int value) + { + return entity.TryGetInt(key, out value); + } + + protected override bool TryGetValuesFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out int[] values) + { + if (!entity.TryGetString(key, out string stringValues)) + { + values = default; + return false; + } + + values = stringValues + .Split(',') + .Select(s => int.TryParse(s, out int result) ? result : default) + .ToArray(); + return true; + } + + protected override void AddFieldToFgd(FgdClass entityClass, string fieldName, int defaultValue, MemberInfo target) + { + target.GetCustomAttributes( + out TooltipAttribute tooltip, + out RangeAttribute range + ); + + // Read range hint, if available + string rangeHint = ""; + if (range != null) + { + rangeHint = $" (valid range: {range.min} - {range.max})"; + } + + entityClass.AddField(new FgdIntegerField + { + Name = fieldName, + Description = (tooltip?.tooltip ?? $"{target.GetFieldOrPropertyType().Name} {target.Name}") + rangeHint, + DefaultValue = defaultValue + }); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/IntFieldConverter.cs.meta b/Assets/Tremble/FieldConverters/IntFieldConverter.cs.meta new file mode 100644 index 0000000..5e3acd0 --- /dev/null +++ b/Assets/Tremble/FieldConverters/IntFieldConverter.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 4f73e981a84ca44b4bfe0fe68379f559 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/IntFieldConverter.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters/MaterialFieldConverter.cs b/Assets/Tremble/FieldConverters/MaterialFieldConverter.cs new file mode 100644 index 0000000..425ac26 --- /dev/null +++ b/Assets/Tremble/FieldConverters/MaterialFieldConverter.cs @@ -0,0 +1,14 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [TrembleFieldConverter(typeof(Material))] + public class MaterialFieldConverter : UnityAssetFieldConverter + { + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/MaterialFieldConverter.cs.meta b/Assets/Tremble/FieldConverters/MaterialFieldConverter.cs.meta new file mode 100644 index 0000000..a0d31aa --- /dev/null +++ b/Assets/Tremble/FieldConverters/MaterialFieldConverter.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ce5b862461044f8f85be37945f4d2ba2 +timeCreated: 1710146712 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/MaterialFieldConverter.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters/PrefabFieldConverter.cs b/Assets/Tremble/FieldConverters/PrefabFieldConverter.cs new file mode 100644 index 0000000..9226ca3 --- /dev/null +++ b/Assets/Tremble/FieldConverters/PrefabFieldConverter.cs @@ -0,0 +1,14 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [TrembleFieldConverter(typeof(GameObject))] + public class PrefabFieldConverter : UnityAssetFieldConverter + { + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/PrefabFieldConverter.cs.meta b/Assets/Tremble/FieldConverters/PrefabFieldConverter.cs.meta new file mode 100644 index 0000000..ffa2912 --- /dev/null +++ b/Assets/Tremble/FieldConverters/PrefabFieldConverter.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: d590871b719743c88547b6587254c7a0 +timeCreated: 1710148685 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/PrefabFieldConverter.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters/ScriptableObjectFieldConverter.cs b/Assets/Tremble/FieldConverters/ScriptableObjectFieldConverter.cs new file mode 100644 index 0000000..da2321e --- /dev/null +++ b/Assets/Tremble/FieldConverters/ScriptableObjectFieldConverter.cs @@ -0,0 +1,14 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [TrembleFieldConverter(typeof(ScriptableObject))] + public class ScriptableObjectFieldConverter : UnityAssetFieldConverter + { + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/ScriptableObjectFieldConverter.cs.meta b/Assets/Tremble/FieldConverters/ScriptableObjectFieldConverter.cs.meta new file mode 100644 index 0000000..0820af7 --- /dev/null +++ b/Assets/Tremble/FieldConverters/ScriptableObjectFieldConverter.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 267ae928b4a54d1e8a4e47c20016b646 +timeCreated: 1710148829 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/ScriptableObjectFieldConverter.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters/StringFieldConverter.cs b/Assets/Tremble/FieldConverters/StringFieldConverter.cs new file mode 100644 index 0000000..e791e15 --- /dev/null +++ b/Assets/Tremble/FieldConverters/StringFieldConverter.cs @@ -0,0 +1,47 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Linq; +using System.Reflection; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [TrembleFieldConverter(typeof(string))] + public class StringFieldConverter : TrembleFieldConverter + { + protected override bool TryGetValueFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out string value) + { + return entity.TryGetString(key, out value); + } + + protected override bool TryGetValuesFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out string[] values) + { + if (!entity.TryGetString(key, out string stringValues)) + { + values = default; + return false; + } + + values = stringValues.Split(',').ToArray(); + return true; + } + + protected override void AddFieldToFgd(FgdClass entityClass, string fieldName, string defaultValue, MemberInfo target) + { + target.GetCustomAttributes( + out TooltipAttribute tooltip + ); + + entityClass.AddField(new FgdStringField + { + Name = fieldName, + Description = tooltip?.tooltip ?? $"{target.GetFieldOrPropertyType().Name} {target.Name}", + DefaultValue = defaultValue + }); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/StringFieldConverter.cs.meta b/Assets/Tremble/FieldConverters/StringFieldConverter.cs.meta new file mode 100644 index 0000000..41ad0ca --- /dev/null +++ b/Assets/Tremble/FieldConverters/StringFieldConverter.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: a40a28dd235b940dda3957abcdb86de6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/StringFieldConverter.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters/TrembleFieldConverter.cs b/Assets/Tremble/FieldConverters/TrembleFieldConverter.cs new file mode 100644 index 0000000..45a5706 --- /dev/null +++ b/Assets/Tremble/FieldConverters/TrembleFieldConverter.cs @@ -0,0 +1,114 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEngine; +using UnityEngine.Scripting; + +namespace TinyGoose.Tremble +{ + [AttributeUsage(AttributeTargets.Class)] + public class TrembleFieldConverterAttribute : PreserveAttribute + { + public TrembleFieldConverterAttribute(Type t) + { + m_Type = t; + } + + private readonly Type m_Type; + public Type Type => m_Type; + } + + [Preserve] + public abstract class TrembleFieldConverter + { + public abstract bool TryGetValueFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out object value); + + public abstract bool TryGetValuesFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out object[] value); + + public abstract void AddFieldToFgd(FgdClass entityClass, string fieldName, object defaultValue, MemberInfo target); + } + + public abstract class TrembleFieldConverter : TrembleFieldConverter + { + public sealed override bool TryGetValueFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out object value) + { + Type targetType = target.GetFieldOrPropertyType(); + + if (targetType.IsArray) + { + value = entity + .GetAllNumberedKeys(key) + .Select(k => TryGetValueFromMap(entity, k, gameObject, target, out T typedValue) ? typedValue : default) + .ToArray(); + return true; + } + else + { + bool success = TryGetValueFromMap(entity, key, gameObject, target, out T typedValue); + value = success ? typedValue : default; + return success; + } + } + + public sealed override bool TryGetValuesFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out object[] values) + { + string[] numberedKeys = entity.GetAllNumberedKeys(key).ToArray(); + if (numberedKeys is { Length: 0 }) + { + values = default; + return false; + } + + List outValues = new(numberedKeys.Length); + + foreach (string numberedKey in numberedKeys) + { + // First get multiple and add if possible + if (TryGetValuesFromMap(entity, numberedKey, gameObject, target, out T[] tValues)) + { + outValues.AddRange(tValues.Cast()); + } + else if (TryGetValueFromMap(entity, numberedKey, gameObject, target, out T value)) + { + outValues.Add(value); + } + } + + values = outValues.ToArray(); + return true; + } + + public sealed override void AddFieldToFgd(FgdClass entityClass, string fieldName, object defaultValue, MemberInfo target) + { + if (defaultValue is Array { Length: > 0 } defaultArray) + { + defaultValue = defaultArray.GetValue(0); + } + + AddFieldToFgd(entityClass, fieldName, (T)defaultValue, target); + } + + protected abstract bool TryGetValueFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out T value); + + protected virtual bool TryGetValuesFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out T[] values) + { + if (!TryGetValueFromMap(entity, key, gameObject, target, out T value)) + { + values = default; + return false; + } + + values = new T[1]; + values[0] = value; + return true; + } + + protected abstract void AddFieldToFgd(FgdClass entityClass, string fieldName, T defaultValue, MemberInfo target); + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/TrembleFieldConverter.cs.meta b/Assets/Tremble/FieldConverters/TrembleFieldConverter.cs.meta new file mode 100644 index 0000000..32b9d11 --- /dev/null +++ b/Assets/Tremble/FieldConverters/TrembleFieldConverter.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: d6a1b8d48d2694bfb8d7dc8cbdc6c7ab +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/TrembleFieldConverter.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters/TrembleFieldConverterCollection.cs b/Assets/Tremble/FieldConverters/TrembleFieldConverterCollection.cs new file mode 100644 index 0000000..ad454b2 --- /dev/null +++ b/Assets/Tremble/FieldConverters/TrembleFieldConverterCollection.cs @@ -0,0 +1,81 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; + +namespace TinyGoose.Tremble +{ + public class TrembleFieldConverterCollection + { + private readonly List m_Converters = new(); + private static readonly Dictionary s_LookupCache = new(); + private static readonly Dictionary s_ConverterSetupCache = new(); + + public TrembleFieldConverterCollection() + { + m_Converters.AddRange(TypeDatabase + .GetTypesWithAttribute() + .Select(t => (TrembleFieldConverter)Activator.CreateInstance(t))); + } + + public TrembleFieldConverter GetConverterForType(Type t) + { + // Array special case - expose as element type of array + if (t.IsArray) + { + t = t.GetElementType(); + } + + // Enum special case! + if (t.IsEnum) + { + return new EnumFieldConverter(); + } + + // First see if we've seen this type before + if (s_LookupCache.TryGetValue(t, out TrembleFieldConverter existingConverter)) + { + return existingConverter; + } + + // Exact match first + foreach (TrembleFieldConverter converter in m_Converters) + { + if (!s_ConverterSetupCache.TryGetValue(converter, out TrembleFieldConverterAttribute tfca)) + { + tfca = converter.GetType().GetCustomAttribute(); + s_ConverterSetupCache.Add(converter, tfca); + } + + if (tfca.Type != t) + continue; + + s_LookupCache[t] = converter; + return converter; + } + + // Nothing exactly matches - look for subclasses too (for Components) + foreach (TrembleFieldConverter converter in m_Converters) + { + if (!s_ConverterSetupCache.TryGetValue(converter, out TrembleFieldConverterAttribute tfca)) + { + tfca = converter.GetType().GetCustomAttribute(); + s_ConverterSetupCache.Add(converter, tfca); + } + + if (!t.IsSubclassOf(tfca.Type)) + continue; + + s_LookupCache[t] = converter; + return converter; + } + + return null; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/TrembleFieldConverterCollection.cs.meta b/Assets/Tremble/FieldConverters/TrembleFieldConverterCollection.cs.meta new file mode 100644 index 0000000..3e5ba44 --- /dev/null +++ b/Assets/Tremble/FieldConverters/TrembleFieldConverterCollection.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 9c34bb2b1df149a9bc168bb41f596387 +timeCreated: 1710858661 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/TrembleFieldConverterCollection.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters/Vector3Converter.cs b/Assets/Tremble/FieldConverters/Vector3Converter.cs new file mode 100644 index 0000000..de4ab94 --- /dev/null +++ b/Assets/Tremble/FieldConverters/Vector3Converter.cs @@ -0,0 +1,82 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Globalization; +using System.Linq; +using System.Reflection; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [TrembleFieldConverter(typeof(Vector3))] + public class Vector3Converter : TrembleFieldConverter + { + protected override bool TryGetValueFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out Vector3 value) + { + target.GetCustomAttributes(out TrembleAttribute tremble); + bool? isRotation = tremble?.IsRotation; + + // Keep raw value if requested, or it's a "rotation" + isRotation ??= key.ContainsInvariant("rotation") || key.ContainsInvariant("rotate"); + + return isRotation.Value + ? entity.TryGetUntransformedVector(key, out value) + : entity.TryGetVector(key, out value); + } + + protected override bool TryGetValuesFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out Vector3[] values) + { + if (!entity.TryGetString(key, out string stringValues)) + { + values = default; + return false; + } + + target.GetCustomAttributes(out TrembleAttribute tremble); + bool? isRotation = tremble?.IsRotation; + + // Keep raw value if requested, or it's a "rotation" + isRotation ??= key.ContainsInvariant("rotation") || key.ContainsInvariant("rotate"); + + values = stringValues + .Split(',') + .Select(s => + { + s.TryParseQ3Vector(out Vector3 result); + + if (!isRotation.GetValueOrDefault(false)) + { + result.Q3ToUnityVector(entity.ImportScale); + } + + return result; + }) + .ToArray(); + return true; + } + + protected override void AddFieldToFgd(FgdClass entityClass, string fieldName, Vector3 defaultValue, MemberInfo target) + { + target.GetCustomAttributes( + out TrembleAttribute tremble, + out TooltipAttribute tooltip + ); + + // Keep raw value if requested, or it's a "rotation" + bool? isRotation = tremble?.IsRotation; + isRotation ??= fieldName.ContainsInvariant("rotation") || fieldName.ContainsInvariant("rotate"); + + entityClass.AddField(new FgdVectorField + { + Name = fieldName, + Description = tooltip?.tooltip ?? $"{target.GetFieldOrPropertyType().Name} {target.Name}", + DefaultValue = defaultValue, + ImportScale = isRotation.Value ? 1f : TrembleSyncSettings.Get().ImportScale, + ConvertToQ3 = true + }); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/Vector3Converter.cs.meta b/Assets/Tremble/FieldConverters/Vector3Converter.cs.meta new file mode 100644 index 0000000..77a5335 --- /dev/null +++ b/Assets/Tremble/FieldConverters/Vector3Converter.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 6e3e987223b8a49f19b5873fcb84b8b4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/Vector3Converter.cs + uploadId: 939664 diff --git a/Assets/Tremble/FieldConverters/Vector3IntConverter.cs b/Assets/Tremble/FieldConverters/Vector3IntConverter.cs new file mode 100644 index 0000000..1e97063 --- /dev/null +++ b/Assets/Tremble/FieldConverters/Vector3IntConverter.cs @@ -0,0 +1,71 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Linq; +using System.Reflection; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [TrembleFieldConverter(typeof(Vector3Int))] + public class Vector3IntConverter : TrembleFieldConverter + { + protected override bool TryGetValueFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out Vector3Int value) + { + if (entity.TryGetUntransformedVector(key, out Vector3 v3Value)) + { + value = new((int)v3Value.x, (int)v3Value.z, (int)v3Value.y); + return true; + } + + value = default; + return false; + } + + protected override bool TryGetValuesFromMap(BspEntity entity, string key, GameObject gameObject, MemberInfo target, out Vector3Int[] values) + { + if (!entity.TryGetString(key, out string stringValues)) + { + values = default; + return false; + } + + target.GetCustomAttributes(out TrembleAttribute tremble); + bool? isRotation = tremble?.IsRotation; + + // Keep raw value if requested, or it's a "rotation" + isRotation ??= key.ContainsInvariant("rotation") || key.ContainsInvariant("rotate"); + + values = stringValues + .Split(',') + .Select(s => + { + s.TryParseQ3Vector(out Vector3 result); + + if (!isRotation.GetValueOrDefault(false)) + { + result.Q3ToUnityVector(entity.ImportScale); + } + + return new Vector3Int((int)result.x, (int)result.z, (int)result.y); + }) + .ToArray(); + return true; + } + + protected override void AddFieldToFgd(FgdClass entityClass, string fieldName, Vector3Int defaultValue, MemberInfo target) + { + string tooltip = target.GetCustomAttribute()?.tooltip; + + entityClass.AddField(new FgdVectorField + { + Name = fieldName, + Description = tooltip ?? $"{target.GetFieldOrPropertyType().Name} {target.Name}", + DefaultValue = defaultValue + }); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/FieldConverters/Vector3IntConverter.cs.meta b/Assets/Tremble/FieldConverters/Vector3IntConverter.cs.meta new file mode 100644 index 0000000..4f89301 --- /dev/null +++ b/Assets/Tremble/FieldConverters/Vector3IntConverter.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 77ccd99169ea24f61a74fcabd01696e1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/FieldConverters/Vector3IntConverter.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO.meta b/Assets/Tremble/IO.meta new file mode 100644 index 0000000..59e2009 --- /dev/null +++ b/Assets/Tremble/IO.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 29a286fb0bdf4e35a4b3259d93adaa83 +timeCreated: 1715671364 \ No newline at end of file diff --git a/Assets/Tremble/IO/BSP.meta b/Assets/Tremble/IO/BSP.meta new file mode 100644 index 0000000..8def375 --- /dev/null +++ b/Assets/Tremble/IO/BSP.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2e90b79b320149d0a8e107ccecdfa7f5 +timeCreated: 1710848891 \ No newline at end of file diff --git a/Assets/Tremble/IO/BSP/BspParser.cs b/Assets/Tremble/IO/BSP/BspParser.cs new file mode 100644 index 0000000..a611917 --- /dev/null +++ b/Assets/Tremble/IO/BSP/BspParser.cs @@ -0,0 +1,461 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// This class based on BSP Map Tools for Unity by John Evans (evans3d512@gmail.com) +// + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public static class BspParser + { + public static MapBsp Parse(string bspPath, float importScale, BspOptions options = null, MapGroupData[] foundGroups = null) + { + StreamReadIO reader = new(bspPath); + + string signature = new (reader.ReadChars(4)); + int version = reader.ReadInt32(); + if (signature != "IBSP" || version != 46) + { + Debug.LogWarning($"BSP Importer: Unknown signature or version. Expected IBSP, 46. Got {signature}, {version}"); + } + + int entitiesOffset = reader.ReadInt32(); + int entitiesLength = reader.ReadInt32(); // 16 + int texturesOffset = reader.ReadInt32(); + int texturesLength = reader.ReadInt32(); // 24 + + int planesOffset = reader.ReadInt32(); + int planesLength = reader.ReadInt32(); + int nodesOffset = reader.ReadInt32(); + int nodesLength = reader.ReadInt32(); + int leavesOffset = reader.ReadInt32(); + int leavesLength = reader.ReadInt32(); + int leafFacesOffset = reader.ReadInt32(); + int leaffacesLength = reader.ReadInt32(); + + reader.Seek(64); + int modelsOffset = reader.ReadInt32(); + int modelsLength = reader.ReadInt32(); + reader.Seek(88); // Vertices + int verticesOffset = reader.ReadInt32(); + int verticesLength = reader.ReadInt32(); + int mVerticesOffset = reader.ReadInt32(); + int mVerticesLength = reader.ReadInt32(); + reader.Seek(112); // Faces + int facesOffset = reader.ReadInt32(); + int facesLength = reader.ReadInt32(); + + int vertexCount = verticesLength / 44; + int mVertexCount = mVerticesLength / 4; + int faceCount = facesLength / 104; + int texCount = texturesLength / 72; + int modelCount = modelsLength / 40; + + int planesCount = planesLength / 16; + int nodesCount = nodesLength / 36; + int leavesCount = leavesLength / 48; + int leafFacesCount = leaffacesLength / 4; + + MapBsp newMapBsp = new() { + MapName = Path.GetFileNameWithoutExtension(bspPath), + ImportScale = importScale, + Options = options ?? new(), + + TexInfos = new TexInfo[texCount], + Planes = new Plane[planesCount], + Nodes = new BspNode[nodesCount], + Leaves = new BspLeaf[leavesCount], + LeafFaces = new int[leafFacesCount], + + Models = new BspModel[modelCount], + Vertices = new BspVertex[vertexCount], + Faces = new BspFace[faceCount], + MeshVertices = new int[mVertexCount], + Entities = new(), + + UsedFaces = new bool[faceCount], + + Groups = foundGroups, + }; + + + reader.Seek(texturesOffset); + for (int i = 0; i < texCount; i++) + { + string tempName = reader.ReadString(64); + if (tempName.StartsWithInvariant("textures/")) + { + tempName = tempName.Substring("textures/".Length); + } + + newMapBsp.TexInfos[i] = new() + { + Name = tempName, + Flags = reader.ReadInt32(), + Contents = reader.ReadInt32(), + }; + } + + reader.Seek(planesOffset); + for (int i = 0; i < planesCount; i++) + { + Vector3 planeNormal = reader.ReadVector3(convertToQ3: true); + + newMapBsp.Planes[i] = new() + { + normal = planeNormal, + distance = reader.ReadSingle() * importScale, + }; + } + + reader.Seek(leavesOffset); + for (int i = 0; i < leavesCount; i++) + { + newMapBsp.Leaves[i] = new() + { + VisCluster = reader.ReadInt32(), + PortalArea = reader.ReadInt32(), + Min = reader.ReadVector3Int(), + Max = reader.ReadVector3Int(), + LeafFaceStartIdx = reader.ReadInt32(), + NumLeafFaces = reader.ReadInt32(), + LeafBrushStartIdx = reader.ReadInt32(), + NumLeafBrushes = reader.ReadInt32(), + }; + } + + reader.Seek(nodesOffset); + for (int i = 0; i < nodesCount; i++) + { + newMapBsp.Nodes[i] = new() + { + PlaneIndex = reader.ReadInt32(), + Child1 = reader.ReadInt32(), + Child2 = reader.ReadInt32(), + Min = reader.ReadVector3Int(), + Max = reader.ReadVector3Int(), + }; + } + + reader.Seek(leafFacesOffset); + for (int i = 0; i < leafFacesCount; i++) + { + newMapBsp.LeafFaces[i] = reader.ReadInt32(); + } + + reader.Seek(modelsOffset); + for (int i = 0; i < modelCount; i++) + { + newMapBsp.Models[i] = new() + { + Min = reader.ReadVector3(convertToQ3: true, scale: importScale), + Max = reader.ReadVector3(convertToQ3: true, scale: importScale), + StartFaceIdx = reader.ReadInt32(), + NumFaces = reader.ReadInt32(), + StartBrushIdx = reader.ReadInt32(), + NumBrushes = reader.ReadInt32(), + }; + } + + reader.Seek(verticesOffset); + for (int i = 0; i < vertexCount; i++) + { + newMapBsp.Vertices[i] = new() + { + Position = reader.ReadVector3(convertToQ3: true, scale: importScale), + TexCoord = reader.ReadUV(), + LightmapCoord = reader.ReadUV(), + Normal = Vector3.Normalize(reader.ReadVector3(convertToQ3: true)), + Color = reader.ReadColour(), + }; + } + + reader.Seek(facesOffset); + for (int i = 0; i < faceCount; i++) + { + newMapBsp.Faces[i] = new() + { + TexID = reader.ReadInt32(), + Effect = reader.ReadInt32(), + Type = reader.ReadInt32(), + VertexStartIdx = reader.ReadInt32(), + NumVertices = reader.ReadInt32(), + MeshVertexStartIdx = reader.ReadInt32(), + NumMeshVertices = reader.ReadInt32(), + LightmapIndex = reader.ReadInt32(), + LightmapStart = reader.ReadVector2Int(), + LightmapSize = reader.ReadVector2Int(), + LightmapOrigin = reader.ReadVector3Int(), + LightmapVector1 = reader.ReadVector3(), + LightmapVector2 = reader.ReadVector3(), + Normal = reader.ReadVector3(convertToQ3: true), + Size = reader.ReadVector2Int(), + }; + } + + reader.Seek(mVerticesOffset); + for (int i = 0; i < mVertexCount; i++) + { + newMapBsp.MeshVertices[i] = reader.ReadInt32(); + } + + // Read entity key/value pairs + reader.Seek(entitiesOffset); + + List kvPairs = new(); + + int entityNumber = 0; + int endOfEntities = entitiesOffset + entitiesLength - 1; + int charsToRead = endOfEntities - reader.Position; + string entities = new(reader.ReadChars(charsToRead)); + + TokenParser tokenParser = new(entities); + do + { + ReadOnlySpan token = tokenParser.ReadToken(); + if (token == null || token.Length == 0) + { + kvPairs.Add(""); + continue; + } + + switch (token[0]) + { + case '{': + { + continue; + } + case '}': + { + Dictionary entries = new(); + for (int kvIdx = 0; kvIdx < kvPairs.Count; kvIdx += 2) + { + entries.Add(kvPairs[kvIdx], kvPairs[kvIdx+1]); + } + + newMapBsp.Entities.Add(new() { SerialNumber = entityNumber++, Entries = entries, ImportScale = newMapBsp.ImportScale}); + kvPairs.Clear(); + + continue; + } + default: + { + kvPairs.Add(token.ToString()); + break; + } + } + } while (!tokenParser.IsAtEnd); + + return newMapBsp; + } + + private static float GetTriangleAreaSqr(in Vector3 v1, in Vector3 v2, in Vector3 v3) + { + // Sqr Magnitudes inlined! + float ax = v1.x - v2.x; + float ay = v1.y - v2.y; + float az = v1.z - v2.z; + float a = ax * ax + ay * ay + az * az; + + float bx = v2.x - v3.x; + float by = v2.y - v3.y; + float bz = v2.z - v3.z; + float b = bx * bx + by * by + bz * bz; + + float cx = v2.x - v3.x; + float cy = v2.y - v3.y; + float cz = v2.z - v3.z; + float c = cx * cx + cy * cy + cz * cz; + + float s = (a + b + c) * 0.25f; + + float surfAreaSqr = Mathf.Sqrt(s * (s - a) * (s - b) * (s - c)); + return float.IsNaN(surfAreaSqr) ? 0f : surfAreaSqr; + } + + public static void GetFaceList(MapBsp mapBsp, BspLeaf leaf, List receiver) + { + int faceMin = mapBsp.Models[0].StartFaceIdx; + int faceMax = faceMin + mapBsp.Models[0].NumFaces; + + for (int faceOffset = leaf.LeafFaceStartIdx; faceOffset < leaf.LeafFaceStartIdx + leaf.NumLeafFaces; faceOffset++) + { + int leafFaceIdx = mapBsp.LeafFaces[faceOffset]; + + if (leafFaceIdx < faceMin || leafFaceIdx > faceMax) + continue; + + if (mapBsp.UsedFaces[leafFaceIdx]) + continue; + + receiver.Add(leafFaceIdx); + mapBsp.UsedFaces[leafFaceIdx] = true; + } + } + + public static void GetFaceList(MapBsp mapBsp, BspNode node, List receiver) + { + if (node.Child1 < 0) + { + GetFaceList(mapBsp, mapBsp.Leaves[-node.Child1 - 1], receiver); + } + else + { + GetFaceList(mapBsp, mapBsp.Nodes[node.Child1], receiver); + } + + if (node.Child2 < 0) + { + GetFaceList(mapBsp, mapBsp.Leaves[-node.Child2 - 1], receiver); + } + else + { + GetFaceList(mapBsp, mapBsp.Nodes[node.Child2], receiver); + } + } + + private static void GetSurfaceAreaSqr(MapBsp mapBsp, BspLeaf leaf, ref float receiver, HashSet faceList) + { + int faceMin = mapBsp.Models[0].StartFaceIdx; + int faceMax = faceMin + mapBsp.Models[0].NumFaces; + + for (int faceOffset = leaf.LeafFaceStartIdx; faceOffset < leaf.LeafFaceStartIdx + leaf.NumLeafFaces; faceOffset++) + { + if (mapBsp.LeafFaces[faceOffset] < faceMin || mapBsp.LeafFaces[faceOffset] > faceMax) + continue; + + int leafFaceIdx = mapBsp.LeafFaces[faceOffset]; + if (faceList.Contains(leafFaceIdx)) + continue; + + BspFace meshFace = mapBsp.Faces[leafFaceIdx]; + for (int vertexOffset = meshFace.MeshVertexStartIdx; vertexOffset < meshFace.MeshVertexStartIdx + meshFace.NumMeshVertices; vertexOffset += 3) + { + receiver += GetTriangleAreaSqr + ( + mapBsp.Vertices[mapBsp.MeshVertices[vertexOffset + 0] + meshFace.VertexStartIdx].Position, + mapBsp.Vertices[mapBsp.MeshVertices[vertexOffset + 1] + meshFace.VertexStartIdx].Position, + mapBsp.Vertices[mapBsp.MeshVertices[vertexOffset + 2] + meshFace.VertexStartIdx].Position + ); + } + + faceList.Add(leafFaceIdx); + } + } + + public static void GetSurfaceAreaSqr(MapBsp mapBsp, BspNode node, ref float receiver, HashSet faceList) + { + if (node.Child1 < 0) + { + GetSurfaceAreaSqr(mapBsp, mapBsp.Leaves[-node.Child1 - 1], ref receiver, faceList); + } + else + { + GetSurfaceAreaSqr(mapBsp, mapBsp.Nodes[node.Child1], ref receiver, faceList); + } + + if (node.Child2 < 0) + { + GetSurfaceAreaSqr(mapBsp, mapBsp.Leaves[-node.Child2 - 1], ref receiver, faceList); + } + else + { + GetSurfaceAreaSqr(mapBsp, mapBsp.Nodes[node.Child2], ref receiver, faceList); + } + } + + + public static void DumpToFile(this MapBsp mapBsp, string file) + { + using FileStream fs = new(file, FileMode.Create, FileAccess.Write); + using StreamWriter sw = new(fs); + + sw.WriteLine($"m_TexInfos[{mapBsp.TexInfos.Length}]:"); + for (int i = 0; i < mapBsp.TexInfos.Length; i++) + { + sw.WriteLine($" [{i}]: {mapBsp.TexInfos[i].Contents} {mapBsp.TexInfos[i].Flags} {mapBsp.TexInfos[i].Name}"); + } + sw.WriteLine(); + + sw.WriteLine($"bsp.Planes[{mapBsp.Planes.Length}]:"); + for (int i = 0; i < mapBsp.Planes.Length; i++) + { + sw.WriteLine($" [{i}]: {mapBsp.Planes[i].normal} {mapBsp.Planes[i].distance}"); + } + sw.WriteLine(); + + sw.WriteLine($"bsp.Nodes[{mapBsp.Nodes.Length}]:"); + for (int i = 0; i < mapBsp.Nodes.Length; i++) + { + sw.WriteLine($" [{i}]: {mapBsp.Nodes[i].Child1} {mapBsp.Nodes[i].Child2} {mapBsp.Nodes[i].PlaneIndex} {mapBsp.Nodes[i].Min} {mapBsp.Nodes[i].Max}"); + } + sw.WriteLine(); + + sw.WriteLine($"bsp.Leaves[{mapBsp.Leaves.Length}]:"); + for (int i = 0; i < mapBsp.Leaves.Length; i++) + { + sw.WriteLine($" [{i}]: {mapBsp.Leaves[i].Min} {mapBsp.Leaves[i].Max} {mapBsp.Leaves[i].LeafBrushStartIdx} {mapBsp.Leaves[i].NumLeafBrushes} {mapBsp.Leaves[i].LeafFaceStartIdx} {mapBsp.Leaves[i].NumLeafFaces}"); + } + sw.WriteLine(); + + sw.WriteLine($"bsp.LeafFaces[{mapBsp.LeafFaces.Length}]:"); + for (int i = 0; i < mapBsp.LeafFaces.Length; i++) + { + sw.WriteLine($" [{i}]: {mapBsp.LeafFaces[i]}"); + } + sw.WriteLine(); + + sw.WriteLine($"bsp.UsedFaces[{mapBsp.UsedFaces.Length}]:"); + for (int i = 0; i < mapBsp.UsedFaces.Length; i++) + { + sw.WriteLine($" [{i}]: {mapBsp.UsedFaces[i]}"); + } + sw.WriteLine(); + + sw.WriteLine($"bsp.Models[{mapBsp.Models.Length}]:"); + for (int i = 0; i < mapBsp.Models.Length; i++) + { + sw.WriteLine($" [{i}]: {mapBsp.Models[i].Min} {mapBsp.Models[i].Max} {mapBsp.Models[i].StartBrushIdx} {mapBsp.Models[i].NumBrushes} {mapBsp.Models[i].StartFaceIdx} {mapBsp.Models[i].NumFaces}"); + } + sw.WriteLine(); + + sw.WriteLine($"bsp.Vertices[{mapBsp.Vertices.Length}]:"); + for (int i = 0; i < mapBsp.Vertices.Length; i++) + { + sw.WriteLine($" [{i}]: {mapBsp.Vertices[i].Position} {mapBsp.Vertices[i].Normal} {mapBsp.Vertices[i].Color} {mapBsp.Vertices[i].TexCoord} {mapBsp.Vertices[i].LightmapCoord}"); + } + sw.WriteLine(); + + sw.WriteLine($"bsp.Faces[{mapBsp.Faces.Length}]:"); + for (int i = 0; i < mapBsp.Faces.Length; i++) + { + sw.WriteLine($" [{i}]: {mapBsp.Faces[i].VertexStartIdx} {mapBsp.Faces[i].NumVertices} {mapBsp.Faces[i].MeshVertexStartIdx} {mapBsp.Faces[i].NumMeshVertices} {mapBsp.Faces[i].Type}"); + } + sw.WriteLine(); + + sw.WriteLine($"bsp.MeshVertices[{mapBsp.MeshVertices.Length}]:"); + for (int i = 0; i < mapBsp.MeshVertices.Length; i++) + { + sw.WriteLine($" [{i}]: {mapBsp.MeshVertices[i]}"); + } + sw.WriteLine(); + + sw.WriteLine($"bsp.Entities[{mapBsp.Entities.Count}]:"); + for (int i = 0; i < mapBsp.Entities.Count; i++) + { + sw.Write($" [{i}]: {mapBsp.Entities[i].GetClassname()} {{"); + foreach (string key in mapBsp.Entities[i].Entries.Keys) + { + sw.Write($" {key}=\"{mapBsp.Entities[i].Entries[key]}\""); + } + sw.WriteLine(" }"); + } + sw.WriteLine(); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/BSP/BspParser.cs.meta b/Assets/Tremble/IO/BSP/BspParser.cs.meta new file mode 100644 index 0000000..69dced5 --- /dev/null +++ b/Assets/Tremble/IO/BSP/BspParser.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 71af40a1b7d341a6a9a72e17150e1a52 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/BSP/BspParser.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD.meta b/Assets/Tremble/IO/FGD.meta new file mode 100644 index 0000000..5ffe4f0 --- /dev/null +++ b/Assets/Tremble/IO/FGD.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 377682f99735490bb297fbe22cf1cd1a +timeCreated: 1710848878 \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FgdClass.cs b/Assets/Tremble/IO/FGD/FgdClass.cs new file mode 100644 index 0000000..f65a087 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FgdClass.cs @@ -0,0 +1,166 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public enum FgdClassType + { + Base, + + Point, + Brush, + } + + public class FgdClass + { + public FgdClass(FgdClassType type, string name, string description) + { + Type = type; + Name = name; + Description = description; + } + + public FgdClassType Type { get; } + public string Name { get; } + public string Description { get; set; } + public bool HasModel { get; init; } + public Color? Colour { get; init; } + public string Sprite { get; init; } + public Bounds? Box { get; init; } + + private readonly List m_BaseClasses = new(); + private readonly List m_Fields = new(); + private readonly List m_SpawnFlags = new(); + + public void AddBaseClass(string baseClass) => m_BaseClasses.Add(baseClass); + + public void AddBaseClassInterfaces(Type entityType) + { + foreach (Type iface in entityType.GetInterfaces()) + { + if (!iface.GetInterfaces().Contains(typeof(ITrembleBaseClass))) + continue; + + AddBaseClass(iface.Name.Substring(1)); // Remove 'I' + break; + } + } + + public void AddField(FgdFieldBase fgdField) + { + if (fgdField is FgdSpawnFlagField flag) + { + m_SpawnFlags.Add(flag); + } + else + { + m_Fields.Add(fgdField); + } + } + + public List AllFields => m_Fields; + public List AllSpawnFlags => m_SpawnFlags; + public List BaseClassNames => m_BaseClasses; + + public bool HasField(string name) => m_Fields.Any(m => m.FieldName.EqualsInvariant(name, caseSensitive: true)); + + public bool HasSpawnFlag(int bit) => m_SpawnFlags.Any(sf => sf.Bit == bit); + + public void AddComment(string comment) + { + m_Fields.Add(new FgdComment { Comment = comment }); + } + + public void WriteFgd(StreamWriter stream, float importScale) + { + string typeString = Type switch + { + FgdClassType.Base => "@BaseClass", + FgdClassType.Point => "@PointClass", + FgdClassType.Brush => "@SolidClass", + _ => throw new ArgumentOutOfRangeException() + }; + + stream.WriteLine(typeString); + + if (m_BaseClasses.Count > 0) + { + string baseList = String.Join(", ", m_BaseClasses); + stream.WriteLine($"\tbase({baseList})"); + } + + if (HasModel) + { + stream.WriteLine($"\tmodel({{ path: \"models/{Name}.md3\", scale: scale }})"); + } + + if (Colour.HasValue) + { + stream.WriteLine($"\tcolor({Colour.Value.ToStringInvariant()})"); + } + + if (!Sprite.IsNullOrEmpty()) + { + stream.WriteLine($"\tsprite(\"models/{Sprite}.png\")"); + } + + if (Box.HasValue) + { + Vector3 q3Min = Box.Value.min.UnityToQ3Vector(scale: importScale); + Vector3 q3Max = Box.Value.max.UnityToQ3Vector(scale: importScale); + + // From xage on TB Discord: bboxes need to be symmetrical + Vector3 extents = new() + { + x = (Mathf.Abs(q3Min.x) + Mathf.Abs(q3Max.x)), + y = (Mathf.Abs(q3Min.y) + Mathf.Abs(q3Max.y)), + z = (Mathf.Abs(q3Min.z) + Mathf.Abs(q3Max.z)) + }; + + stream.WriteLine($"\tsize({Mathf.RoundToInt(extents.x)} {Mathf.RoundToInt(extents.y)} {Mathf.RoundToInt(extents.z)})"); + } + + stream.Write($" = {Name} : \"{Description}\""); + + // Write fields, and then spawnflags fields + if (m_Fields.Count == 0 && m_SpawnFlags.Count == 0) + { + stream.WriteLine(" []"); + } + else + { + stream.WriteLine(); + stream.WriteLine("["); + + foreach (FgdFieldBase variable in m_Fields) + { + stream.Write("\t"); + variable.Write(stream); + } + + if (m_SpawnFlags.Count > 0) + { + stream.WriteLine("\tspawnflags(Flags) = "); + stream.WriteLine("\t["); + foreach (FgdSpawnFlagField flag in m_SpawnFlags.OrderBy(sf => sf.Bit)) + { + stream.Write("\t\t"); + flag.Write(stream); + } + + stream.WriteLine("\t]"); + } + + stream.WriteLine("]"); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FgdClass.cs.meta b/Assets/Tremble/IO/FGD/FgdClass.cs.meta new file mode 100644 index 0000000..8f09d98 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FgdClass.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: e3de2d23101644c9a58c281bfcca7eae +timeCreated: 1709808579 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FgdClass.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FgdFieldBase.cs b/Assets/Tremble/IO/FGD/FgdFieldBase.cs new file mode 100644 index 0000000..4ccefaa --- /dev/null +++ b/Assets/Tremble/IO/FGD/FgdFieldBase.cs @@ -0,0 +1,89 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; + +namespace TinyGoose.Tremble +{ + public abstract class FgdFieldBase + { + public abstract void Write(StreamWriter sw); + public abstract void WriteCSharpClass(StreamWriter sw, int indent); + public abstract void WriteCSharpInterface(StreamWriter sw, int indent); + + public virtual string FieldName => null; + + public string FriendlyTypeName + { + get + { + string friendlyTypeName = GetType().Name; + if (friendlyTypeName.StartsWithInvariant("Fgd", caseSensitive: true)) + { + friendlyTypeName = friendlyTypeName.Remove(0, 3); + } + + if (friendlyTypeName.EndsWithInvariant("Field", caseSensitive: true)) + { + friendlyTypeName = friendlyTypeName.Remove(friendlyTypeName.Length - 5, 5); + } + return friendlyTypeName; + } + } + + protected void WriteClassField(StreamWriter sw, int indent, string unityType, string name, string description, string defaultValue = null, string extraAttributes = null) + { + sw.WriteIndent(indent); + + sw.Write("["); + { + if (!TrembleSyncSettings.Get().SyncSerializedFields) + { + sw.Write("Tremble, "); + } + + sw.Write($"SerializeField"); + if (!description.IsNullOrEmpty()) + { + sw.Write($", Tooltip(\"{description}\")"); + } + } + + if (!extraAttributes.IsNullOrEmpty()) + { + sw.Write(", "); + sw.Write(extraAttributes); + } + + sw.Write("] "); + + sw.Write($"private {unityType} m_{name.ToNamingConvention(NamingConvention.UpperCamelCase)}"); + + if (defaultValue == null) + { + sw.WriteLine(";"); + } + else + { + sw.WriteLine($" = {defaultValue};"); + } + } + protected void WriteInterfaceProperty(StreamWriter sw, int indent, string unityType, string name, string description, string attributes = null) + { + sw.WriteIndent(indent); + + if (!attributes.IsNullOrEmpty()) + { + sw.Write("["); + sw.Write(attributes); + sw.Write("] "); + } + + sw.Write($"public {unityType} {name.ToNamingConvention(NamingConvention.UpperCamelCase)} => default;"); + sw.WriteLine(description.IsNullOrEmpty() ? "" : $" // \"{description}\""); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FgdFieldBase.cs.meta b/Assets/Tremble/IO/FGD/FgdFieldBase.cs.meta new file mode 100644 index 0000000..0287e7f --- /dev/null +++ b/Assets/Tremble/IO/FGD/FgdFieldBase.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: f13869dde160409ca3a827a856d24d48 +timeCreated: 1698227234 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FgdFieldBase.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FgdFieldFactory.cs b/Assets/Tremble/IO/FGD/FgdFieldFactory.cs new file mode 100644 index 0000000..cbb76e0 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FgdFieldFactory.cs @@ -0,0 +1,86 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Globalization; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public static class FgdFieldFactory + { + public static FgdFieldBase CreateField(string typename, string name, string description, string defaultValue) + { + switch (typename.ToLowerInvariant()) + { + case "float": + return new FgdFloatField + { + Name = name, + Description = description, + DefaultValue = defaultValue != null ? float.Parse(defaultValue, NumberStyles.Any, CultureInfo.InvariantCulture) : 0f + }; + case "integer": + return new FgdIntegerField + { + Name = name, + Description = description, + DefaultValue = defaultValue != null ? int.Parse(defaultValue, NumberStyles.Any, CultureInfo.InvariantCulture) : 0 + }; + case "vector": + if (defaultValue == null || !defaultValue.TryParseQ3Vector(out Vector3 vector)) + { + vector = Vector3.zero; + } + + return new FgdVectorField + { + Name = name, + Description = description, + DefaultValue = vector + }; + case "color": + if (!defaultValue.TryParseQ3Colour(out Color colour)) + { + colour = Color.white; + } + + return new FgdColourField + { + Name = name, + Description = description, + DefaultColour = colour + }; + case "string": + return new FgdStringField + { + Name = name, + Description = description, + DefaultValue = defaultValue + }; + case "target_source": + return new FgdTargetSourceField + { + Name = name, + Description = description, + DefaultValue = defaultValue + }; + case "target_destination": + return new FgdTargetDestinationField + { + Name = name, + Description = description, + DefaultValue = defaultValue + }; + } + + return new FgdStringField + { + Name = name, + Description = description, + DefaultValue = defaultValue + }; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FgdFieldFactory.cs.meta b/Assets/Tremble/IO/FGD/FgdFieldFactory.cs.meta new file mode 100644 index 0000000..bc16d6c --- /dev/null +++ b/Assets/Tremble/IO/FGD/FgdFieldFactory.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: b3806920a91d5469f8c9ef060771e83b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FgdFieldFactory.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FgdInferredFieldExtensions.cs b/Assets/Tremble/IO/FGD/FgdInferredFieldExtensions.cs new file mode 100644 index 0000000..dc8ca48 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FgdInferredFieldExtensions.cs @@ -0,0 +1,130 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Globalization; + +namespace TinyGoose.Tremble +{ + public static class FgdInferredFieldExtensions + { + public static void TryAddInferredField(this FgdClass fgdClass, string key, string value) + { + // ID property (or "targetname") + string identityProperty = TrembleSyncSettings.Get().IdentityPropertyName; + if (key.EqualsInvariant("targetname") || key.EqualsInvariant(identityProperty, caseSensitive: true)) + { + return; + } + + // "Target" + if (key.ContainsInvariant(FgdConsts.PROPERTY_TARGET)) + { + fgdClass.AddField(new FgdTargetDestinationField + { + Name = key, + Description = $"{key.ToNamingConvention(NamingConvention.UpperCamelCase)} of this Entity" + }); + + return; + } + + // "Origin" - skip + if (key.EqualsInvariant(FgdConsts.PROPERTY_ORIGIN)) + { + return; + } + + // "Scale" - skip + if (key.EqualsInvariant(FgdConsts.PROPERTY_SCALE)) + { + return; + } + + // "Parent" - skip + if (key.EqualsInvariant(FgdConsts.PROPERTY_PARENT)) + { + return; + } + + // Angles - skip + if (key.EqualsInvariant(FgdConsts.PROPERTY_ANGLES)) + { + return; + } + + // _tb_textures, group, etc - skip + if (key.StartsWithInvariant(TBConsts.TB_PREFIX)) + { + return; + } + + // Spawnflags + if (key.EqualsInvariant(FgdConsts.PROPERTY_SPAWNFLAGS)) + { + if (!int.TryParse(value, out int flags)) + return; + + int bit = 0; + while (flags > 0) + { + if (!fgdClass.HasSpawnFlag(bit)) + { + fgdClass.AddField(new FgdSpawnFlagField + { + Bit = bit, + Description = $"Unknown spawnflag bit #{bit}" + }); + } + + bit++; + flags >>= 1; + } + + return; + } + + // Anything else? Try to infer type. + if (IsValueVector(value)) + { + fgdClass.AddField(new FgdVectorField + { + Name = key, + Description = $"Vector {key}", + }); + } + else if (IsValueFloat(value)) + { + fgdClass.AddField(new FgdFloatField + { + Name = key, + Description = $"Float {key}", + }); + } + else + { + fgdClass.AddField(new FgdStringField + { + Name = key, + Description = $"String {key}", + }); + } + } + + private static bool IsValueFloat(string value) => value.TryParseFloat(out float _); + + private static bool IsValueVector(string value) + { + if (value.IsNullOrEmpty()) + return false; + + string[] parts = value.Split(' '); + if (parts.Length != 3) + return false; + + return IsValueFloat(parts[0]) && IsValueFloat(parts[1]) && IsValueFloat(parts[2]); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FgdInferredFieldExtensions.cs.meta b/Assets/Tremble/IO/FGD/FgdInferredFieldExtensions.cs.meta new file mode 100644 index 0000000..f091461 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FgdInferredFieldExtensions.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a207e07b3115419e90f7b5092c0ea67f +timeCreated: 1712223098 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FgdInferredFieldExtensions.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FgdParser.cs b/Assets/Tremble/IO/FGD/FgdParser.cs new file mode 100644 index 0000000..8b81e5b --- /dev/null +++ b/Assets/Tremble/IO/FGD/FgdParser.cs @@ -0,0 +1,283 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using UnityEngine; + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace TinyGoose.Tremble +{ + public record EnumDefinition(string Name, string[] Values); + + public static class FgdParser + { + public static void Import(string fgdFilePath) + { + string fgdName = Path.GetFileNameWithoutExtension(fgdFilePath).ToNamingConvention(NamingConvention.UpperCamelCase); + + TokenParser tokenParser = new(File.ReadAllText(fgdFilePath)); + + List baseClasses = new(16); + List concreteClasses = new(64); + + List enums = new(64); + + // Work out type of class and parse + while (!tokenParser.IsAtEnd) + { + string classType = tokenParser.ReadToken(eatAllBracketContent: true).ToString(); + + switch (classType.ToLowerInvariant()) + { + case "@baseclass": + baseClasses.Add(ParseClass(FgdClassType.Base, tokenParser, fgdName, enums)); + break; + case "@pointclass": + concreteClasses.Add(ParseClass(FgdClassType.Point, tokenParser, fgdName, enums)); + break; + case "@solidclass": + concreteClasses.Add(ParseClass(FgdClassType.Brush, tokenParser, fgdName, enums)); + break; + default: + continue; + } + } + + string basePath = Path.GetDirectoryName(fgdFilePath); + string baseEnumPath = Path.Combine(basePath, fgdName, "Enums"); + string baseEntitiesPath = Path.Combine(basePath, fgdName, "Entities"); + + DirectoryUtil.CreateAllDirectories(baseEnumPath); + DirectoryUtil.CreateAllDirectories(baseEntitiesPath); + + // Write Enums first + foreach (EnumDefinition enumDef in enums) + { + string enumFile = Path.Combine(baseEnumPath, enumDef.Name + ".cs"); + enumDef.WriteCSharp(enumFile, fgdName); + } + + // ... then base classes ... + foreach (FgdClass baseClass in baseClasses) + { + string namespaceName = fgdName; + string folderPath = baseEntitiesPath; + + baseClass.Name.Split('_', out string folderName, out string bareClassName); + if (!folderName.IsNullOrEmpty()) + { + namespaceName = $"{fgdName.ToNamingConvention(NamingConvention.UpperCamelCase)}.{folderName.ToNamingConvention(NamingConvention.UpperCamelCase)}"; + folderPath = Path.Combine(folderPath, folderName); + } + + DirectoryUtil.CreateAllDirectories(folderPath); + + string classFile = Path.Combine(folderPath, "I" + bareClassName.ToNamingConvention(NamingConvention.UpperCamelCase) + ".cs"); + baseClass.WriteCSharp(classFile, baseClasses, namespaceName); + } + + // ... finally concrete classes + foreach (FgdClass concreteClass in concreteClasses) + { + string namespaceName = fgdName; + string folderPath = baseEntitiesPath; + + concreteClass.Name.Split('_', out string folderName, out string bareClassName); + if (!folderName.IsNullOrEmpty()) + { + namespaceName = $"{fgdName.ToNamingConvention(NamingConvention.UpperCamelCase)}.{folderName.ToNamingConvention(NamingConvention.UpperCamelCase)}"; + folderPath = Path.Combine(folderPath, folderName); + } + + DirectoryUtil.CreateAllDirectories(folderPath); + + string classFile = Path.Combine(folderPath, bareClassName.ToNamingConvention(NamingConvention.UpperCamelCase) + ".cs"); + concreteClass.WriteCSharp(classFile, baseClasses, namespaceName); + } + + // Refresh code, in editor +#if UNITY_EDITOR + AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); +#endif + } + + private static FgdClass ParseClass(FgdClassType type, TokenParser tokenParser, string fgdNamespace, List outEnumDefinitions) + { + Dictionary metadata = new(); + while (!tokenParser.PeekToken("=", eatAllBracketContent: true)) + { + string metadataString = tokenParser.ReadToken(eatAllBracketContent: true).ToString(); // e.g. base(asfasf, asdgs) or model({f: "fasf"}) + metadataString.Split('(', out string key, out string value); + + metadata[key.ToLowerInvariant()] = value[..^1]; + } + + tokenParser.MatchToken("=", eatAllBracketContent: true); + + ReadOnlySpan classname = tokenParser.ReadToken(); + string classDescription = null; + + classname.Split('_', out string _, out string unityClassname); + unityClassname = unityClassname.ToNamingConvention(NamingConvention.UpperCamelCase); + + if (tokenParser.PeekToken(":")) + { + tokenParser.ReadToken(); + classDescription = tokenParser.ReadToken().ToString(); + } + + FgdClass newClass = new(type, classname.ToString(), classDescription ?? $"{unityClassname} Class"); + + // Add base classes + if (metadata.TryGetValue("base", out string bases)) + { + foreach (string baseClass in bases.Split(",")) + { + newClass.AddBaseClass(baseClass.Trim()); + } + } + + //TODO(jwf): what about model, colour, size, etc? + + if (!tokenParser.PeekToken("[]")) + { + tokenParser.MatchToken("["); // Eat '[' + + while (!tokenParser.IsAtEnd && !tokenParser.PeekToken("]")) + { + // Get name and type + ReadOnlySpan typeString = tokenParser.ReadToken(eatAllBracketContent: true); // e.g. thing(Integer) + typeString.Split('(', out string varName, out string typename); + typename = typename[..^1]; + + string description = null; + string defaultValue = null; + + // Has description? + if (tokenParser.PeekToken(":")) + { + tokenParser.MatchToken(":"); + description = tokenParser.ReadToken().ToString(); + } + + // Has default value? + if (tokenParser.PeekToken(":")) + { + tokenParser.MatchToken(":"); + defaultValue = tokenParser.ReadToken().ToString(); + } + + // Has multiple selections? + if (tokenParser.PeekToken("=")) + { + tokenParser.MatchToken("="); + tokenParser.MatchToken("["); + + if (typename.EqualsInvariant("choices")) + { + // Collect values (not necessarily in order, not necessarily sequential) + Dictionary values = new(64); + int counter = 0; + + while (!tokenParser.PeekToken("]")) + { + if (!int.TryParse(tokenParser.ReadToken(supportCommentsAndQuotes: false), NumberStyles.Any, CultureInfo.InvariantCulture, out int enumValue)) + { + enumValue = counter++; + } + tokenParser.MatchToken(":"); + string enumValueName = NamingConventionUtil.FromHuman(tokenParser.ReadToken()); + values[enumValue] = enumValueName; + } + + tokenParser.MatchToken("]"); + + int maxEnumValue = values.Keys.Max(); + string[] valueStrings = new string[maxEnumValue+1]; + for (int i = 0; i <= maxEnumValue; i++) + { + valueStrings[i] = values.TryGetValue(i, out string valueName) ? valueName : $"Value_{i}"; + } + + string enumName = $"{unityClassname.ToNamingConvention(NamingConvention.UpperCamelCase)}{varName.ToNamingConvention(NamingConvention.UpperCamelCase)}"; + outEnumDefinitions.Add(new + ( + Name: enumName, + Values: valueStrings + )); + + newClass.AddField(new FgdEnumField + { + Name = varName, + Description = description, + EnumClassName = $"{fgdNamespace}.{enumName}", + DefaultValue = 0, + Values = valueStrings, + }); + } + else if (typename.EqualsInvariant("flags")) + { + //TODO(jwf): this assumes all "flags" are "spawnflags" - we should support other flags + while (!tokenParser.PeekToken("]")) + { + int flagBit = (int)Math.Log(int.Parse(tokenParser.ReadToken(), NumberStyles.Any, CultureInfo.InvariantCulture), 2); + tokenParser.MatchToken(":"); + ReadOnlySpan flagName = tokenParser.ReadToken(); + int flagDefaultValue = 0; + + if (tokenParser.PeekToken(":")) + { + tokenParser.MatchToken(":"); + flagDefaultValue = int.Parse(tokenParser.ReadToken(), NumberStyles.Any, CultureInfo.InvariantCulture); + } + + newClass.AddField(new FgdSpawnFlagField + { + Bit = flagBit, + Description = flagName.ToString(), + DefaultValue = flagDefaultValue == 1 + }); + } + } + else + { + Debug.LogWarning("Unexpected options list... skipping..."); + + while (!tokenParser.PeekToken("]")) + { + tokenParser.ReadToken(); + } + } + } + else + { + FgdFieldBase field = FgdFieldFactory.CreateField(typename, varName, description, defaultValue); + if (field == null) + { + Debug.LogWarning($"Could not parse field '{varName}' of type '{typename}'"); + continue; + } + + newClass.AddField(field); + } + } + } + else + { + // Eat "[]" + tokenParser.MatchToken("[]"); + } + + return newClass; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FgdParser.cs.meta b/Assets/Tremble/IO/FGD/FgdParser.cs.meta new file mode 100644 index 0000000..3f36e05 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FgdParser.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: af5ff8df18459483090b8292fe668523 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FgdParser.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FgdWriter.cs b/Assets/Tremble/IO/FGD/FgdWriter.cs new file mode 100644 index 0000000..12a9ba6 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FgdWriter.cs @@ -0,0 +1,239 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public class FgdWriter + { + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private FgdClass m_WorldSpawn; + private readonly List m_OtherClasses = new(); + private readonly List m_BaseClasses = new(); + private readonly string m_VersionString; + private readonly float m_ImportScale; + + public FgdWriter(string versionString, TrembleSyncSettings settings) + { + m_VersionString = versionString; + m_ImportScale = settings.ImportScale; + + // Add base entities + AddMapBaseEntity(); + AddMapPointBaseEntity(); + AddMapPrefabBaseEntity(); + } + + public FgdClass WorldspawnClass + { + get => m_WorldSpawn; + set => m_WorldSpawn = value; + } + + public IReadOnlyList BaseClasses => m_BaseClasses; + public IReadOnlyList Classes => m_OtherClasses; + + public void AddClass(FgdClass entityClass) + { + if (entityClass.Name.Length > 31) + { + Debug.LogError($"Class '{entityClass.Name}' is too long - it cannot be longer than 31 characters." + + " Add a custom [PrefabEntity], [BrushEntity], or [PointEntity] attribute to this MonoBehaviour and set a shorter name!"); + } + + if (entityClass.Type == FgdClassType.Base) + { + int insertionIdx = m_BaseClasses.BinarySearch(entityClass, Comparer.Create((c1, c2) => String.Compare(c1.Name, c2.Name, StringComparison.Ordinal))); + if (insertionIdx < 0) + { + m_BaseClasses.Add(entityClass); + } + else + { + m_BaseClasses.Insert(insertionIdx, entityClass); + } + } + else + { + int insertionIdx = m_OtherClasses.BinarySearch(entityClass, Comparer.Create((c1, c2) => String.Compare(c1.Name, c2.Name, StringComparison.Ordinal))); + if (insertionIdx < 0) + { + m_OtherClasses.Add(entityClass); + } + else + { + m_OtherClasses.Insert(insertionIdx, entityClass); + } + } + } + + public void WriteFgd(StreamWriter stream, bool humanReadable = true) + { + if (humanReadable) + { + stream.WriteLine("// TrenchBroom game definition file (.fgd)"); + stream.WriteLine($"// Generated by Tremble for Unity v{m_VersionString}"); + stream.WriteLine($"// For: {Application.productName}. (c) {DateTime.UtcNow.Year} {Application.companyName}"); + stream.WriteLine(); + stream.WriteLine(); + + stream.WriteLine("// ----------------------------------------------------------------------------------------------------"); + stream.WriteLine("//"); + stream.WriteLine("// Base Classes"); + stream.WriteLine("//"); + stream.WriteLine("// ----------------------------------------------------------------------------------------------------"); + } + + // Base entities + foreach (FgdClass entity in m_BaseClasses) + { + if (humanReadable) + { + stream.WriteLine("// ----------------------------------------------------------------------------------------------------"); + stream.WriteLine($"// Tremble Base Class '{entity.Name}'"); + stream.WriteLine($"// {entity.Description}"); + stream.WriteLine("// ----------------------------------------------------------------------------------------------------"); + } + + entity.WriteFgd(stream, m_ImportScale); + + if (humanReadable) + { + stream.WriteLine(); + stream.WriteLine(); + } + } + + if (m_WorldSpawn != null) + { + if (humanReadable) + { + stream.WriteLine(); + stream.WriteLine(); + stream.WriteLine(); + stream.WriteLine("// ----------------------------------------------------------------------------------------------------"); + stream.WriteLine("//"); + stream.WriteLine("// worldspawn - World Root Properties"); + stream.WriteLine("//"); + stream.WriteLine("// ----------------------------------------------------------------------------------------------------"); + } + + m_WorldSpawn.WriteFgd(stream, m_ImportScale); + + if (humanReadable) + { + stream.WriteLine(); + stream.WriteLine(); + } + } + + if (humanReadable) + { + stream.WriteLine(); + stream.WriteLine(); + stream.WriteLine(); + stream.WriteLine("// ----------------------------------------------------------------------------------------------------"); + stream.WriteLine("//"); + stream.WriteLine("// Game Entities"); + stream.WriteLine("//"); + stream.WriteLine("// ----------------------------------------------------------------------------------------------------"); + stream.WriteLine(); + } + + foreach (FgdClass entity in m_OtherClasses) + { + if (humanReadable) + { + string type = entity.Type switch + { + FgdClassType.Base => nameof(ITrembleBaseClass), + FgdClassType.Point => "Point Entity", + FgdClassType.Brush => "Brush Entity", + _ => throw new ArgumentOutOfRangeException() + }; + + stream.WriteLine("// ----------------------------------------------------------------------------------------------------"); + stream.WriteLine($"// {type}"); + stream.WriteLine($"// {entity.Description}"); + stream.WriteLine("// ----------------------------------------------------------------------------------------------------"); + } + + entity.WriteFgd(stream, m_ImportScale); + } + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Helpers + // ----------------------------------------------------------------------------------------------------------------------------- + private void AddMapBaseEntity() + { + FgdClass mapBase = new(FgdClassType.Base, FgdConsts.CLASS_MAP_BASE, "The base class for all map entities"); + mapBase.Description = "Base class for common map properties"; + + mapBase.AddField(new FgdTargetSourceField + { + Name = TrembleSyncSettings.Get().IdentityPropertyName, + Description = "The ID/Name of this entity", + DefaultValue = "" + }); + + mapBase.AddField(new FgdAnglesField + { + Name = FgdConsts.PROPERTY_ANGLES, + Description = "Rotation Angles", + DefaultValue = Vector3.zero + }); + + mapBase.AddField(new FgdVectorField + { + Name = FgdConsts.PROPERTY_ORIGIN, + Description = "Spawn position of this entity", + DefaultValue = Vector3.zero, + ConvertToQ3 = true, + ImportScale = m_ImportScale + }); + + AddClass(mapBase); + } + private void AddMapPointBaseEntity() + { + FgdClass mapBase = new(FgdClassType.Base, FgdConsts.CLASS_MAP_POINT_BASE, "The base class for all Point entities"); + mapBase.Description = "Base class for common Point properties"; + + mapBase.AddField(new FgdTargetDestinationField + { + Name = FgdConsts.PROPERTY_PARENT, + Description = "Parent Transform", + DefaultValue = null + }); + + AddClass(mapBase); + } + + private void AddMapPrefabBaseEntity() + { + FgdClass mapBase = new(FgdClassType.Base, FgdConsts.CLASS_MAP_PREFAB_BASE, "The base class for all Prefab entities"); + mapBase.Description = "Base class for common Prefab properties"; + + mapBase.AddBaseClass(FgdConsts.CLASS_MAP_POINT_BASE); + + mapBase.AddField(new FgdVectorField + { + Name = FgdConsts.PROPERTY_SCALE, + Description = "Prefab Scale", + DefaultValue = Vector3.one + }); + + AddClass(mapBase); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FgdWriter.cs.meta b/Assets/Tremble/IO/FGD/FgdWriter.cs.meta new file mode 100644 index 0000000..4c388f5 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FgdWriter.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 8ae2428dfb70468ab002a264f8bc17de +timeCreated: 1698227021 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FgdWriter.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes.meta b/Assets/Tremble/IO/FGD/FieldTypes.meta new file mode 100644 index 0000000..47c8ea8 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 80fdd27eed8a4e8cbca74e05b26cfc12 +timeCreated: 1712223157 \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdAnglesField.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdAnglesField.cs new file mode 100644 index 0000000..61a9b64 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdAnglesField.cs @@ -0,0 +1,44 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdAnglesField : FgdFieldBase + { + public string Name { get; init; } + public string Description { get; init; } + public Vector3 DefaultValue { get; init; } + + public override string FieldName => Name; + + public override void Write(StreamWriter sw) + { + if (Mathf.Approximately(DefaultValue.x, DefaultValue.y) && Mathf.Approximately(DefaultValue.y, DefaultValue.z)) + { + sw.WriteLine($"{Name}(float) : \"{Description.Replace("\"", "'")}\" : \"{DefaultValue.x.ToStringInvariant()}\""); + } + else + { + sw.WriteLine($"{Name}(float) : \"{Description.Replace("\"", "'")}\" : \"{DefaultValue.ToStringInvariant()}\""); + } + } + + public override void WriteCSharpClass(StreamWriter sw, int indent) + { + string defaultValueString = DefaultValue == Vector3.zero + ? "Vector3.zero" + : $"new Vector3({DefaultValue.x.ToStringInvariant()}, {DefaultValue.y.ToStringInvariant()}, {DefaultValue.z.ToStringInvariant()})"; + WriteClassField(sw, indent, nameof(Vector3), Name, Description, defaultValueString); + } + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + => WriteInterfaceProperty(sw, indent, nameof(Vector3), Name, Description); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdAnglesField.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdAnglesField.cs.meta new file mode 100644 index 0000000..4395425 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdAnglesField.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 67ec51e0586d4dedaad0c34cef140416 +timeCreated: 1712223260 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdAnglesField.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdBooleanField.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdBooleanField.cs new file mode 100644 index 0000000..25c5050 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdBooleanField.cs @@ -0,0 +1,39 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdBooleanField : FgdFieldBase + { + public string Name { get; init; } + public string Description { get; init; } + public bool DefaultValue { get; init; } + + public override string FieldName => Name; + + public override void Write(StreamWriter sw) + { + string description = Description != null ? Description.Replace("\"", "'") : Name; + + sw.WriteLine($"{Name}(choices) : \"{description}\" : {(DefaultValue ? "1" : "0")} = "); + sw.WriteLine("\t["); + { + sw.WriteLine("\t\t0 : \"False\""); + sw.WriteLine("\t\t1 : \"True\""); + } + sw.WriteLine("\t]"); + } + + public override void WriteCSharpClass(StreamWriter sw, int indent) + => WriteClassField(sw, indent, "bool", Name, Description, DefaultValue ? "true" : null); + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + => WriteInterfaceProperty(sw, indent, "bool", Name, Description); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdBooleanField.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdBooleanField.cs.meta new file mode 100644 index 0000000..fab95e1 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdBooleanField.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 31b88cf082164f41b2a7d78f67919483 +timeCreated: 1712223319 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdBooleanField.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdChoicesIntField.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdChoicesIntField.cs new file mode 100644 index 0000000..8691669 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdChoicesIntField.cs @@ -0,0 +1,48 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdChoicesIntField : FgdFieldBase + { + public string Name { get; init; } + public string Description { get; init; } + public string[] Choices { get; init; } + public int DefaultValue { get; init; } + + public override string FieldName => Name; + + public override void Write(StreamWriter sw) + { + if (DefaultValue == 0) + { + sw.WriteLine($"{Name}(choices) : \"{Description.Replace("\"", "'")}\" = "); + } + else + { + sw.WriteLine($"{Name}(choices) : \"{Description.Replace("\"", "'")}\" : {DefaultValue} = "); + } + + sw.WriteLine("\t["); + { + for (int i = 0; i < Choices.Length; i++) + { + sw.WriteLine($"\t\t{i} : \"{Choices[i]}\""); + } + } + sw.WriteLine("\t]"); + } + + public override void WriteCSharpClass(StreamWriter sw, int indent) + => WriteClassField(sw, indent, "int", Name, Description, DefaultValue == 0 ? null : DefaultValue.ToString()); + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + => WriteInterfaceProperty(sw, indent, "int", Name, Description); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdChoicesIntField.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdChoicesIntField.cs.meta new file mode 100644 index 0000000..4dca110 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdChoicesIntField.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 8b1808df0f9246d981380501211318d8 +timeCreated: 1712223378 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdChoicesIntField.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdChoicesStringField.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdChoicesStringField.cs new file mode 100644 index 0000000..10d7819 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdChoicesStringField.cs @@ -0,0 +1,48 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdChoicesStringField : FgdFieldBase + { + public string Name { get; init; } + public string Description { get; init; } + public string[] Choices { get; init; } + public string DefaultValue { get; init; } + + public override string FieldName => Name; + + public override void Write(StreamWriter sw) + { + sw.WriteLine($"{Name}(choices) : \"{Description.Replace("\"", "'")}\" : \"{DefaultValue ?? Choices[0]}\" = "); + sw.WriteLine("\t["); + { + foreach (string choice in Choices) + { + if (choice.IsNullOrEmpty()) + { + sw.WriteLine("\t\t\"\" : \"(none)\""); + } + else + { + sw.WriteLine($"\t\t\"{choice}\" : \"{choice.ToNamingConvention(NamingConvention.HumanFriendly)}\""); + } + } + } + sw.WriteLine("\t]"); + } + + //TODO(jwf): support default values? + public override void WriteCSharpClass(StreamWriter sw, int indent) + => WriteClassField(sw, indent, "string", Name, Description); + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + => WriteInterfaceProperty(sw, indent, "string", Name, Description); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdChoicesStringField.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdChoicesStringField.cs.meta new file mode 100644 index 0000000..81b1128 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdChoicesStringField.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 6c59811822b3441d835a848021e6ef17 +timeCreated: 1712223387 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdChoicesStringField.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdColourField.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdColourField.cs new file mode 100644 index 0000000..d5b126c --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdColourField.cs @@ -0,0 +1,39 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Globalization; +using System.IO; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdColourField : FgdFieldBase + { + public string Name { get; init; } + public string Description { get; init; } + public Color DefaultColour { get; init; } + + public override string FieldName => Name; + + public override void Write(StreamWriter sw) + { + sw.WriteLine($"{Name}(color) : \"{Description.Replace("\"", "'")}\" : \"{DefaultColour.ToStringInvariant()}\""); + } + + public override void WriteCSharpClass(StreamWriter sw, int indent) + { + string defaultValueString = DefaultColour == Color.white + ? "Color.white" + : $"new Color({DefaultColour.r.ToStringInvariant()}, {DefaultColour.g.ToStringInvariant()}, {DefaultColour.b.ToStringInvariant()})"; + + WriteClassField(sw, indent, nameof(Color), Name, Description, DefaultColour == Color.white ? null : defaultValueString); + } + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + => WriteInterfaceProperty(sw, indent, nameof(Color), Name, Description); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdColourField.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdColourField.cs.meta new file mode 100644 index 0000000..e115e09 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdColourField.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: d14b410b2bd14d4e8a9a0b9e4cc5d984 +timeCreated: 1712223272 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdColourField.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdComment.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdComment.cs new file mode 100644 index 0000000..8099cb5 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdComment.cs @@ -0,0 +1,33 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdComment : FgdFieldBase + { + public string Comment { get; init; } + + public override void Write(StreamWriter sw) + { + sw.WriteLine($"// {Comment}"); + } + + public override void WriteCSharpClass(StreamWriter sw, int indent) + { + sw.WriteIndent(indent); + sw.WriteLine($"// {Comment}"); + } + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + { + sw.WriteIndent(indent); + sw.WriteLine($"// {Comment}"); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdComment.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdComment.cs.meta new file mode 100644 index 0000000..4931697 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdComment.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a46440a8a9254de1aad67d79e4cb1509 +timeCreated: 1712223182 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdComment.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdEnumField.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdEnumField.cs new file mode 100644 index 0000000..5a2af20 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdEnumField.cs @@ -0,0 +1,124 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; +using System.Linq; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdEnumField : FgdFieldBase + { + public string Name { get; init; } + public string Description { get; init; } + public string EnumClassName { get; init; } + public int DefaultValue { get; init; } + public string[] Values { get; set; } + + public override string FieldName => Name; + + private string[] EnumValuesOrCached + { + get + { + if (Values == null || Values.Length == 0) + { + if (EnumClassName.ContainsInvariant("+")) + { + EnumClassName.Split('+', out string className, out string enumName); + + Debug.LogError($"Couldn't use {enumName} enum. Enums embedded in classes are " + + $"not supported by Tremble :(. Move your '{enumName}' enum " + + $"outside of {className} to use it!"); + return Array.Empty(); + } + + Type enumType = TypeDatabase.GetType(EnumClassName); + string[] names = Enum.GetNames(enumType); + + int[] values = Enum.GetValues(enumType).Cast().ToArray(); + int maxValue = values.Max(); + + Values = new string[maxValue + 1]; + for (int i = 0; i <= maxValue; i++) + { + int nameIdx = Array.FindIndex(values, v => v == i); + if (nameIdx == -1) + { + Values[i] = "_"; + } + else + { + Values[i] = names[nameIdx]; + } + } + } + + return Values; + } + } + + public override void Write(StreamWriter sw) + { + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + + if (syncSettings.SyncEnumsAsStringValue) + { + string[] values = EnumValuesOrCached; + string defaultString = values.Length > DefaultValue && !values[DefaultValue].EqualsInvariant("_") ? values[DefaultValue] : "(none)"; + sw.WriteLine($"{Name}(choices) : \"{Description.Replace("\"", "'")}\" : \"{defaultString}\" = "); + } + else + { + if (DefaultValue == 0) + { + sw.WriteLine($"{Name}(choices) : \"{Description.Replace("\"", "'")}\""); + } + else + { + sw.WriteLine($"{Name}(choices) : \"{Description.Replace("\"", "'")}\" : {DefaultValue} = "); + } + } + + sw.WriteLine("\t["); + { + for (int i = 0; i < EnumValuesOrCached.Length; i++) + { + string value = EnumValuesOrCached[i]; + if (value.EqualsInvariant("_")) + continue; + + if (syncSettings.SyncEnumsAsStringValue) + { + sw.WriteLine($"\t\t\"{value}\" : \"{value}\""); + } + else + { + sw.WriteLine($"\t\t{i} : \"{value}\""); + } + } + } + sw.WriteLine("\t]"); + } + + public override void WriteCSharpClass(StreamWriter sw, int indent) + { + string enumTypeName = EnumClassName; + int lastDot = enumTypeName.LastIndexOf('.'); + if (lastDot != -1) + { + enumTypeName = enumTypeName.Substring(lastDot + 1); + } + + string defaultValueString = $"{EnumClassName}.{EnumValuesOrCached[DefaultValue]}"; + WriteClassField(sw, indent, enumTypeName, Name, Description, defaultValueString); + } + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + => WriteInterfaceProperty(sw, indent, EnumClassName, Name, Description); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdEnumField.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdEnumField.cs.meta new file mode 100644 index 0000000..3fb1660 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdEnumField.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 7cb83d47f4a14179baba19b9197b90ea +timeCreated: 1712223369 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdEnumField.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdFlagsField.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdFlagsField.cs new file mode 100644 index 0000000..0dfc75d --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdFlagsField.cs @@ -0,0 +1,97 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdFlagsField : FgdFieldBase + { + public string Name { get; init; } + public string Description { get; init; } + public string EnumClassName { get; init; } + public string[] EnumNames { get; set; } + + public override string FieldName => Name; + + private string[] EnumNamesOrCached + { + get + { + if (EnumNames == null || EnumNames.Length == 0) + { + if (EnumClassName.ContainsInvariant("+")) + { + EnumClassName.Split('+', out string className, out string enumName); + + Debug.LogError($"Couldn't use {enumName} enum. Enums embedded in classes are " + + $"not supported by Tremble :(. Move your '{enumName}' enum " + + $"outside of {className} to use it!"); + return Array.Empty(); + } + + Type enumType = TypeDatabase.GetType(EnumClassName); + string[] names = Enum.GetNames(enumType); + int[] values = Enum.GetValues(enumType).Cast().ToArray(); + + int maxValue = values.Max(); + EnumNames = new string[maxValue + 1]; + + for (int i = 0; i <= maxValue; i++) + { + int nameIdx = Array.FindIndex(values, v => v == i); + if (nameIdx == -1) + { + EnumNames[i] = "_"; + } + else + { + EnumNames[i] = names[nameIdx]; + } + } + } + + return EnumNames; + } + } + + public override void Write(StreamWriter sw) + { + sw.WriteLine($"{Name}(flags) = "); + sw.WriteLine("\t["); + { + for (int i = 0; i < EnumNamesOrCached.Length; i++) + { + string name = EnumNamesOrCached[i]; + if (name.EqualsInvariant("_")) + continue; + + sw.WriteLine($"\t\t{i} : \"{name}\" : 0"); + } + } + sw.WriteLine("\t]"); + } + + public override void WriteCSharpClass(StreamWriter sw, int indent) + { + string enumTypeName = EnumClassName; + int lastDot = enumTypeName.LastIndexOf('.'); + if (lastDot != -1) + { + enumTypeName = enumTypeName.Substring(lastDot + 1); + } + + WriteClassField(sw, indent, enumTypeName, Name, Description, "default"); + } + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + => WriteInterfaceProperty(sw, indent, EnumClassName, Name, Description, "Flags"); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdFlagsField.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdFlagsField.cs.meta new file mode 100644 index 0000000..4b6a914 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdFlagsField.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 86f42cfbe8b54eeeaf7d8102766a3fba +timeCreated: 1774358034 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdFlagsField.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdFloatField.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdFloatField.cs new file mode 100644 index 0000000..4e80e8f --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdFloatField.cs @@ -0,0 +1,38 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdFloatField : FgdFieldBase + { + public string Name { get; init; } + public string Description { get; init; } + public float DefaultValue { get; init; } + + public override string FieldName => Name; + + public override void Write(StreamWriter sw) + { + if (DefaultValue == 0f) + { + sw.WriteLine($"{Name}(float) : \"{Description.Replace("\"", "'")}\""); + } + else + { + sw.WriteLine($"{Name}(float) : \"{Description.Replace("\"", "'")}\" : \"{DefaultValue.ToStringInvariant()}\""); + } + } + + public override void WriteCSharpClass(StreamWriter sw, int indent) + => WriteClassField(sw, indent, "float", Name, Description, DefaultValue == 0f ? null : DefaultValue.ToStringInvariant() + "f"); + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + => WriteInterfaceProperty(sw, indent, "float", Name, Description); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdFloatField.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdFloatField.cs.meta new file mode 100644 index 0000000..df35b19 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdFloatField.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 56cba705d7a240a8b2b05ae6edb8ddeb +timeCreated: 1712223287 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdFloatField.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdIntegerField.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdIntegerField.cs new file mode 100644 index 0000000..b2d3aaa --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdIntegerField.cs @@ -0,0 +1,38 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdIntegerField : FgdFieldBase + { + public string Name { get; init; } + public string Description { get; init; } + public int DefaultValue { get; init; } + + public override string FieldName => Name; + + public override void Write(StreamWriter sw) + { + if (DefaultValue == 0) + { + sw.WriteLine($"{Name}(integer) : \"{Description.Replace("\"", "'")}\""); + } + else + { + sw.WriteLine($"{Name}(integer) : \"{Description.Replace("\"", "'")}\" : {DefaultValue}"); + } + } + + public override void WriteCSharpClass(StreamWriter sw, int indent) + => WriteClassField(sw, indent, "int", Name, Description, DefaultValue == 0 ? null : DefaultValue.ToString()); + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + => WriteInterfaceProperty(sw, indent, "int", Name, Description); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdIntegerField.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdIntegerField.cs.meta new file mode 100644 index 0000000..ade4a7b --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdIntegerField.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 96bcc84614cf430590935b78d98f0ca0 +timeCreated: 1712223311 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdIntegerField.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdSpawnFlagField.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdSpawnFlagField.cs new file mode 100644 index 0000000..7eedd7c --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdSpawnFlagField.cs @@ -0,0 +1,33 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdSpawnFlagField : FgdFieldBase + { + public int Bit { get; init; } + public string Description { get; init; } + public bool DefaultValue { get; init; } + + public override string FieldName => NamingConventionUtil.FromHuman(Description); + + public override void Write(StreamWriter sw) + { + int bitDefaultValue = 1 << Bit; + + sw.WriteLine($"{bitDefaultValue} : \"{Description.Replace("\"", "'")}\" : {(DefaultValue ? "1" : "0")}"); + } + + public override void WriteCSharpClass(StreamWriter sw, int indent) + => WriteClassField(sw, indent, "bool", FieldName, Description, DefaultValue ? "true" : null, extraAttributes: $"SpawnFlags({Bit})"); + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + => WriteInterfaceProperty(sw, indent, "bool", FieldName, Description, attributes: $"SpawnFlags({Bit})"); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdSpawnFlagField.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdSpawnFlagField.cs.meta new file mode 100644 index 0000000..0a7c357 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdSpawnFlagField.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: d5d3344597c842eb8c287ffb9e4e6854 +timeCreated: 1712223402 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdSpawnFlagField.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdStringField.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdStringField.cs new file mode 100644 index 0000000..5cb753d --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdStringField.cs @@ -0,0 +1,38 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdStringField : FgdFieldBase + { + public string Name { get; init; } + public string Description { get; init; } + public string DefaultValue { get; init; } + + public override string FieldName => Name; + + public override void Write(StreamWriter sw) + { + if (DefaultValue.IsNullOrEmpty()) + { + sw.WriteLine($"{Name}(string) : \"{Description.Replace("\"", "'")}\""); + } + else + { + sw.WriteLine($"{Name}(string) : \"{Description.Replace("\"", "'")}\" : \"{DefaultValue}\""); + } + } + + public override void WriteCSharpClass(StreamWriter sw, int indent) + => WriteClassField(sw, indent, "string", Name, Description, DefaultValue.IsNullOrEmpty() ? null : $"\"{DefaultValue}\""); + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + => WriteInterfaceProperty(sw, indent, "string", Name, Description); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdStringField.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdStringField.cs.meta new file mode 100644 index 0000000..fd8315f --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdStringField.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: b475d7d5cead4105af48ebd7252e50db +timeCreated: 1712223334 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdStringField.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdTargetDestinationField.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdTargetDestinationField.cs new file mode 100644 index 0000000..59c3caa --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdTargetDestinationField.cs @@ -0,0 +1,40 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdTargetDestinationField : FgdFieldBase + { + public string Name { get; init; } + public string Description { get; init; } + public string DefaultValue { get; init; } + + public override string FieldName => Name; + + public override void Write(StreamWriter sw) + { + if (DefaultValue.IsNullOrEmpty()) + { + sw.WriteLine($"{Name}(target_destination) : \"{Description.Replace("\"", "'")}\""); + } + else + { + sw.WriteLine($"{Name}(target_destination) : \"{Description.Replace("\"", "'")}\" : \"{DefaultValue}\""); + } + } + + //TODO(jwf): support default values? + public override void WriteCSharpClass(StreamWriter sw, int indent) + => WriteClassField(sw, indent, nameof(Transform), Name, Description); + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + => WriteInterfaceProperty(sw, indent, nameof(Transform), Name, Description); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdTargetDestinationField.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdTargetDestinationField.cs.meta new file mode 100644 index 0000000..4a207f7 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdTargetDestinationField.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ce6a69e950e34780a3a25026a94798b1 +timeCreated: 1712223349 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdTargetDestinationField.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdTargetSourceField.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdTargetSourceField.cs new file mode 100644 index 0000000..bba812f --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdTargetSourceField.cs @@ -0,0 +1,38 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdTargetSourceField : FgdFieldBase + { + public string Name { get; init; } + public string Description { get; init; } + public string DefaultValue { get; init; } + + public override string FieldName => Name; + + public override void Write(StreamWriter sw) + { + if (DefaultValue.IsNullOrEmpty()) + { + sw.WriteLine($"{Name}(target_source) : \"{Description.Replace("\"", "'")}\""); + } + else + { + sw.WriteLine($"{Name}(target_source) : \"{Description.Replace("\"", "'")}\" : \"{DefaultValue}\""); + } + } + + public override void WriteCSharpClass(StreamWriter sw, int indent) + => WriteClassField(sw, indent, "string", Name, Description, DefaultValue.IsNullOrEmpty() ? null : $"\"{DefaultValue}\""); + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + => WriteInterfaceProperty(sw, indent, "string", Name, Description); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdTargetSourceField.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdTargetSourceField.cs.meta new file mode 100644 index 0000000..4dac2bc --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdTargetSourceField.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ef716bdc4952478b80d299a922219b1a +timeCreated: 1712223341 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdTargetSourceField.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdVectorField.cs b/Assets/Tremble/IO/FGD/FieldTypes/FgdVectorField.cs new file mode 100644 index 0000000..3216122 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdVectorField.cs @@ -0,0 +1,53 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class FgdVectorField : FgdFieldBase + { + public string Name { get; init; } + public string Description { get; init; } + public Vector3 DefaultValue { get; init; } + public bool ConvertToQ3 { get; init; } + public float ImportScale { get; init; } + + public override string FieldName => Name; + + public override void Write(StreamWriter sw) + { + Vector3 value = DefaultValue; + + if (ConvertToQ3) + { + value = new Vector3(-value.x, -value.z, value.y) / ImportScale; + } + + if (Mathf.Approximately(value.x, value.y) && Mathf.Approximately(value.y, value.z)) + { + sw.WriteLine($"{Name}(float) : \"{Description.Replace("\"", "'")}\" : \"{value.x.ToStringInvariant()}\""); + } + else + { + sw.WriteLine($"{Name}(float) : \"{Description.Replace("\"", "'")}\" : \"{value.ToStringInvariant()}\""); + } + } + + public override void WriteCSharpClass(StreamWriter sw, int indent) + { + string defaultValueString = DefaultValue == Vector3.zero + ? "Vector3.zero" + : $"new Vector3({DefaultValue.x.ToStringInvariant()}, {DefaultValue.y.ToStringInvariant()}, {DefaultValue.z.ToStringInvariant()})"; + WriteClassField(sw, indent, nameof(Vector3), Name, Description, defaultValueString); + } + + public override void WriteCSharpInterface(StreamWriter sw, int indent) + => WriteInterfaceProperty(sw, indent, nameof(Vector3), Name, Description); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/FieldTypes/FgdVectorField.cs.meta b/Assets/Tremble/IO/FGD/FieldTypes/FgdVectorField.cs.meta new file mode 100644 index 0000000..b277523 --- /dev/null +++ b/Assets/Tremble/IO/FGD/FieldTypes/FgdVectorField.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 078725a3929747ceb3f93ad3e68e36d5 +timeCreated: 1712223216 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/FieldTypes/FgdVectorField.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/Writers.meta b/Assets/Tremble/IO/FGD/Writers.meta new file mode 100644 index 0000000..c6c588c --- /dev/null +++ b/Assets/Tremble/IO/FGD/Writers.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f8e7b72eacf0406e90949f0230906787 +timeCreated: 1712323557 \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/Writers/EntityClassWriter.cs b/Assets/Tremble/IO/FGD/Writers/EntityClassWriter.cs new file mode 100644 index 0000000..be38ae2 --- /dev/null +++ b/Assets/Tremble/IO/FGD/Writers/EntityClassWriter.cs @@ -0,0 +1,330 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace TinyGoose.Tremble +{ + public static class EntityClassWriter + { + public static void WriteCSharp(this FgdClass fgdClass, string file, List allBaseClasses = null, string namespaceName = null) + { + if (fgdClass.Type == FgdClassType.Base) + { + WriteCSharpInterface(fgdClass, file, namespaceName); + } + else + { + WriteCSharpClass(fgdClass, file, allBaseClasses, namespaceName); + } + } + + private static void WriteCSharpClass(this FgdClass fgdClass, string file, List allBaseClasses = null, string namespaceName = null) + { + using FileStream classFile = new(file, FileMode.Create, FileAccess.Write); + using StreamWriter writer = new(classFile); + + writer.WriteLine($"// Class '{fgdClass.Name}'"); + writer.WriteLine($"// Generated by Tremble v{TrembleConsts.VERSION_STRING}"); + writer.WriteLine(); + + writer.WriteLine("using UnityEngine;"); + writer.WriteLine("using TinyGoose.Tremble;"); + writer.WriteLine(); + + writer.WriteLine("// Disable 'Field is assigned but its value is never used' warning"); + writer.WriteLine("#pragma warning disable CS0414"); + writer.WriteLine(); + + bool hasNamespace = !namespaceName.IsNullOrEmpty(); + + if (hasNamespace) + { + writer.WriteLine($"namespace {namespaceName}"); + writer.WriteLine("{"); + } + + if (!fgdClass.Description.IsNullOrEmpty()) + { + writer.WriteLine($"\t// \"{fgdClass.Description}\""); + } + + { + fgdClass.Name.Split('_', out string category, out string classname); + + if (fgdClass.Type == FgdClassType.Brush) + { + if (hasNamespace) + { + writer.Write("\t"); + } + writer.Write("[BrushEntity("); + } + else + { + if (hasNamespace) + { + writer.Write("\t"); + } + writer.Write("[PointEntity("); + } + + writer.Write($"\"{classname}\""); + + if (category.IsNullOrEmpty()) + { + writer.Write($", category: \"\" /* empty category - gross, but necessary */"); + } + else + { + writer.Write($", category: \"{category}\""); + } + + if (fgdClass.Type == FgdClassType.Brush && fgdClass.Name.ContainsInvariant("trigger")) + { + writer.Write($", type: BrushType.Trigger"); + } + + writer.WriteLine(")]"); + + string csharpClassname = classname.ToNamingConvention(NamingConvention.UpperCamelCase); + if (!category.IsNullOrEmpty() + && !category.EqualsInvariant("misc") + && !category.EqualsInvariant("func")) + { + csharpClassname += category.ToNamingConvention(NamingConvention.UpperCamelCase); + } + + if (csharpClassname.EqualsInvariant("light")) + { + // Hack: you can't call a MonoBehaviour "Light" in Unity, but Quake for example + // has an entity called "light" - let's call it LightEntity + csharpClassname = "LightEntity"; + } + + if (hasNamespace) + { + writer.Write("\t"); + } + writer.Write($"public class {csharpClassname} : MonoBehaviour"); + + foreach (string baseClass in fgdClass.BaseClassNames) + { + // Not the Tremble ones! + if (baseClass.EqualsInvariant(FgdConsts.CLASS_MAP_BASE, caseSensitive: true) + || baseClass.EqualsInvariant(FgdConsts.CLASS_MAP_POINT_BASE, caseSensitive: true)) + continue; + + writer.Write($", I{baseClass}"); + } + writer.WriteLine(); + + if (hasNamespace) + { + writer.Write("\t"); + } + writer.WriteLine("{"); + + if (fgdClass.AllFields.Count > 0) + { + writer.WriteIndent(hasNamespace ? 2 : 1); + writer.WriteLine("// Fields:"); + + foreach (FgdFieldBase field in fgdClass.AllFields) + { + field.WriteCSharpClass(writer, hasNamespace ? 2 : 1); + } + + writer.WriteLine(); + } + + if (fgdClass.AllSpawnFlags.Count > 0) + { + writer.WriteIndent(hasNamespace ? 2 : 1); + writer.WriteLine("// Spawnflags: "); + foreach (FgdSpawnFlagField spawnFlagField in fgdClass.AllSpawnFlags) + { + spawnFlagField.WriteCSharpClass(writer, hasNamespace ? 2 : 1); + } + + writer.WriteLine(); + } + + // Write base class fields + if (allBaseClasses != null) + { + List writtenBaseClasses = new(64); + List writtenFields = new(64); + + foreach (string baseClassName in fgdClass.BaseClassNames) + { + AddBaseClassFields(fgdClass, writer, hasNamespace, baseClassName, writtenBaseClasses, writtenFields, allBaseClasses); + } + } + + if (hasNamespace) + { + writer.Write("\t"); + } + writer.WriteLine("}"); + } + + if (hasNamespace) + { + writer.WriteLine("}"); + } + + writer.WriteLine(); + writer.WriteLine("#pragma warning restore CS0414"); + } + + private static void AddBaseClassFields(FgdClass thisClass, StreamWriter writer, bool hasNamespace, string baseClassName, List writtenBaseClasses, List writtenFields, List allBaseClasses) + { + // Find the base class and add! + FgdClass baseClass = allBaseClasses.FirstOrDefault(bc => bc.Name.EqualsInvariant(baseClassName, caseSensitive: true)); + if (baseClass == null) + return; + + if (baseClass.AllFields.Count + baseClass.AllSpawnFlags.Count == 0) + return; + + if (writtenBaseClasses.Contains(baseClassName)) + return; + + writtenBaseClasses.Add(baseClassName); + + foreach (string baseBaseClassName in baseClass.BaseClassNames) + { + AddBaseClassFields(thisClass, writer, hasNamespace, baseBaseClassName, writtenBaseClasses, writtenFields, allBaseClasses); + } + + writer.WriteLine(); + writer.WriteIndent(hasNamespace ? 2 : 1); + writer.WriteLine($"// From Base Class '{baseClassName}':"); + + foreach (FgdFieldBase field in baseClass.AllFields) + { + if (writtenFields.Contains(field.FieldName)) + { + writer.WriteIndent(hasNamespace ? 2 : 1); + writer.WriteLine($"// Skipped '{field.FieldName}' - already defined by a base class!"); + continue; + } + + writtenFields.Add(field.FieldName); + + bool overridden = thisClass.AllFields.Any(m => m.FieldName.EqualsInvariant(field.FieldName, caseSensitive: true)); + if (overridden) + { + writer.WriteLine("/* (overriden by subclass)"); + } + + field.WriteCSharpClass(writer, hasNamespace ? 2 : 1); + + if (overridden) + { + writer.WriteLine("(overriden by subclass) */"); + } + } + + foreach (FgdSpawnFlagField spawnFlag in baseClass.AllSpawnFlags) + { + bool overridden = thisClass.AllSpawnFlags.Any(m => m.FieldName.EqualsInvariant(spawnFlag.FieldName, caseSensitive: true)); + if (overridden) + { + writer.WriteLine("/* (overriden by subclass)"); + } + + spawnFlag.WriteCSharpClass(writer, hasNamespace ? 2 : 1); + + if (overridden) + { + writer.WriteLine("(overriden by subclass) */"); + } + } + } + + + private static void WriteCSharpInterface(this FgdClass fgdClass, string file, string namespaceOrNull) + { + using FileStream classFile = new(file, FileMode.Create, FileAccess.Write); + using StreamWriter writer = new(classFile); + + writer.WriteLine($"// Interface 'I{fgdClass.Name}'"); + writer.WriteLine($"// Generated by Tremble v{TrembleConsts.VERSION_STRING}"); + writer.WriteLine(); + + writer.WriteLine("using UnityEngine;"); + writer.WriteLine("using TinyGoose.Tremble;"); + writer.WriteLine(); + + bool hasNamespace = !namespaceOrNull.IsNullOrEmpty(); + + if (hasNamespace) + { + writer.WriteLine($"namespace {namespaceOrNull}"); + writer.WriteLine("{"); + } + + { + fgdClass.Name.Split('_', out string _, out string classname); + string csharpClassname = classname.ToNamingConvention(NamingConvention.UpperCamelCase); + + if (hasNamespace) + { + writer.Write("\t"); + } + writer.WriteLine($"public interface I{csharpClassname} : ITrembleBaseClass"); + + if (hasNamespace) + { + writer.Write("\t"); + } + writer.WriteLine("{"); + + if (fgdClass.AllFields.Count > 0) + { + if (hasNamespace) + { + writer.Write("\t"); + } + writer.WriteLine("\t// Fields:"); + + foreach (FgdFieldBase field in fgdClass.AllFields) + { + field.WriteCSharpInterface(writer, hasNamespace ? 2 : 1); + } + } + + if (fgdClass.AllSpawnFlags.Count > 0) + { + if (hasNamespace) + { + writer.Write("\t"); + } + writer.WriteLine("\t// Spawnflags: "); + foreach (FgdSpawnFlagField spawnFlagField in fgdClass.AllSpawnFlags) + { + spawnFlagField.WriteCSharpInterface(writer, hasNamespace ? 2 : 1); + } + } + + if (hasNamespace) + { + writer.Write("\t"); + } + writer.WriteLine("}"); + } + + if (hasNamespace) + { + writer.WriteLine("}"); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/Writers/EntityClassWriter.cs.meta b/Assets/Tremble/IO/FGD/Writers/EntityClassWriter.cs.meta new file mode 100644 index 0000000..5240c23 --- /dev/null +++ b/Assets/Tremble/IO/FGD/Writers/EntityClassWriter.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ae5ecd0fb11d4baf988975b57deb3f53 +timeCreated: 1712132457 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/Writers/EntityClassWriter.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/FGD/Writers/EntityEnumWriter.cs b/Assets/Tremble/IO/FGD/Writers/EntityEnumWriter.cs new file mode 100644 index 0000000..d9421ac --- /dev/null +++ b/Assets/Tremble/IO/FGD/Writers/EntityEnumWriter.cs @@ -0,0 +1,69 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.IO; + +namespace TinyGoose.Tremble +{ + public static class EntityEnumWriter + { + public static void WriteCSharp(this EnumDefinition enumDefinition, string file, string namespaceOrNull) + { + using FileStream classFile = new(file, FileMode.Create, FileAccess.Write); + using StreamWriter writer = new(classFile); + + writer.WriteLine($"// Enum '{enumDefinition.Name}'"); + writer.WriteLine($"// Generated by Tremble v{TrembleConsts.VERSION_STRING}"); + writer.WriteLine(); + + writer.WriteLine("using UnityEngine;"); + writer.WriteLine("using TinyGoose.Tremble;"); + writer.WriteLine(); + + bool hasNamespace = !namespaceOrNull.IsNullOrEmpty(); + + if (hasNamespace) + { + writer.WriteLine($"namespace {namespaceOrNull}"); + writer.WriteLine("{"); + } + + + if (hasNamespace) + { + writer.Write("\t"); + } + writer.WriteLine($"public enum {enumDefinition.Name}"); + + if (hasNamespace) + { + writer.Write("\t"); + } + writer.WriteLine("{"); + + for (int i = 0; i < enumDefinition.Values.Length; i++) + { + string value = enumDefinition.Values[i]; + + writer.Write("\t"); + if (hasNamespace) + { + writer.Write("\t"); + } + writer.WriteLine($"{value} = {i},"); + } + if (hasNamespace) + { + writer.Write("\t"); + } + writer.WriteLine("}"); + + if (hasNamespace) + { + writer.WriteLine("}"); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/FGD/Writers/EntityEnumWriter.cs.meta b/Assets/Tremble/IO/FGD/Writers/EntityEnumWriter.cs.meta new file mode 100644 index 0000000..40f1a82 --- /dev/null +++ b/Assets/Tremble/IO/FGD/Writers/EntityEnumWriter.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: a0ba86bd49f1a4af5b7b8522b5e470de +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/FGD/Writers/EntityEnumWriter.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/MAP.meta b/Assets/Tremble/IO/MAP.meta new file mode 100644 index 0000000..c5bbd68 --- /dev/null +++ b/Assets/Tremble/IO/MAP.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 17bd3f5d03144731a1a86bfdc8852b41 +timeCreated: 1711272095 \ No newline at end of file diff --git a/Assets/Tremble/IO/MAP/MapParser.cs b/Assets/Tremble/IO/MAP/MapParser.cs new file mode 100644 index 0000000..bf90add --- /dev/null +++ b/Assets/Tremble/IO/MAP/MapParser.cs @@ -0,0 +1,294 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using UnityEngine; + +namespace TinyGoose.Tremble.Editor +{ + public class MapBrushFace + { + // public Vector3 Position { get; init; } + // public Vector3 Normal { get; init; } + public Vector3 P1 { get; set; } + public Vector3 P2 { get; set; } + public Vector3 P3 { get; set; } + public string TextureName { get; set; } + public float[] TexU { get; init; } + public float[] TexV { get; init; } + public float Rotation { get; init; } + public Vector2 Scale { get; init; } + } + + public class MapBrush + { + public List Faces { get; init; } + } + + public class MapEntity + { + public Dictionary Entries { get; init; } + public List Brushes { get; init; } + + public string Classname => Entries.GetValueOrDefault("classname", null); + } + + public class Map + { + public Dictionary Metadata { get; init; } + public List Entities { get; init; } + + public void WriteTo(string path) + { + using FileStream fs = new(path, FileMode.Create, FileAccess.Write); + using StreamWriter sw = new(fs); + + sw.WriteLine($"// Game: {TrembleConsts.GAME_NAME}"); + sw.WriteLine("// Format: Quake3 (Valve)"); + + for (int entityIdx = 0; entityIdx < Entities.Count; entityIdx++) + { + sw.WriteLine($"// entity {entityIdx}"); + sw.WriteLine("{"); + foreach ((string key, string value) in Entities[entityIdx].Entries) + { + sw.WriteLine($"\"{key}\" \"{value}\""); + } + + if (Entities[entityIdx].Brushes != null) + { + for (int brushIdx = 0; brushIdx < Entities[entityIdx].Brushes.Count; brushIdx++) + { + MapBrush brush = Entities[entityIdx].Brushes[brushIdx]; + + sw.WriteLine($"// brush {brushIdx}"); + sw.WriteLine("{"); + foreach (MapBrushFace face in brush.Faces) + { + //Vector3[] points = new Vector3[3]; + + // Vector3 arb = Vector3.Normalize(face.Normal + new Vector3(2f, 3f, 1f)); + // points[0] = face.Position; + // points[1] = face.Position + Vector3.Cross(face.Normal, arb); + // points[2] = face.Position + Vector3.Cross(points[1], face.Normal); + // foreach (Vector3 p in points) + // { + // sw.Write($"( {p.x} {p.y} {p.z} ) "); + // } + + + sw.Write($"( {face.P1.ToStringInvariant()} ) "); + sw.Write($"( {face.P2.ToStringInvariant()} ) "); + sw.Write($"( {face.P3.ToStringInvariant()} ) "); + + sw.Write(face.TextureName); + sw.Write(" [ "); + foreach (float f in face.TexU) + { + sw.Write(f.ToStringInvariant(5)); + sw.Write(" "); + } + + sw.Write("] [ "); + foreach (float f in face.TexV) + { + sw.Write(f.ToStringInvariant(5)); + sw.Write(" "); + } + + sw.WriteLine($"] {face.Rotation.ToStringInvariant()} {face.Scale.ToStringInvariant()}"); + } + + sw.WriteLine("}"); + } + } + + sw.WriteLine("}"); + } + } + } + + public static class MapParser + { + private const string TOKEN_START = "{"; + private const string TOKEN_END = "}"; + + public static Map Parse(string mapPath) + { + List entities = new(512); + Dictionary metadata = new(16); + + // Quicker than using streams (wtf?) + string mapContents = File.ReadAllText(mapPath).Replace("\r", ""); + + // Read metadata + string remaining = mapContents; + while (remaining.StartsWithInvariant("//") && remaining.ContainsInvariant(":")) + { + remaining.Split('\n', out string thisLine, out remaining); + + thisLine.Substring(2).Split(':', out string key, out string value); + if (key == null || value == null) + break; + + metadata[key] = value; + } + + // Parse map + TokenParser parser = new(mapContents); + while (!parser.IsAtEnd) + { + entities.Add(parser.ReadEntity()); + } + + return new() { Metadata = metadata, Entities = entities }; + } + public static Dictionary ParseMetadataOnly(string mapPath) + { + Dictionary metadata = new(16); + + // Quicker than using streams (wtf?) + using FileStream file = new(mapPath, FileMode.Open, FileAccess.Read); + using StreamReader sr = new(file, Encoding.ASCII); + + // Read metadata + while (!sr.EndOfStream) + { + string line = sr.ReadLine(); + if (line == null) + break; + + if (!line.StartsWithInvariant("//") || !line.ContainsInvariant(":")) + break; + + line.Substring(2).Split(':', out string key, out string value); + if (key == null || value == null) + break; + + metadata[key] = value; + } + + return metadata; + } + + private static MapEntity ReadEntity(this TokenParser parser) + { + if (!parser.MatchToken(TOKEN_START)) + return new(); + + Dictionary entries = new(64); + + while (!parser.IsAtEnd) + { + ReadOnlySpan token = parser.PeekToken(); + + if (token.EqualsInvariant(TOKEN_START, caseSensitive: true)) + { + // Found brushes, parse them + List brushes = ParseBrushes(parser); + parser.MatchToken(TOKEN_END); // Consume end brace of entity + + return new() { Brushes = brushes, Entries = entries }; + } + else if (token.EqualsInvariant(TOKEN_END, caseSensitive: true)) + { + // Found end - with no brushes + parser.MatchToken(TOKEN_END); // Consume end brace of entity + return new() { Brushes = new(), Entries = entries }; + } + else + { + // Still parsing entries + string key = parser.ReadToken().ToString(); + string value = parser.ReadToken().ToString(); + entries.Add(key, value); + } + } + + return new(); + } + + private static List ParseBrushes(in TokenParser parser) + { + List brushes = new(64); + + while (true) + { + brushes.Add(parser.ReadBrush()); + + if (parser.PeekToken(TOKEN_END)) + break; + } + + return brushes; + } + + private static MapBrush ReadBrush(this TokenParser parser) + { + parser.MatchToken(TOKEN_START); // Consume open brace + + List faces = new(64); + while (!parser.IsAtEnd) + { + ReadOnlySpan token = parser.PeekToken(); + if (token.EqualsInvariant(TOKEN_END)) + { + // End of brush faces + break; + } + + faces.Add(parser.ReadBrushFace()); + } + + parser.MatchToken(TOKEN_END); // Consume close brace + + return new() { Faces = faces }; + } + private static MapBrushFace ReadBrushFace(this TokenParser parser) + { + Vector3 v0 = parser.ReadVector3(false); + Vector3 v1 = parser.ReadVector3(false); + Vector3 v2 = parser.ReadVector3(false); + + ReadOnlySpan textureName = parser.ReadToken(disableNumLock: true); + float[] texU, texV; + if (parser.PeekToken("[")) + { + // Valve format + texU = parser.ReadMatrix(4); + texV = parser.ReadMatrix(4); + } + else + { + // Standard format + Vector3 u = Vector3.Normalize(v0 - v1); + Vector3 v = Vector3.Normalize(v2 - v1); + texU = new [] { u.x, u.y, u.z, parser.ReadFloat() }; + texV = new [] { v.x, v.y, v.z, parser.ReadFloat() }; + } + //Vector3 planeNormal = Vector3.Normalize(Vector3.Cross(v1 - v0, v2 - v0)); + + float rotation = parser.ReadFloat(); + Vector2 scale = new() { x = parser.ReadFloat(), y = parser.ReadFloat() }; + + return new() + { + // Position = v0, + // Normal = planeNormal, + P1 = v0, + P2 = v1, + P3 = v2, + TextureName = textureName.ToString(), + TexU = texU, + TexV = texV, + Rotation = rotation, + Scale = scale, + }; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/MAP/MapParser.cs.meta b/Assets/Tremble/IO/MAP/MapParser.cs.meta new file mode 100644 index 0000000..dfa58fe --- /dev/null +++ b/Assets/Tremble/IO/MAP/MapParser.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: aecd40d2f27c43f1b907b5479abb07f8 +timeCreated: 1711272189 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/MAP/MapParser.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/StreamIO.cs b/Assets/Tremble/IO/StreamIO.cs new file mode 100644 index 0000000..e7d1bc1 --- /dev/null +++ b/Assets/Tremble/IO/StreamIO.cs @@ -0,0 +1,246 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + // ----------------------------------------------------------------------------------------------------------------------------- + // Writing + // ----------------------------------------------------------------------------------------------------------------------------- + // For writing to the MD3 stream, we bypass BinaryWriter because it's MUCH slower. + // I think it's because the BinaryWriter does Endianness and Encoding related things, which we + // don't need for our limited use-case of ASCII-encoded MD3 models. + public class StreamWriteIO : IDisposable + { + private const int BUFFER_SIZE_KB = 160; // 160kB buffer + + public StreamWriteIO(Stream stream) + { + m_Stream = stream; + } + public void Dispose() + { + Flush(); + } + + private readonly Stream m_Stream; + private readonly byte[] m_Buffer = new byte[BUFFER_SIZE_KB * 1024]; + private int m_BufPtr; + + private readonly float[] m_Floats = new float[1]; + private readonly byte[] m_Bytes = new byte[4]; + + public void WriteInt32(int value) + { + WriteByte((byte)(value & 0xFF)); + WriteByte((byte)((value >> 8) & 0xFF)); + WriteByte((byte)((value >> 16) & 0xFF)); + WriteByte((byte)((value >> 24) & 0xFF)); + } + + public void WriteFloat(float value) + { + // Block copy the float value's bytes into preallocated buffer + m_Floats[0] = value; + Buffer.BlockCopy(m_Floats, 0, m_Bytes, 0, 4); + + // Write out + WriteByte(m_Bytes[0]); + WriteByte(m_Bytes[1]); + WriteByte(m_Bytes[2]); + WriteByte(m_Bytes[3]); + } + + public void WriteInt16(short value) + { + WriteByte((byte)(value & 0xFF)); + WriteByte((byte)((value >> 8) & 0xFF)); + } + + public void WriteNormalAsLatLong(Vector3 normal) + { + const float BYTE_TO_DEG = (255.0f / 360.0f) * Mathf.Rad2Deg; + Vector3 q3Normal = normal.UnityToQ3Vector(scale: 1f); + + if (q3Normal is { x: 0, y: 0 }) + { + WriteByte(q3Normal.z > 0 ? (byte)0x00 : (byte)0x80); // U + WriteByte(0x00); // V + } + else + { + WriteByte((byte)(Mathf.Acos(q3Normal.z) * BYTE_TO_DEG)); // U + WriteByte((byte)(Mathf.Atan2(q3Normal.y, q3Normal.x) * BYTE_TO_DEG)); // V + } + } + + public void WriteBytes(byte[] bytes) + { + foreach (byte b in bytes) + { + WriteByte(b); + } + } + public void WriteBytes(byte[] buffer, int count) + { + for (int b = 0; b < count; b++) + { + WriteByte(buffer[b]); + } + } + + public void WriteString(string value) + { + foreach (char c in value) + { + WriteByte((byte)c); + } + } + + public void WriteString(string value, int length) + { + for (int i = 0; i < length; i++) + { + if (i < value.Length) + { + WriteByte((byte)value[i]); + } + else + { + WriteByte(0x00); + } + } + } + + private void WriteByte(byte b) + { + if (m_BufPtr >= m_Buffer.Length) + { + Flush(); + } + + m_Buffer[m_BufPtr++] = b; + } + + private void Flush() + { + if (m_BufPtr == 0) + return; + + m_Stream.Write(m_Buffer, 0, m_BufPtr); + m_BufPtr = 0; + } + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Reading + // ----------------------------------------------------------------------------------------------------------------------------- + public class StreamReadIO + { + private readonly float[] m_Floats = new float[1]; + private readonly byte[] m_Bytes = new byte[8]; + + private readonly byte[] m_StreamContents; + private int m_Offset; + + public StreamReadIO(string path) + { + m_StreamContents = File.ReadAllBytes(path); + } + + public void Seek(int offset) + { + m_Offset = offset; + } + public int Position => m_Offset; + + public byte ReadByte() + { + return m_StreamContents[m_Offset++]; + } + + public void SkipBytes(int count) + { + m_Offset += count; + } + + public short ReadInt16() + { + m_Bytes[0] = ReadByte(); + m_Bytes[1] = ReadByte(); + + return (short)(m_Bytes[0] | m_Bytes[1] << 8); + } + + public int ReadInt32() + { + m_Bytes[0] = ReadByte(); + m_Bytes[1] = ReadByte(); + m_Bytes[2] = ReadByte(); + m_Bytes[3] = ReadByte(); + + return (int)(m_Bytes[0] | m_Bytes[1] << 8 | m_Bytes[2] << 16 | m_Bytes[3] << 24); + } + + public float ReadSingle() + { + // Block copy the bytes into a float, using a preallocated buffer + m_Bytes[0] = ReadByte(); + m_Bytes[1] = ReadByte(); + m_Bytes[2] = ReadByte(); + m_Bytes[3] = ReadByte(); + Buffer.BlockCopy(m_Bytes, 0, m_Floats, 0, 4); + + // Return + return m_Floats[0]; + } + + public char[] ReadChars(int numChars) + { + char[] result = new char[numChars]; + for (int i = 0; i < numChars; i++) + { + result[i] = (char)ReadByte(); + } + return result; + } + + public byte[] ReadBytes(int numBytes) + { + byte[] result = new byte[numBytes]; + + Buffer.BlockCopy(m_StreamContents, m_Offset, result, 0, numBytes); + m_Offset += numBytes; + + return result; + } + + public string ReadString(int numChars) + { + string result = new(ReadChars(numChars)); + int nulCharacter = result.IndexOf('\0'); + + return nulCharacter > 0 ? result.Substring(0, nulCharacter) : result; + } + + public Vector3 ReadVector3(bool convertToQ3 = false, float scale = 1f) + { + Vector3 result = new(ReadSingle() * scale, ReadSingle() * scale, ReadSingle() * scale); + return convertToQ3 ? result.Q3ToUnityVector() : result; + } + public Vector2 ReadUV() + => new(ReadSingle() + 0.5f, 1f - ReadSingle() + 0.5f); // Flip Y and offset by 0.5, 0.5 + + public Color32 ReadColour() + => new(ReadByte(), ReadByte(), ReadByte(), ReadByte()); + + public Vector3Int ReadVector3Int() => new(ReadInt32(), ReadInt32(), ReadInt32()); + + public Vector2Int ReadVector2Int() => new(ReadInt32(), ReadInt32()); + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/StreamIO.cs.meta b/Assets/Tremble/IO/StreamIO.cs.meta new file mode 100644 index 0000000..fd915d9 --- /dev/null +++ b/Assets/Tremble/IO/StreamIO.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 06ba2a69ad404fb2a03db07dd4ce5ccf +timeCreated: 1710420269 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/StreamIO.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/TokenParser.cs b/Assets/Tremble/IO/TokenParser.cs new file mode 100644 index 0000000..a543b00 --- /dev/null +++ b/Assets/Tremble/IO/TokenParser.cs @@ -0,0 +1,251 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Globalization; +using System.IO; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public class TokenParser + { + private readonly string m_String; + private int m_Index; + + public TokenParser(string inString) + { + m_String = inString.Replace("\r", ""); // Remove Windows newlines + m_Index = 0; + } + + public bool IsAtEnd + { + get + { + // Fast-forward to next non-whitespace character, if we can + int index = m_Index; + while (index < m_String.Length) + { + if (m_String[index] is '\n' or '\t') + { + index++; + continue; + } + + break; + } + + return (index >= m_String.Length); + } + } + +#if UNITY_EDITOR + public string DEBUG_CurrentBuffer + { + get + { + const int WINDOW_SIZE = 20; + string before = m_String.Substring(Math.Max(0, m_Index - WINDOW_SIZE), WINDOW_SIZE); + string after = m_String.Substring(m_Index + 1, Math.Min(m_String.Length - m_Index - 1, WINDOW_SIZE)); + + return $"{before} -->{PeekToken().ToString()}<-- {after}"; + } + } +#endif + + private char Take() => !IsAtEnd ? m_String[m_Index++] : '\n'; + + private char Peek() => !IsAtEnd ? m_String[m_Index] : '\n'; + + private void Skip() => m_Index++; + + private void FastForwardTo(char target) + { + while (!IsAtEnd && m_String[m_Index] != target) + { + Skip(); + } + } + + public ReadOnlySpan ReadToken(bool supportCommentsAndQuotes = true, bool eatAllBracketContent = false, bool disableNumLock = false) + { + if (IsAtEnd) + return "\n"; + + // Skip newlines and leading whitespace + while (Peek() is '\n' or '\t' or ' ') + { + Take(); + } + + bool quoteLock = false; + if (supportCommentsAndQuotes) + { + // Handle comment lines: + // If it's a /, check for // and if found, skip to end of line + while (Peek() == '/') + { + int commentStartIdx = m_Index; + Skip(); + + if (Peek() != '/') + { + // No second /? Weird, roll back and continue as normal + m_Index = commentStartIdx; + break; + } + + // Fast-forwarding to EOL... + FastForwardTo('\n'); + Skip(); + + // Skip newlines if found + while (Peek() == '\n') + { + Take(); + } + } + + // Turn on "quote lock" and skip the quote if the token starts with a quote + quoteLock = Peek() == '"'; + if (quoteLock) + { + Skip(); + } + } + + int startIdx = m_Index; + int numChars = 0; + bool numLock = false; + int inBrackets = 0; // keep track of whether inside brackets + + while (m_Index < m_String.Length) + { + char nextChar = Take(); + numChars++; + + // Turn on numlock when we see a number outside brackets/quotes + if (!disableNumLock && IsCharNumberFast(nextChar) && inBrackets == 0 && !quoteLock) + { + numLock = true; + } + + // In numlock, but that wasn't a number or "number punctuation"! + if (numLock && !IsCharNumberFast(nextChar) && nextChar is not '.' and not ',' and not 'e' and not 'E' and not '-' and not '\'') + { + if (!IsAtEnd) + { + m_Index--; // rewind if not at end! + } + + break; + } + + // End of line - that's it! + if (inBrackets == 0 && nextChar == '\n') + break; + + if (eatAllBracketContent && nextChar == '(') { inBrackets++; } + if (eatAllBracketContent && nextChar == ')') { inBrackets--; } + + // Not in quote-lock - found space + if (inBrackets == 0 && !quoteLock && nextChar == ' ') + break; + + // We're in quote-lock and we hit the end-quote + if (nextChar == '"' && quoteLock) + break; + } + + // Return string slice + return (numChars == 0) ? "" : m_String.AsSpan(startIdx, numChars - 1); + } + + private bool IsCharNumberFast(char c) => c is >= '0' and <= '9'; + + public ReadOnlySpan PeekToken(bool supportCommentsAndQuotes = true, bool eatAllBracketContent = false, bool disableNumLock = false) + { + int index = m_Index; + + try + { + return ReadToken(supportCommentsAndQuotes, eatAllBracketContent, disableNumLock); + } + finally + { + m_Index = index; + } + } + + public bool PeekToken(string expected, bool supportCommentsAndQuotes = true, bool eatAllBracketContent = false, bool disableNumLock = false) + { + return PeekToken(supportCommentsAndQuotes, eatAllBracketContent, disableNumLock).Equals(expected.AsSpan(), StringComparison.InvariantCultureIgnoreCase); + } + + public bool MatchToken(string expected, bool supportCommentsAndQuotes = true, bool eatAllBracketContent = false, bool disableNumLock = false) + { + ReadOnlySpan token = ReadToken(supportCommentsAndQuotes, eatAllBracketContent, disableNumLock); + + bool tokenMatches; + if (expected.Length == 1) + { + tokenMatches = (token[0] == expected[0]); + } + else + { + tokenMatches = token.Equals(expected.AsSpan(), StringComparison.InvariantCulture); + } + + if (tokenMatches) + return true; + + throw new InvalidDataException($"Expected a '{expected}', got a '{token.ToString()}'"); + } + + public Vector3 ReadVector3(bool convertToUnity = true) + { + MatchToken("("); + Vector3 vec = new() + { + x = ReadFloat(), + y = ReadFloat(), + z = ReadFloat() + }; + MatchToken(")"); + + float scale = TrembleSyncSettings.Get().ImportScale; + return convertToUnity ? vec.Q3ToUnityVector(scale) : vec; + } + + public float ReadFloat() + { + ReadOnlySpan floatValue = ReadToken(supportCommentsAndQuotes: false); + if (!floatValue.TryParseFloat(out float val)) + { + Debug.Log($"Not a float '{floatValue.ToString()}'!"); + } + + return val; + } + + public ulong ReadUlong() => ulong.Parse(ReadToken(supportCommentsAndQuotes: false), NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat); + + + public float[] ReadMatrix(int length) + { + float[] matrix = new float[length]; + + MatchToken("["); + for (int tok = 0; tok < length; tok++) + { + matrix[tok] = ReadFloat(); + } + MatchToken("]"); + + return matrix; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/TokenParser.cs.meta b/Assets/Tremble/IO/TokenParser.cs.meta new file mode 100644 index 0000000..76979b4 --- /dev/null +++ b/Assets/Tremble/IO/TokenParser.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 58dbe14b462d43a8a9f6ccb02d2ebf86 +timeCreated: 1702378526 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/TokenParser.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/WAD.meta b/Assets/Tremble/IO/WAD.meta new file mode 100644 index 0000000..ac16217 --- /dev/null +++ b/Assets/Tremble/IO/WAD.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d3a206c04d254db180f8492831596dad +timeCreated: 1722843889 \ No newline at end of file diff --git a/Assets/Tremble/IO/WAD/WadFile.cs b/Assets/Tremble/IO/WAD/WadFile.cs new file mode 100644 index 0000000..242064c --- /dev/null +++ b/Assets/Tremble/IO/WAD/WadFile.cs @@ -0,0 +1,304 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Collections.Generic; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public class WadPalette + { + private Color32[] m_Colours; + public ref Color32 Get(int pos) => ref m_Colours[pos]; + + private static WadPalette s_QuakePalette; + public static WadPalette QuakePalette + { + get + { + if (s_QuakePalette == null) + { + s_QuakePalette = new() + { + m_Colours = new Color32[] + { + new(0x00, 0x00, 0x00, 0xFF), + new(0x0F, 0x0F, 0x0F, 0xFF), + new(0x1F, 0x1F, 0x1F, 0xFF), + new(0x2F, 0x2F, 0x2F, 0xFF), + new(0x3F, 0x3F, 0x3F, 0xFF), + new(0x4B, 0x4B, 0x4B, 0xFF), + new(0x5B, 0x5B, 0x5B, 0xFF), + new(0x6B, 0x6B, 0x6B, 0xFF), + new(0x7B, 0x7B, 0x7B, 0xFF), + new(0x8B, 0x8B, 0x8B, 0xFF), + new(0x9B, 0x9B, 0x9B, 0xFF), + new(0xAB, 0xAB, 0xAB, 0xFF), + new(0xBB, 0xBB, 0xBB, 0xFF), + new(0xCB, 0xCB, 0xCB, 0xFF), + new(0xDB, 0xDB, 0xDB, 0xFF), + new(0xEB, 0xEB, 0xEB, 0xFF), + new(0x0F, 0x0B, 0x07, 0xFF), + new(0x17, 0x0F, 0x0B, 0xFF), + new(0x1F, 0x17, 0x0B, 0xFF), + new(0x27, 0x1B, 0x0F, 0xFF), + new(0x2F, 0x23, 0x13, 0xFF), + new(0x37, 0x2B, 0x17, 0xFF), + new(0x3F, 0x2F, 0x17, 0xFF), + new(0x4B, 0x37, 0x1B, 0xFF), + new(0x53, 0x3B, 0x1B, 0xFF), + new(0x5B, 0x43, 0x1F, 0xFF), + new(0x63, 0x4B, 0x1F, 0xFF), + new(0x6B, 0x53, 0x1F, 0xFF), + new(0x73, 0x57, 0x1F, 0xFF), + new(0x7B, 0x5F, 0x23, 0xFF), + new(0x83, 0x67, 0x23, 0xFF), + new(0x8F, 0x6F, 0x23, 0xFF), + new(0x0B, 0x0B, 0x0F, 0xFF), + new(0x13, 0x13, 0x1B, 0xFF), + new(0x1B, 0x1B, 0x27, 0xFF), + new(0x27, 0x27, 0x33, 0xFF), + new(0x2F, 0x2F, 0x3F, 0xFF), + new(0x37, 0x37, 0x4B, 0xFF), + new(0x3F, 0x3F, 0x57, 0xFF), + new(0x47, 0x47, 0x67, 0xFF), + new(0x4F, 0x4F, 0x73, 0xFF), + new(0x5B, 0x5B, 0x7F, 0xFF), + new(0x63, 0x63, 0x8B, 0xFF), + new(0x6B, 0x6B, 0x97, 0xFF), + new(0x73, 0x73, 0xA3, 0xFF), + new(0x7B, 0x7B, 0xAF, 0xFF), + new(0x83, 0x83, 0xBB, 0xFF), + new(0x8B, 0x8B, 0xCB, 0xFF), + new(0x00, 0x00, 0x00, 0xFF), + new(0x07, 0x07, 0x00, 0xFF), + new(0x0B, 0x0B, 0x00, 0xFF), + new(0x13, 0x13, 0x00, 0xFF), + new(0x1B, 0x1B, 0x00, 0xFF), + new(0x23, 0x23, 0x00, 0xFF), + new(0x2B, 0x2B, 0x07, 0xFF), + new(0x2F, 0x2F, 0x07, 0xFF), + new(0x37, 0x37, 0x07, 0xFF), + new(0x3F, 0x3F, 0x07, 0xFF), + new(0x47, 0x47, 0x07, 0xFF), + new(0x4B, 0x4B, 0x0B, 0xFF), + new(0x53, 0x53, 0x0B, 0xFF), + new(0x5B, 0x5B, 0x0B, 0xFF), + new(0x63, 0x63, 0x0B, 0xFF), + new(0x6B, 0x6B, 0x0F, 0xFF), + new(0x07, 0x00, 0x00, 0xFF), + new(0x0F, 0x00, 0x00, 0xFF), + new(0x17, 0x00, 0x00, 0xFF), + new(0x1F, 0x00, 0x00, 0xFF), + new(0x27, 0x00, 0x00, 0xFF), + new(0x2F, 0x00, 0x00, 0xFF), + new(0x37, 0x00, 0x00, 0xFF), + new(0x3F, 0x00, 0x00, 0xFF), + new(0x47, 0x00, 0x00, 0xFF), + new(0x4F, 0x00, 0x00, 0xFF), + new(0x57, 0x00, 0x00, 0xFF), + new(0x5F, 0x00, 0x00, 0xFF), + new(0x67, 0x00, 0x00, 0xFF), + new(0x6F, 0x00, 0x00, 0xFF), + new(0x77, 0x00, 0x00, 0xFF), + new(0x7F, 0x00, 0x00, 0xFF), + new(0x13, 0x13, 0x00, 0xFF), + new(0x1B, 0x1B, 0x00, 0xFF), + new(0x23, 0x23, 0x00, 0xFF), + new(0x2F, 0x2B, 0x00, 0xFF), + new(0x37, 0x2F, 0x00, 0xFF), + new(0x43, 0x37, 0x00, 0xFF), + new(0x4B, 0x3B, 0x07, 0xFF), + new(0x57, 0x43, 0x07, 0xFF), + new(0x5F, 0x47, 0x07, 0xFF), + new(0x6B, 0x4B, 0x0B, 0xFF), + new(0x77, 0x53, 0x0F, 0xFF), + new(0x83, 0x57, 0x13, 0xFF), + new(0x8B, 0x5B, 0x13, 0xFF), + new(0x97, 0x5F, 0x1B, 0xFF), + new(0xA3, 0x63, 0x1F, 0xFF), + new(0xAF, 0x67, 0x23, 0xFF), + new(0x23, 0x13, 0x07, 0xFF), + new(0x2F, 0x17, 0x0B, 0xFF), + new(0x3B, 0x1F, 0x0F, 0xFF), + new(0x4B, 0x23, 0x13, 0xFF), + new(0x57, 0x2B, 0x17, 0xFF), + new(0x63, 0x2F, 0x1F, 0xFF), + new(0x73, 0x37, 0x23, 0xFF), + new(0x7F, 0x3B, 0x2B, 0xFF), + new(0x8F, 0x43, 0x33, 0xFF), + new(0x9F, 0x4F, 0x33, 0xFF), + new(0xAF, 0x63, 0x2F, 0xFF), + new(0xBF, 0x77, 0x2F, 0xFF), + new(0xCF, 0x8F, 0x2B, 0xFF), + new(0xDF, 0xAB, 0x27, 0xFF), + new(0xEF, 0xCB, 0x1F, 0xFF), + new(0xFF, 0xF3, 0x1B, 0xFF), + new(0x0B, 0x07, 0x00, 0xFF), + new(0x1B, 0x13, 0x00, 0xFF), + new(0x2B, 0x23, 0x0F, 0xFF), + new(0x37, 0x2B, 0x13, 0xFF), + new(0x47, 0x33, 0x1B, 0xFF), + new(0x53, 0x37, 0x23, 0xFF), + new(0x63, 0x3F, 0x2B, 0xFF), + new(0x6F, 0x47, 0x33, 0xFF), + new(0x7F, 0x53, 0x3F, 0xFF), + new(0x8B, 0x5F, 0x47, 0xFF), + new(0x9B, 0x6B, 0x53, 0xFF), + new(0xA7, 0x7B, 0x5F, 0xFF), + new(0xB7, 0x87, 0x6B, 0xFF), + new(0xC3, 0x93, 0x7B, 0xFF), + new(0xD3, 0xA3, 0x8B, 0xFF), + new(0xE3, 0xB3, 0x97, 0xFF), + new(0xAB, 0x8B, 0xA3, 0xFF), + new(0x9F, 0x7F, 0x97, 0xFF), + new(0x93, 0x73, 0x87, 0xFF), + new(0x8B, 0x67, 0x7B, 0xFF), + new(0x7F, 0x5B, 0x6F, 0xFF), + new(0x77, 0x53, 0x63, 0xFF), + new(0x6B, 0x4B, 0x57, 0xFF), + new(0x5F, 0x3F, 0x4B, 0xFF), + new(0x57, 0x37, 0x43, 0xFF), + new(0x4B, 0x2F, 0x37, 0xFF), + new(0x43, 0x27, 0x2F, 0xFF), + new(0x37, 0x1F, 0x23, 0xFF), + new(0x2B, 0x17, 0x1B, 0xFF), + new(0x23, 0x13, 0x13, 0xFF), + new(0x17, 0x0B, 0x0B, 0xFF), + new(0x0F, 0x07, 0x07, 0xFF), + new(0xBB, 0x73, 0x9F, 0xFF), + new(0xAF, 0x6B, 0x8F, 0xFF), + new(0xA3, 0x5F, 0x83, 0xFF), + new(0x97, 0x57, 0x77, 0xFF), + new(0x8B, 0x4F, 0x6B, 0xFF), + new(0x7F, 0x4B, 0x5F, 0xFF), + new(0x73, 0x43, 0x53, 0xFF), + new(0x6B, 0x3B, 0x4B, 0xFF), + new(0x5F, 0x33, 0x3F, 0xFF), + new(0x53, 0x2B, 0x37, 0xFF), + new(0x47, 0x23, 0x2B, 0xFF), + new(0x3B, 0x1F, 0x23, 0xFF), + new(0x2F, 0x17, 0x1B, 0xFF), + new(0x23, 0x13, 0x13, 0xFF), + new(0x17, 0x0B, 0x0B, 0xFF), + new(0x0F, 0x07, 0x07, 0xFF), + new(0xDB, 0xC3, 0xBB, 0xFF), + new(0xCB, 0xB3, 0xA7, 0xFF), + new(0xBF, 0xA3, 0x9B, 0xFF), + new(0xAF, 0x97, 0x8B, 0xFF), + new(0xA3, 0x87, 0x7B, 0xFF), + new(0x97, 0x7B, 0x6F, 0xFF), + new(0x87, 0x6F, 0x5F, 0xFF), + new(0x7B, 0x63, 0x53, 0xFF), + new(0x6B, 0x57, 0x47, 0xFF), + new(0x5F, 0x4B, 0x3B, 0xFF), + new(0x53, 0x3F, 0x33, 0xFF), + new(0x43, 0x33, 0x27, 0xFF), + new(0x37, 0x2B, 0x1F, 0xFF), + new(0x27, 0x1F, 0x17, 0xFF), + new(0x1B, 0x13, 0x0F, 0xFF), + new(0x0F, 0x0B, 0x07, 0xFF), + new(0x6F, 0x83, 0x7B, 0xFF), + new(0x67, 0x7B, 0x6F, 0xFF), + new(0x5F, 0x73, 0x67, 0xFF), + new(0x57, 0x6B, 0x5F, 0xFF), + new(0x4F, 0x63, 0x57, 0xFF), + new(0x47, 0x5B, 0x4F, 0xFF), + new(0x3F, 0x53, 0x47, 0xFF), + new(0x37, 0x4B, 0x3F, 0xFF), + new(0x2F, 0x43, 0x37, 0xFF), + new(0x2B, 0x3B, 0x2F, 0xFF), + new(0x23, 0x33, 0x27, 0xFF), + new(0x1F, 0x2B, 0x1F, 0xFF), + new(0x17, 0x23, 0x17, 0xFF), + new(0x0F, 0x1B, 0x13, 0xFF), + new(0x0B, 0x13, 0x0B, 0xFF), + new(0x07, 0x0B, 0x07, 0xFF), + new(0xFF, 0xF3, 0x1B, 0xFF), + new(0xEF, 0xDF, 0x17, 0xFF), + new(0xDB, 0xCB, 0x13, 0xFF), + new(0xCB, 0xB7, 0x0F, 0xFF), + new(0xBB, 0xA7, 0x0F, 0xFF), + new(0xAB, 0x97, 0x0B, 0xFF), + new(0x9B, 0x83, 0x07, 0xFF), + new(0x8B, 0x73, 0x07, 0xFF), + new(0x7B, 0x63, 0x07, 0xFF), + new(0x6B, 0x53, 0x00, 0xFF), + new(0x5B, 0x47, 0x00, 0xFF), + new(0x4B, 0x37, 0x00, 0xFF), + new(0x3B, 0x2B, 0x00, 0xFF), + new(0x2B, 0x1F, 0x00, 0xFF), + new(0x1B, 0x0F, 0x00, 0xFF), + new(0x0B, 0x07, 0x00, 0xFF), + new(0x00, 0x00, 0xFF, 0xFF), + new(0x0B, 0x0B, 0xEF, 0xFF), + new(0x13, 0x13, 0xDF, 0xFF), + new(0x1B, 0x1B, 0xCF, 0xFF), + new(0x23, 0x23, 0xBF, 0xFF), + new(0x2B, 0x2B, 0xAF, 0xFF), + new(0x2F, 0x2F, 0x9F, 0xFF), + new(0x2F, 0x2F, 0x8F, 0xFF), + new(0x2F, 0x2F, 0x7F, 0xFF), + new(0x2F, 0x2F, 0x6F, 0xFF), + new(0x2F, 0x2F, 0x5F, 0xFF), + new(0x2B, 0x2B, 0x4F, 0xFF), + new(0x23, 0x23, 0x3F, 0xFF), + new(0x1B, 0x1B, 0x2F, 0xFF), + new(0x13, 0x13, 0x1F, 0xFF), + new(0x0B, 0x0B, 0x0F, 0xFF), + new(0x2B, 0x00, 0x00, 0xFF), + new(0x3B, 0x00, 0x00, 0xFF), + new(0x4B, 0x07, 0x00, 0xFF), + new(0x5F, 0x07, 0x00, 0xFF), + new(0x6F, 0x0F, 0x00, 0xFF), + new(0x7F, 0x17, 0x07, 0xFF), + new(0x93, 0x1F, 0x07, 0xFF), + new(0xA3, 0x27, 0x0B, 0xFF), + new(0xB7, 0x33, 0x0F, 0xFF), + new(0xC3, 0x4B, 0x1B, 0xFF), + new(0xCF, 0x63, 0x2B, 0xFF), + new(0xDB, 0x7F, 0x3B, 0xFF), + new(0xE3, 0x97, 0x4F, 0xFF), + new(0xE7, 0xAB, 0x5F, 0xFF), + new(0xEF, 0xBF, 0x77, 0xFF), + new(0xF7, 0xD3, 0x8B, 0xFF), + new(0xA7, 0x7B, 0x3B, 0xFF), + new(0xB7, 0x9B, 0x37, 0xFF), + new(0xC7, 0xC3, 0x37, 0xFF), + new(0xE7, 0xE3, 0x57, 0xFF), + new(0x7F, 0xBF, 0xFF, 0xFF), + new(0xAB, 0xE7, 0xFF, 0xFF), + new(0xD7, 0xFF, 0xFF, 0xFF), + new(0x67, 0x00, 0x00, 0xFF), + new(0x8B, 0x00, 0x00, 0xFF), + new(0xB3, 0x00, 0x00, 0xFF), + new(0xD7, 0x00, 0x00, 0xFF), + new(0xFF, 0x00, 0x00, 0xFF), + new(0xFF, 0xF3, 0x93, 0xFF), + new(0xFF, 0xF7, 0xC7, 0xFF), + new(0xFF, 0xFF, 0xFF, 0xFF), + new(0x9F, 0x5B, 0x53, 0xFF) + } + }; + } + + return s_QuakePalette; + } + } + } + + public readonly struct WadEntry + { + public int Address { get; init; } + public int Size { get; init; } + public char Type { get; init; } + public string Name { get; init; } + } + + public record WadFile + { + public List Entries { get; init; } + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/WAD/WadFile.cs.meta b/Assets/Tremble/IO/WAD/WadFile.cs.meta new file mode 100644 index 0000000..b2041a5 --- /dev/null +++ b/Assets/Tremble/IO/WAD/WadFile.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 81577f4367354726bf894c329ef36a6c +timeCreated: 1722844184 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/WAD/WadFile.cs + uploadId: 939664 diff --git a/Assets/Tremble/IO/WAD/WadParser.cs b/Assets/Tremble/IO/WAD/WadParser.cs new file mode 100644 index 0000000..be2c7a2 --- /dev/null +++ b/Assets/Tremble/IO/WAD/WadParser.cs @@ -0,0 +1,102 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using UnityEngine.Experimental.Rendering; + +namespace TinyGoose.Tremble +{ + public class WadParser + { + private readonly StreamReadIO m_Stream; + + public WadParser(string filename) + { + m_Stream = new(filename); + } + + public void WriteTextureToFile(in WadEntry entry, string outFile) + { + m_Stream.Seek(entry.Address); + + string name = m_Stream.ReadString(16); + int width = m_Stream.ReadInt32(); + int height = m_Stream.ReadInt32(); + m_Stream.SkipBytes(16); + + byte[] palettedTextureData = m_Stream.ReadBytes(width * height); + byte[] rgbTextureData = new byte[palettedTextureData.Length * 3]; + + // Copy paletted to RGB, flipping as we go + for (int x = 0; x < width; x++) + { + for (int y = 0; y < height; y++) + { + int readOffset = y * width + x; + + int invY = height - y - 1; + int writeOffset = (invY * width + x) * 3; + + ref Color32 colour = ref WadPalette.QuakePalette.Get(palettedTextureData[readOffset]); + + rgbTextureData[writeOffset + 0] = colour.r; + rgbTextureData[writeOffset + 1] = colour.g; + rgbTextureData[writeOffset + 2] = colour.b; + } + } + + byte[] pngBytes = ImageConversion.EncodeArrayToPNG(rgbTextureData, GraphicsFormat.R8G8B8_UNorm, (uint)width, (uint)height); + File.WriteAllBytes(outFile, pngBytes); + } + + public WadFile Parse() + { + m_Stream.Seek(0); + + string magic = new(m_Stream.ReadChars(4)); + if (!magic.EqualsInvariant("wad2")) + { + Debug.LogError($"File was not a WAD2 :("); + return default; + } + + int numEntries = m_Stream.ReadInt32(); + int dirOffset = m_Stream.ReadInt32(); + + m_Stream.Seek(dirOffset); + + List entries = new(numEntries); + for (int entryIdx = 0; entryIdx < numEntries; entryIdx++) + { + int entryAddress = m_Stream.ReadInt32(); + int entrySize = m_Stream.ReadInt32(); + m_Stream.SkipBytes(4); + char type = (char)m_Stream.ReadByte(); + m_Stream.SkipBytes(3); + string name = new(m_Stream.ReadString(16)); + + // Skip anything that's not a texture + if (type != 'D') + continue; + + entries.Add(new() + { + Address = entryAddress, + Size = entrySize, + Type = type, + Name = name.Replace('*', '_') // * is not a valid name for an asset! + }); + } + + return new() + { + Entries = entries + }; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/IO/WAD/WadParser.cs.meta b/Assets/Tremble/IO/WAD/WadParser.cs.meta new file mode 100644 index 0000000..af914b8 --- /dev/null +++ b/Assets/Tremble/IO/WAD/WadParser.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: f8ecbbe775a9445a9f8f2148c4a06be2 +timeCreated: 1722843896 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/IO/WAD/WadParser.cs + uploadId: 939664 diff --git a/Assets/Tremble/Import.meta b/Assets/Tremble/Import.meta new file mode 100644 index 0000000..10aed26 --- /dev/null +++ b/Assets/Tremble/Import.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 01055f4101704d119202151097873557 +timeCreated: 1715673698 \ No newline at end of file diff --git a/Assets/Tremble/Import/MapCompiler.cs b/Assets/Tremble/Import/MapCompiler.cs new file mode 100644 index 0000000..596564d --- /dev/null +++ b/Assets/Tremble/Import/MapCompiler.cs @@ -0,0 +1,232 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.IO; +using System.Text; +using UnityEngine; + +#if UNITY_EDITOR +using UnityEditor; +#endif + + +namespace TinyGoose.Tremble +{ + public static class MapCompiler + { + public static MapBsp BuildBsp(TrembleSyncSettings syncSettings, string mapPath, string extraCommandLineArgs, out Q3Map2Result result, + Action onOutputMessage = null) + { + string mapName = Path.GetFileNameWithoutExtension(mapPath); + string stagingFolder = Path.Combine(Application.temporaryCachePath, $"Build_{mapName}"); + + try + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Copy to staging folder + // ----------------------------------------------------------------------------------------------------------------------------- + DirectoryUtil.EmptyAndCreateDirectory(stagingFolder); + + string stageMapPath = Path.Combine(stagingFolder, Path.GetFileName(mapPath)); + CopyMapToStagingFolder(mapPath, stageMapPath, out MapGroupData[] foundGroups); + + + // ----------------------------------------------------------------------------------------------------------------------------- + // Run Q3Map2 + // ----------------------------------------------------------------------------------------------------------------------------- + Q3Map2Result? overrideResult; + + using (TrembleTimerScope __ = new(TrembleTimer.Context.RunQ3Map2)) + { + // Combine all args + string[] extraArgs = extraCommandLineArgs.Split(" ", StringSplitOptions.RemoveEmptyEntries); + + // Get output filename + MapCompilerOutputHandler.Init(onOutputMessage); + { + int returnCode = Q3Map2Dll.ConvertMap(stageMapPath, MapCompilerOutputHandler.HandleOutput, extraArgs); + result = returnCode == 0 ? Q3Map2Result.Succeeded : Q3Map2Result.Failed; + } + overrideResult = MapCompilerOutputHandler.DeInit(); + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Parse BSP + // ----------------------------------------------------------------------------------------------------------------------------- + string bspPath = Path.ChangeExtension(stageMapPath, "bsp"); + if (!File.Exists(bspPath)) + { + result = Q3Map2Result.Failed; + return null; + } + + result = overrideResult ?? result; + + using TrembleTimerScope _ = new(TrembleTimer.Context.ParseBsp); + return BspParser.Parse(bspPath, syncSettings.ImportScale, foundGroups: foundGroups); + } + catch (DllNotFoundException dll) + { +#if UNITY_EDITOR + Debug.LogException(dll); + EditorUtility.DisplayDialog("DLL Not Found", "Tremble's DLL was not found or couldn't be loaded. You should try to reinstall it from the Asset Store, or visit our Discord if this keeps happening!", "Okay"); +#else + Debug.LogException(dll); + Debug.LogError($"Missing q3map2 DLL file for platform: {Application.platform}"); +#endif + + result = Q3Map2Result.Failed; + return null; + } + finally + { + if (Directory.Exists(stagingFolder)) + { + Directory.Delete(stagingFolder, true); + } + } + } + + private static void CopyMapToStagingFolder(string inputMap, string buildMap, out MapGroupData[] groups) + { + using TrembleTimerScope _ = new(TrembleTimer.Context.ExportMapToStaging); + + // Open map + using FileStream file = new(inputMap, FileMode.Open, FileAccess.Read); + using StreamReader sr = new(file, Encoding.ASCII); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Pass 1 - Gather groups + // ----------------------------------------------------------------------------------------------------------------------------- + groups = new MapGroupData[32]; // Start with 32 groups, but can grow + groups[0] = new() { Name = "Default", IsNoExport = false }; + + while (!sr.EndOfStream) + { + string line = sr.ReadLine(); + + if (line == null || !line.ContainsInvariant(FgdConsts.PROPERTY_CLASSNAME, caseSensitive: true) || !line.ContainsInvariant("func_group", caseSensitive: true)) + continue; + + int groupIdx = 0; + string groupName = "Default"; + bool isNoExport = false; + bool isLayer = false; + + while (!sr.EndOfStream && line != null && !line.Trim().EqualsInvariant("}", caseSensitive: true) && !line.StartsWithInvariant("//", caseSensitive: true)) + { + TokenParser tokenParser = new(line); + ReadOnlySpan key = tokenParser.ReadToken(); + ReadOnlySpan value = tokenParser.ReadToken(); + + if (key.EqualsInvariant(TBConsts.ID, caseSensitive: true)) + { + groupIdx = int.Parse(value); + } + else if (key.EqualsInvariant(TBConsts.NAME, caseSensitive: true)) + { + groupName = value.ToString(); + } + else if (key.EqualsInvariant(TBConsts.TYPE, caseSensitive: true)) + { + isLayer = value.EqualsInvariant(TBConsts.LAYER, caseSensitive: true); + } + else if (key.EqualsInvariant(TBConsts.OMIT_FROM_EXPORT, caseSensitive: true) && int.TryParse(value, out int noExportInt)) + { + isNoExport = noExportInt == 1; + } + + line = sr.ReadLine(); + } + + // Resize groups array if needed + if (groupIdx >= groups.Length) + { + Array.Resize(ref groups, groupIdx + 1); + } + + groups[groupIdx] = new() { Name = groupName, IsNoExport = isNoExport, IsLayer = isLayer }; + } + + int numGroups = groups.Length - 1; + while (groups[numGroups].Name == null) + { + numGroups--; + } + + Array.Resize(ref groups, numGroups + 1); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Pass 2 - Copy map into staging folder without "omit from export" layers + // ----------------------------------------------------------------------------------------------------------------------------- + using FileStream outputStream = new(buildMap, FileMode.Create, FileAccess.Write); + using StreamWriter writer = new(outputStream, Encoding.ASCII); + + // Copy each line from reader -> writer, ignoring no export layers + StringBuilder entity = new(); + bool wroteKeepLights = false; + int depth = 0; + int thisLayerOrGroupIdx = 0; + + sr.BaseStream.Seek(0, SeekOrigin.Begin); + + while (!sr.EndOfStream) + { + string line = sr.ReadLine(); + if (line == null) + break; + + if (line.IsNullOrEmpty()) + continue; + + entity.AppendLine(line); + + if (line[0] == '{') depth++; + else if (line[0] == '}') depth--; + + // Ensure "_keepLights" is 1 + if (depth == 1 && !wroteKeepLights) + { + entity.AppendLine("\"_keepLights\" \"1\""); + wroteKeepLights = true; + } + + if (line.ContainsInvariant(TBConsts.ID, caseSensitive: true)) + { + TokenParser tokenParser = new(line); + tokenParser.ReadToken(); // skip id + ReadOnlySpan value = tokenParser.ReadToken(); + + if (int.TryParse(value, out int layerOrGroupIdx)) + { + thisLayerOrGroupIdx = layerOrGroupIdx; + } + } + + if (depth == 0) + { + if (thisLayerOrGroupIdx >= groups.Length || !groups[thisLayerOrGroupIdx].IsNoExport) + { + writer.WriteLine(entity); + } + + entity.Clear(); + } + } + + // This is lame. We add a fake entity called ent_mapfix which the importer + // is set to ignore. Without this, sometimes map builds fail on Mac! + if (!TrembleSyncSettings.Get().UseClassicQuakeCulling) + { + writer.WriteLine("// fix for q3map2"); + writer.WriteLine("{"); + writer.WriteLine($"\"classname\" \"{TrembleConsts.MAPFIX_ENTITY_NAME}\""); + writer.WriteLine("\"origin\" \"32000 32000 32000\""); + writer.WriteLine("}"); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Import/MapCompiler.cs.meta b/Assets/Tremble/Import/MapCompiler.cs.meta new file mode 100644 index 0000000..20aafcb --- /dev/null +++ b/Assets/Tremble/Import/MapCompiler.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: bce55202224c4dc69f433ae5c1a51aa5 +timeCreated: 1713266083 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Import/MapCompiler.cs + uploadId: 939664 diff --git a/Assets/Tremble/Import/MapCompilerOutputHandler.cs b/Assets/Tremble/Import/MapCompilerOutputHandler.cs new file mode 100644 index 0000000..6fee204 --- /dev/null +++ b/Assets/Tremble/Import/MapCompilerOutputHandler.cs @@ -0,0 +1,59 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using AOT; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + // This class encapsulates the logic of parsing messages from Q3Map2, passing them on and + // retaining any overrides to the end result. + // + // It used to be a nice lambda in MapCompiler.cs, but IL2CPP does not support instance method callbacks + // from native code :( + public static class MapCompilerOutputHandler + { + private static Action s_OnOutputMessage; + private static Q3Map2Result? s_OverrideResult; + + public static void Init(Action onOutputMessage) + { + s_OnOutputMessage = onOutputMessage; + s_OverrideResult = null; + } + + public static Q3Map2Result? DeInit() + { + s_OnOutputMessage = null; + return s_OverrideResult; + } + + [MonoPInvokeCallback(typeof(Action))] + public static void HandleOutput(string message) + { + if (message.ContainsInvariant("Couldn't find image")) + { + if (!message.ContainsInvariant("__TB") && + !message.ContainsInvariant("special/") && + !message.ContainsInvariant(TBConsts.CLIP_TEXTURE) && + !message.ContainsInvariant(TBConsts.SKIP_TEXTURE) && + !message.ContainsInvariant(TBConsts.TRIGGER_TEXTURE)) + { + s_OverrideResult = Q3Map2Result.FailedWithMissingTextures; + } + } + else if (message.StartsWithInvariant("WARNING:") && + !message.ContainsInvariant("Unknown option") && + !message.ContainsInvariant("90 percent structural map")) + { + Debug.LogWarning($"Q3Map2: {message}"); + s_OverrideResult = Q3Map2Result.SucceededWithWarnings; + } + + s_OnOutputMessage?.Invoke(message); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Import/MapCompilerOutputHandler.cs.meta b/Assets/Tremble/Import/MapCompilerOutputHandler.cs.meta new file mode 100644 index 0000000..7d44082 --- /dev/null +++ b/Assets/Tremble/Import/MapCompilerOutputHandler.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 96f77a2ed09c4489b7ddc58dddd66940 +timeCreated: 1720944183 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Import/MapCompilerOutputHandler.cs + uploadId: 939664 diff --git a/Assets/Tremble/Import/MapProcessorBase.cs b/Assets/Tremble/Import/MapProcessorBase.cs new file mode 100644 index 0000000..bb187b2 --- /dev/null +++ b/Assets/Tremble/Import/MapProcessorBase.cs @@ -0,0 +1,38 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; +using UnityEngine.Scripting; + +namespace TinyGoose.Tremble +{ + public abstract class MapProcessorBase + { + [Preserve] + public static string Description => null; + + private Transform m_RootTransform; + public Transform RootTransform + { + get => m_RootTransform; + set => m_RootTransform = value; + } + + public virtual void ProcessWorldSpawnProperties(MapBsp mapBsp, BspEntity entity, GameObject rootGameObject) { } + public virtual void ProcessPrefabEntity(MapBsp mapBsp, BspEntity entity, GameObject prefab) { } + public virtual void ProcessBrushEntity(MapBsp mapBsp, BspEntity entity, GameObject brush) { } + public virtual void ProcessPointEntity(MapBsp mapBsp, BspEntity entity, GameObject point) { } + + public virtual void OnProcessingStarted(GameObject root, MapBsp mapBsp) { } + public virtual void OnProcessingCompleted(GameObject root, MapBsp mapBsp) { } + + + public TWorldspawn GetWorldspawn() where TWorldspawn : Worldspawn + => m_RootTransform.GetComponentInChildren(); + + public GameObject InstantiatePrefab(GameObject prefab, Transform parent = null) + => PrefabUtil.InstantiatePrefab(prefab, parent ?? m_RootTransform); + } +} \ No newline at end of file diff --git a/Assets/Tremble/Import/MapProcessorBase.cs.meta b/Assets/Tremble/Import/MapProcessorBase.cs.meta new file mode 100644 index 0000000..7ff6c23 --- /dev/null +++ b/Assets/Tremble/Import/MapProcessorBase.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 1780f2d2510242499740fb1f7fbf0205 +timeCreated: 1699005929 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Import/MapProcessorBase.cs + uploadId: 939664 diff --git a/Assets/Tremble/Import/Q3Map2Dll.cs b/Assets/Tremble/Import/Q3Map2Dll.cs new file mode 100644 index 0000000..ca62e62 --- /dev/null +++ b/Assets/Tremble/Import/Q3Map2Dll.cs @@ -0,0 +1,196 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +using UnityEngine; + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace TinyGoose.Tremble +{ + // ----------------------------------------------------------------------------------------------------------------------------- + // Actual DLL call + // ----------------------------------------------------------------------------------------------------------------------------- + public enum Q3Map2Result + { + Succeeded, + SucceededWithWarnings, + FailedWithMissingTextures, + Failed, + } + public static class Q3Map2Dll + { + private static bool s_IsLoaded = false; + public static bool IsLoaded => s_IsLoaded; + + // Callback function signature + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void MessageHandlerFunc(string output); + + // Change lib name based on platform +#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX || UNITY_STANDALONE_LINUX || UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX + private const string Q3MAP2_LIB_NAME = "q3map2"; +#else +//TODO(jwf): ATV: No q3map2 - solution: use "__Internal" as the name and build as static lib + #warning Unknown platform - libq3map must be built as a static lib! + private const string Q3MAP2_LIB_NAME = "__Internal"; +#endif + +#if UNITY_WEBGL || UNITY_TVOS + // Stub for WebGL, tvOS + public static int DLL_ConvertMap( + string mapFile, + string fsPath, + MessageHandlerFunc functionCallback, + string[] inArgs, + int inArgCount) + { + return -1; + } +#else + // DLL entry point for conversion + [DllImport(Q3MAP2_LIB_NAME, EntryPoint = "convert_map_unity", CallingConvention = CallingConvention.Cdecl)] + private static extern int DLL_ConvertMap( + [MarshalAs(UnmanagedType.LPStr)] string mapFile, + [MarshalAs(UnmanagedType.LPStr)] string fsPath, + [MarshalAs(UnmanagedType.FunctionPtr)] MessageHandlerFunc functionCallback, + [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 4)] string[] inArgs, + [MarshalAs(UnmanagedType.SysInt)] int inArgCount); +#endif + + public static int ConvertMap(string mapFile, MessageHandlerFunc functionCallback, string[] inArgs) + => ConvertMap(mapFile, "Library", functionCallback, inArgs); + + public static int ConvertMap(string mapFile, string fsPath, MessageHandlerFunc functionCallback, string[] inArgs) + { + try + { + s_IsLoaded = true; + + // Use another thread to do the actual compilation, + // so that we can control the stack size. + const int STACK_SIZE_MB = 8; + + int exitCode = 0; + void CompileOnOtherThread() + => exitCode = DLL_ConvertMap(mapFile, fsPath, functionCallback, inArgs, inArgs.Length); + + Thread compilerThread = new( + start: CompileOnOtherThread, + maxStackSize: STACK_SIZE_MB * 1024 * 1024 + ); + compilerThread.Start(); + compilerThread.Join(); + + return exitCode; + } + catch (DllNotFoundException) + { + s_IsLoaded = false; + return -0xdead; + } + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Plugins Folder + // ----------------------------------------------------------------------------------------------------------------------------- +#if UNITY_EDITOR + private static string PluginsFolder => Path.Combine(TrembleConsts.EDITOR_GetTrembleInstallFolder(), "Plugins"); + public static bool EDITOR_PluginsFolderExists() => Directory.Exists(PluginsFolder); + + public static void EDITOR_DeletePluginsFolder() + { + if (!EDITOR_PluginsFolderExists()) + return; + + EDITOR_IsPluginsFolderFlaggedForDeletion = false; + + try + { + Directory.Delete(PluginsFolder, true); + + string metaFile = PluginsFolder + ".meta"; + if (File.Exists(metaFile)) + { + File.Delete(PluginsFolder + ".meta"); + } + } + catch (UnauthorizedAccessException) + { + EDITOR_IsPluginsFolderFlaggedForDeletion = true; + + EditorUtility.DisplayDialog( + title: "Q3Map2 Upgrade", + message: $"Unfortunately, the auto-upgrader has encountered an error. Please quit Unity, and manually delete {PluginsFolder} in your file explorer. Sorry!", + ok: "Got it, no worries!" + ); + } + } + + public static bool EDITOR_IsPluginsFolderFlaggedForDeletion + { + get => EditorPrefs.GetBool($"Tremble_{Application.productName}_DeletePluginsNow", false); + set => EditorPrefs.SetBool($"Tremble_{Application.productName}_DeletePluginsNow", value); + } +#endif + + // ----------------------------------------------------------------------------------------------------------------------------- + // Version Info + // ----------------------------------------------------------------------------------------------------------------------------- + public static Q3Map2VersionInfo GetTinyGooseVersionInfo() + { + const string LIB_Q3_MAP2 = "libQ3Map2 (Tiny Goose)"; + + Dictionary info = GetVersionInfo(); + return Q3Map2VersionInfo.Parse(info.GetValueOrDefault(LIB_Q3_MAP2, null)); // e.g. v2.5.1n-git-f278fa + } + + public static Dictionary GetVersionInfo() + { + string[] args = { "-v" }; + List outputLines = new(); + + ConvertMap("", line => outputLines.Add(line), args); + + Dictionary info = new(); + foreach (string line in outputLines) + { + if (!TrySplitLineIntoKeyValue(line, out string key, out string value)) + continue; + + info[key] = value; + } + + return info; + } + + private static bool TrySplitLineIntoKeyValue(string line, out string key, out string value) + { + Span separators = stackalloc char[2]; + separators[0] = '-'; + separators[1] = ':'; + + foreach (char separator in separators) + { + int sepIdx = line.IndexOf(separator); + if (sepIdx == -1) + continue; + + key = line.Substring(0, sepIdx).Trim(); + value = line.Substring(sepIdx + 1).Trim(); + return true; + } + + key = value = null; + return false; + } + } +} diff --git a/Assets/Tremble/Import/Q3Map2Dll.cs.meta b/Assets/Tremble/Import/Q3Map2Dll.cs.meta new file mode 100644 index 0000000..ff86739 --- /dev/null +++ b/Assets/Tremble/Import/Q3Map2Dll.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 71dcd1e650e444787a70e52840cf86f5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Import/Q3Map2Dll.cs + uploadId: 939664 diff --git a/Assets/Tremble/Import/Q3Map2VersionInfo.cs b/Assets/Tremble/Import/Q3Map2VersionInfo.cs new file mode 100644 index 0000000..64db61e --- /dev/null +++ b/Assets/Tremble/Import/Q3Map2VersionInfo.cs @@ -0,0 +1,45 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; + +namespace TinyGoose.Tremble +{ + public struct Q3Map2VersionInfo + { + public int Major; + public int Minor; + public int Patch; + public char Letter; + public string GitHash; + + public override string ToString() => $"v{Major}.{Minor}.{Patch}{Letter}-git-{GitHash}"; + + private static Q3Map2VersionInfo Empty => new() { Major = 0, Minor = 0, Patch = 0, Letter = 'x', GitHash = "deadbeef" }; + + public static Q3Map2VersionInfo Parse(string version) + { + if (String.IsNullOrEmpty(version) || !version.ContainsInvariant("-") || !version.ContainsInvariant(".")) + return Empty; + + string[] rootVersionInfo = version.Split('-'); + if (rootVersionInfo.Length != 3) + return Empty; + + string[] versionParts = rootVersionInfo[0].Split('.'); + if (versionParts.Length != 3) + return Empty; + + Q3Map2VersionInfo info; + info.Major = int.Parse(versionParts[0].Substring(1)); + info.Minor = int.Parse(versionParts[1]); + info.Patch = int.Parse(versionParts[2].Substring(0, versionParts[2].Length - 1)); + info.Letter = versionParts[2][^1]; + info.GitHash = rootVersionInfo[2]; + + return info; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Import/Q3Map2VersionInfo.cs.meta b/Assets/Tremble/Import/Q3Map2VersionInfo.cs.meta new file mode 100644 index 0000000..e65b1a7 --- /dev/null +++ b/Assets/Tremble/Import/Q3Map2VersionInfo.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 11da1594d9414433b92548628283ce8e +timeCreated: 1735838685 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Import/Q3Map2VersionInfo.cs + uploadId: 939664 diff --git a/Assets/Tremble/Interfaces.meta b/Assets/Tremble/Interfaces.meta new file mode 100644 index 0000000..4c980bd --- /dev/null +++ b/Assets/Tremble/Interfaces.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 8eb4d3f7ca494494ae6d10b0f0868f83 +timeCreated: 1700514703 \ No newline at end of file diff --git a/Assets/Tremble/Interfaces/IOnImportFromMapEntity.cs b/Assets/Tremble/Interfaces/IOnImportFromMapEntity.cs new file mode 100644 index 0000000..bf1a2cd --- /dev/null +++ b/Assets/Tremble/Interfaces/IOnImportFromMapEntity.cs @@ -0,0 +1,21 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble +{ + /// + /// Interface for [PrefabEntityEntity], [BrushEntity], and [PointEntity] classes, to + /// perform additional processing after import from a map file. + /// + /// If these modifications after import are complicated, need to occur using Editor + /// functionality, or refer to other objects you may wish to consider instead + /// using a custom Map Processor for your map to process them at the top level. + /// + public interface IOnImportFromMapEntity + { + // Change ITrembleBaseClass if this changes!! + void OnImportFromMapEntity(MapBsp mapBsp, BspEntity entity); + } +} \ No newline at end of file diff --git a/Assets/Tremble/Interfaces/IOnImportFromMapEntity.cs.meta b/Assets/Tremble/Interfaces/IOnImportFromMapEntity.cs.meta new file mode 100644 index 0000000..886ee02 --- /dev/null +++ b/Assets/Tremble/Interfaces/IOnImportFromMapEntity.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 91fd71f9e91f4033a8c4ee1bb7cfd9d6 +timeCreated: 1700514722 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Interfaces/IOnImportFromMapEntity.cs + uploadId: 939664 diff --git a/Assets/Tremble/Interfaces/IOnLiveUpdate.cs b/Assets/Tremble/Interfaces/IOnLiveUpdate.cs new file mode 100644 index 0000000..347cd2b --- /dev/null +++ b/Assets/Tremble/Interfaces/IOnLiveUpdate.cs @@ -0,0 +1,18 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +namespace TinyGoose.Tremble +{ + // Custom LiveUpdate + public interface IOnLiveUpdate + { + void OnLiveUpdated(); + } + + // Simple LiveUpdate - just call OnDestroy followed by Start! + public interface IOnLiveUpdate_Simple + { + } +} \ No newline at end of file diff --git a/Assets/Tremble/Interfaces/IOnLiveUpdate.cs.meta b/Assets/Tremble/Interfaces/IOnLiveUpdate.cs.meta new file mode 100644 index 0000000..a04a24f --- /dev/null +++ b/Assets/Tremble/Interfaces/IOnLiveUpdate.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 5bcd0f6915f34e92968ea5066ba1848a +timeCreated: 1710424030 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Interfaces/IOnLiveUpdate.cs + uploadId: 939664 diff --git a/Assets/Tremble/Interfaces/ITrembleBaseClass.cs b/Assets/Tremble/Interfaces/ITrembleBaseClass.cs new file mode 100644 index 0000000..db0c06f --- /dev/null +++ b/Assets/Tremble/Interfaces/ITrembleBaseClass.cs @@ -0,0 +1,41 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Reflection; +using System.Reflection.Emit; + +namespace TinyGoose.Tremble +{ + public interface ITrembleBaseClass + { + + } + + public static class TrembleBaseClassDefault + { + public static ITrembleBaseClass CreateDefault(Type baseClass) + { + AssemblyName assName = new("Tremble.Editor.BaseClasses"); + AssemblyBuilder assBuilder = AssemblyBuilder.DefineDynamicAssembly(assName, AssemblyBuilderAccess.Run); + ModuleBuilder moduleBuilder = assBuilder.DefineDynamicModule(assName + ".dll"); + TypeBuilder typeBuilder = moduleBuilder.DefineType(baseClass.Name + "Test"); + typeBuilder.AddInterfaceImplementation(baseClass); + + MethodBuilder importMethod = typeBuilder.DefineMethod(nameof(IOnImportFromMapEntity.OnImportFromMapEntity), + MethodAttributes.Public | MethodAttributes.Virtual, + CallingConventions.HasThis, + null, + new[] { typeof(MapBsp), typeof(BspEntity) }); + + ILGenerator ilGenerator = importMethod.GetILGenerator(); + ilGenerator.Emit(OpCodes.Nop); + ilGenerator.Emit(OpCodes.Ret); + + Type type = typeBuilder.CreateType(); + return (ITrembleBaseClass)Activator.CreateInstance(type); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Interfaces/ITrembleBaseClass.cs.meta b/Assets/Tremble/Interfaces/ITrembleBaseClass.cs.meta new file mode 100644 index 0000000..cef25c6 --- /dev/null +++ b/Assets/Tremble/Interfaces/ITrembleBaseClass.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 53a4ed95b3924b65b8ff49bd3174edb2 +timeCreated: 1710851762 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Interfaces/ITrembleBaseClass.cs + uploadId: 939664 diff --git a/Assets/Tremble/LICENSE b/Assets/Tremble/LICENSE new file mode 100644 index 0000000..b126090 --- /dev/null +++ b/Assets/Tremble/LICENSE @@ -0,0 +1,327 @@ +Copyright (c) 2023-2025 Tiny Goose. + +Portions of this code are based on UBSPMapTools by John Evans. +This package makes use of Q3Map2, part of GtkRadiant. +Q3Map2 was modified from its original source to incorporate support for "Valve 220 format" maps. + + + + + +UBSPMapTools +============ +Original at: https://github.com/JohnEvans512/UBSPMapTools +Original Licence Follows: + +Copyright (c) 2021 John Evans + +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. + + + + + +Q3Map2 +====== +Original at: https://github.com/Elzair/q3map2 +Modified by Tiny Goose to support Valve 220 style maps and to build as a dynamic library. +Modified version available at: https://github.com/tinygooseuk/q3map2 + +Original Licence Follows: + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/Assets/Tremble/LICENSE.meta b/Assets/Tremble/LICENSE.meta new file mode 100644 index 0000000..05f18a9 --- /dev/null +++ b/Assets/Tremble/LICENSE.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 6852ea38713c4089b39298e609ac1672 +timeCreated: 1698306093 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/LICENSE + uploadId: 939664 diff --git a/Assets/Tremble/Materials.meta b/Assets/Tremble/Materials.meta new file mode 100644 index 0000000..8ef1133 --- /dev/null +++ b/Assets/Tremble/Materials.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4fcd38034c63844aca611cc49bce4b86 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tremble/Materials/Clip.shader b/Assets/Tremble/Materials/Clip.shader new file mode 100644 index 0000000..aa2e029 --- /dev/null +++ b/Assets/Tremble/Materials/Clip.shader @@ -0,0 +1,38 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024 TinyGoose Ltd., All Rights Reserved. +// + +Shader "Unlit/NoDraw" +{ + // This is an incredibly dumb shader, until such time as I can split render and collision + // meshes up easily. It just discards all pixels thrown at it :) + + Properties + { + } + SubShader + { + Tags { "RenderType"="Opaque" "ForceNoShadowCasting"="On" } + LOD 100 + + Pass + { + CGPROGRAM + + #pragma vertex EmptyVertex + #pragma fragment EmptyFragment + + // Do literally nothing + void EmptyVertex() { } + + // Discard all pixels, or failing that output a transparent one + fixed4 EmptyFragment() : SV_Target + { + discard; + return fixed4(0., 0., 0., 0.); // Required on Metal + } + ENDCG + } + } +} diff --git a/Assets/Tremble/Materials/Clip.shader.meta b/Assets/Tremble/Materials/Clip.shader.meta new file mode 100644 index 0000000..4cbeaf6 --- /dev/null +++ b/Assets/Tremble/Materials/Clip.shader.meta @@ -0,0 +1,16 @@ +fileFormatVersion: 2 +guid: 937aa9fd9252d4b3b9787657eb809aa4 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Materials/Clip.shader + uploadId: 939664 diff --git a/Assets/Tremble/Materials/M_NullRender.mat b/Assets/Tremble/Materials/M_NullRender.mat new file mode 100644 index 0000000..f8bff04 --- /dev/null +++ b/Assets/Tremble/Materials/M_NullRender.mat @@ -0,0 +1,154 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 8 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: M_NullRender + m_Shader: {fileID: 4800000, guid: 937aa9fd9252d4b3b9787657eb809aa4, type: 3} + m_Parent: {fileID: 0} + m_ModifiedSerializedProperties: 0 + m_ValidKeywords: [] + m_InvalidKeywords: [] + m_LightmapFlags: 0 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 1 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: + - MOTIONVECTORS + m_LockedProperties: _BumpMap + m_SavedProperties: + serializedVersion: 3 + m_TexEnvs: + - _BaseMap: + 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} + - _SpecGlossMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - unity_Lightmaps: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - unity_LightmapsInd: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - unity_ShadowMasks: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Ints: [] + m_Floats: + - _AddPrecomputedVelocity: 0 + - _AlphaClip: 1 + - _AlphaToMask: 1 + - _Blend: 0 + - _BlendModePreserveSpecular: 1 + - _BlendOp: 0 + - _BumpScale: 1 + - _CameraFadingEnabled: 0 + - _CameraFarFadeDistance: 2 + - _CameraNearFadeDistance: 1 + - _ClearCoatMask: 0 + - _ClearCoatSmoothness: 0 + - _ColorMode: 0 + - _Cull: 0 + - _Cutoff: 0.5 + - _DetailAlbedoMapScale: 1 + - _DetailNormalMapScale: 1 + - _DistortionBlend: 0.5 + - _DistortionEnabled: 0 + - _DistortionStrength: 1 + - _DistortionStrengthScaled: 0 + - _DstBlend: 0 + - _DstBlendAlpha: 0 + - _EmissionEnabled: 0 + - _EnvironmentReflections: 1 + - _FlipbookMode: 0 + - _GlossMapScale: 0 + - _Glossiness: 0 + - _GlossyReflections: 0 + - _LightingEnabled: 0 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.005 + - _QueueOffset: 0 + - _ReceiveShadows: 1 + - _Smoothness: 0.5 + - _SmoothnessTextureChannel: 0 + - _SoftParticlesEnabled: 0 + - _SoftParticlesFarFadeDistance: 1 + - _SoftParticlesNearFadeDistance: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _SrcBlendAlpha: 1 + - _Surface: 0 + - _WorkflowMode: 1 + - _ZWrite: 1 + m_Colors: + - _BaseColor: {r: 1, g: 1, b: 1, a: 0} + - _CameraFadeParams: {r: 0, g: Infinity, b: 0, a: 0} + - _Color: {r: 1, g: 1, b: 1, a: 0} + - _ColorAddSubDiff: {r: 0, g: 0, b: 0, a: 0} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} + - _SoftParticleFadeParams: {r: 0, g: 0, b: 0, a: 0} + - _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1} + m_BuildTextureStacks: [] + m_AllowLocking: 1 +--- !u!114 &4961750165995888414 +MonoBehaviour: + m_ObjectHideFlags: 11 + 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: d0353a89b1f911e48b9e16bdc9f2e058, type: 3} + m_Name: + m_EditorClassIdentifier: + version: 9 diff --git a/Assets/Tremble/Materials/M_NullRender.mat.meta b/Assets/Tremble/Materials/M_NullRender.mat.meta new file mode 100644 index 0000000..61f1ec7 --- /dev/null +++ b/Assets/Tremble/Materials/M_NullRender.mat.meta @@ -0,0 +1,15 @@ +fileFormatVersion: 2 +guid: ebc2e2b22a4174f9e9867d979b7008b8 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Materials/M_NullRender.mat + uploadId: 939664 diff --git a/Assets/Tremble/MonoBehaviours.meta b/Assets/Tremble/MonoBehaviours.meta new file mode 100644 index 0000000..edb5390 --- /dev/null +++ b/Assets/Tremble/MonoBehaviours.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1cfa1c3283494a2e8136da3366806342 +timeCreated: 1698412703 \ No newline at end of file diff --git a/Assets/Tremble/MonoBehaviours/MapDocument.cs b/Assets/Tremble/MonoBehaviours/MapDocument.cs new file mode 100644 index 0000000..eb3f8ae --- /dev/null +++ b/Assets/Tremble/MonoBehaviours/MapDocument.cs @@ -0,0 +1,288 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using UnityEngine; +using UnityEngine.Scripting; +using Debug = UnityEngine.Debug; + +#if UNITY_EDITOR +using UnityEditor; +using UnityEditor.SceneManagement; +#endif + +namespace TinyGoose.Tremble +{ + [Serializable] + public struct IDMapping + { + [SerializeField] private string m_ID; + [SerializeField] private GameObject[] m_Objects; + + public string ID => m_ID; + public GameObject[] Objects => m_Objects; + + public static IDMapping Create(string name, GameObject[] objects) => new() + { + m_ID = name, + m_Objects = objects, + }; + } + + /// + /// The root of a map file. + /// Provides a way to connect entities in maps to MonoBehaviours outside of the map. + /// + [DefaultExecutionOrder(-1000), Preserve, ExecuteInEditMode, AddComponentMenu("")] + public class MapDocument : MonoBehaviour + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Exposed + // ----------------------------------------------------------------------------------------------------------------------------- + [SerializeField, HideInInspector] private string m_BspName; + [SerializeField, HideInInspector] private IDMapping[] m_EntityIDs; + + [SerializeField, HideInInspector] private string m_OriginalAssetGuid; + [SerializeField, HideInInspector] private GameObject m_WorldspawnObject; + [SerializeField, HideInInspector] private ulong m_MapImportedTime; + + private Q3Map2Result m_Result = Q3Map2Result.Succeeded; + private string m_ResultReason; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Properties + // ----------------------------------------------------------------------------------------------------------------------------- + public string BspName => m_BspName; + public TWorldspawn GetWorldspawn() where TWorldspawn : Worldspawn => m_WorldspawnObject.GetComponent(); + + public bool TryGetWorldspawn(out TWorldspawn worldspawn) where TWorldspawn : Worldspawn + { + worldspawn = GetWorldspawn(); + return worldspawn; + } + + public Q3Map2Result Result => m_Result; + public string ResultReason => m_ResultReason; + +#if UNITY_EDITOR + public IDMapping[] EntityIDs => m_EntityIDs; + public string OriginalAssetGuid => m_OriginalAssetGuid; + public GameObject WorldspawnObject => m_WorldspawnObject; + public ulong MapImportedTime => m_MapImportedTime; +#endif + + [Conditional("UNITY_EDITOR")] + private void OnEnable() + { +#if UNITY_EDITOR + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + + if (syncSettings.PrefabOverrideHandling != PrefabOverrideHandling.AllowOverrides) + { + bool hasAnyOverrides = PrefabUtility.HasPrefabInstanceAnyOverrides(gameObject, true); + + List addedComponents = PrefabUtility.IsAnyPrefabInstanceRoot(gameObject) ? PrefabUtility.GetAddedComponents(gameObject) : new(); + List removedComponents = PrefabUtility.IsAnyPrefabInstanceRoot(gameObject) ? PrefabUtility.GetRemovedComponents(gameObject) : new(); + + int numChangedItems = addedComponents.Count + removedComponents.Count; + +#if UNITY_2022_1_OR_NEWER + List removedGOs = PrefabUtility.IsAnyPrefabInstanceRoot(gameObject) ? PrefabUtility.GetRemovedGameObjects(gameObject) : new(); + numChangedItems += removedGOs.Count; +#endif + + if (hasAnyOverrides || numChangedItems > 0) + { + bool needsRevert = false; + + foreach (PropertyModification propChanged in PrefabUtility.GetPropertyModifications(gameObject)) + { + if (!propChanged.target) + continue; + + if (propChanged.propertyPath.EqualsInvariant("name", caseSensitive: false) || + propChanged.propertyPath.EqualsInvariant("m_Name", caseSensitive: false)) + continue; + + // TextMeshPro adds a hidden MeshFilter with overriden props, and then hides it. We can ignore this + // one since the user can't see it! + if ((propChanged.target.hideFlags & HideFlags.HideInHierarchy) != 0) + continue; + + string niceName = propChanged.propertyPath.Split('.')[0].ToNamingConvention(NamingConvention.HumanFriendly); + GameObject changedInstance = gameObject.Find_Recursive(propChanged.target.name); + + needsRevert = true; + + if (syncSettings.PrefabOverrideHandling == PrefabOverrideHandling.WarnOnOverridesFound) + { + Debug.LogWarning($"Property override found: '{niceName}' ({propChanged.propertyPath}) on '{propChanged.target.name}' ({propChanged.target.GetType().Name}) - please change this value in TrenchBroom instead of Unity!", changedInstance); + } + else if (syncSettings.PrefabOverrideHandling == PrefabOverrideHandling.AutomaticallyRevert) + { + Debug.LogWarning($"Auto-reverted overridden property '{niceName}' ({propChanged.propertyPath}) on '{propChanged.target.name}' ({propChanged.target.GetType().Name}) - please change this value in TrenchBroom instead of Unity!", changedInstance); + } + } + + foreach (AddedComponent addedComponent in addedComponents) + { + if (addedComponent.instanceComponent.GetType().Name.EqualsInvariant("UniversalAdditionalLightData", caseSensitive: true) || + addedComponent.instanceComponent.GetType().Name.EqualsInvariant("HDAdditionalLightData", caseSensitive: true)) + { + numChangedItems--; + continue; + } + + if (syncSettings.PrefabOverrideHandling == PrefabOverrideHandling.WarnOnOverridesFound) + { + Debug.LogWarning($"Added component found: '{addedComponent.instanceComponent.GetType().Name}' on '{addedComponent.instanceComponent.name}' - please change this value in TrenchBroom instead of Unity!", addedComponent.instanceComponent); + } + else if (syncSettings.PrefabOverrideHandling == PrefabOverrideHandling.AutomaticallyRevert) + { + Debug.LogWarning($"Auto-reverted added component '{addedComponent.instanceComponent.GetType().Name}' on '{addedComponent.instanceComponent.name}' - please change this value in TrenchBroom instead of Unity!", addedComponent.instanceComponent); + addedComponent.Revert(InteractionMode.AutomatedAction); + } + } + + foreach (RemovedComponent removedComponent in removedComponents) + { + if (syncSettings.PrefabOverrideHandling == PrefabOverrideHandling.WarnOnOverridesFound) + { + Debug.LogWarning($"Removed component found: '{removedComponent.assetComponent.GetType().Name}' on '{removedComponent.assetComponent.name}' - please change this value in TrenchBroom instead of Unity!", removedComponent.containingInstanceGameObject); + } + else if (syncSettings.PrefabOverrideHandling == PrefabOverrideHandling.AutomaticallyRevert) + { + Debug.LogWarning($"Auto-reverted removed component '{removedComponent.assetComponent.GetType().Name}' on '{removedComponent.assetComponent.name}' - please change this value in TrenchBroom instead of Unity!", removedComponent.containingInstanceGameObject); + removedComponent.Revert(InteractionMode.AutomatedAction); + } + } + +#if UNITY_2022_1_OR_NEWER + foreach (RemovedGameObject removedGO in removedGOs) + { + if (syncSettings.PrefabOverrideHandling == PrefabOverrideHandling.WarnOnOverridesFound) + { + Debug.LogWarning($"Removed GameObject found: '{removedGO.assetGameObject.name}' - please change this value in TrenchBroom instead of Unity!", removedGO.parentOfRemovedGameObjectInInstance); + } + else if (syncSettings.PrefabOverrideHandling == PrefabOverrideHandling.AutomaticallyRevert) + { + Debug.LogWarning($"Auto-reverted removed GameObject '{removedGO.assetGameObject.name}' - please change this value in TrenchBroom instead of Unity!", removedGO.parentOfRemovedGameObjectInInstance); + removedGO.Revert(InteractionMode.AutomatedAction); + } + } +#endif + + if (needsRevert && syncSettings.PrefabOverrideHandling == PrefabOverrideHandling.AutomaticallyRevert) + { + PrefabUtility.RevertPrefabInstance(gameObject, InteractionMode.AutomatedAction); + } + } + } +#endif + } + + internal void INTERNAL_SetResult(Q3Map2Result result, string reason) + { + m_Result = result; + m_ResultReason = reason; + } + + internal void INTERNAL_SetData(string bspName, IDMapping[] ids, string originalAssetGuid, GameObject worldspawnObject, ulong mapImportedTime) + { + m_BspName = bspName; + m_EntityIDs = ids; + m_OriginalAssetGuid = originalAssetGuid; + m_WorldspawnObject = worldspawnObject; + m_MapImportedTime = mapImportedTime; + } + + // Find a list of entities with a given id + public bool Q(string id, out GameObject[] foundObjects) + { + if (m_EntityIDs == null || m_EntityIDs.Length == 0) + { + foundObjects = null; + return false; + } + + foreach (IDMapping mapping in m_EntityIDs) + { + if (!mapping.ID.EqualsInvariant(id)) + continue; + + foundObjects = mapping.Objects; + return true; + } + + foundObjects = Array.Empty(); + return false; + } + + // Find a list of components from entities with a given id + public bool Q(string id, out List foundComponents) + where TComponent : Component + { + foundComponents = new(); + + if (!Q(id, out GameObject[] foundObjects)) + { + return false; + } + + foreach (GameObject foundObject in foundObjects) + { + foundComponents.AddRange(foundObject.GetComponentsInChildren()); + } + + return foundComponents.Count > 0; + } + // Find a single entity with a id + public bool Q(string id, out GameObject foundObject) + { + bool wasFound = Q(id, out GameObject[] foundObjects); + + foundObject = wasFound ? foundObjects[0] : null; + return wasFound; + } + // Find a component on a single entity with a id + public bool Q(string id, out TComponent foundComponent) + where TComponent : Component + { + bool wasFound = Q(id, out List foundComponents); + + foundComponent = wasFound ? foundComponents[0] : null; + return wasFound; + } + + // Find a list of components from entities with a given id + public bool Q(string id, Type componentType, out List foundComponents) + { + foundComponents = new(); + + if (!Q(id, out GameObject[] foundObjects)) + { + return false; + } + + foreach (GameObject foundObject in foundObjects) + { + foundComponents.AddRange(foundObject.GetComponentsInChildren(componentType)); + } + + return foundComponents.Count > 0; + } + + // Find a component on a single entity with a id + public bool Q(string id, Type componentType, out Component foundComponent) + { + bool wasFound = Q(id, componentType, out List foundComponents); + + foundComponent = wasFound ? foundComponents[0] : null; + return wasFound; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/MonoBehaviours/MapDocument.cs.meta b/Assets/Tremble/MonoBehaviours/MapDocument.cs.meta new file mode 100644 index 0000000..54c9680 --- /dev/null +++ b/Assets/Tremble/MonoBehaviours/MapDocument.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 40181e5341c64b86bf8f57109d47ebce +timeCreated: 1706952539 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/MonoBehaviours/MapDocument.cs + uploadId: 939664 diff --git a/Assets/Tremble/MonoBehaviours/SeparateMesh.cs b/Assets/Tremble/MonoBehaviours/SeparateMesh.cs new file mode 100644 index 0000000..9d9a8a2 --- /dev/null +++ b/Assets/Tremble/MonoBehaviours/SeparateMesh.cs @@ -0,0 +1,18 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +namespace TinyGoose.Tremble +{ + /// + /// Disconnects arbitrary brushes from the main worldspawn. + /// + [BrushEntity("separate", category: "misc")] + [AddComponentMenu("")] + public class SeparateMesh : MonoBehaviour + { + } +} \ No newline at end of file diff --git a/Assets/Tremble/MonoBehaviours/SeparateMesh.cs.meta b/Assets/Tremble/MonoBehaviours/SeparateMesh.cs.meta new file mode 100644 index 0000000..37e3c28 --- /dev/null +++ b/Assets/Tremble/MonoBehaviours/SeparateMesh.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 47ad5647e26f4839a384fedd97611250 +timeCreated: 1706712777 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/MonoBehaviours/SeparateMesh.cs + uploadId: 939664 diff --git a/Assets/Tremble/MonoBehaviours/TrembleSpawnablePrefab.cs b/Assets/Tremble/MonoBehaviours/TrembleSpawnablePrefab.cs new file mode 100644 index 0000000..d10c0f5 --- /dev/null +++ b/Assets/Tremble/MonoBehaviours/TrembleSpawnablePrefab.cs @@ -0,0 +1,25 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +namespace TinyGoose.Tremble +{ + /// + /// Add this component to an existing Prefab which doesn't contain a + /// MonoBehaviour to allow it to be placed in TrenchBroom easily. + /// + [PrefabEntity] + public sealed class TrembleSpawnablePrefab : MonoBehaviour + { + [SerializeField, NoTremble] private string m_Category; + [SerializeField, NoTremble] private Texture2D m_OverrideSprite; + [SerializeField, NoTremble] private bool m_OnlyVariants; + + public string Category => m_Category; + public Texture2D OverrideSprite => m_OverrideSprite; + public bool OnlyVariants => m_OnlyVariants; + } +} \ No newline at end of file diff --git a/Assets/Tremble/MonoBehaviours/TrembleSpawnablePrefab.cs.meta b/Assets/Tremble/MonoBehaviours/TrembleSpawnablePrefab.cs.meta new file mode 100644 index 0000000..961aef2 --- /dev/null +++ b/Assets/Tremble/MonoBehaviours/TrembleSpawnablePrefab.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 3770c55e1e67e4805bcf322ae01885f3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/MonoBehaviours/TrembleSpawnablePrefab.cs + uploadId: 939664 diff --git a/Assets/Tremble/MonoBehaviours/Worldspawn.cs b/Assets/Tremble/MonoBehaviours/Worldspawn.cs new file mode 100644 index 0000000..35c8ec2 --- /dev/null +++ b/Assets/Tremble/MonoBehaviours/Worldspawn.cs @@ -0,0 +1,15 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [DefaultExecutionOrder(-50)] + public class Worldspawn : MonoBehaviour + { + + } +} \ No newline at end of file diff --git a/Assets/Tremble/MonoBehaviours/Worldspawn.cs.meta b/Assets/Tremble/MonoBehaviours/Worldspawn.cs.meta new file mode 100644 index 0000000..585bd10 --- /dev/null +++ b/Assets/Tremble/MonoBehaviours/Worldspawn.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 78f4dd27e14848d793e71189be81527b +timeCreated: 1710154074 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/MonoBehaviours/Worldspawn.cs + uploadId: 939664 diff --git a/Assets/Tremble/Plugins.meta b/Assets/Tremble/Plugins.meta new file mode 100644 index 0000000..52ff09c --- /dev/null +++ b/Assets/Tremble/Plugins.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c3f804cf6c9b443e4a34d349d74fcfa9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tremble/Plugins/ARM64.meta b/Assets/Tremble/Plugins/ARM64.meta new file mode 100644 index 0000000..22f8acf --- /dev/null +++ b/Assets/Tremble/Plugins/ARM64.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6c5f7c0f20a324ce39975aad419785d2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tremble/Plugins/ARM64/q3map2.dylib b/Assets/Tremble/Plugins/ARM64/q3map2.dylib new file mode 100644 index 0000000..b7b1609 Binary files /dev/null and b/Assets/Tremble/Plugins/ARM64/q3map2.dylib differ diff --git a/Assets/Tremble/Plugins/ARM64/q3map2.dylib.meta b/Assets/Tremble/Plugins/ARM64/q3map2.dylib.meta new file mode 100644 index 0000000..1683302 --- /dev/null +++ b/Assets/Tremble/Plugins/ARM64/q3map2.dylib.meta @@ -0,0 +1,70 @@ +fileFormatVersion: 2 +guid: 4067a617b86bd4e7cb653cf30b027d10 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 1 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + : Any + second: + enabled: 0 + settings: + Exclude Editor: 0 + Exclude Linux64: 0 + Exclude OSXUniversal: 0 + Exclude Win: 0 + Exclude Win64: 0 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: ARM64 + DefaultValueInitialized: true + OS: OSX + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: ARM64 + - first: + Standalone: Win + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: None + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Plugins/ARM64/q3map2.dylib + uploadId: 939664 diff --git a/Assets/Tremble/Plugins/x86_64.meta b/Assets/Tremble/Plugins/x86_64.meta new file mode 100644 index 0000000..ec9fc8f --- /dev/null +++ b/Assets/Tremble/Plugins/x86_64.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d472bbc7e5aa14c03a0dff6862c60cb1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tremble/Plugins/x86_64/q3map2.dll b/Assets/Tremble/Plugins/x86_64/q3map2.dll new file mode 100644 index 0000000..265d9ec --- /dev/null +++ b/Assets/Tremble/Plugins/x86_64/q3map2.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e6a9b4c386fa77e5b468ee4afac4d369f5f02d4cfd3cd7755a03ade0ae940e1 +size 799744 diff --git a/Assets/Tremble/Plugins/x86_64/q3map2.dll.meta b/Assets/Tremble/Plugins/x86_64/q3map2.dll.meta new file mode 100644 index 0000000..3683c12 --- /dev/null +++ b/Assets/Tremble/Plugins/x86_64/q3map2.dll.meta @@ -0,0 +1,70 @@ +fileFormatVersion: 2 +guid: c24183706fbea40ad8b5ce6218bf21b2 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 1 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + : Any + second: + enabled: 0 + settings: + Exclude Editor: 0 + Exclude Linux64: 0 + Exclude OSXUniversal: 0 + Exclude Win: 0 + Exclude Win64: 0 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: Windows + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: x86_64 + - first: + Standalone: Win + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: x86_64 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Plugins/x86_64/q3map2.dll + uploadId: 939664 diff --git a/Assets/Tremble/Plugins/x86_64/q3map2.dylib b/Assets/Tremble/Plugins/x86_64/q3map2.dylib new file mode 100644 index 0000000..d194be9 Binary files /dev/null and b/Assets/Tremble/Plugins/x86_64/q3map2.dylib differ diff --git a/Assets/Tremble/Plugins/x86_64/q3map2.dylib.meta b/Assets/Tremble/Plugins/x86_64/q3map2.dylib.meta new file mode 100644 index 0000000..75c6933 --- /dev/null +++ b/Assets/Tremble/Plugins/x86_64/q3map2.dylib.meta @@ -0,0 +1,70 @@ +fileFormatVersion: 2 +guid: 236285b2d48a84966ab17c142fdfe0de +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 1 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + : Any + second: + enabled: 0 + settings: + Exclude Editor: 0 + Exclude Linux64: 0 + Exclude OSXUniversal: 0 + Exclude Win: 0 + Exclude Win64: 0 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: OSX + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: x86_64 + - first: + Standalone: Win + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: x86_64 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Plugins/x86_64/q3map2.dylib + uploadId: 939664 diff --git a/Assets/Tremble/Plugins/x86_64/q3map2.so b/Assets/Tremble/Plugins/x86_64/q3map2.so new file mode 100644 index 0000000..ad638f3 --- /dev/null +++ b/Assets/Tremble/Plugins/x86_64/q3map2.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43adeead36037800b7255e5443a7f34044b3332def5cf4a166fca77581e59ab1 +size 1144112 diff --git a/Assets/Tremble/Plugins/x86_64/q3map2.so.meta b/Assets/Tremble/Plugins/x86_64/q3map2.so.meta new file mode 100644 index 0000000..289202a --- /dev/null +++ b/Assets/Tremble/Plugins/x86_64/q3map2.so.meta @@ -0,0 +1,70 @@ +fileFormatVersion: 2 +guid: 3330b3446524f4e879e99161d11d60ff +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 1 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + : Any + second: + enabled: 0 + settings: + Exclude Editor: 0 + Exclude Linux64: 0 + Exclude OSXUniversal: 1 + Exclude Win: 0 + Exclude Win64: 0 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: Linux + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: x86_64 + - first: + Standalone: Win + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: x86_64 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Plugins/x86_64/q3map2.so + uploadId: 939664 diff --git a/Assets/Tremble/ScriptableObjects.meta b/Assets/Tremble/ScriptableObjects.meta new file mode 100644 index 0000000..bf9122c --- /dev/null +++ b/Assets/Tremble/ScriptableObjects.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: aea3d94de7ec4ca0a6e686340f6f0e41 +timeCreated: 1724924367 \ No newline at end of file diff --git a/Assets/Tremble/ScriptableObjects/FgdFileAsset.cs b/Assets/Tremble/ScriptableObjects/FgdFileAsset.cs new file mode 100644 index 0000000..d31a443 --- /dev/null +++ b/Assets/Tremble/ScriptableObjects/FgdFileAsset.cs @@ -0,0 +1,13 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public class FgdFileAsset : ScriptableObject + { + } +} \ No newline at end of file diff --git a/Assets/Tremble/ScriptableObjects/FgdFileAsset.cs.meta b/Assets/Tremble/ScriptableObjects/FgdFileAsset.cs.meta new file mode 100644 index 0000000..e97898c --- /dev/null +++ b/Assets/Tremble/ScriptableObjects/FgdFileAsset.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 7a6a6b15029746b1b1f5e06eeac8f5fa +timeCreated: 1724694785 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/ScriptableObjects/FgdFileAsset.cs + uploadId: 939664 diff --git a/Assets/Tremble/ScriptableObjects/MapFileAsset.cs b/Assets/Tremble/ScriptableObjects/MapFileAsset.cs new file mode 100644 index 0000000..eab5d9a --- /dev/null +++ b/Assets/Tremble/ScriptableObjects/MapFileAsset.cs @@ -0,0 +1,22 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +namespace TinyGoose.Tremble +{ + /// + /// A "Map Request" file. This gets around a shortcoming in Unity where + /// you cannot create new assets that are not ".asset" files. + /// + /// We create a blank "Map Request" asset in Unity, and then an Asset + /// Postprocessor picks this new asset up, and creates a blank + /// TrenchBroom map with the same name (and deletes the request). + /// + [CreateAssetMenu(menuName = "Tremble Map", fileName = "New Map")] + public class MapFileAsset : ScriptableObject + { + } +} \ No newline at end of file diff --git a/Assets/Tremble/ScriptableObjects/MapFileAsset.cs.meta b/Assets/Tremble/ScriptableObjects/MapFileAsset.cs.meta new file mode 100644 index 0000000..678fd3b --- /dev/null +++ b/Assets/Tremble/ScriptableObjects/MapFileAsset.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: a44b84a65567e4fb59dac2929aba0b09 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/ScriptableObjects/MapFileAsset.cs + uploadId: 939664 diff --git a/Assets/Tremble/ScriptableObjects/WadFileAsset.cs b/Assets/Tremble/ScriptableObjects/WadFileAsset.cs new file mode 100644 index 0000000..f6341c9 --- /dev/null +++ b/Assets/Tremble/ScriptableObjects/WadFileAsset.cs @@ -0,0 +1,15 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public class WadFileAsset : ScriptableObject + { + [SerializeField] private string[] m_MaterialNames; + public string[] MaterialNames => m_MaterialNames; + } +} \ No newline at end of file diff --git a/Assets/Tremble/ScriptableObjects/WadFileAsset.cs.meta b/Assets/Tremble/ScriptableObjects/WadFileAsset.cs.meta new file mode 100644 index 0000000..b625ed7 --- /dev/null +++ b/Assets/Tremble/ScriptableObjects/WadFileAsset.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: f29bae78f79b41c987bf2ac26f8dd83a +timeCreated: 1722849572 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/ScriptableObjects/WadFileAsset.cs + uploadId: 939664 diff --git a/Assets/Tremble/TinyGoose.Tremble.asmdef b/Assets/Tremble/TinyGoose.Tremble.asmdef new file mode 100644 index 0000000..ae6efbf --- /dev/null +++ b/Assets/Tremble/TinyGoose.Tremble.asmdef @@ -0,0 +1,33 @@ +{ + "name": "TinyGoose.Tremble", + "rootNamespace": "TinyGoose.Tremble", + "references": [ + "Unity.Addressables", + "Unity.ResourceManager" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [ + { + "name": "com.unity.addressables", + "expression": "0.0.0", + "define": "ADDRESSABLES_INSTALLED" + }, + { + "name": "com.unity.render-pipelines.universal", + "expression": "0.0.0", + "define": "URP_INSTALLED" + }, + { + "name": "com.unity.render-pipelines.high-definition", + "expression": "0.0.0", + "define": "HDRP_INSTALLED" + } + ], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/Tremble/TinyGoose.Tremble.asmdef.meta b/Assets/Tremble/TinyGoose.Tremble.asmdef.meta new file mode 100644 index 0000000..235bba1 --- /dev/null +++ b/Assets/Tremble/TinyGoose.Tremble.asmdef.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: a27430ba1f5c045a0a61beb51ecf4f90 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/TinyGoose.Tremble.asmdef + uploadId: 939664 diff --git a/Assets/Tremble/Tremble User Guide.pdf b/Assets/Tremble/Tremble User Guide.pdf new file mode 100644 index 0000000..9f11c44 Binary files /dev/null and b/Assets/Tremble/Tremble User Guide.pdf differ diff --git a/Assets/Tremble/Tremble User Guide.pdf.meta b/Assets/Tremble/Tremble User Guide.pdf.meta new file mode 100644 index 0000000..ca70f68 --- /dev/null +++ b/Assets/Tremble/Tremble User Guide.pdf.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 16fef24a289c8492e8e4b8cd8362dd68 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Tremble User Guide.pdf + uploadId: 939664 diff --git a/Assets/Tremble/TrembleConsts.cs b/Assets/Tremble/TrembleConsts.cs new file mode 100644 index 0000000..1394415 --- /dev/null +++ b/Assets/Tremble/TrembleConsts.cs @@ -0,0 +1,88 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public static class TrembleConsts + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Consts + // ----------------------------------------------------------------------------------------------------------------------------- + + // Version + private const int VERSION_MAJOR = 1; + private const int VERSION_MINOR = 11; + private const int VERSION_PATCH = 1; + public static readonly string VERSION_STRING = $"{VERSION_MAJOR}.{VERSION_MINOR}.{VERSION_PATCH}"; + + // Game name + public static readonly string GAME_NAME = $"Unity: {Application.productName}"; + public static readonly string ASSET_STORE_GAME_NAME = "Unity: AssetStore_Tremble"; + public static bool INTERNAL_IsTrembleAssetStoreProject => GAME_NAME.EqualsInvariant(ASSET_STORE_GAME_NAME); + + // Baseq3 path + public static readonly string BASEQ3_PATH = Path.Combine(Directory.GetCurrentDirectory(), "Library", "baseq3"); + public static readonly string BASEQ3_PATH_OLD = Path.Combine(Directory.GetCurrentDirectory(), "Library", "baseq3_old"); + + public static readonly string BASE_MODELS_PATH = Path.Combine(BASEQ3_PATH, "models"); + public static readonly string BASE_MATERIALS_PATH = Path.Combine(BASEQ3_PATH, "textures"); + public static readonly string MODTIME_DB_PATH = new(Path.Combine(BASEQ3_PATH, "modtime.db")); + + public const string MAPFIX_ENTITY_NAME = "ent_mapfix"; + +#if UNITY_EDITOR + private static string s_TrembleInstallFolder; + public static string EDITOR_GetTrembleInstallFolder() + { + // Use cached version + if (s_TrembleInstallFolder != null && Directory.Exists(s_TrembleInstallFolder)) + return s_TrembleInstallFolder; + + // Find + string path = AssetDatabase.FindAssets("t:asmdef tinygoose.tremble.editor") + .Select(AssetDatabase.GUIDToAssetPath) + .FirstOrDefault(); + + if (path == null) + return null; + + string dir = Path.GetDirectoryName(path); // Editor folder + dir = Path.GetDirectoryName(dir); // Root folder + + s_TrembleInstallFolder = dir; + return s_TrembleInstallFolder; + } +#endif + } + + public static class FgdConsts + { + // Classes + public const string CLASS_MAP_BASE = "Tremble"; + public const string CLASS_MAP_POINT_BASE = "PointEntity"; + public const string CLASS_MAP_PREFAB_BASE = "PrefabEntity"; + + // Properties + public const string WORLDSPAWN = "worldspawn"; + + public const string PROPERTY_SPAWNFLAGS = "spawnflags"; + public const string PROPERTY_CLASSNAME = "classname"; + public const string PROPERTY_TARGET = "target"; + public const string PROPERTY_PARENT = "parent"; + + public const string PROPERTY_ORIGIN = "origin"; + public const string PROPERTY_ANGLES = "angles"; + public const string PROPERTY_SCALE = "scale"; + + public const string PREFAB_PREFIX = "prefab"; + public const string POINT_PREFIX = "ent"; + public const string BRUSH_PREFIX = "func"; + } +} \ No newline at end of file diff --git a/Assets/Tremble/TrembleConsts.cs.meta b/Assets/Tremble/TrembleConsts.cs.meta new file mode 100644 index 0000000..e9ee7f8 --- /dev/null +++ b/Assets/Tremble/TrembleConsts.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: de6da792c01149e6a4cdcde6e0e533a6 +timeCreated: 1699008987 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/TrembleConsts.cs + uploadId: 939664 diff --git a/Assets/Tremble/TrembleMapImport.cs b/Assets/Tremble/TrembleMapImport.cs new file mode 100644 index 0000000..e67061f --- /dev/null +++ b/Assets/Tremble/TrembleMapImport.cs @@ -0,0 +1,1086 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// This class based on BSP Map Tools for Unity by John Evans (evans3d512@gmail.com) +// + +using System; +using UnityEngine; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using UnityEngine.Serialization; +using Debug = UnityEngine.Debug; +using Object = UnityEngine.Object; + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace TinyGoose.Tremble +{ + public static class TBConsts + { + public const string TB_PREFIX = "_tb_"; + + public const string ID = TB_PREFIX + "id"; + public const string NAME = TB_PREFIX + "name"; + public const string OMIT_FROM_EXPORT = TB_PREFIX + "layer_omit_from_export"; + + public const string GROUP = TB_PREFIX + "group"; + public const string LAYER = TB_PREFIX + "layer"; + public const string TYPE = TB_PREFIX + "type"; + public const string TEXTURES = TB_PREFIX + "textures"; + + public const string EMPTY_TEXTURE = "__TB_empty"; + public const string CLIP_TEXTURE = "clip"; + public const string SKIP_TEXTURE = "skip"; + public const string TRIGGER_TEXTURE = "trigger"; + public const string SPECIAL_TEXTURE = "special"; + } + + public class TrembleMapImportSettings + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Statics + // ----------------------------------------------------------------------------------------------------------------------------- + private static TrembleMapImportSettings s_CurrentImportSettings; + internal static void INTERNAL_SetCurrent(TrembleMapImportSettings settings) => s_CurrentImportSettings = settings; + + public static TrembleMapImportSettings Current + { + get + { + if (s_CurrentImportSettings == null) + { + Debug.LogError("Cannot get TrembleMapImportSettings when no import is in progress!"); + } + + return s_CurrentImportSettings; + } + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private MapProcessorBase[] m_MapProcessors; + private readonly Dictionary> m_EntityIDToGameObjects = new(); + private readonly Dictionary m_SerialNumberToGameObject = new(); + + public MapProcessorClass[] ProcessorClasses { private get; init; } + + public bool SplitMesh { get; init; } = true; + public float MaxMeshSurfaceArea { get; init; } = 3000; + public float SmoothingAngle { get; init; } = 45; + public string ExtraCommandLineArgs { get; init; } = ""; + + public string AssetGUID { get; init; } = null; + + public Action OnObjectAdded { private get; init; } = null; + public Action OnDependencyAdded { get; init; } + public Action OnEntityAdded { get; init; } = null; + public Action OnWadsFound { get; init; } = null; + public Action OnWarning { private get; init; } = null; + public Action OnError { private get; init; } = null; + public Action> OnQ3Map2Result { get; init; } = null; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Getters + // ----------------------------------------------------------------------------------------------------------------------------- + public static TrembleMapImportSettings Default => new(); + + public MapProcessorBase[] Processors + { + get + { + if (m_MapProcessors == null) + { + m_MapProcessors = ProcessorClasses == null + ? Array.Empty() + : ProcessorClasses + .Where(pc => pc is { IsValid: true }) + .Select(pc => pc.CreateInstance()) + .ToArray(); + } + + return m_MapProcessors; + } + } + + public Dictionary> AllEntityIDs => m_EntityIDToGameObjects; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Public API + // ----------------------------------------------------------------------------------------------------------------------------- + public void MapGameObjectToEntity(GameObject obj, BspEntity entity) + { + m_SerialNumberToGameObject[entity.SerialNumber] = obj; + + if (entity.HasID()) + { + if (m_EntityIDToGameObjects.TryGetValue(entity.GetID(), out List list)) + { + list.Add(obj); + } + else + { + m_EntityIDToGameObjects.Add(entity.GetID(), new() { obj }); + } + } + } + + public bool TryGetGameObjectsForID(string id, out List objs) + { + if (id == null) + { + objs = null; + return false; + } + + return m_EntityIDToGameObjects.TryGetValue(id, out objs); + } + + public bool TryGetGameObjectForEntity(BspEntity entity, out GameObject obj) => m_SerialNumberToGameObject.TryGetValue(entity.SerialNumber, out obj); + + public bool TryGetComponentForEntity(BspEntity entity, out TComponent component) + where TComponent : Component + { + if (!m_SerialNumberToGameObject.TryGetValue(entity.SerialNumber, out GameObject obj) + || !obj.TryGetComponent(out component)) + { + component = default; + return false; + } + + return true; + } + + + public void Warn(string warning) + { + if (OnWarning != null) + OnWarning.Invoke(warning); + else + Debug.LogWarning(warning); + } + + public void Error(string error) + { + if (OnError != null) + OnError.Invoke(error); + else + Debug.LogError(error); + } + + public void AddDependency(Object obj) + { + if (!obj) + return; + + OnDependencyAdded?.Invoke(obj); + } + + public void SaveObjectInMap(string meshName, Object obj) => OnObjectAdded?.Invoke(meshName, obj); + } + + public class TrembleMapImport + { + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private readonly TrembleMapImportSettings m_ImportSettings; + private TrembleSyncSettings m_SyncSettings; + + private static readonly Dictionary s_MaterialCache = new(); + + private MeshBuilder m_MeshBuilder; + private int m_GroupCounter; + + // Groups + private Transform[] m_GroupTransforms; + + private MapTypeLookup m_MapTypeLookup; + private PrefabNameLookup m_PrefabNameLookup; + private MaterialNameLookup m_MaterialNameLookup; + private TrembleFieldConverterCollection m_FieldConverter; + + public TrembleMapImport(TrembleMapImportSettings importSettings) + { + m_ImportSettings = importSettings; + } + + private MapDocument CreateFailedMap(Q3Map2Result result, string reason) + { + GameObject nullObj = new($"Map: {result}"); + MapDocument doc = nullObj.AddComponent(); + doc.INTERNAL_SetResult(result, reason); + return doc; + } + + public async Task ImportMapAndCreatePrefab(string mapFilePath, MapBsp existingMapBsp = null) + { + if (mapFilePath == null || !File.Exists(mapFilePath)) + return CreateFailedMap(Q3Map2Result.Failed, $"Map file path '{mapFilePath}' was NULL or does not exist!"); + + TrembleMapImportSettings.INTERNAL_SetCurrent(m_ImportSettings); + m_SyncSettings = TrembleSyncSettings.Get(); + + int task = ProgressUtil.Start($"Import {Path.GetFileName(mapFilePath)}"); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Set up build folder, and discover groups + // ----------------------------------------------------------------------------------------------------------------------------- + ProgressUtil.Report(task, 1, 2, "Setting up build"); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Create lookups + // ----------------------------------------------------------------------------------------------------------------------------- + using (TrembleTimerScope _ = new(TrembleTimer.Context.CreateTypeLookups)) + { + m_MapTypeLookup = new(m_SyncSettings); + m_PrefabNameLookup = new(m_SyncSettings); + m_MaterialNameLookup = new(m_SyncSettings); + m_FieldConverter = new(); + } + + MapBsp mapBsp = existingMapBsp; + if (mapBsp == null) + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Run Q3Map2 + // ----------------------------------------------------------------------------------------------------------------------------- + ProgressUtil.Report(task, 2, 2, "Running Q3Map2"); + + List output = new(1024); + + mapBsp = MapCompiler.BuildBsp( + m_SyncSettings, + mapFilePath, + $"{m_SyncSettings.ExtraCommandLineArgs} {m_ImportSettings.ExtraCommandLineArgs}", + out Q3Map2Result result, + onOutputMessage: m => output.Add(m)); + + m_ImportSettings.OnQ3Map2Result?.Invoke(result, output); + + switch (result) + { + case Q3Map2Result.Failed: + ProgressUtil.Fail(task); + + m_ImportSettings.Error("Map compiler did not run correctly or was not found! Try syncing and then reimporting your map."); + return CreateFailedMap(Q3Map2Result.Failed, "Map compiler did not run correctly!"); + + case Q3Map2Result.FailedWithMissingTextures: + m_ImportSettings.Error("Map compiler did not find textures correctly!"); + +#if UNITY_EDITOR + if (!Application.isBatchMode && !Application.isPlaying) + { + if (SceneView.lastActiveSceneView) + { + SceneView.lastActiveSceneView.ShowNotification(new("Tremble: Reimport this map to fix texture UVs!")); + } + } +#endif + + break; + } + + if (mapBsp == null) + { + m_ImportSettings.Error("Map compiler did not generate a BSP file."); + ProgressUtil.Fail(task); + + return CreateFailedMap(Q3Map2Result.Failed, "Map compiler did not generate a BSP file."); + } + } + + // Preload assets, if required + if (TrembleAssetLoader.SupportsPreloading) + { + List pathsToPreload = new(128); + mapBsp.GatherResourceList(m_MaterialNameLookup, m_PrefabNameLookup, pathsToPreload); + + await TrembleAssetLoader.PreloadAssetsByPaths(pathsToPreload); + } + + // Check if the map has a Wad file set + BspEntity worldspawn = mapBsp.GetWorldspawnEntity(); + if (worldspawn.TryGetString("wad", out string wadEntry) && !wadEntry.IsNullOrEmpty()) + { + m_ImportSettings.OnWadsFound?.Invoke(wadEntry.Split(";")); + } + + // Finally create objects + m_GroupTransforms = new Transform[mapBsp.Groups.Length]; + + MapDocument mapDocument = ParseBspIntoGameObject(mapBsp); + + ProgressUtil.Succeed(task); + + TrembleMapImportSettings.INTERNAL_SetCurrent(null); + return mapDocument; + } + + private void ForeachProcessor(Action action) + { + using TrembleTimerScope __ = new(TrembleTimer.Context.RunMapProcessors); + + foreach (MapProcessorBase p in m_ImportSettings.Processors) + { + using TrembleTimerScope _ = new(p.GetType()); + action(p); + } + } + + private MapDocument ParseBspIntoGameObject(MapBsp mapBsp) + { + using TrembleTimerScope __ = new(TrembleTimer.Context.CreateGameObjects); + // Thank you John Evans. This is quite close to the original UBSPMapTools code. + + // Create processor + GameObject root = new(mapBsp.MapName, typeof(MapDocument)); + Transform rootTransform = root.transform; + ForeachProcessor(processor => processor.RootTransform = rootTransform); + + GameObject looseEntities = new("entities"); + looseEntities.transform.SetParent(rootTransform); + + ForeachProcessor(processor => processor.OnProcessingStarted(root, mapBsp)); + + // Build meshes from brushes + int unityLayer = LayerMask.NameToLayer(m_SyncSettings.WorldspawnLayer); + if (unityLayer < 0) + { + m_ImportSettings.Warn($"Could not found layer {m_SyncSettings.WorldspawnLayer} - using Default!"); + unityLayer = 0; + } + + m_MeshBuilder = new(m_ImportSettings, FindMaterial, m_SyncSettings.MainMeshName, m_ImportSettings.SmoothingAngle, m_ImportSettings.MaxMeshSurfaceArea); + + GameObject worldspawnObject; + + if (!m_SyncSettings.PipelineSplitMesh || !m_ImportSettings.SplitMesh) + { + string mainName = m_SyncSettings.MainMeshName; + worldspawnObject = m_MeshBuilder.BuildMesh(mapBsp, rootTransform, 0, true, mainName, false, Vector3.zero, true); + if (worldspawnObject) + { + worldspawnObject.layer = unityLayer; + } + else + { + m_ImportSettings.Error("Missing worldspawn brush?!"); + } + } + else + { + using TrembleTimerScope _ = new(TrembleTimer.Context.SplitMesh); + + worldspawnObject = new(m_SyncSettings.MainMeshName); + worldspawnObject.transform.SetParent(rootTransform); + worldspawnObject.layer = unityLayer; + + HashSet uniqueFaceList = new(2048); + m_MeshBuilder.BuildMesh_Recursive(mapBsp, worldspawnObject.transform, 0, uniqueFaceList, m_SyncSettings.ImportScale, unityLayer); + } + + // Add the worldspawn script + Type worldspawnScriptType = m_SyncSettings.WorldspawnScript?.Class ?? typeof(Worldspawn); + Worldspawn worldspawnScript = (Worldspawn)worldspawnObject.AddComponent(worldspawnScriptType); + + // Custom entities/prefabs/brushes/etc - create scripts and spawn + foreach (BspEntity entity in mapBsp.Entities) + { + // Work out layer/group + int groupIdx = 0; + + if (!m_SyncSettings.DiscardMapGroups) + { + if (entity.TryGetInt(TBConsts.GROUP, out int group)) + { + groupIdx = group; + } + + if (entity.TryGetInt(TBConsts.LAYER, out int layer)) + { + groupIdx = layer; + } + + if (entity.TryGetInt(TBConsts.ID, out int groupOrLayer)) + { + groupIdx = groupOrLayer; + } + } + + // Process entity and store in group if needed + Transform parent = FindOrCreateGroup(mapBsp, groupIdx, rootTransform, looseEntities.transform); + if (!parent) + { + // Owning group/layer is not for export! + continue; + } + + try + { + GameObject entityGameObject = CreateEntityGameObject(mapBsp, root, worldspawnObject, parent, entity); + if (!entityGameObject) + continue; + + entityGameObject.transform.SetAsLastSibling(); + + // Store IDs + m_ImportSettings.MapGameObjectToEntity(entityGameObject, entity); + } + catch (Exception ex) + { + m_ImportSettings.Error($"Failed to create entity '{entity.GetID()}' - {ex.Message}"); + Debug.LogException(ex); + } + } + + // Now set script values on all entities + foreach (BspEntity entity in mapBsp.Entities) + { + if (!m_ImportSettings.TryGetGameObjectForEntity(entity, out GameObject instance)) + continue; + + SetFieldValuesOnAllScripts(instance, entity); + + // Move to parent, if it has one + if (entity.TryGetString(FgdConsts.PROPERTY_PARENT, out string parentTarget) && + TryFindParent(parentTarget, entity, out Transform newParent)) + { + instance.transform.SetParent(newParent, true); + } + } + + // Now fire OnImportFromMapEntity + foreach (BspEntity entity in mapBsp.Entities) + { + if (!m_ImportSettings.TryGetGameObjectForEntity(entity, out GameObject instance)) + continue; + + foreach (IOnImportFromMapEntity pifme in instance.GetComponents()) + { + pifme.OnImportFromMapEntity(mapBsp, entity); + } + } + + ForeachProcessor(processor => processor.OnProcessingCompleted(root, mapBsp)); + + // Move loose entities to end + looseEntities.transform.SetAsLastSibling(); + + // Write data into the Worldspawn + // (BSP name, original asset GUID, worldspawn root, and targetname lookup) + List mappings = new(256); + + foreach (KeyValuePair> kvp in m_ImportSettings.AllEntityIDs) + { + mappings.Add(IDMapping.Create(kvp.Key, kvp.Value.ToArray())); + } + + MapDocument mapDocument = root.GetComponent(); + mapDocument.INTERNAL_SetData( + bspName: mapBsp.MapName, + originalAssetGuid: m_ImportSettings.AssetGUID ?? Guid.NewGuid().ToString(), + worldspawnObject: worldspawnScript.gameObject, + mapImportedTime: (ulong)DateTime.UtcNow.Ticks, + ids: mappings.ToArray()); + + return mapDocument; + } + + private bool TryFindParent(string parentTarget, BspEntity entity, out Transform parent) + { + if (!m_ImportSettings.TryGetGameObjectsForID(parentTarget, out List targets) || targets.Count == 0) + { + m_ImportSettings.Warn($"Could not find parent '{parentTarget}' for {entity.GetClassname()} entity '{entity.GetID()}'"); + parent = null; + return false; + } + + parent = targets[0].transform; + return true; + } + + private GameObject CreateEntityGameObject(MapBsp mapBsp, GameObject root, GameObject worldspawnObject, Transform parentTransform, BspEntity entity) + { + // Class name + string classname = entity.GetClassname(); + + if (classname.EqualsInvariant(FgdConsts.WORLDSPAWN, caseSensitive: true)) // "worldspawn" entities are just part of the world! + { + ForeachProcessor(processor => processor.ProcessWorldSpawnProperties(mapBsp, entity, root)); + return worldspawnObject; + } + + // It's a prefab? + if (m_PrefabNameLookup.IsValidAsset(classname) && m_PrefabNameLookup.TryGetPrefabPathFromMapName(classname, out string prefabPath)) + { + GameObject prefab = TrembleAssetLoader.LoadPrefabByPath(prefabPath); + m_ImportSettings.AddDependency(prefab); + + if (!prefab) + { + m_ImportSettings.Error($"Couldn't find prefab at path '{prefabPath}' for classname '{classname}'!"); + return null; + } + + bool wasActivePrefab = prefab.activeSelf; + prefab.SetActive(false); + + GameObject instance = PrefabUtil.InstantiatePrefab(prefab, parentTransform); + + if (wasActivePrefab) + { + prefab.SetActive(true); + } + + SetObjectName(root, instance, entity); + + Vector3 offset = Vector3.zero; + if (TrembleAssetLoader.TryGetAssetDataFromMapName(classname, out AssetMetadata metadata)) + { + offset = metadata.SpawnOffset; + } + else + { + Debug.LogWarning($"Could not find spawn offset for prefab '{prefab.name}'!"); + } + + SetTransformValuesFromEntity(instance, entity, offset); + ForeachProcessor(processor => processor.ProcessPrefabEntity(mapBsp, entity, instance)); + + if (wasActivePrefab) + { + instance.SetActive(true); + } + + return instance; + } + + // It's a brush or point entity + if (m_MapTypeLookup.TryGetEntityTypeFromMapName(classname, out EntityType type)) + { + if (type == EntityType.Brush) // brush entity + { + if (!entity.TryGetString("model", out string modelIdxString) || !modelIdxString.StartsWith("*")) + return null; + + int modelIdx = int.Parse(modelIdxString.Substring(1)); + string brushClass = entity.GetClassname(); + + m_MapTypeLookup.TryGetClassFromMapName(brushClass, out Type componentType); + BrushEntityAttribute bea = componentType.GetCustomAttribute(); + + Vector3 modelCentre = (mapBsp.Models[modelIdx].Min + mapBsp.Models[modelIdx].Max) * 0.5f; + + // Rotate back properly + Quaternion? rotation = null; + Quaternion? inverseRotation = null; + if (entity.TryGetRotation(FgdConsts.PROPERTY_ANGLES, out Quaternion angles)) + { + rotation = angles; + inverseRotation = Quaternion.Inverse(rotation.Value); + } + + int unityLayer = 0; + if (!bea.LayerName.IsNullOrEmpty()) + { + unityLayer = LayerMask.NameToLayer(bea.LayerName); + if (unityLayer < 0) + { + m_ImportSettings.Warn($"Could not found layer {bea.LayerName} - using Default!"); + unityLayer = 0; + } + } + + // Allow configuring a smoothing angle per brush entity. + float smoothingAngle = m_ImportSettings.SmoothingAngle; + if (TrembleSyncSettings.Get().PipelineSmoothMeshNormals) + { + // By default the smoothing pipeline acts as "_phong=1" + // Allow the official terminology to override the smoothing angle + smoothingAngle = entity.GetFloat("_phong_angle", smoothingAngle); + + // We allow inverted behaviour where users can write "_phong=0" to disable smoothing + if (entity.GetInt("_phong", 1) == 0) + { + smoothingAngle = 0f; + } + } + + // Implement a "_static=1" flag for detail brush entities that need UV2 + bool isStatic = entity.GetBoolean("_static", false); + + GameObject brush = m_MeshBuilder.BuildMesh(mapBsp, parentTransform, modelIdx, false, brushClass, false, modelCentre, isStatic, inverseRotation, smoothingAngle); + if (!brush) + { + Debug.LogError($"Discarded brush entity of class {brushClass} due to its model being degenerate!"); + return null; + } + + brush.transform.position = modelCentre; + if (rotation.HasValue) + { + brush.transform.rotation = rotation.Value; + } + + SetObjectName(root, brush, entity); + + // Find type + brush.AddComponent(componentType); + m_ImportSettings.OnEntityAdded?.Invoke(brush, componentType); + + // Modify components based on type + if (bea.BrushType is BrushType.Trigger or BrushType.Liquid) + { + // Remove the mesh renderer/filter unless liquid + if (bea.BrushType != BrushType.Liquid) + { + GameObject.DestroyImmediate(brush.GetComponent()); + GameObject.DestroyImmediate(brush.GetComponent()); + } + + // Make it a trigger instead + if (brush.TryGetComponent(out MeshCollider meshCollider)) + { + meshCollider.convex = true; + meshCollider.isTrigger = true; + } + } + + if (bea.BrushType == BrushType.Invisible) + { + // Remove the mesh renderer/filter + GameObject.DestroyImmediate(brush.GetComponent()); + GameObject.DestroyImmediate(brush.GetComponent()); + } + + // Change layer if needed + if (!bea.LayerName.IsNullOrEmpty()) + { + brush.layer = unityLayer; + } + + ForeachProcessor(processor => processor.ProcessBrushEntity(mapBsp, entity, brush)); + + return brush; + } + else // point entity + { + string pointClass = entity.GetClassname(); + if (pointClass.EqualsInvariant(TrembleConsts.MAPFIX_ENTITY_NAME, caseSensitive: true)) + { + // This point entity is used to fix map import - ignore it! + return null; + } + + GameObject pointEntity = new(pointClass); + pointEntity.transform.SetParent(parentTransform); + SetTransformValuesFromEntity(pointEntity, entity); + SetObjectName(root, pointEntity, entity); + + // Find type + if (m_MapTypeLookup.TryGetClassFromMapName(pointClass, out Type componentType)) + { + pointEntity.AddComponent(componentType); + m_ImportSettings.OnEntityAdded?.Invoke(pointEntity, componentType); + } + else + { + m_ImportSettings.Warn($"No type found for Point entity class: {pointClass} in map! Try Map Repair."); + } + + ForeachProcessor(processor => processor.ProcessPointEntity(mapBsp, entity, pointEntity)); + + return pointEntity; + } + } + + if (!classname.EqualsInvariant(TrembleConsts.MAPFIX_ENTITY_NAME, caseSensitive: true)) + { + m_ImportSettings.Warn($"No type found for entity class: {classname} in map! Try Map Repair."); + } + + return null; + } + + + // ----------------------------------------------------------------------------------------------------------------------------- + // Helpers + // ----------------------------------------------------------------------------------------------------------------------------- + private Material FindMaterial(string mapName) + { + // Have we seen this material before? + if (s_MaterialCache.TryGetValue(mapName, out Material foundMaterial) && foundMaterial) + return foundMaterial; + + // Special case: "__TB_empty" to null + if (mapName.EqualsInvariant(TBConsts.EMPTY_TEXTURE) || + mapName.ContainsInvariant(TBConsts.SKIP_TEXTURE)) + return null; + + // Special case: map "clip" to "M_NullRender" + if (mapName.ContainsInvariant(TBConsts.CLIP_TEXTURE)) + { + Material clipMaterial = TrembleAssetLoader.LoadClipMaterial(); + s_MaterialCache[mapName] = clipMaterial; + return clipMaterial; + } + + // Look it up + if (!m_MaterialNameLookup.TryGetMaterialPathFromMapName(mapName, out string materialPath)) + { +#if !UNITY_EDITOR && !UNITY_SERVER + string texturePath = Path.Combine(TrembleConsts.BASEQ3_PATH, "textures", mapName + ".png"); + if (File.Exists(texturePath)) + { + // Try to create a runtime material for loose PNG + Material looseMaterial = CreateRuntimeMaterial(texturePath); + s_MaterialCache[mapName] = looseMaterial; + return looseMaterial; + } +#endif + + if (!mapName.Contains(TBConsts.SPECIAL_TEXTURE)) + { + m_ImportSettings.Warn($"Failed to find a Unity material for {mapName}!"); + } + + return null; + } + + // Load it up + Material material = TrembleAssetLoader.LoadAssetByPath(materialPath); + if (!material) + { + m_ImportSettings.Warn($"Material at path '{materialPath}' could not be loaded!"); + return null; + } + + s_MaterialCache[mapName] = material; + return material; + } + +#if UNITY_EDITOR + public static Material CreateEditorMaterial(string textureAssetPath, float smoothness = -1f, float metallic = -1) + { + Texture2D texture = AssetDatabase.LoadAssetAtPath(textureAssetPath); + string textureName = Path.GetFileNameWithoutExtension(textureAssetPath); + + return CreateMaterial(textureName, texture, smoothness, metallic); + } +#endif + + public static Material CreateRuntimeMaterial(string pngPath, float smoothness = -1f, float metallic = -1) + { + // Load texture + byte[] textureData = File.ReadAllBytes(pngPath); + Texture2D texture = new(1, 1); + texture.LoadImage(textureData, markNonReadable: true); + + string textureName = Path.GetFileNameWithoutExtension(pngPath); + + return CreateMaterial(textureName, texture, smoothness, metallic); + } + + public static Material CreateMaterial(string textureName, Texture2D texture, float smoothness = -1f, float metallic = -1) + { + if (smoothness == -1) + { + smoothness = GetParamValue(textureName, "s", 0.5f); + } + + if (metallic == -1) + { + metallic = GetParamValue(textureName, "m", 0f); + } + + // Create material +#if URP_INSTALLED + Material m = new(Shader.Find("Universal Render Pipeline/Lit")); + m.mainTexture = texture; + m.SetFloat("_Smoothness", smoothness); + m.SetFloat("_Metallic", metallic); + return m; +#elif HDRP_INSTALLED + Material m = new(Shader.Find("HDRP/Lit")); + m.SetTexture("_BaseColorMap", texture); // Use _BaseColorMap instead of _MainTex + m.SetFloat("_Smoothness", smoothness); + m.SetFloat("_Metallic", metallic); + return m; +#else + Material m = new(Shader.Find("Standard")); + m.mainTexture = texture; + m.SetFloat("_Glossiness", smoothness); // Use _Glossiness instead of _Smoothness + m.SetFloat("_Metallic", metallic); + return m; +#endif + } + + private static float GetParamValue(string input, string param, float defaultValue) + { + string marker = $"_{param}"; + + // Find marker! + int index = input.IndexOfInvariant(marker); + if (index == -1) + return defaultValue; + + index += marker.Length; + + // Collect numbers into array + char[] buffer = new char[8]; + int bufPtr = 0; + + while (index < input.Length && bufPtr < buffer.Length && Char.IsNumber(input[index])) + { + buffer[bufPtr++] = input[index++]; + } + + // Parse to float + ReadOnlySpan strBuffer = new(buffer); + if (!strBuffer.TryParseFloat(out float value)) + return defaultValue; + + return value / 100f; + } + + private readonly StringBuilder m_NameBuilder = new(128); + + private void SetObjectName(GameObject root, GameObject go, BspEntity entity) + { + m_NameBuilder.Clear(); + + string classname = entity.GetClassname(); + m_NameBuilder.Append(classname); + m_NameBuilder.Append(' '); + + bool appendSerialNumber = true; + + string id = entity.GetID(); + if (id != null) + { + m_NameBuilder.Append('\''); + m_NameBuilder.Append(id); + m_NameBuilder.Append('\''); + + GameObject existing = root.Find_Recursive(m_NameBuilder.ToString()); + if (existing) + { + m_NameBuilder.Append(' '); + } + else + { + appendSerialNumber = false; + } + } + + if (appendSerialNumber) + { + // Append global entity counter, e.g. #12 if not named + m_NameBuilder.Append('#'); + m_NameBuilder.Append(entity.SerialNumber); + } + + go.name = m_NameBuilder.ToString(); + } + + private void SetTransformValuesFromEntity(GameObject instance, BspEntity entity) => SetTransformValuesFromEntity(instance, entity, Vector3.zero); + + private void SetTransformValuesFromEntity(GameObject instance, BspEntity entity, Vector3 offset) + { + Transform instanceTransform = instance.transform; + + // Set position + instanceTransform.position = entity.GetPosition(); + + // Set scale + if (entity.TryGetUntransformedVector(FgdConsts.PROPERTY_SCALE, out Vector3 scale)) + { + instanceTransform.localScale = scale.Q3ToUnityVector(); + } + + // Set rotation + if (entity.TryGetRotation(FgdConsts.PROPERTY_ANGLES, out Quaternion angles)) + { + instanceTransform.rotation = angles; + } + + // Finally move by offset, based on scaling and rotation + Vector3 scaledOffset = offset; + scaledOffset.Scale(instanceTransform.localScale); + instanceTransform.position += instanceTransform.rotation * scaledOffset; + +#if !UNITY_EDITOR + if (instance.TryGetComponent(out Rigidbody rb)) + { +#if UNITY_2022_1_OR_NEWER + rb.Move(instanceTransform.position, instanceTransform.rotation); +#else + rb.position = instanceTransform.position; + rb.rotation = instanceTransform.rotation; +#endif + } +#endif + } + + private void SetFieldValuesOnAllScripts(GameObject instance, BspEntity entity) + { + bool hasSetFieldValues = false; // Only set fields on first EntityAttributeBase found + + foreach (MonoBehaviour mb in instance.GetComponents()) + { + if (!mb) + { + Debug.LogWarning($"Prefab '{instance.name}' has a missing script!'"); + continue; + } + + Type scriptType = mb.GetType(); + if (!hasSetFieldValues && scriptType.IsSubclassOf(typeof(Worldspawn)) || scriptType.HasCustomAttribute()) + { + foreach (FieldInfo fi in scriptType.GetAllInstanceFieldsIncludingPrivateAndBaseClasses()) + { + SetFieldValue(entity, mb, fi); + } + + hasSetFieldValues = true; + } + } + } + + private void SetFieldValue(BspEntity entity, MonoBehaviour mb, FieldInfo target) + { + target.GetCustomAttributes(out TrembleAttribute ta, out NoTrembleAttribute nta, out SerializeField sfa, out FormerlySerializedAsAttribute fsa); + + // Work out names for this field + List knownFieldNames = new() { target.Name.GetFieldNameInMap(m_SyncSettings.FieldNamingConvention) }; + if (ta?.OverrideName != null) + { + knownFieldNames.Insert(0, ta.OverrideName); + } + + if (fsa != null) + { + knownFieldNames.Add(fsa.oldName.GetFieldNameInMap(m_SyncSettings.FieldNamingConvention)); + } + + if (ta == null && !(m_SyncSettings.SyncSerializedFields && sfa != null) && !target.IsPublic) + { + // If not public, and not [Tremble], skip! + return; + } + + if (nta != null) + { + // Specifically NOT serialised in maps - skip! + return; + } + + // Special case: Prefabs and Materials + bool isMaterialOrPrefabField = target.FieldType == typeof(Material) || target.FieldType == typeof(GameObject); + if (isMaterialOrPrefabField && ta == null && !m_SyncSettings.SyncMaterialsAndPrefabs) + { + // This is a Material or Prefab but we've turned off the setting + return; + } + + // Work out which name to use + int matchingFieldIdx = 0; + for (int knownFieldIdx = 0; knownFieldIdx < knownFieldNames.Count; knownFieldIdx++) + { + string knownFieldName = knownFieldNames[knownFieldIdx]; + if (!entity.HasKey(knownFieldName)) + continue; + + matchingFieldIdx = knownFieldIdx; + break; + } + + // Try to convert value! + string fieldName = knownFieldNames[matchingFieldIdx]; + TrembleFieldConverter converter = m_FieldConverter.GetConverterForType(target.FieldType); + + if (converter != null) + { + if (target.FieldType.IsArray) + { + // Use a converter to convert the map value + if (!converter.TryGetValuesFromMap(entity, fieldName, mb.gameObject, target, out object[] values)) + return; + + Type targetElementType = target.FieldType.GetElementType()!; + + Array filteredArray = Array.CreateInstance(targetElementType, values.Length); + for (int i = 0; i < values.Length; i++) + { + object valueAtIndex = values[i]; + if (valueAtIndex == null) + continue; + + if (targetElementType.IsAssignableFrom(valueAtIndex.GetType())) + { + filteredArray.SetValue(valueAtIndex, i); + } + else + { + Debug.LogWarning($"Element {i} of {mb.name}::{target.Name} is NOT compatible with an array of {targetElementType}s (it's a {valueAtIndex.GetType().Name}) and was skipped!"); + } + } + + target.SetValue(mb, filteredArray); + } + else + { + // Use a converter to convert the map value + if (!converter.TryGetValueFromMap(entity, fieldName, mb.gameObject, target, out object value)) + return; + + if (target.FieldType == typeof(Transform) && value is Component c) + { + value = c.transform; + } + + target.SetValue(mb, value); + } + } + else if (ta != null) + { + // Nothing worked - log an import warning + m_ImportSettings.Warn($"Saw field '{target.Name}' of type {target.FieldType}, which is not yet supported. Try adding a custom {nameof(TrembleFieldConverter)} for it, if you like!"); + } + } + + private Transform FindOrCreateGroup(MapBsp mapBsp, int groupIdx, Transform rootTransform, Transform otherEntitiesTransform) + { + // Root group, or we have no matching group + if (groupIdx == 0 || m_GroupTransforms == null || groupIdx >= m_GroupTransforms.Length) + return otherEntitiesTransform; + + // Existing - return it! + if (m_GroupTransforms[groupIdx]) + return m_GroupTransforms[groupIdx]; + + if (mapBsp.Groups[groupIdx].IsNoExport) + return null; + + // New group, create and return - but be careful not to name the same as others + string newName = $"{mapBsp.Groups[groupIdx].LabelName} #{++m_GroupCounter}"; + + GameObject group = new(newName); + group.transform.SetParent(rootTransform, false); + m_GroupTransforms[groupIdx] = group.transform; + + return m_GroupTransforms[groupIdx]; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/TrembleMapImport.cs.meta b/Assets/Tremble/TrembleMapImport.cs.meta new file mode 100644 index 0000000..9a25f2f --- /dev/null +++ b/Assets/Tremble/TrembleMapImport.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 3ce2dc4c83e14628a2248df5176356fd +timeCreated: 1715620813 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/TrembleMapImport.cs + uploadId: 939664 diff --git a/Assets/Tremble/TrembleRuntimeAPI.cs b/Assets/Tremble/TrembleRuntimeAPI.cs new file mode 100644 index 0000000..8c3efd0 --- /dev/null +++ b/Assets/Tremble/TrembleRuntimeAPI.cs @@ -0,0 +1,130 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Collections.Generic; +using System.Threading.Tasks; +using UnityEngine; + +#if ADDRESSABLES_INSTALLED +using UnityEngine.AddressableAssets; +using UnityEngine.ResourceManagement.AsyncOperations; +using System.Linq; +#endif + +namespace TinyGoose.Tremble +{ + public static class TrembleRuntimeAPI + { + public const string TREMBLE_GAME_RESOURCE = "Tremble_Game"; + public const string TREMBLE_BASEQ3_RESOURCE = "Tremble_BaseQ3"; + + private static bool s_Initialised = false; + + public static async Task Initialise() + { + if (s_Initialised) + return; + +#if ADDRESSABLES_INSTALLED && !UNITY_EDITOR + if (Addressables.ResourceLocators == null || !Addressables.ResourceLocators.Any()) + { + await Addressables.InitializeAsync().Task; + } + else + { + Debug.Log("Addressables is already initialised!"); + } +#endif + +#if !UNITY_EDITOR || USE_TYPEUTIL_IN_EDITOR + TypeDatabase.GenerateClassLookup(); +#endif + + // Only do this for PC platforms - for consoles/mobile... we need something else +#if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX + // Unpack textures/models for TB + Task unpack1 = PackedResourceUtil.UnpackResourceIntoFolder(TREMBLE_BASEQ3_RESOURCE, TrembleConsts.BASEQ3_PATH); + + // Unpack game definition for TB + Task unpack2 = PackedResourceUtil.UnpackResourceIntoFolder(TREMBLE_GAME_RESOURCE, TrenchBroomUtil.GetGameFolder()); + + await Task.WhenAll(unpack1, unpack2); + + // Write engine path into TB + await TrenchBroomUtil.WriteEnginePathIntoTrenchBroomPrefs(); +#endif + + s_Initialised = true; + } + + public static void DestroyAllExistingMaps() + { +#if UNITY_6000_5_OR_NEWER + MapDocument[] maps = GameObject.FindObjectsByType(FindObjectsInactive.Include); +#elif UNITY_2022_1_OR_NEWER + MapDocument[] maps = GameObject.FindObjectsByType(FindObjectsInactive.Include, FindObjectsSortMode.None); +#else + MapDocument[] maps = GameObject.FindObjectsOfType(true); +#endif + foreach (MapDocument map in maps) + { + GameObject.Destroy(map.gameObject); + } + } + + public static async Task LoadMapAsync(string mapFile, MapProcessorClass[] processors = null, bool outputErrorsAndWarnings = false, float? maxMeshSurfaceArea = null, float? smoothingAngle = null) + { + if (!s_Initialised) + { + Debug.Log("TrembleRuntimeAPI was not initialised - doing that now. Call TrembleRuntimeAPI.Initialise() somewhere during game launch to avoid hitches!"); + await Initialise(); + } + + MapBsp mapBsp = await PreloadResourcesForMapAsync(mapFile); + + Q3Map2Result? overrideResult = null; + + TrembleMapImport importer = new(new() + { + ProcessorClasses = processors, + + SplitMesh = maxMeshSurfaceArea.HasValue, + MaxMeshSurfaceArea = maxMeshSurfaceArea.GetValueOrDefault(0f), + SmoothingAngle = smoothingAngle.GetValueOrDefault(359f), + + OnError = outputErrorsAndWarnings ? Debug.LogError : null, + OnWarning = outputErrorsAndWarnings ? Debug.LogWarning : null, + OnQ3Map2Result = (r, _) => overrideResult = r + }); + + MapDocument document = await importer.ImportMapAndCreatePrefab(mapFile, mapBsp); + if (overrideResult.HasValue) + { + document.INTERNAL_SetResult(overrideResult.Value, overrideResult.ToString()); + } + return document; + } + + public static async Task PreloadResourcesForMapAsync(string mapFile) + { + if (!TrembleAssetLoader.SupportsPreloading) + return null; + + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + + MapBsp mapBsp = MapCompiler.BuildBsp(syncSettings, mapFile, syncSettings.ExtraCommandLineArgs, out Q3Map2Result result); + + if (result == Q3Map2Result.Failed) + return null; + + List pathsToPreload = new(128); + mapBsp.GatherResourceList(pathsToPreload); + + await TrembleAssetLoader.PreloadAssetsByPaths(pathsToPreload); + + return mapBsp; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/TrembleRuntimeAPI.cs.meta b/Assets/Tremble/TrembleRuntimeAPI.cs.meta new file mode 100644 index 0000000..286fd70 --- /dev/null +++ b/Assets/Tremble/TrembleRuntimeAPI.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: b995a47ec2514247a717fac9b66cd034 +timeCreated: 1715764021 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/TrembleRuntimeAPI.cs + uploadId: 939664 diff --git a/Assets/Tremble/TrembleSyncSettings.cs b/Assets/Tremble/TrembleSyncSettings.cs new file mode 100644 index 0000000..c6ff44e --- /dev/null +++ b/Assets/Tremble/TrembleSyncSettings.cs @@ -0,0 +1,400 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using System.IO; +using System.Reflection; + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace TinyGoose.Tremble +{ + public enum TrenchBroomVersion + { + Version2023_1, + Version2024_1, + Version2024_2, + Version2025_3, + Version2026_1, + VersionNext, + } + + public enum NamingConvention + { + SnakeCase, + UpperCamelCase, + LowerCamelCase, + PreserveExact, + HumanFriendly, + } + + public enum Q3Map2ResultDisplayType + { + NeverShow, + ShowWhenWarningsOccur, + AlwaysShow + } + + public enum FgdFormattingStyle + { + Fast, + HumanReadable, + VeryVerbose + } + + public enum EntityIconStyle + { + Nothing, + ColouredDiamondShapes, + ColouredLabels, + } + + public enum PrefabOverrideHandling + { + AllowOverrides, + WarnOnOverridesFound, + AutomaticallyRevert + } + + [Serializable] + public struct MapProcessorEntry + { + public MapProcessorClass Class; + public bool Enabled; + } + + [Serializable] + public struct MaterialGroup + { + public string Name; + public Material[] Materials; + + public static MaterialGroup CreateDefault() + { + return new() + { + Name = "game", + Materials = TrembleAssetLoader.FindAssetPaths() + .Where(p => Path.GetExtension(p).EqualsInvariant(".mat")) + .Where(p => !p.ContainsInvariant("M_NullRender")) + .Select(TrembleAssetLoader.LoadAssetByPath) + .ToArray() + }; + } + } + + [Serializable] + public struct AssetMetadata + { + public string MapName; + public string Path; + public string FullTypeName; + +#if ADDRESSABLES_INSTALLED + public string AddressableName; +#endif + + public Vector3 SpawnOffset; + } + + public class TrembleSyncSettings : ScriptableObject + { +#if ADDRESSABLES_INSTALLED + public const string ADDRESSABLE_KEY = "TrembleSyncSettings"; +#endif + + // ----------------------------------------------------------------------------------------------------------------------------- + // Singleton + // ----------------------------------------------------------------------------------------------------------------------------- + private static TrembleSyncSettings s_TrembleSyncSettings; + public static TrembleSyncSettings Get(bool createIfNotExists = true) + { + // Return cached? + if (s_TrembleSyncSettings) + return s_TrembleSyncSettings; + + // Load & cache if possible + s_TrembleSyncSettings = TrembleAssetLoader.LoadSyncSettings(); + if (s_TrembleSyncSettings || !createIfNotExists) + return s_TrembleSyncSettings; + + // Return, or create temporary + s_TrembleSyncSettings = CreateInstance(); +#if UNITY_EDITOR + AssetDatabase.CreateAsset(s_TrembleSyncSettings, Path.Combine("Assets", "Tremble Sync Settings.asset")); +#endif + return s_TrembleSyncSettings; + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Basic Settings + // ----------------------------------------------------------------------------------------------------------------------------- + [SerializeField, Tooltip("Automagically keep project in-sync with TrenchBroom when compiling sources? Turn off if this is slow for your project.")] + private bool m_AutoSyncOnCompile = true; + + [SerializeField, Tooltip("(Experimental!) Allow importing of maps in standalone/retail builds? Requires the Addressables package. Tremble will add Addressable Groups for your materials and entity prefabs to support in-game import, and will package up your entities.fgd and baseq3 data into your game.")] + private bool m_AllowStandaloneImport = false; + + [SerializeField, Tooltip("TrenchBroom Version (2023 = GameConfig v4, 2024_1 = GameConfig v8, 2024_2, 2025_3 = GameConfig v9).")] + private TrenchBroomVersion m_TrenchBroomVersion = TrenchBroomVersion.Version2026_1; + + public bool IsTrenchBroomVersionAtLeast(TrenchBroomVersion version) => (int)m_TrenchBroomVersion >= (int)version; + + [SerializeField, Tooltip("The map to use as a template when creating new ones. Leave blank to generate an empty map.")] + private GameObject m_TemplateMap = null; + + [SerializeField, Tooltip("The Worldspawn script to use. Use this to set map-wide variables (such as difficulty level, etc.). This affects all maps in your game.")] + private WorldspawnScript m_WorldspawnScript; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Naming Conventions + // ----------------------------------------------------------------------------------------------------------------------------- + [SerializeField, Tooltip("The naming convention to use for entity classes.")] + private NamingConvention m_TypeNamingConvention = NamingConvention.PreserveExact; + + [SerializeField, Tooltip("The naming convention to use for variables in TrenchBroom.")] + private NamingConvention m_FieldNamingConvention = NamingConvention.SnakeCase; + + [SerializeField, Tooltip("The naming convention to use for SpawnFlag variables in TrenchBroom.")] + private NamingConvention m_SpawnFlagNamingConvention = NamingConvention.HumanFriendly; + + [SerializeField, Tooltip("The naming convention to use for materials in TrenchBroom.")] + private NamingConvention m_MaterialNamingConvention = NamingConvention.PreserveExact; + + [SerializeField, Tooltip("The name of the property used to identify entities")] + private string m_IdentityPropertyName = "targetname"; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Material Settings + // ----------------------------------------------------------------------------------------------------------------------------- + [SerializeField, Tooltip("How to export materials into groups. Leave the group list blank to export ALL materials in the project.")] + private MaterialGroup[] m_MaterialGroups = Array.Empty(); + //TODO(jwf): move into MRD below! + + [SerializeField, Tooltip("Render settings for materials")] + private List m_MaterialRenderData = new(); + + + // ----------------------------------------------------------------------------------------------------------------------------- + // Pipeline Settings + // ----------------------------------------------------------------------------------------------------------------------------- + [SerializeField, Tooltip("Split mesh into smaller meshes for better rendering performance? Turn off if not needed or too slow.")] + private bool m_PipelineSplitMesh = true; + + [SerializeField, Tooltip("Smooth mesh normals based on map settings? Turn off for more of a low-poly aesthetic.")] + private bool m_PipelineSmoothMeshNormals = true; + + [SerializeField, Tooltip("Simplify collisions to increase runtime performance? Turn off if your meshes don't need this.")] + private bool m_PipelineSimplifyCollisionMeshes = true; + + [SerializeField, Tooltip("Unwrap UV2 so that meshes can be lightmapped? Turn off if your project doesn't use lightbaking.")] + private bool m_PipelineUnwrapUV2 = true; + + [SerializeField, Tooltip("Run project-wide map processors? Per-map map processors are always run.")] + private bool m_PipelineRunMapProcessors = true; + + [SerializeField, Tooltip("Which custom map processors to run. Use Unity 2022+ to enable a better UI for this!")] + private MapProcessorEntry[] m_MapProcessors; + + + // ----------------------------------------------------------------------------------------------------------------------------- + // Advanced Settings + // ----------------------------------------------------------------------------------------------------------------------------- + [SerializeField, Tooltip("Print debug info when syncing and importing?")] + private bool m_LogOnImportAndSync = false; + + [SerializeField, Tooltip("Allow live updating of maps while in playmode? Not all changes are supported.")] + private bool m_UseLiveUpdate = true; + + [SerializeField, Tooltip("Whether to reimport maps when prefabs/materials inside them change?")] + private bool m_AutomaticallyReimportWhenDependencyChanges = true; + + [SerializeField, Tooltip("Which kind of gizmos to add to Entities in editor?")] + private EntityIconStyle m_EntityIconStyle = EntityIconStyle.ColouredDiamondShapes; + + [SerializeField, Tooltip("Allow prefab overrides on maps? This can cause hard-to-debug issues with materials and field values - but change this if you have a legitimate reason to use overrides (and know what you're doing!)")] + private PrefabOverrideHandling m_PrefabOverrideHandling = PrefabOverrideHandling.AutomaticallyRevert; + + [SerializeField, Tooltip("Use class Quake-style culling? This removes all areas inaccessible by point entities, including exteriors. Maps without point/prefabs entities may import blank!")] + private bool m_UseClassicQuakeCulling = false; + + [SerializeField, Tooltip("Under which circumstances would you like to see the output from Q3Map2? This can be used to debug map issues.")] + private Q3Map2ResultDisplayType m_Q3Map2ResultDisplayType = Q3Map2ResultDisplayType.ShowWhenWarningsOccur; + + [SerializeField, Tooltip("When writing the entities.fgd file for TrenchBroom, how should it be formatted? Very Verbose will be much slower to parse but great for debugging issues manually. We recommend Human Readable.")] + private FgdFormattingStyle m_FgdFormattingStyle = FgdFormattingStyle.HumanReadable; + + [SerializeField, Tooltip("Subdivide worldspawn mesh down to the leaf level, ignoring surface area? This could be faster but less efficient at runtime.")] + private bool m_SubdivideAllLeafs; + + [SerializeField, Tooltip("Always pack booleans into spawnflags? If off, booleans will separately appear as 0 or 1 values. You can use [SpawnFlags] or [NoSpawnFlags] to override this on a per-field basis.")] + private bool m_AlwaysPackBoolsIntoSpawnFlags = true; + + [SerializeField, Tooltip("Show enum values as strings in TrenchBroom? Turn off to use ints, which is faster but a bit more clunky to work with.")] + private bool m_SyncEnumsAsStringValue = true; + + [SerializeField, Tooltip("Show all [SerializeField]s in TrenchBroom by default? Use [NoTremble] to override this on a per-field basis, or [Tremble] to mark fields as map-serialisable.")] + private bool m_SyncSerializedFields = true; + + [SerializeField, Tooltip("Automatically sync Unity Prefab and Material properties by default? Use [NoTremble] to override this on a per-field basis, or [Tremble] to mark fields as map-serialisable.")] + private bool m_SyncMaterialsAndPrefabs = true; + + [SerializeField, Tooltip("The Unity layer to place Worldspawn brushes on.")] + private string m_WorldspawnLayer = "Default"; + + [SerializeField, Tooltip("Flatten entities and brushes instead of using the groups that were seen in the map?")] + private bool m_DiscardMapGroups = false; + + [SerializeField, Tooltip("The name for the 'worldspawn' brush GameObject(s) in Unity.")] + private string m_MainMeshName = "worldspawn"; + + [SerializeField, Tooltip("Automagically remove TrenchBroom's autosave backups when syncing?")] + private bool m_AutoDeleteMapBackups = false; + + [SerializeField, Tooltip("Extra commandline args to pass to Q3Map2 - see https://en.wikibooks.org/wiki/Q3Map2 for more info.")] + private string m_ExtraCommandLineArgs = "-threads 8 -meta -v"; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Advanced Materials + // ----------------------------------------------------------------------------------------------------------------------------- + [SerializeField, Tooltip("Determines the base render resolution for materials rendering with Legacy Mode. PLEASE NOTE: Changing this size will affect UVing on your existing maps!")] + private MaterialExportSize m_MaterialExportSize = MaterialExportSize.Size512; + + [SerializeField, Tooltip("The light intensity to use when capturing materials (default = 0.5)"), Range(0f, 1f)] + private float m_MaterialCaptureLightIntensity = 0.5f; + + [SerializeField, Tooltip("The light angle to use when capturing materials. 0.0 means a perpendicular light, 1.0 means a parallel light. Purely parallel lights can 'blow out' materials with low roughness, but purely perpendicular lights will not illuminate your materials well. (default = 0.75)"), Range(0f, 1f)] + private float m_MaterialCaptureLightAngle = 0.75f; + + [SerializeField, Tooltip("Export clip and skip textures?")] + private bool m_ExportClipSkipTextures = true; + + + // ----------------------------------------------------------------------------------------------------------------------------- + // Import Scale + // ----------------------------------------------------------------------------------------------------------------------------- + [SerializeField, Tooltip("The scaling to use when importing maps. Default is 0.015625.")] + private float m_ImportScale = 1f / 64f; + + + + // ----------------------------------------------------------------------------------------------------------------------------- + // Addressables metadata storage + // ----------------------------------------------------------------------------------------------------------------------------- + [SerializeField] private AssetMetadata[] m_AssetMetadatas = null; + + public AssetMetadata[] AssetMetadatas + { + get => m_AssetMetadatas; +#if UNITY_EDITOR + set => m_AssetMetadatas = value; +#endif + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Public API + // ----------------------------------------------------------------------------------------------------------------------------- + // Basic Settings + public bool AutoSyncOnCompile => m_AutoSyncOnCompile; + public bool AllowStandaloneImport => m_AllowStandaloneImport; + public TrenchBroomVersion TrenchBroomVersion => m_TrenchBroomVersion; + public string TrenchBroomGameConfigVersion => TrenchBroomVersion switch + { + TrenchBroomVersion.Version2023_1 => "4", + TrenchBroomVersion.Version2024_1 => "8", + TrenchBroomVersion.Version2024_2 => "9", + TrenchBroomVersion.Version2025_3 => "9", + TrenchBroomVersion.Version2026_1 => "9", + TrenchBroomVersion.VersionNext => "9", + _ => "0" + }; + public GameObject TemplateMap => m_TemplateMap; + public WorldspawnScript WorldspawnScript => m_WorldspawnScript; + + // Naming Convention + public NamingConvention TypeNamingConvention => m_TypeNamingConvention; + public NamingConvention FieldNamingConvention => m_FieldNamingConvention; + public NamingConvention SpawnFlagNamingConvention => m_SpawnFlagNamingConvention; + public NamingConvention MaterialNamingConvention => m_MaterialNamingConvention; + public string IdentityPropertyName => m_IdentityPropertyName; + + // Material Settings + public MaterialGroup[] MaterialGroups => m_MaterialGroups; + + public List GetMaterialGroupsOrDefault() + { + List materialGroups = new(); + if (m_MaterialGroups is { Length: > 0 }) + { + materialGroups.AddRange(m_MaterialGroups); + } + else + { + materialGroups.Add(MaterialGroup.CreateDefault()); + } + + return materialGroups; + } + + public MaterialRenderData GetMaterialRenderData(Material material) + { + MaterialRenderData existing = m_MaterialRenderData.FirstOrDefault(mrd => mrd.Material == material); + if (existing == null) + { + existing = new(material); + m_MaterialRenderData.Add(existing); + } + + return existing; + } + + // Pipeline Settings + public bool PipelineSplitMesh => m_PipelineSplitMesh; + public bool PipelineSmoothMeshNormals => m_PipelineSmoothMeshNormals; + + public bool PipelineSimplifyCollisionMeshes => m_PipelineSimplifyCollisionMeshes; + + public bool PipelineUnwrapUV2 => m_PipelineUnwrapUV2; + public bool PipelineRunMapProcessors => m_PipelineRunMapProcessors; + public MapProcessorEntry[] MapProcessors => m_MapProcessors; + public MapProcessorClass[] EnabledMapProcessors => m_MapProcessors == null ? Array.Empty() : m_MapProcessors.Where(mp => mp.Enabled).Select(mp => mp.Class).ToArray(); + + + // Advanced Settings + public bool LogOnImportAndSync => m_LogOnImportAndSync; + public bool UseLiveUpdate => m_UseLiveUpdate; + public bool AutomaticallyReimportWhenDependencyChanges => m_AutomaticallyReimportWhenDependencyChanges; + public EntityIconStyle EntityIconStyle => m_EntityIconStyle; + public PrefabOverrideHandling PrefabOverrideHandling => m_PrefabOverrideHandling; + public bool UseClassicQuakeCulling => m_UseClassicQuakeCulling; + public Q3Map2ResultDisplayType Q3Map2ResultDisplayType => m_Q3Map2ResultDisplayType; + public FgdFormattingStyle FgdFormattingStyle => m_FgdFormattingStyle; + public bool SubdivideAllLeafs => m_SubdivideAllLeafs; + public bool AlwaysPackBoolsIntoSpawnFlags => m_AlwaysPackBoolsIntoSpawnFlags; + public bool SyncEnumsAsStringValue => m_SyncEnumsAsStringValue; + public bool SyncSerializedFields => m_SyncSerializedFields; + public bool SyncMaterialsAndPrefabs => m_SyncMaterialsAndPrefabs; + public string WorldspawnLayer => m_WorldspawnLayer; + public bool DiscardMapGroups => m_DiscardMapGroups; + public string MainMeshName => m_MainMeshName; + public bool AutoDeleteMapBackups => m_AutoDeleteMapBackups; + public string ExtraCommandLineArgs => m_ExtraCommandLineArgs; + + // Advanced materials + public MaterialExportSize MaterialExportSize => m_MaterialExportSize; + public float MaterialCaptureLightIntensity => m_MaterialCaptureLightIntensity; + public float MaterialCaptureLightAngle => m_MaterialCaptureLightAngle; + + public bool ExportClipSkipTextures => m_ExportClipSkipTextures; + + // Prefixes and Import Scale + public float ImportScale => m_ImportScale; + } +} \ No newline at end of file diff --git a/Assets/Tremble/TrembleSyncSettings.cs.meta b/Assets/Tremble/TrembleSyncSettings.cs.meta new file mode 100644 index 0000000..01c1433 --- /dev/null +++ b/Assets/Tremble/TrembleSyncSettings.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 4a88c8a3ff11450b94453ed26fba8f5c +timeCreated: 1699378582 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/TrembleSyncSettings.cs + uploadId: 939664 diff --git a/Assets/Tremble/TypeLookups.meta b/Assets/Tremble/TypeLookups.meta new file mode 100644 index 0000000..79eaaf2 --- /dev/null +++ b/Assets/Tremble/TypeLookups.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 328e476649af54e1081822c2fac89266 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tremble/TypeLookups/MapTypeLookup.cs b/Assets/Tremble/TypeLookups/MapTypeLookup.cs new file mode 100644 index 0000000..65a0f04 --- /dev/null +++ b/Assets/Tremble/TypeLookups/MapTypeLookup.cs @@ -0,0 +1,94 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace TinyGoose.Tremble +{ + public class MapTypeLookup + { + public MapTypeLookup(TrembleSyncSettings syncSettings) + { + m_TypeNamingConvention = syncSettings.TypeNamingConvention; + + GenerateLookup(); + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Setup + // ----------------------------------------------------------------------------------------------------------------------------- + private readonly NamingConvention m_TypeNamingConvention; + + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private readonly Dictionary m_MapNameToClass = new(); + private readonly Dictionary m_MapNameToEntityType = new(); + private readonly Dictionary m_TypeToMapName = new(); + + public IEnumerable AllTypes => m_TypeToMapName.Keys; + + public bool TryGetClassFromMapName(string mapName, out Type foundType) + { + return m_MapNameToClass.TryGetValue(mapName, out foundType); + } + public bool TryGetEntityTypeFromMapName(string mapName, out EntityType foundType) + { + return m_MapNameToEntityType.TryGetValue(mapName, out foundType); + } + public bool TryGetMapNameFromClass(Type type, out string foundName) + { + return m_TypeToMapName.TryGetValue(type, out foundName); + } + + private void GenerateLookup() + { + foreach (Type type in TypeDatabase.GetTypesWithAttribute()) + { + if (type == typeof(TrembleSpawnablePrefab)) + continue; + + EntityAttributeBase attribute = type.GetCustomAttribute(); + string baseName = attribute.TrenchBroomName ?? type.Name.ToNamingConvention(m_TypeNamingConvention); + + if (attribute is BrushEntityAttribute { BrushType: BrushType.Trigger } + && !baseName.ContainsInvariant("trigger") + && (attribute.Category == null || !attribute.Category.ContainsInvariant("trigger"))) + { + UnityEngine.Debug.LogWarning($"Brush Entity of type '{type.Name}' is marked as a trigger. Consider adding 'trigger' into the name '{baseName}' so that TrenchBroom renders it appropriately."); + } + + try + { + switch (attribute) + { + case PointEntityAttribute: + string pointPrefix = attribute.Category ?? FgdConsts.POINT_PREFIX; + string fullPointName = (pointPrefix.Length == 0) ? baseName : $"{pointPrefix}_{baseName}"; + + m_MapNameToClass.Add(fullPointName, type); + m_MapNameToEntityType.Add(fullPointName, EntityType.Point); + m_TypeToMapName.Add(type, fullPointName); + break; + case BrushEntityAttribute: + string brushPrefix = attribute.Category ?? FgdConsts.BRUSH_PREFIX; + string fullBrushName = (brushPrefix.Length == 0) ? baseName : $"{brushPrefix}_{baseName}"; + + m_MapNameToClass.Add(fullBrushName, type); + m_MapNameToEntityType.Add(fullBrushName, EntityType.Brush); + m_TypeToMapName.Add(type, fullBrushName); + break; + } + } + catch (ArgumentException) + { + UnityEngine.Debug.LogError($"Type '{type.Name}' or name '{baseName}' already used!}}"); + } + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/TypeLookups/MapTypeLookup.cs.meta b/Assets/Tremble/TypeLookups/MapTypeLookup.cs.meta new file mode 100644 index 0000000..94591a0 --- /dev/null +++ b/Assets/Tremble/TypeLookups/MapTypeLookup.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: e34c8bfb658a448d8979c62b58a61b90 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/TypeLookups/MapTypeLookup.cs + uploadId: 939664 diff --git a/Assets/Tremble/TypeLookups/MaterialNameLookup.cs b/Assets/Tremble/TypeLookups/MaterialNameLookup.cs new file mode 100644 index 0000000..2ea42ee --- /dev/null +++ b/Assets/Tremble/TypeLookups/MaterialNameLookup.cs @@ -0,0 +1,107 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Collections.Generic; +using System.IO; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public class MaterialNameLookup + { + public MaterialNameLookup(TrembleSyncSettings syncSettings) + { + m_NamingConvention = syncSettings.MaterialNamingConvention; + +#if UNITY_EDITOR + GenerateLookup(syncSettings); +#endif + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private readonly NamingConvention m_NamingConvention; + + private readonly TwoWayDictionary m_MapNameToMaterialPath = new(); + + public IEnumerable AllMaterialPaths => m_MapNameToMaterialPath.Values; + + public bool TryGetMaterialPathFromMapName(string mapName, out string foundMaterialPath) + { +#if !UNITY_EDITOR + if (TrembleAssetLoader.TryGetAssetDataFromMapName(mapName, out AssetMetadata data)) + { + foundMaterialPath = data.Path; + return true; + } + + foundMaterialPath = mapName; + return false; +#else + Debug.Assert(m_MapNameToMaterialPath != null, nameof(m_MapNameToMaterialPath) + " != null"); + return m_MapNameToMaterialPath.TryGetValue(mapName, out foundMaterialPath); +#endif + } + public bool TryGetMapNameFromMaterialPath(string materialPath, out string foundName) + { + Debug.Assert(m_MapNameToMaterialPath != null, nameof(m_MapNameToMaterialPath) + " != null"); + return m_MapNameToMaterialPath.TryGetKey(materialPath, out foundName); + } + + public string GetPrefabNameFromMaterialPath(string materialPath) + { + string mapName = Path.GetFileNameWithoutExtension(materialPath); + + if (m_NamingConvention != NamingConvention.PreserveExact && mapName.StartsWith("M_")) + { + mapName = mapName.Substring(2); + } + + return mapName.ToNamingConvention(m_NamingConvention); + } + +#if UNITY_EDITOR + private void GenerateLookup(TrembleSyncSettings syncSettings) + { + foreach (MaterialGroup mg in syncSettings.GetMaterialGroupsOrDefault()) + { + foreach (Material mat in mg.Materials) + { + if (!mat) + continue; + + string materialPath = TrembleAssetLoader.GetPath(mat); + string mapName = mat.name; + + if (m_NamingConvention != NamingConvention.PreserveExact && mapName.StartsWith("M_")) + { + if (mapName.StartsWith("M_")) + { + mapName = mapName.Substring(2); + } + } + + mapName = mapName.ToNamingConvention(m_NamingConvention); + + // Replace spaces with underscores + mapName = mapName.Sanitise(new() { ' ' }, '_'); + + // Prepend group name + mapName = mg.Name + "/" + mapName; + + // Already seen, and this is not a .mat - skip + if (m_MapNameToMaterialPath.ContainsValue(mapName) && !materialPath.EndsWith(".mat")) + { + continue; + } + + m_MapNameToMaterialPath[mapName] = materialPath; + } + } + } +#endif + } +} \ No newline at end of file diff --git a/Assets/Tremble/TypeLookups/MaterialNameLookup.cs.meta b/Assets/Tremble/TypeLookups/MaterialNameLookup.cs.meta new file mode 100644 index 0000000..eafe748 --- /dev/null +++ b/Assets/Tremble/TypeLookups/MaterialNameLookup.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 4e4e764a2eb96413e95877bace55f05d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/TypeLookups/MaterialNameLookup.cs + uploadId: 939664 diff --git a/Assets/Tremble/TypeLookups/PrefabNameLookup.cs b/Assets/Tremble/TypeLookups/PrefabNameLookup.cs new file mode 100644 index 0000000..8d6f550 --- /dev/null +++ b/Assets/Tremble/TypeLookups/PrefabNameLookup.cs @@ -0,0 +1,177 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEngine; + +#if UNITY_EDITOR +using System.Text; +using UnityEditor; +#endif + +namespace TinyGoose.Tremble +{ + public class PrefabNameLookup + { + public PrefabNameLookup(TrembleSyncSettings syncSettings) + { + m_SyncSettings = syncSettings; + +#if UNITY_EDITOR + GenerateLookup(); +#endif + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Setup + // ----------------------------------------------------------------------------------------------------------------------------- + private readonly TrembleSyncSettings m_SyncSettings; + + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private readonly TwoWayDictionary m_PrefabPathToMapName = new(); + + public bool TryGetPrefabPathFromMapName(string mapName, out string foundName) + { +#if !UNITY_EDITOR + if (TrembleAssetLoader.TryGetAssetDataFromMapName(mapName, out AssetMetadata data)) + { + foundName = data.Path; + return true; + } + + foundName = mapName; + return false; +#else + Debug.Assert(m_PrefabPathToMapName != null, nameof(m_PrefabPathToMapName) + " != null"); + return m_PrefabPathToMapName.TryGetKey(mapName, out foundName); +#endif + } + public bool TryGetMapNameFromPrefabPath(string prefabPath, out string foundName) + { + Debug.Assert(m_PrefabPathToMapName != null, nameof(m_PrefabPathToMapName) + " != null"); + return m_PrefabPathToMapName.TryGetValue(prefabPath, out foundName); + } + + public bool IsValidAsset(string mapName) + { + return TrembleAssetLoader.TryGetAssetDataFromMapName(mapName, out _); + } + + public List AllPrefabPaths => m_PrefabPathToMapName.Keys.ToList(); + +#if UNITY_EDITOR + private void GenerateLookup() + { + foreach (string prefabEntityPath in TrembleAssetLoader.FindAssetPaths()) + { + GameObject asset = TrembleAssetLoader.LoadPrefabByPath(prefabEntityPath); + if (!asset) + continue; + + // Work out prefix/name for this prefab + string prefix = FgdConsts.PREFAB_PREFIX; + + string mapName = Path.GetFileNameWithoutExtension(prefabEntityPath); + mapName = mapName.Sanitise(new() { '{', '}', ' ', '[', ']', '"', '\'', '.', ',' }); + + if (m_SyncSettings.TypeNamingConvention != NamingConvention.PreserveExact && mapName.StartsWithInvariant("P_", caseSensitive: true)) + { + mapName = mapName.Substring(2); + } + + mapName = mapName.ToNamingConvention(m_SyncSettings.TypeNamingConvention); + + bool isExportedType = false; + + if (asset.TryGetComponent(out TrembleSpawnablePrefab spawnablePrefab)) + { + if (!spawnablePrefab.Category.IsNullOrEmpty()) + { + prefix = spawnablePrefab.Category; + } + + isExportedType = !spawnablePrefab.OnlyVariants || EDITOR_IsVariant(asset); + } + else + { + foreach (MonoBehaviour component in asset.GetComponents()) + { + if (!component) + { + Debug.LogWarning($"Missing component on prefab {asset.name}!", asset); + continue; + } + + if (!component.GetType().TryGetCustomAttribute(out PrefabEntityAttribute pea)) + continue; + + if (pea.Category != null) + { + prefix = pea.Category; + } + + if (pea.TrenchBroomName != null) + { + mapName = pea.TrenchBroomName; + } + + isExportedType = !pea.OnlyVariants || EDITOR_IsVariant(asset); + + break; + } + } + + if (!isExportedType) + continue; + + if (!mapName.StartsWithInvariant(prefix, caseSensitive: true)) + { + mapName = prefix + "_" + mapName; + } + + try + { + m_PrefabPathToMapName.Add(prefabEntityPath, mapName); + } + catch (ArgumentException) + { + Debug.LogError($"Prefab path '{prefabEntityPath}' or map name '{mapName}' already used!}}"); + } + } + } +#endif + +#if UNITY_EDITOR + private bool EDITOR_IsVariant(GameObject asset) + { + // Not a variant - don't export! + if (PrefabUtility.GetPrefabAssetType(asset) != PrefabAssetType.Variant) + return false; + + // It's a variant - check first if the parent is a regular prefab or + // a variant of a prefab... i.e. NOT a model prefab. + GameObject parent = PrefabUtility.GetCorrespondingObjectFromSource(asset); + if (parent) + { + PrefabAssetType parentType = PrefabUtility.GetPrefabAssetType(parent); + return parentType switch + { + PrefabAssetType.Regular => true, + PrefabAssetType.Variant => true, + + _ => false + }; + } + + return true; + } +#endif + } +} \ No newline at end of file diff --git a/Assets/Tremble/TypeLookups/PrefabNameLookup.cs.meta b/Assets/Tremble/TypeLookups/PrefabNameLookup.cs.meta new file mode 100644 index 0000000..cc5b7e1 --- /dev/null +++ b/Assets/Tremble/TypeLookups/PrefabNameLookup.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 8632018739db74abc82c2fc22b75b1c6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/TypeLookups/PrefabNameLookup.cs + uploadId: 939664 diff --git a/Assets/Tremble/Types.meta b/Assets/Tremble/Types.meta new file mode 100644 index 0000000..74b3e46 --- /dev/null +++ b/Assets/Tremble/Types.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 695a9db014e645699a42e8fa372eb9c4 +timeCreated: 1704198631 \ No newline at end of file diff --git a/Assets/Tremble/Types/BspTypes.cs b/Assets/Tremble/Types/BspTypes.cs new file mode 100644 index 0000000..47d7622 --- /dev/null +++ b/Assets/Tremble/Types/BspTypes.cs @@ -0,0 +1,306 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public record BspOptions(float UV2Padding = 0.02f); + + public class MapBsp + { + public string MapName { get; init; } + public float ImportScale { get; init; } + + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + public TexInfo[] TexInfos { get; init; } + public Plane[] Planes { get; init; } + public BspNode[] Nodes { get; init; } + public BspLeaf[] Leaves { get; init; } + public int[] LeafFaces { get; init; } + public bool[] UsedFaces { get; init; } + + public BspModel[] Models { get; init; } + public BspVertex[] Vertices { get; init; } + public BspFace[] Faces { get; init; } + public int[] MeshVertices { get; init; } + + public List Entities { get; init; } + + public BspOptions Options { get; init; } + + public MapGroupData[] Groups { get; init; } + + public void GatherResourceList(List outPaths) + { + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + + MaterialNameLookup materialNameLookup = new(syncSettings); + PrefabNameLookup prefabNameLookup = new(syncSettings); + + GatherResourceList(materialNameLookup, prefabNameLookup, outPaths); + } + + public void GatherResourceList(MaterialNameLookup materialNameLookup, PrefabNameLookup prefabNameLookup, List outPaths) + { + foreach (TexInfo texInfo in TexInfos) + { + if (!materialNameLookup.TryGetMaterialPathFromMapName(texInfo.Name, out string materialPath)) + continue; + + outPaths.Add(materialPath); + } + + foreach (BspEntity entity in Entities) + { + if (!prefabNameLookup.TryGetPrefabPathFromMapName(entity.GetClassname(), out string prefabPath)) + continue; + + outPaths.Add(prefabPath); + } + } + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Map Types + // ----------------------------------------------------------------------------------------------------------------------------- + public readonly struct MapGroupData + { + public string Name { get; init; } + public bool IsNoExport { get; init; } + public bool IsLayer { get; init; } + + public string LabelName => (IsLayer ? "layer: " : "group: ") + Name; + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // BSPTypes + // ----------------------------------------------------------------------------------------------------------------------------- + public readonly struct BspEntity : IEquatable + { + public int SerialNumber { get; init; } + public Dictionary Entries { get; init; } + public float ImportScale { get; init; } + + public bool Equals(BspEntity other) + { + return other.SerialNumber == SerialNumber; + } + + public override bool Equals(object obj) + { + return obj is BspEntity other && Equals(other); + } + + public override int GetHashCode() + { + return SerialNumber; + } + + public static bool operator ==(BspEntity left, BspEntity right) + { + return left.Equals(right); + } + + public static bool operator !=(BspEntity left, BspEntity right) + { + return !left.Equals(right); + } + } + + public readonly struct TexInfo + { + public string Name { get; init; } + public int Flags { get; init; } + public int Contents { get; init; } + } + + public readonly struct BspVertex + { + public Vector3 Position { get; init; } + public Vector3 Normal { get; init; } + public Color32 Color { get; init; } + public Vector2 TexCoord { get; init; } + public Vector2 LightmapCoord { get; init; } + } + + public readonly struct BspFace + { + public int TexID { get; init; } + public int Effect { get; init; } + public int Type { get; init; } // 1=polygon, 2=patch, 3=mesh, 4=billboard + + public int VertexStartIdx { get; init; } + public int NumVertices { get; init; } + + public int MeshVertexStartIdx { get; init; } + public int NumMeshVertices { get; init; } + + public int LightmapIndex { get; init; } + public Vector2Int LightmapStart { get; init; } + public Vector2Int LightmapSize { get; init; } + + public Vector3 LightmapOrigin { get; init; } + public Vector3 LightmapVector1 { get; init; } + public Vector3 LightmapVector2 { get; init; } + public Vector3 Normal { get; init; } + + public Vector2Int Size { get; init; } + } + + public readonly struct BspModel + { + public Vector3 Min { get; init; } + public Vector3 Max { get; init; } + + public int StartFaceIdx { get; init; } + public int NumFaces { get; init; } + + public int StartBrushIdx { get; init; } + public int NumBrushes { get; init; } + } + + public readonly struct BspMeshVertex + { + public Vector3 Position { get; init; } + public Vector3 Normal { get; init; } + public Vector2 UV { get; init; } + + public int BaseIndex { get; init; } + } + + public struct BspSubMesh + { + public int TexID { get; init; } + public List Triangles { get; init; } + } + + public readonly struct BspNode + { + public int PlaneIndex { get; init; } + + public int Child1 { get; init; } // negative numbers are leafs + public int Child2 { get; init; } + public Vector3Int Min { get; init; } + public Vector3Int Max { get; init; } + } + + public readonly struct BspLeaf + { + public int VisCluster { get; init; } + public int PortalArea { get; init; } + + public Vector3Int Min { get; init; } + public Vector3Int Max { get; init; } + + public int LeafFaceStartIdx { get; init; } + public int NumLeafFaces { get; init; } + + public int LeafBrushStartIdx { get; init; } + public int NumLeafBrushes { get; init; } + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // MD3 Types + // ----------------------------------------------------------------------------------------------------------------------------- + public readonly struct MD3Surface + { + public Vector3[] Vertices { get; init; } + public Vector2[] Uvs { get; init; } + public Vector3[] Normals { get; init; } + public string Texture { get; init; } + public string Name { get; init; } + + public int DataSize => Vertices.Length * 16 + Vertices.Length * 4 + 176; + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Vector Conversions + // ----------------------------------------------------------------------------------------------------------------------------- + public static class Q3VectorExtensions + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Q3ToUnityVector(this Vector3 q3Vector, float scale = 1f) + => new Vector3(q3Vector.x, q3Vector.z, q3Vector.y) * scale; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 UnityToQ3Vector(this Vector3 unityVector, float scale = 1f) + => new Vector3(unityVector.x, unityVector.z, unityVector.y) / scale; + + public static bool TryParseQ3Vector(this string inVector, out Vector3 value) + { + string[] parts = inVector.Split(" "); + + // Vector, e.g. "x y z" + if (parts.Length == 3 && + parts[0].TryParseFloat(out float x) && + parts[1].TryParseFloat(out float y) && + parts[2].TryParseFloat(out float z)) + { + value = new(x, y, z); + return true; + } + + // Float, e.g. "x" + if (parts.Length == 1 && parts[0].TryParseFloat(out float f)) + { + value = new(f, f, f); + return true; + } + + value = Vector3.zero; + return false; + } + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Colour Conversions + // ----------------------------------------------------------------------------------------------------------------------------- + public static class Q3ColourExtensions + { + public static bool TryParseQ3Colour(this string inColour, out Color value) + { + if (inColour.IsNullOrEmpty()) + { + value = Color.white; + return false; + } + + string[] parts = inColour.Split(" "); + if (parts.Length != 3) + { + value = default; + return false; + } + + if (!parts[0].TryParseFloat(out float r) + || !parts[1].TryParseFloat(out float g) + || !parts[2].TryParseFloat(out float b)) + { + value = default; + return false; + } + + if (r > 1f || g > 1f || b > 1f) + { + // Assume BYTE values, 0-255 + value = new(r / 255f, g / 255f, b / 255f); + return true; + } + else + { + // Assume FLOAT values, 0-1 + value = new(r, g, b); + return true; + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Types/BspTypes.cs.meta b/Assets/Tremble/Types/BspTypes.cs.meta new file mode 100644 index 0000000..a970b5e --- /dev/null +++ b/Assets/Tremble/Types/BspTypes.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a502265f744340118b51b9ce63ad42bc +timeCreated: 1698058785 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Types/BspTypes.cs + uploadId: 939664 diff --git a/Assets/Tremble/Types/MapBspGetters.cs b/Assets/Tremble/Types/MapBspGetters.cs new file mode 100644 index 0000000..955c91a --- /dev/null +++ b/Assets/Tremble/Types/MapBspGetters.cs @@ -0,0 +1,290 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public enum EntityType + { + Brush, + Point + } + + public static class MapBspGetters + { + private static TrembleFieldConverterCollection s_ConverterCollection; + + public static bool FindEntityById(this MapBsp mapBsp, string id, out BspEntity entity) + { + string identityProperty = TrembleSyncSettings.Get().IdentityPropertyName; + + foreach (BspEntity ent in mapBsp.Entities) + { + if (!ent.TryGetString(identityProperty, out string foundId) || !foundId.EqualsInvariant(id, caseSensitive: true)) + continue; + + entity = ent; + return true; + } + + entity = default; + return false; + } + + public static List FindEntitiesById(this MapBsp mapBsp, string id) + { + string identityProperty = TrembleSyncSettings.Get().IdentityPropertyName; + + List entities = new(); + foreach (BspEntity ent in mapBsp.Entities) + { + if (!ent.TryGetString(identityProperty, out string foundId) || !foundId.EqualsInvariant(id, caseSensitive: true)) + continue; + + entities.Add(ent); + } + return entities; + } + + public static BspEntity FindFirstEntityOfClass(this MapBsp mapBsp, string className) + { + foreach (BspEntity ent in mapBsp.Entities) + { + if (ent.GetClassname().EqualsInvariant(className, caseSensitive: true)) + return ent; + } + + return default; + } + public static List FindEntitiesOfClass(this MapBsp mapBsp, string className) + { + List entities = new(); + + foreach (BspEntity ent in mapBsp.Entities) + { + if (!ent.GetClassname().EqualsInvariant(className, caseSensitive: true)) + continue; + + entities.Add(ent); + } + + return entities; + } + + public static TReturnType GetBaseClassData(this BspEntity entity, ITrembleBaseClass instance, string name) + { + PropertyInfo defaultProperty = instance + .GetType() + .GetInterfaces() + .SelectMany(i => i.GetProperties()) + .FirstOrDefault(p => p.Name.EqualsInvariant(name, caseSensitive: true)); + + if (defaultProperty == null) + return default; + + string fieldName = name.GetFieldNameInMap(TrembleSyncSettings.Get().FieldNamingConvention); + + s_ConverterCollection ??= new(); + + TrembleFieldConverter converter = s_ConverterCollection.GetConverterForType(defaultProperty.PropertyType); + if (converter != null) + { + // Use a converter to convert the map value + if (converter.TryGetValueFromMap(entity, fieldName, null, defaultProperty, out object mapValue)) + { + if (defaultProperty.GetFieldOrPropertyTypeOrElementType() == typeof(Transform) && mapValue is Component c) + { + mapValue = c.transform; + } + + return (TReturnType)mapValue; + } + + // Couldn't convert - read the default value from the interface base + return (TReturnType)defaultProperty.GetValue(instance); + } + + // Nothing worked - log a warning + Debug.LogWarning($"Saw field '{defaultProperty.Name}' of type {defaultProperty.GetFieldOrPropertyType()}, which is not yet supported. Try adding a custom TrembleFieldConverter for it, if you like!"); + + return (TReturnType)defaultProperty.GetValue(instance); + } + + + public static BspEntity GetWorldspawnEntity(this MapBsp mapBsp) + { + return FindFirstEntityOfClass(mapBsp, "worldspawn"); + } + + public static string GetClassname(this BspEntity entity) + => entity.GetString(FgdConsts.PROPERTY_CLASSNAME); + + public static string GetID(this BspEntity entity) + => entity.GetString(TrembleSyncSettings.Get().IdentityPropertyName); + + public static bool HasID(this BspEntity entity) + => entity.Entries.ContainsKey(TrembleSyncSettings.Get().IdentityPropertyName); + + public static bool HasKey(this BspEntity entity, string key) => entity.Entries.ContainsKey(key); + + public static IEnumerable GetAllNumberedKeys(this BspEntity entity, string prefix) + { + return entity.Entries.Keys + .Where(k => k.StartsWithInvariant(prefix, caseSensitive: true)) + .OrderBy(k => k); + } + + public static bool TryGetString(this BspEntity entity, string key, out string value) => entity.Entries.TryGetValue(key, out value); + public static string GetString(this BspEntity entity, string key, string defaultValue = null) + => entity.Entries.GetValueOrDefault(key, defaultValue); + public static string[] GetStrings(this BspEntity entity, string keyPrefix) + => entity.GetAllNumberedKeys(keyPrefix).Select(key => entity.GetString(key)).ToArray(); + + public static bool TryGetInt(this BspEntity entity, string key, out int value) + { + if (!entity.Entries.TryGetValue(key, out string strValue)) + { + value = default; + return false; + } + + return int.TryParse(strValue, out value); + } + public static int GetInt(this BspEntity entity, string key, int defaultValue) + => TryGetInt(entity, key, out int value) ? value : defaultValue; + public static int[] GetInts(this BspEntity entity, string keyPrefix) + => entity.GetAllNumberedKeys(keyPrefix).Select(key => entity.GetInt(key, 0)).ToArray(); + + public static bool TryGetFloat(this BspEntity entity, string key, out float value) + { + if (!entity.Entries.TryGetValue(key, out string strValue)) + { + value = default; + return false; + } + + return strValue.TryParseFloat(out value); + } + public static float GetFloat(this BspEntity entity, string key, float defaultValue) + => TryGetFloat(entity, key, out float value) ? value : defaultValue; + public static float[] GetFloats(this BspEntity entity, string keyPrefix) + => entity.GetAllNumberedKeys(keyPrefix).Select(key => entity.GetFloat(key, 0f)).ToArray(); + + public static bool TryGetBoolean(this BspEntity entity, string key, out bool value) + { + if (!entity.Entries.TryGetValue(key, out string strValue) + || !int.TryParse(strValue, out int intValue)) + { + value = default; + return false; + } + + value = (intValue > 0); + return true; + } + public static bool GetBoolean(this BspEntity entity, string key, bool defaultValue) + => TryGetBoolean(entity, key, out bool value) ? value : defaultValue; + public static bool[] GetBooleans(this BspEntity entity, string keyPrefix) + => entity.GetAllNumberedKeys(keyPrefix).Select(key => entity.GetBoolean(key, false)).ToArray(); + + + public static bool TryGetSpawnFlag(this BspEntity entity, int bit, out bool value) + { + int bitValue = 1 << bit; + + if (!entity.Entries.TryGetValue(FgdConsts.PROPERTY_SPAWNFLAGS, out string strValue) + || !int.TryParse(strValue, out int intValue)) + { + value = default; + return false; + } + + value = (intValue & bitValue) > 0; + return true; + } + public static bool GetSpawnFlag(this BspEntity entity, int bit, bool defaultValue) + => TryGetSpawnFlag(entity, bit, out bool value) ? value : defaultValue; + + public static bool TryGetUntransformedVector(this BspEntity entity, string key, out Vector3 value) + { + if (!entity.Entries.TryGetValue(key, out string strValue)) + { + value = default; + return false; + } + + return strValue.TryParseQ3Vector(out value); + } + public static Vector3 GetUntransformedVector(this BspEntity entity, string key, Vector3 defaultValue) + => TryGetUntransformedVector(entity, key, out Vector3 value) ? value : defaultValue; + public static Vector3[] GetUntransformedVectors(this BspEntity entity, string keyPrefix) + => entity.GetAllNumberedKeys(keyPrefix).Select(key => entity.GetUntransformedVector(key, Vector3.zero)).ToArray(); + + + public static bool TryGetVector(this BspEntity entity, string key, out Vector3 value) + { + if (!TryGetUntransformedVector(entity, key, out Vector3 rawValue)) + { + value = rawValue; + return false; + } + + value = rawValue.Q3ToUnityVector(scale: entity.ImportScale); + return true; + } + public static Vector3 GetVector(this BspEntity entity, string key, Vector3 defaultValue) + => TryGetVector(entity, key, out Vector3 value) ? value : defaultValue; + public static Vector3[] GetVectors(this BspEntity entity, string keyPrefix) + => entity.GetAllNumberedKeys(keyPrefix).Select(key => entity.GetVector(key, Vector3.zero)).ToArray(); + + public static bool TryGetRotation(this BspEntity entity, string key, out Quaternion value) + { + if (entity.TryGetUntransformedVector(key, out Vector3 rawAngles)) + { + // From TB Docs: "angles" is interpreted as "pitch yaw roll" (if the entity model is a Quake MDL, pitch is inverted) + Quaternion quat = Quaternion.identity; + if (rawAngles.z != 0) quat = Quaternion.AngleAxis(-rawAngles.z, Vector3.right) * quat; // pitch + if (rawAngles.x != 0) quat = Quaternion.AngleAxis(-rawAngles.x, Vector3.forward) * quat; // roll + if (rawAngles.y != 0) quat = Quaternion.AngleAxis(-rawAngles.y, Vector3.up) * quat; // yaw + + value = quat; + return true; + } + + value = default; + return false; + } + public static Quaternion GetRotation(this BspEntity entity, string key, Quaternion defaultValue) + => TryGetRotation(entity, key, out Quaternion value) ? value : defaultValue; + public static Quaternion[] GetRotations(this BspEntity entity, string keyPrefix) + => entity.GetAllNumberedKeys(keyPrefix).Select(key => entity.GetRotation(key, Quaternion.identity)).ToArray(); + + + public static Vector3 GetPosition(this BspEntity entity) + => TryGetVector(entity, FgdConsts.PROPERTY_ORIGIN, out Vector3 value) ? value : Vector3.zero; + + + public static bool TryGetColour(this BspEntity entity, string key, out Color value) + { + if (!entity.Entries.TryGetValue(key, out string strValue)) + { + value = default; + return false; + } + + return strValue.TryParseQ3Colour(out value); + } + public static Color GetColour(this BspEntity entity, string key, Color defaultValue) + => TryGetColour(entity, key, out Color value) ? value : defaultValue; + public static Color[] GetColours(this BspEntity entity, string keyPrefix) + => entity.GetAllNumberedKeys(keyPrefix).Select(key => entity.GetColour(key, Color.white)).ToArray(); + + } +} \ No newline at end of file diff --git a/Assets/Tremble/Types/MapBspGetters.cs.meta b/Assets/Tremble/Types/MapBspGetters.cs.meta new file mode 100644 index 0000000..5c8d686 --- /dev/null +++ b/Assets/Tremble/Types/MapBspGetters.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 282f35cb4fdd4cc59aeffd3c688fb299 +timeCreated: 1698070299 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Types/MapBspGetters.cs + uploadId: 939664 diff --git a/Assets/Tremble/Types/MapProcessorClass.cs b/Assets/Tremble/Types/MapProcessorClass.cs new file mode 100644 index 0000000..1e1d37c --- /dev/null +++ b/Assets/Tremble/Types/MapProcessorClass.cs @@ -0,0 +1,125 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using UnityEngine; +using Assembly = System.Reflection.Assembly; + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace TinyGoose.Tremble +{ + [Serializable] + public class MapProcessorClass + { + // ----------------------------------------------------------------------------------------------------------------------------- + // Serialised + // ----------------------------------------------------------------------------------------------------------------------------- + [SerializeField] private string m_MapClassName; + + // ----------------------------------------------------------------------------------------------------------------------------- + // Static lookup + // ----------------------------------------------------------------------------------------------------------------------------- + private static readonly Dictionary s_MapClassLookup = new(); + + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private Type m_Class; + + public MapProcessorClass(string mapClassName = null) + { + m_MapClassName = mapClassName; + } + public MapProcessorClass(Type mapClass) + { + m_Class = mapClass; + m_MapClassName = mapClass.FullName; + } + + public static implicit operator MapProcessorClass(Type t) => new(t); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Equality + // ----------------------------------------------------------------------------------------------------------------------------- + protected bool Equals(MapProcessorClass other) => m_MapClassName == other.m_MapClassName; + + public override bool Equals(object obj) + { + if (obj is null) + return false; + if (ReferenceEquals(this, obj)) + return true; + + return obj.GetType() == GetType() && Equals((MapProcessorClass) obj); + } + public override int GetHashCode() => m_MapClassName?.GetHashCode() ?? 0; + + public static bool operator ==(MapProcessorClass left, MapProcessorClass right) => Equals(left, right); + public static bool operator !=(MapProcessorClass left, MapProcessorClass right) => !Equals(left, right); + + public Type Class + { + get + { + // Have cached type? + if (m_Class != null) + return m_Class; + + m_Class = GetClassWithName(m_MapClassName); + return m_Class; + } + } + + public static Type GetClassWithName(string className) + { +#if UNITY_EDITOR + // Unsupported - but hopefully fine! + return Unsupported.GetTypeFromFullName(className); +#else + if (className == null) + return null; + + if (s_MapClassLookup.Count == 0) + { + GenerateClassLookup(); + } + + // Try looking up - we should refresh if not + if (s_MapClassLookup.TryGetValue(className, out Type foundClass)) + return foundClass; + + return null; +#endif + } + + public MapProcessorBase CreateInstance() => (MapProcessorBase)Activator.CreateInstance(Class); + + public bool IsValid => Class != null; + public bool IsA() => Class == typeof(T) || Class.IsSubclassOf(typeof(T)); + + private static void GenerateClassLookup() + { + List typesFound = new(1024); + foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) + typesFound.AddRange(assembly.GetTypes()); + + s_MapClassLookup.Clear(); + + foreach (Type availableType in typesFound) + { + string fullName = availableType.FullName; + + if (fullName == null) + continue; + + s_MapClassLookup[fullName] = availableType; + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Types/MapProcessorClass.cs.meta b/Assets/Tremble/Types/MapProcessorClass.cs.meta new file mode 100644 index 0000000..4cb0ee3 --- /dev/null +++ b/Assets/Tremble/Types/MapProcessorClass.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: b1c6f641d81f4c8b81744a96934911ef +timeCreated: 1707729910 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Types/MapProcessorClass.cs + uploadId: 939664 diff --git a/Assets/Tremble/Types/MaterialExportSize.cs b/Assets/Tremble/Types/MaterialExportSize.cs new file mode 100644 index 0000000..67cbb6c --- /dev/null +++ b/Assets/Tremble/Types/MaterialExportSize.cs @@ -0,0 +1,41 @@ +using System; +using System.Linq; +using System.Reflection; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public enum MaterialExportSize + { + [InspectorName("16")] Size16, + [InspectorName("32")] Size32, + [InspectorName("64")] Size64, + [InspectorName("128")] Size128, + [InspectorName("256")] Size256, + [InspectorName("512")] Size512, + [InspectorName("1024")] Size1024, + [InspectorName("2048")] Size2048, + } + + public static class MaterialExportSizeUtils + { + public static MaterialExportSize GetDefault() => MaterialExportSize.Size64; + + public static string[] Names => + s_Names ??= Enum.GetValues(typeof(MaterialExportSize)) + .Cast() + .Select(mes => typeof(MaterialExportSize) + .GetMember(mes.ToString())[0] + .GetCustomAttribute()?.displayName ?? mes.ToString()) + .ToArray(); + + private static int[] IntSizes => s_Sizes ??= Names.Select(int.Parse).ToArray(); + + public static int ToIntSize(this MaterialExportSize mes) => IntSizes[(int)mes]; + + public static Vector2Int ToVector2IntSize(this MaterialExportSize mes) => new(mes.ToIntSize(), mes.ToIntSize()); + + private static string[] s_Names; + private static int[] s_Sizes; + } +} \ No newline at end of file diff --git a/Assets/Tremble/Types/MaterialExportSize.cs.meta b/Assets/Tremble/Types/MaterialExportSize.cs.meta new file mode 100644 index 0000000..cf04afb --- /dev/null +++ b/Assets/Tremble/Types/MaterialExportSize.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: c9d6ab96c78649b2a9c2b1c4d6cda752 +timeCreated: 1753866627 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Types/MaterialExportSize.cs + uploadId: 939664 diff --git a/Assets/Tremble/Types/MaterialRenderData.cs b/Assets/Tremble/Types/MaterialRenderData.cs new file mode 100644 index 0000000..3950bd8 --- /dev/null +++ b/Assets/Tremble/Types/MaterialRenderData.cs @@ -0,0 +1,81 @@ +using System; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class MaterialRenderData + { + public MaterialRenderData(Material material) + { + m_Material = material; + } + + [SerializeField] private Material m_Material; + [SerializeField] private MaterialImportMode m_ExportMode; + [SerializeField] private bool m_IsResolutionOverridden; + [SerializeField] private MaterialExportSize m_ResolutionX = MaterialExportSize.Size64; + [SerializeField] private MaterialExportSize m_ResolutionY = MaterialExportSize.Size64; + [SerializeField] private bool m_Dirty; + + public Material Material => m_Material; + + public MaterialImportMode ExportMode + { + get => m_ExportMode; + set + { + m_ExportMode = value; + m_Dirty = true; + } + } + + public bool IsResolutionOverridden + { + get => m_IsResolutionOverridden; + set + { + m_IsResolutionOverridden = value; + m_Dirty = true; + } + } + + public MaterialExportSize ResolutionX + { + get => m_ResolutionX; + set + { + m_ResolutionX = value; + m_Dirty = true; + } + } + + public MaterialExportSize ResolutionY + { + get => m_ResolutionY; + set + { + m_ResolutionY = value; + m_Dirty = true; + } + } + + public Vector2Int GetResolutionOrDefault() + { + if (!m_IsResolutionOverridden) + return TrembleSyncSettings.Get().MaterialExportSize.ToVector2IntSize(); + + return new(m_ResolutionX.ToIntSize(), m_ResolutionY.ToIntSize()); + } + + public bool IsDirty => m_Dirty; + public void ClearDirty() => m_Dirty = false; + } + + + public enum MaterialImportMode + { + Dynamic, + FixedSize, + } +} \ No newline at end of file diff --git a/Assets/Tremble/Types/MaterialRenderData.cs.meta b/Assets/Tremble/Types/MaterialRenderData.cs.meta new file mode 100644 index 0000000..70a6e3e --- /dev/null +++ b/Assets/Tremble/Types/MaterialRenderData.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 5008febfabec473983456dc18bc3cf5d +timeCreated: 1753866661 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Types/MaterialRenderData.cs + uploadId: 939664 diff --git a/Assets/Tremble/Types/TpakArchive.cs b/Assets/Tremble/Types/TpakArchive.cs new file mode 100644 index 0000000..08ddd37 --- /dev/null +++ b/Assets/Tremble/Types/TpakArchive.cs @@ -0,0 +1,136 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [Serializable] + public struct TpakTocEntry + { + public string Path; + public string SourcePath; + + public int FileLength; + } + + public class TpakArchive + { + private const string TPAK_MAGIC = "TPAK"; + private const int TPAK_MAX_PATH = 255; + + private readonly string m_ArchiveFile; + private readonly List m_Entries = new(); + + public TpakArchive(string archiveFile) + { + m_ArchiveFile = archiveFile; + } + + public void AddDirectory(string directory) + { + AddDirectory_Recursive(directory, null); + } + + public void AddFile(string filePath, string filenameInTpak) + { + m_Entries.Add(new() + { + Path = filenameInTpak, + SourcePath = filePath, + FileLength = (int)(new FileInfo(filePath).Length) + }); + } + + public async Task UnpackAsync(string folder) + { + StreamReadIO pakIn = new(m_ArchiveFile); + if (!pakIn.ReadString(4).EqualsInvariant(TPAK_MAGIC, caseSensitive: true)) + { + Debug.LogError($"Invalid magic reading tpak '{m_ArchiveFile}'!"); + return false; + } + + int numEntries = pakIn.ReadInt32(); + for (int entryIdx = 0; entryIdx < numEntries; entryIdx++) + { + int pathLength = pakIn.ReadInt32(); + + TpakTocEntry entry = new() + { + Path = pakIn.ReadString(pathLength), + FileLength = pakIn.ReadInt32(), + }; + entry.SourcePath = Path.Combine(folder, entry.Path); + DirectoryUtil.CreateAllDirectories(entry.SourcePath); + + m_Entries.Add(entry); + } + + foreach (TpakTocEntry entry in m_Entries) + { + if (File.Exists(entry.SourcePath)) + { + pakIn.SkipBytes(entry.FileLength); + continue; + } + + byte[] file = pakIn.ReadBytes(entry.FileLength); + await File.WriteAllBytesAsync(entry.SourcePath, file); + } + + return true; + } + + public async Task PackAsync() + { + await using FileStream pakOutStream = new(m_ArchiveFile, FileMode.Create, FileAccess.Write); + + using StreamWriteIO pakOut = new(pakOutStream); + pakOut.WriteString(TPAK_MAGIC, 4); + pakOut.WriteInt32(m_Entries.Count); + + foreach (TpakTocEntry entry in m_Entries) + { + pakOut.WriteInt32(entry.Path.Length); + pakOut.WriteString(entry.Path); + pakOut.WriteInt32(entry.FileLength); + } + + byte[] buffer = new byte[1024]; + foreach (TpakTocEntry entry in m_Entries) + { + await using FileStream entryFile = new(entry.SourcePath, FileMode.Open, FileAccess.Read); + using BinaryReader entryIn = new(entryFile); + + int readBytes; + do + { + readBytes = entryIn.Read(buffer, 0, buffer.Length); + pakOut.WriteBytes(buffer, readBytes); + } while (readBytes > 0); + } + } + + private void AddDirectory_Recursive(string directory, string currentPath) + { + foreach (string file in Directory.EnumerateFiles(directory)) + { + string path = currentPath == null ? Path.GetFileName(file) : Path.Combine(currentPath, Path.GetFileName(file)); + AddFile(file, path); + } + + foreach (string dir in Directory.EnumerateDirectories(directory)) + { + string newCurrentPath = currentPath == null ? Path.GetFileName(dir) : Path.Combine(currentPath, Path.GetFileName(dir)); + AddDirectory_Recursive(dir, newCurrentPath); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Types/TpakArchive.cs.meta b/Assets/Tremble/Types/TpakArchive.cs.meta new file mode 100644 index 0000000..03c50d9 --- /dev/null +++ b/Assets/Tremble/Types/TpakArchive.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: fd52ece1f19743039da2022e11fbe16c +timeCreated: 1728651734 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Types/TpakArchive.cs + uploadId: 939664 diff --git a/Assets/Tremble/Types/TrembleTimer.cs b/Assets/Tremble/Types/TrembleTimer.cs new file mode 100644 index 0000000..3b21de4 --- /dev/null +++ b/Assets/Tremble/Types/TrembleTimer.cs @@ -0,0 +1,149 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using UnityEngine; + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace TinyGoose.Tremble +{ + [Serializable] + public struct StoredTrembleTimer + { + public string Context; + public long LastMillis; + } + + public struct TrembleTimerScope : IDisposable + { + private readonly TrembleTimer m_Timer; + private bool m_Disposed; + + public TrembleTimerScope(Type type) + { + m_Timer = TrembleTimer.GetTimer(type); + m_Timer.BeginCapture(); + + m_Disposed = false; + } + public TrembleTimerScope(TrembleTimer.Context context) + { + m_Timer = TrembleTimer.GetTimer(context); + m_Timer.BeginCapture(); + + m_Disposed = false; + } + + public void Dispose() + { + if (m_Disposed) + return; + + m_Disposed = true; + m_Timer.EndCapture(); + } + } + + public class TrembleTimer + { + public enum Context + { + // Import + ExportMapToStaging, + RunQ3Map2, + ParseBsp, + CreateGameObjects, + SplitMesh, + SmoothMeshNormals, + SimplifyCollisionMeshes, + GenerateUV2, + RunMapProcessors, + + // Sync + CreateTypeLookups, + ExportEntities, + GatherDataAssets, + ExportMaterials, + WriteEntitiesFgdAndGameConfig, + Cleanup, + ExportAddressableDataForStandalone, + } + + private static readonly Dictionary s_CurrentTimers = new(); + private static string s_SessionContext; + private static DateTime s_SessionStart; + + private DateTime m_CaptureStart; + private long m_TotalMilliseconds; + + public long TotalMilliseconds => m_TotalMilliseconds; + + public static void BeginSession(string sessionContext) + { + s_SessionStart = DateTime.Now; + s_SessionContext = sessionContext; + s_CurrentTimers.Clear(); + } + + public static void EndSession() + { + if (TrembleSyncSettings.Get().LogOnImportAndSync) + { + float seconds = (float)(DateTime.Now - s_SessionStart).TotalSeconds; + Debug.Log($"{s_SessionContext} complete in {seconds:F3}s!"); + } + + foreach ((string name, TrembleTimer timer) in s_CurrentTimers) + { +#if UNITY_EDITOR + EditorPrefs.SetInt($"TrembleTimer_{name}", (int)timer.TotalMilliseconds); +#endif + + if (TrembleSyncSettings.Get().LogOnImportAndSync) + { + Debug.Log($" {name} took {timer.TotalMilliseconds}ms"); + } + } + } + + public static TrembleTimer GetTimer(Type processorType) => GetTimer(processorType.FullName); + public static TrembleTimer GetTimer(Context context) => GetTimer(context.ToString()); + + private static TrembleTimer GetTimer(string name) + { + if (!s_CurrentTimers.TryGetValue(name, out TrembleTimer timer)) + { + timer = new(); + s_CurrentTimers[name] = timer; + } + + return timer; + } + + public static long GetLastTime(Type processorType) => GetLastTime(processorType.FullName); + public static long GetLastTime(Context context) => GetLastTime(context.ToString()); + + private static long GetLastTime(string name) +#if UNITY_EDITOR + => EditorPrefs.GetInt($"TrembleTimer_{name}", -1); +#else + => 0L; +#endif + + + public void BeginCapture() + { + m_CaptureStart = DateTime.Now; + } + public void EndCapture() + { + m_TotalMilliseconds += (long)(DateTime.Now - m_CaptureStart).TotalMilliseconds; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Types/TrembleTimer.cs.meta b/Assets/Tremble/Types/TrembleTimer.cs.meta new file mode 100644 index 0000000..f616e8d --- /dev/null +++ b/Assets/Tremble/Types/TrembleTimer.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: fcf63be3ebf546e598559701514185f6 +timeCreated: 1728729960 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Types/TrembleTimer.cs + uploadId: 939664 diff --git a/Assets/Tremble/Types/TwoWayDictionary.cs b/Assets/Tremble/Types/TwoWayDictionary.cs new file mode 100644 index 0000000..d90462f --- /dev/null +++ b/Assets/Tremble/Types/TwoWayDictionary.cs @@ -0,0 +1,77 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Collections.Generic; +using System.IO; + +namespace TinyGoose.Tremble +{ + public class TwoWayDictionary + { + private readonly Dictionary m_Lookup; + private readonly Dictionary m_ReverseLookup; + + public TwoWayDictionary() + { + m_Lookup = new(); + m_ReverseLookup = new(); + } + + public TwoWayDictionary(int capacity) + { + m_Lookup = new(capacity); + m_ReverseLookup = new(capacity); + } + + public TValue GetValue(TKey key) + { + return m_Lookup[key]; + } + public TKey GetKey(TValue value) + { + return m_ReverseLookup[value]; + } + + public bool ContainsKey(TKey key) => m_Lookup.ContainsKey(key); + public bool ContainsValue(TValue value) => m_ReverseLookup.ContainsKey(value); + + public bool TryGetValue(TKey key, out TValue value) => m_Lookup.TryGetValue(key, out value); + public bool TryGetKey(TValue value, out TKey key) => m_ReverseLookup.TryGetValue(value, out key); + + public IEnumerable Keys => m_Lookup.Keys; + public IEnumerable Values => m_Lookup.Values; + + public void Clear() + { + m_Lookup.Clear(); + m_ReverseLookup.Clear(); + } + + public TValue this[TKey key] + { + get => GetValue(key); + set + { + m_Lookup[key] = value; + m_ReverseLookup[value] = key; + } + } + + public void Add(TKey key, TValue value) + { + m_Lookup.Add(key, value); + m_ReverseLookup.Add(value, key); + } + + public void Remove(TKey key) + { + if (m_Lookup.TryGetValue(key, out TValue value)) + { + m_ReverseLookup.Remove(value); + } + m_Lookup.Remove(key); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Types/TwoWayDictionary.cs.meta b/Assets/Tremble/Types/TwoWayDictionary.cs.meta new file mode 100644 index 0000000..555164d --- /dev/null +++ b/Assets/Tremble/Types/TwoWayDictionary.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ab6c6d9d07924bbebafee07655e56466 +timeCreated: 1740748009 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Types/TwoWayDictionary.cs + uploadId: 939664 diff --git a/Assets/Tremble/Types/WorldspawnScript.cs b/Assets/Tremble/Types/WorldspawnScript.cs new file mode 100644 index 0000000..4d8f2b8 --- /dev/null +++ b/Assets/Tremble/Types/WorldspawnScript.cs @@ -0,0 +1,36 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + [Serializable] + public class WorldspawnScript + { + private static readonly int DEFAULT_TYPE_HASHCODE = typeof(Worldspawn).FullName?.GetHashCode() ?? 0; + private static readonly int EMPTY_STRING_HASHCODE = "".GetHashCode(); + + public WorldspawnScript(string scriptName = null) + { + m_ScriptName = scriptName; + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Serialised + // ----------------------------------------------------------------------------------------------------------------------------- + [SerializeField] private string m_ScriptName; + + public string ScriptName => m_ScriptName; + public Type Class => TypeDatabase.GetType(m_ScriptName); + + public override int GetHashCode() + { + int hash = m_ScriptName.GetHashCode(); + return hash == DEFAULT_TYPE_HASHCODE ? EMPTY_STRING_HASHCODE : hash; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Types/WorldspawnScript.cs.meta b/Assets/Tremble/Types/WorldspawnScript.cs.meta new file mode 100644 index 0000000..98487f2 --- /dev/null +++ b/Assets/Tremble/Types/WorldspawnScript.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 4b44834781104ac6941bd9a435d8dae3 +timeCreated: 1710152777 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Types/WorldspawnScript.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils.meta b/Assets/Tremble/Utils.meta new file mode 100644 index 0000000..804c46d --- /dev/null +++ b/Assets/Tremble/Utils.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: cef952683a4c4f9fa03155142f1e7872 +timeCreated: 1715666864 \ No newline at end of file diff --git a/Assets/Tremble/Utils/DirectoryUtil.cs b/Assets/Tremble/Utils/DirectoryUtil.cs new file mode 100644 index 0000000..6f93d7b --- /dev/null +++ b/Assets/Tremble/Utils/DirectoryUtil.cs @@ -0,0 +1,85 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.IO; +using System.Threading.Tasks; + +namespace TinyGoose.Tremble +{ + public static class DirectoryUtil + { + private static readonly char[] s_PathSeparators = { '\\', '/' }; + + public static void EmptyAndCreateDirectory(string folder) + { + if (Directory.Exists(folder)) + { + Directory.Delete(folder, true); + } + + CreateAllDirectories(folder); + } + + public static int CreateAllDirectories(string folders) + { + int numCreated = 0; + + string[] pathFolders = folders.Split(s_PathSeparators); + if (pathFolders.Length <= 1) + return numCreated; + + string path = pathFolders[0]; + + for (int i = 1; i < pathFolders.Length; i++) + { + // Path.Combine breaks when it's absolute (because /Users becomes Users) + path += Path.DirectorySeparatorChar + pathFolders[i]; + + if (i == pathFolders.Length - 1 && pathFolders[i].Contains('.')) + { + // Last component and it has a dot - it's a file! + break; + } + + if (!Directory.Exists(path)) + { + Directory.CreateDirectory(path); + numCreated++; + } + } + + return numCreated; + } + + public static async Task CopyDirectory(string source, string destination) + { + DirectoryInfo dir = new(source); + + // Check if the source directory exists + if (!dir.Exists) + return false; + + EmptyAndCreateDirectory(destination); + + await Task.Run(async () => + { + foreach (FileInfo file in dir.GetFiles()) + { + string targetFilePath = Path.Combine(destination, file.Name); + file.CopyTo(targetFilePath); + } + + // Recurse! + foreach (DirectoryInfo subDir in dir.GetDirectories()) + { + string newDestinationDir = Path.Combine(destination, subDir.Name); + await CopyDirectory(subDir.FullName, newDestinationDir); + } + }); + + return true; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/DirectoryUtil.cs.meta b/Assets/Tremble/Utils/DirectoryUtil.cs.meta new file mode 100644 index 0000000..b49b2e7 --- /dev/null +++ b/Assets/Tremble/Utils/DirectoryUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 9657858345914445b2cabe032ca32b33 +timeCreated: 1707729759 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/DirectoryUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/FieldUtil.cs b/Assets/Tremble/Utils/FieldUtil.cs new file mode 100644 index 0000000..7812215 --- /dev/null +++ b/Assets/Tremble/Utils/FieldUtil.cs @@ -0,0 +1,327 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Reflection; +using UnityEngine; +using Type = System.Type; + +namespace TinyGoose.Tremble +{ + public static class FieldUtil + { + private static readonly string[] KNOWN_PREFIXES = { "m_", "_" }; + + private static readonly Dictionary s_CachedTypeAttributes = new(); + private static readonly Dictionary s_CachedFieldAttributes = new(); + private static readonly Dictionary s_AllInstanceFieldsIncludingPrivateAndBaseClasses = new(); + + public static bool TryGetCustomAttribute(this Type type, out TAttribute att) + where TAttribute : Attribute + { + att = type.GetCachedAttribute(); + return att != null; + } + + public static bool HasCustomAttribute(this FieldInfo field) + where TAttribute : Attribute + { + return field.GetCachedAttribute() != null; + } + + public static bool HasCustomAttribute(this Type type) + where TAttribute : Attribute + { + return type.GetCachedAttribute() != null; + } + + public static void GetCustomAttributes(this MemberInfo member, out TAttribute1 attr1) + where TAttribute1 : Attribute + { + attr1 = default; + + foreach (Attribute attribute in member.GetCachedAttributes()) + { + if (attribute is TAttribute1 tAttribute1) + attr1 = tAttribute1; + } + } + + public static void GetCustomAttributes(this MemberInfo member, out TAttribute1 attr1, out TAttribute2 attr2) + where TAttribute1 : Attribute + where TAttribute2 : Attribute + { + attr1 = default; + attr2 = default; + + foreach (Attribute attribute in member.GetCachedAttributes()) + { + if (attribute is TAttribute1 tAttribute1) + attr1 = tAttribute1; + if (attribute is TAttribute2 tAttribute2) + attr2 = tAttribute2; + } + } + + public static void GetCustomAttributes(this MemberInfo member, out TAttribute1 attr1, out TAttribute2 attr2, out TAttribute3 attr3) + where TAttribute1 : Attribute + where TAttribute2 : Attribute + where TAttribute3 : Attribute + { + attr1 = default; + attr2 = default; + attr3 = default; + + foreach (Attribute attribute in member.GetCachedAttributes()) + { + if (attribute is TAttribute1 tAttribute1) + attr1 = tAttribute1; + if (attribute is TAttribute2 tAttribute2) + attr2 = tAttribute2; + if (attribute is TAttribute3 tAttribute3) + attr3 = tAttribute3; + } + } + + public static void GetCustomAttributes(this MemberInfo member, out TAttribute1 attr1, out TAttribute2 attr2, out TAttribute3 attr3, out TAttribute4 attr4) + where TAttribute1 : Attribute + where TAttribute2 : Attribute + where TAttribute3 : Attribute + where TAttribute4 : Attribute + { + attr1 = default; + attr2 = default; + attr3 = default; + attr4 = default; + + foreach (Attribute attribute in member.GetCachedAttributes()) + { + if (attribute is TAttribute1 tAttribute1) + attr1 = tAttribute1; + if (attribute is TAttribute2 tAttribute2) + attr2 = tAttribute2; + if (attribute is TAttribute3 tAttribute3) + attr3 = tAttribute3; + if (attribute is TAttribute4 tAttribute4) + attr4 = tAttribute4; + } + } + + public static void GetCustomAttributes(this MemberInfo member, out TAttribute1 attr1, out TAttribute2 attr2, out TAttribute3 attr3, out TAttribute4 attr4, out TAttribute5 attr5) + where TAttribute1 : Attribute + where TAttribute2 : Attribute + where TAttribute3 : Attribute + where TAttribute4 : Attribute + where TAttribute5 : Attribute + { + attr1 = default; + attr2 = default; + attr3 = default; + attr4 = default; + attr5 = default; + + foreach (Attribute attribute in member.GetCachedAttributes()) + { + if (attribute is TAttribute1 tAttribute1) + attr1 = tAttribute1; + if (attribute is TAttribute2 tAttribute2) + attr2 = tAttribute2; + if (attribute is TAttribute3 tAttribute3) + attr3 = tAttribute3; + if (attribute is TAttribute4 tAttribute4) + attr4 = tAttribute4; + if (attribute is TAttribute5 tAttribute5) + attr5 = tAttribute5; + } + } + + public static void GetCustomAttributes(this MemberInfo member, out TAttribute1 attr1, out TAttribute2 attr2, out TAttribute3 attr3, out TAttribute4 attr4, out TAttribute5 attr5, out TAttribute6 attr6) + where TAttribute1 : Attribute + where TAttribute2 : Attribute + where TAttribute3 : Attribute + where TAttribute4 : Attribute + where TAttribute5 : Attribute + where TAttribute6 : Attribute + { + attr1 = default; + attr2 = default; + attr3 = default; + attr4 = default; + attr5 = default; + attr6 = default; + + foreach (Attribute attribute in member.GetCachedAttributes()) + { + if (attribute is TAttribute1 tAttribute1) + attr1 = tAttribute1; + if (attribute is TAttribute2 tAttribute2) + attr2 = tAttribute2; + if (attribute is TAttribute3 tAttribute3) + attr3 = tAttribute3; + if (attribute is TAttribute4 tAttribute4) + attr4 = tAttribute4; + if (attribute is TAttribute5 tAttribute5) + attr5 = tAttribute5; + if (attribute is TAttribute6 tAttribute6) + attr6 = tAttribute6; + } + } + + private static object[] GetCachedAttributes(this MemberInfo member) + { + if (s_CachedFieldAttributes.TryGetValue(member, out object[] attributes)) + return attributes; + + attributes = member.GetCustomAttributes(true); + s_CachedFieldAttributes[member] = attributes; + + return attributes; + } + + private static object[] GetCachedAttributes(this Type type) + { + if (s_CachedTypeAttributes.TryGetValue(type, out object[] attributes)) + return attributes; + + attributes = type.GetCustomAttributes(true); + s_CachedTypeAttributes[type] = attributes; + + return attributes; + } + + private static TAttribute GetCachedAttribute(this MemberInfo member) + { + foreach (object availableAttribute in member.GetCachedAttributes()) + { + if (availableAttribute is TAttribute castedAttribute) + return castedAttribute; + } + + return default; + } + + private static TAttribute GetCachedAttribute(this Type type) + { + foreach (object availableAttribute in type.GetCachedAttributes()) + { + if (availableAttribute is TAttribute castedAttribute) + return castedAttribute; + } + + return default; + } + + public static string GetFieldNameInMap(this string fieldName, NamingConvention fnc) + { + // Remove prefixes + if (fnc != NamingConvention.PreserveExact) + { + foreach (string prefix in KNOWN_PREFIXES) + { + if (!fieldName.StartsWithInvariant(prefix, caseSensitive: true)) + continue; + + fieldName = fieldName.Substring(prefix.Length); + } + } + + return fieldName.ToNamingConvention(fnc); + } + + public static int GetBitForSpawnFlagsField(this SpawnFlagsAttribute spawnFlags, TrembleSyncSettings syncSettings, MemberInfo mi) + { + if (spawnFlags is { Bit: >= 0 }) + return spawnFlags.Bit; + + int bit = -1; + foreach (FieldInfo availableField in mi.DeclaringType.GetAllInstanceFieldsIncludingPrivateAndBaseClasses()) + { + // This isn't a boolean! + if (availableField.FieldType != typeof(Boolean)) + continue; + + availableField.GetCustomAttributes( + out SpawnFlagsAttribute sfa, + out NoSpawnFlagsAttribute noSfa, + out TrembleAttribute ta, + out NoTrembleAttribute nta, + out SerializeField sf + ); + + // This is categorically NOT a spawnflags var + if (noSfa != null) + continue; + + // Not for Tremble + if (nta != null) + continue; + + // This field doesn't have spawn flags - doesn't count! + if (sfa == null && !syncSettings.AlwaysPackBoolsIntoSpawnFlags) + continue; + + // No tremble attribute, or no SerializeField/we're not considering SFs + if (ta == null && (sf == null || !syncSettings.SyncSerializedFields)) + continue; + + // It's a spawnflags field, increment + bit++; + + // It's the one we're looking for - stop! + if (availableField == mi) + break; + } + + return bit; + } + + public static Type GetFieldOrPropertyType(this MemberInfo mi) + { + switch (mi) + { + case PropertyInfo pi: + return pi.PropertyType; + + case FieldInfo fi: + return fi.FieldType; + } + + Debug.LogError($"Unsupported field type {mi.GetType()}!"); + return null; + } + + public static Type GetFieldOrPropertyTypeOrElementType(this MemberInfo mi) + { + Type type = mi.GetFieldOrPropertyType(); + if (type is { IsArray: true }) + { + type = type.GetElementType(); + } + + return type; + } + + public static FieldInfo[] GetAllInstanceFieldsIncludingPrivateAndBaseClasses(this Type t) + { + Type originalType = t; + + if (!s_AllInstanceFieldsIncludingPrivateAndBaseClasses.TryGetValue(originalType, out FieldInfo[] fields)) + { + List fieldList = new(64); + while (t != null && (t.Namespace == null || !t.Namespace.ContainsInvariant("UnityEngine", caseSensitive: true))) + { + fieldList.InsertRange(0, t.GetFields(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public)); + t = t.BaseType; + } + + fields = fieldList.ToArray(); + s_AllInstanceFieldsIncludingPrivateAndBaseClasses[originalType] = fields; + } + + return fields; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/FieldUtil.cs.meta b/Assets/Tremble/Utils/FieldUtil.cs.meta new file mode 100644 index 0000000..240e115 --- /dev/null +++ b/Assets/Tremble/Utils/FieldUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 52da94c615dc49adbb44d9880ad075c6 +timeCreated: 1705686190 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/FieldUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/FloatFormatUtil.cs b/Assets/Tremble/Utils/FloatFormatUtil.cs new file mode 100644 index 0000000..8e8e395 --- /dev/null +++ b/Assets/Tremble/Utils/FloatFormatUtil.cs @@ -0,0 +1,39 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Globalization; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public static class FloatFormatUtil + { + private static readonly char[] s_FormatArr = { 'F', '0' }; + + public static string ToStringInvariant(this float f, int decimals = 2) + { + if (decimals > 9) + throw new ArgumentException("ToStringInvariant only supports up to 9 decimal places :("); + + s_FormatArr[1] = (char)('0' + decimals); + return f.ToString(new(s_FormatArr), CultureInfo.InvariantCulture); + } + + public static string ToStringInvariant(this Vector2 v, int decimals = 2) + => $"{v.x.ToStringInvariant(decimals)} {v.y.ToStringInvariant(decimals)}"; + + public static string ToStringInvariant(this Vector3 v, int decimals = 2) + => $"{v.x.ToStringInvariant(decimals)} {v.y.ToStringInvariant(decimals)} {v.z.ToStringInvariant(decimals)}"; + + public static string ToStringInvariant(this Color c, int decimals = 2) + => $"{c.r.ToStringInvariant(decimals)} {c.g.ToStringInvariant(decimals)} {c.b.ToStringInvariant(decimals)}"; + + public static bool TryParseFloat(this string s, out float f) + => float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out f); + public static bool TryParseFloat(this ReadOnlySpan s, out float f) + => float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out f); + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/FloatFormatUtil.cs.meta b/Assets/Tremble/Utils/FloatFormatUtil.cs.meta new file mode 100644 index 0000000..ff7c5a6 --- /dev/null +++ b/Assets/Tremble/Utils/FloatFormatUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 42bb3c4e19fb4804bfaa5dd98d17cee0 +timeCreated: 1722209446 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/FloatFormatUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/GameObjectUtil.cs b/Assets/Tremble/Utils/GameObjectUtil.cs new file mode 100644 index 0000000..5345064 --- /dev/null +++ b/Assets/Tremble/Utils/GameObjectUtil.cs @@ -0,0 +1,28 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public static class GameObjectUtil + { + public static GameObject Find_Recursive(this GameObject go, string findName) + { + if (go.name.EqualsInvariant(findName, caseSensitive: true)) + return go; + + for (int i = 0; i < go.transform.childCount; i++) + { + GameObject inner = Find_Recursive(go.transform.GetChild(i).gameObject, findName); + if (inner) + return inner; + } + + return null; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/GameObjectUtil.cs.meta b/Assets/Tremble/Utils/GameObjectUtil.cs.meta new file mode 100644 index 0000000..850ffd9 --- /dev/null +++ b/Assets/Tremble/Utils/GameObjectUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 9a7a9d2123c941af9e5751aad84bf341 +timeCreated: 1724939527 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/GameObjectUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/InitHack.cs b/Assets/Tremble/Utils/InitHack.cs new file mode 100644 index 0000000..7c33f7b --- /dev/null +++ b/Assets/Tremble/Utils/InitHack.cs @@ -0,0 +1,11 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +// This allows you to use properties with init-only setters, +// e.g. public int MyProperty { get; init; } +namespace System.Runtime.CompilerServices +{ + public struct IsExternalInit {} +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/InitHack.cs.meta b/Assets/Tremble/Utils/InitHack.cs.meta new file mode 100644 index 0000000..10e1f2c --- /dev/null +++ b/Assets/Tremble/Utils/InitHack.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: b9c41efc8d38494ebd53a358fbff6c96 +timeCreated: 1707729573 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/InitHack.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/MD3Util.cs b/Assets/Tremble/Utils/MD3Util.cs new file mode 100644 index 0000000..d5e1c97 --- /dev/null +++ b/Assets/Tremble/Utils/MD3Util.cs @@ -0,0 +1,361 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// This class based on BSP Map Tools for Unity by John Evans (evans3d512@gmail.com) +// + +using System; +using System.Collections.Generic; +using UnityEngine; +using System.IO; + +namespace TinyGoose.Tremble +{ + public static class MD3Util + { + private const int MAX_SURF_INDICES = 12000; + + private const string IDP3_SIGNATURE = "IDP3"; + private const int IDP3_VERSION = 15; + + public static bool HasModel(GameObject prefab, out Bounds bounds) + { + bool result = false; + bounds = new(); + + foreach (MeshFilter mf in prefab.GetComponentsInChildren()) + { + MeshRenderer mr = mf.GetComponent(); + if (!mr) + continue; + + if (!mf.sharedMesh) + continue; + + result = true; + GetTransformedMeshVertices(mr.transform, isSkinnedMesh: false, mf.sharedMesh, ref bounds); + } + + foreach (SkinnedMeshRenderer smr in prefab.GetComponentsInChildren()) + { + if (!smr.sharedMesh) + continue; + + result = true; + GetTransformedMeshVertices(smr.transform, isSkinnedMesh: true, smr.sharedMesh, ref bounds); + } + + return result; + } + + private static Bounds GetPrefabBounds(GameObject prefab) + { + Bounds boundingBox = new(); + + foreach (MeshFilter mf in prefab.GetComponentsInChildren()) + { + MeshRenderer mr = mf.GetComponent(); + if (!mr) + continue; + + if (!mf.sharedMesh) + continue; + + GetTransformedMeshVertices(mr.transform, isSkinnedMesh: false, mf.sharedMesh, ref boundingBox); + } + + foreach (SkinnedMeshRenderer smr in prefab.GetComponentsInChildren()) + { + if (!smr.sharedMesh) + continue; + GetTransformedMeshVertices(smr.transform, isSkinnedMesh: true, smr.sharedMesh, ref boundingBox); + } + + return boundingBox; + } + + public static Vector3 GetPrefabUnitySpawnOffset(GameObject prefab, float importScale) + { + Bounds boundingBox = GetPrefabBounds(prefab); + + Vector3 boundsMin = boundingBox.min.UnityToQ3Vector(scale: importScale); + Vector3 boundsMax = boundingBox.max.UnityToQ3Vector(scale: importScale); + Vector3 boundsCentre = (boundsMin + boundsMax) / 2f; + + return -boundsCentre.Q3ToUnityVector(importScale); + } + + public static bool SaveMD3(GameObject prefab, string md3Path, MaterialNameLookup materialNameLookup, float importScale, out Bounds boundingBox) + { + // Gather MD3 surfaces to write from renderers + List surfaces = GatherMD3SurfacesFromRenderers(prefab, materialNameLookup, out boundingBox, out int allSurfacesSize); + if (surfaces.Count == 0) + return false; + + // Now write the MD3 file + int fileSize = allSurfacesSize + 164; + string modelName = GetPathInFolder(md3Path, "baseq3"); + + using FileStream stream = new(md3Path, FileMode.Create, FileAccess.Write, FileShare.None, 32768); + using StreamWriteIO writer = new(stream); + + // IDP3 signature & version + writer.WriteString(IDP3_SIGNATURE); + writer.WriteInt32(IDP3_VERSION); + + // Model name (64 chars) + writer.WriteString(modelName, 64); + + // Flags, frames, tags, surfaces, skins + writer.WriteInt32(0); // flags 0 + writer.WriteInt32(1); // frames + writer.WriteInt32(0); // tags 0 + writer.WriteInt32(surfaces.Count); // surfaces + writer.WriteInt32(0); // skins 0 + + // Write metrics + const int FRAME_OFFSET = 108; + writer.WriteInt32(FRAME_OFFSET); + const int TAGS_OFFSET = 164; + writer.WriteInt32(TAGS_OFFSET); + const int SURFACE_OFFSET = 164; + writer.WriteInt32(SURFACE_OFFSET); + + writer.WriteInt32(fileSize); // file size bytes + + // Write first frame + Vector3 boundsMin = boundingBox.min.UnityToQ3Vector(scale: importScale); + Vector3 boundsMax = boundingBox.max.UnityToQ3Vector(scale: importScale); + Vector3 boundsCentre = (boundsMin + boundsMax) / 2f; + FixBounds(ref boundsMin, ref boundsMax); + + writer.WriteFloat(boundsMin.x); // bounds (min) + writer.WriteFloat(boundsMin.y); + writer.WriteFloat(boundsMin.z); + + writer.WriteFloat(boundsMax.x); // bounds (max) + writer.WriteFloat(boundsMax.y); + writer.WriteFloat(boundsMax.z); + + writer.WriteFloat(0f); // origin + writer.WriteFloat(0f); + writer.WriteFloat(0f); + + writer.WriteFloat((boundsMax - boundsMin).magnitude); // radius + + writer.WriteString("frame1", 16); // frame name + + // Write surfaces + for (int surfIdx = 0; surfIdx < surfaces.Count; surfIdx++) + { + MD3Surface surface = surfaces[surfIdx]; + int surfVertCount = surface.Vertices.Length; + + int triangleCount = surfVertCount / 3; + int triangleOffset = 176; + int shaderOffset = 108; + int uvsOffset = triangleOffset + triangleCount * 12; + int vtxOffset = uvsOffset + surfVertCount * 8; + + writer.WriteString(IDP3_SIGNATURE); // IDP3 + + // Surface + writer.WriteString(surface.Name, 64); // surf name + writer.WriteInt32(0); // flags 0 + writer.WriteInt32(1); // frames + writer.WriteInt32(1); // shaders + + writer.WriteInt32(surfVertCount); + writer.WriteInt32(triangleCount); + writer.WriteInt32(triangleOffset); + writer.WriteInt32(shaderOffset); + writer.WriteInt32(uvsOffset); + writer.WriteInt32(vtxOffset); + writer.WriteInt32(surface.DataSize); + + // Shader + writer.WriteString($"models/{surface.Texture}.png", 64); // shader name + writer.WriteInt32(surfIdx); // Shader index + + // Tris + for (int triIdx = 0; triIdx < surfVertCount; triIdx++) + { + writer.WriteInt32(triIdx); + } + + // Surfs + for (int uvIdx = 0; uvIdx < surface.Uvs.Length; uvIdx++) + { + writer.WriteFloat(surface.Uvs[uvIdx].x); + writer.WriteFloat(1f - surface.Uvs[uvIdx].y); + } + + // Verts + for (int vertIdx = 0; vertIdx < surfVertCount; vertIdx++) + { + Vector3 md3Vector = surface.Vertices[vertIdx].UnityToQ3Vector(scale: importScale); + md3Vector -= boundsCentre; + + writer.WriteInt16((short)(md3Vector.x * 64f)); + writer.WriteInt16((short)(md3Vector.y * 64f)); + writer.WriteInt16((short)(md3Vector.z * 64f)); + writer.WriteNormalAsLatLong(surface.Normals[vertIdx]); + } + } + + return true; + } + + private static List GatherMD3SurfacesFromRenderers(GameObject prefab, MaterialNameLookup materialNameLookup, out Bounds boundingBox, out int allSurfacesSize) + { + List surfaces = new(); + allSurfacesSize = 0; + + boundingBox = new(); + + foreach (MeshFilter mf in prefab.GetComponentsInChildren()) + { + MeshRenderer mr = mf.GetComponent(); + if (!mr) + continue; + + AddMeshToMD3(mr.transform, isSkinnedMesh: false, mf.sharedMesh, mr.sharedMaterials, surfaces, materialNameLookup, ref allSurfacesSize, ref boundingBox); + } + + foreach (SkinnedMeshRenderer smr in prefab.GetComponentsInChildren()) + { + AddMeshToMD3(smr.transform, isSkinnedMesh: true, smr.sharedMesh, smr.sharedMaterials, surfaces, materialNameLookup, ref allSurfacesSize, ref boundingBox); + } + + return surfaces; + } + + private static void FixBounds(ref Vector3 min, ref Vector3 max) + { + Vector3 newMin = new(Mathf.Min(min.x, max.x), Mathf.Min(min.y, max.y), Mathf.Min(min.z, max.z)); + Vector3 newMax = new(Mathf.Max(min.x, max.x), Mathf.Max(min.y, max.y), Mathf.Max(min.z, max.z)); + + min = newMin; + max = newMax; + } + + private static Vector3[] GetTransformedMeshVertices(Transform meshTransform, bool isSkinnedMesh, Mesh unityMesh, ref Bounds allBounds) + { + // Gather mesh data + Vector3[] meshVertices = unityMesh.vertices; + + Vector3 min = allBounds.min; + Vector3 max = allBounds.max; + + Matrix4x4 ltwMatrix = meshTransform.localToWorldMatrix; + for (int i = 0; i < meshVertices.Length; i++) + { + // Transform vertex according to the prefab root it's from + if (isSkinnedMesh) + { + meshVertices[i] = meshTransform.TransformVector(meshVertices[i]); + } + else + { + meshVertices[i] = ltwMatrix.MultiplyPoint(meshVertices[i]); + } + + // Clamp vertices, MD3 uses Int16 vectors for vertex positions, so each vertex can be in range from -12.75 to 12.75 + float meshVertX = meshVertices[i].x; // = Mathf.Clamp(meshVertices[i].x, -12.75f, +12.75f); + float meshVertY = meshVertices[i].y; // = Mathf.Clamp(meshVertices[i].y, -12.75f, +12.75f); + float meshVertZ = meshVertices[i].z; // = Mathf.Clamp(meshVertices[i].z, -12.75f, +12.75f); + + // Inlined Mathf.Min and Mathf.Max + min.x = min.x < meshVertX ? min.x : meshVertX; + min.y = min.y < meshVertY ? min.y : meshVertY; + min.z = min.z < meshVertZ ? min.z : meshVertZ; + + max.x = max.x > meshVertX ? max.x : meshVertX; + max.y = max.y > meshVertY ? max.y : meshVertY; + max.z = max.z > meshVertZ ? max.z : meshVertZ; + } + allBounds.SetMinMax(min, max); + + return meshVertices; + } + + private static void AddMeshToMD3(Transform meshTransform, bool isSkinnedMesh, Mesh unityMesh, Material[] materials, List surfaces, MaterialNameLookup materialNameLookup, ref int allSurfacesSize, ref Bounds allBounds) + { + // Gather triangles per submesh + List submeshTriIndices = new(unityMesh.subMeshCount); + for (int i = 0; i < unityMesh.subMeshCount; i++) + { + submeshTriIndices.Add(unityMesh.GetTriangles(i)); + } + + // Gather mesh data + Vector3[] meshVertices = GetTransformedMeshVertices(meshTransform, isSkinnedMesh, unityMesh, ref allBounds); + Vector3[] meshNormals = unityMesh.normals; + Vector2[] meshUVs = unityMesh.uv; + + // Write one surface per Unity submesh + for (int submeshIdx = 0; submeshIdx < unityMesh.subMeshCount; submeshIdx++) + { + if (submeshTriIndices[submeshIdx].Length >= MAX_SURF_INDICES) + { + Debug.LogError("Mesh has too many surfaces - skipping!"); + continue; + } + + // Add verts and triangles + int vertIndexCount = submeshTriIndices[submeshIdx].Length; + + Vector3[] surfaceVertices = new Vector3[vertIndexCount]; + Vector3[] surfaceNormals = new Vector3[vertIndexCount]; + Vector2[] surfaceUVs = new Vector2[vertIndexCount]; + + int[] thisSubmeshTriIndices = submeshTriIndices[submeshIdx]; + for (int vIdx = 0; vIdx < vertIndexCount; vIdx++) + { + int index = thisSubmeshTriIndices[vIdx]; + + surfaceVertices[vIdx] = meshVertices[index]; + surfaceNormals[vIdx] = meshNormals[index]; + + // Some meshes have no UVs (uh-oh...) + if (meshUVs.Length > 0) + { + surfaceUVs[vIdx] = meshUVs[index]; + } + } + + // Write material names + string textureName; + if (materials[submeshIdx] && materialNameLookup != null) + { + string path = TrembleAssetLoader.GetPath(materials[submeshIdx]); + textureName = materialNameLookup.GetPrefabNameFromMaterialPath(path); + } + else + { + textureName = "missing"; + } + + // Create surface + MD3Surface currentSurface = new() + { + Name = $"surface{surfaces.Count}", + Texture = textureName, + + Vertices = surfaceVertices, + Normals = surfaceNormals, + Uvs = surfaceUVs, + }; + + surfaces.Add(currentSurface); + allSurfacesSize += currentSurface.DataSize; + } + } + + private static string GetPathInFolder(string path, string folder) + { + int i = path.IndexOfInvariant(folder + "/"); + return path.Substring(i + folder.Length + 1); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/MD3Util.cs.meta b/Assets/Tremble/Utils/MD3Util.cs.meta new file mode 100644 index 0000000..29d184e --- /dev/null +++ b/Assets/Tremble/Utils/MD3Util.cs.meta @@ -0,0 +1,19 @@ +fileFormatVersion: 2 +guid: b6df817cee22fba4bb61fab7a3e48367 +timeCreated: 1628505675 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/MD3Util.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/MapTextureSnapshotter.cs b/Assets/Tremble/Utils/MapTextureSnapshotter.cs new file mode 100644 index 0000000..a4160ac --- /dev/null +++ b/Assets/Tremble/Utils/MapTextureSnapshotter.cs @@ -0,0 +1,468 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using UnityEngine; +using UnityEngine.Experimental.Rendering; +using UnityEngine.Rendering; +using Debug = UnityEngine.Debug; + +#if HDRP_INSTALLED +using File = System.IO.File; +#endif + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace TinyGoose.Tremble +{ + /// + /// Camera/lighting setup for taking material screenshots. Do not use directly. + /// + public class MapTextureSnapshotter + { + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private GameObject m_SceneRoot; + private Camera m_Camera; + private MeshRenderer m_Renderer; + + private readonly Dictionary m_RenderTextures = new(); + private Texture2D m_CaptureTexture; + private Light m_StudioLight; + + private AmbientMode m_OriginalAmbientMode; + private Color m_OriginalAmbientColour; + private float m_OriginalAmbientIntensity; + + private readonly List m_Lights = new(); + + private TrembleSyncSettings m_Settings; + + private struct TexturePair + { + public Texture2D Texture; + public RenderTexture RenderTexture; + } + + public void Init(TrembleSyncSettings settings) + { + m_Settings = settings; + + SetupGameObjects(m_Settings.MaterialCaptureLightIntensity, m_Settings.MaterialCaptureLightAngle); + + List resolutions = new() + { + m_Settings.MaterialExportSize.ToVector2IntSize() + }; + + foreach (Material material in m_Settings.GetMaterialGroupsOrDefault().SelectMany(mg => mg.Materials)) + { + MaterialRenderData renderData = m_Settings.GetMaterialRenderData(material); + Vector2Int dataRes = new(renderData.ResolutionX.ToIntSize(), renderData.ResolutionY.ToIntSize()); + + if (!resolutions.Contains(dataRes)) + resolutions.Add(dataRes); + + if (!material.TryGetMainTex(out Texture2D tex)) + continue; + + Vector2Int res = new(tex.width, tex.height); + if (!resolutions.Contains(res)) + resolutions.Add(res); + } + + foreach (Vector2Int res in resolutions) + { + GetOrCreateTexturePair(res); + } + + // Move far away! + m_SceneRoot.transform.position = Vector3.up * 10000f; + + // Set up lighting + m_OriginalAmbientMode = RenderSettings.ambientMode; + m_OriginalAmbientColour = RenderSettings.ambientLight; + m_OriginalAmbientIntensity = RenderSettings.ambientIntensity; + +#if UNITY_6000_5_OR_NEWER + foreach (Light foundLight in GameObject.FindObjectsByType(FindObjectsInactive.Exclude)) +#elif UNITY_2022_1_OR_NEWER + foreach (Light foundLight in GameObject.FindObjectsByType(FindObjectsInactive.Exclude, FindObjectsSortMode.None)) +#else + foreach (Light foundLight in GameObject.FindObjectsOfType(false)) +#endif + { + if (!foundLight.gameObject.activeSelf || foundLight == m_StudioLight) + continue; + + m_Lights.Add(foundLight.gameObject); + foundLight.gameObject.SetActive(false); + } + + RenderSettings.ambientMode = AmbientMode.Flat; + RenderSettings.ambientLight = Color.white; + } + + public void DeInit() + { + GameObject.DestroyImmediate(m_SceneRoot); + + if (m_RenderTextures.Values.Any(x => RenderTexture.active == x.RenderTexture)) + { + RenderTexture.active = null; + } + + // Release RT next frame - it seems if it's active above, it's not + // cleared/unset until next frame causing an error (: + foreach (TexturePair texPair in m_RenderTextures.Values) + { +#if UNITY_EDITOR + EditorApplication.delayCall += () => + { + if (texPair.RenderTexture) + { +#endif + texPair.RenderTexture.Release(); +#if UNITY_EDITOR + } + }; +#endif + } + m_RenderTextures.Clear(); + + foreach (GameObject foundLight in m_Lights) + { + foundLight.SetActive(true); + } + m_Lights.Clear(); + + // Restore lighting + RenderSettings.ambientMode = m_OriginalAmbientMode; + RenderSettings.ambientLight = m_OriginalAmbientColour; + RenderSettings.ambientIntensity = m_OriginalAmbientIntensity; + } + + private TexturePair GetOrCreateTexturePair(Vector2Int resolution) + { + if (!m_RenderTextures.TryGetValue(resolution, out TexturePair texturePair)) + { + RenderTexture rt = new(resolution.x, resolution.y, 8, GraphicsFormat.R8G8B8A8_UNorm); + rt.Create(); + + Texture2D output = new(resolution.x, resolution.y, rt.graphicsFormat, TextureCreationFlags.None); + + m_RenderTextures[resolution] = texturePair = new() + { + Texture = output, + RenderTexture = rt, + }; + } + + return texturePair; + } + + public void SnapshotMaterial(Material m, string outPath) + { + MaterialRenderData renderData = m_Settings.GetMaterialRenderData(m); + + Vector2Int res = renderData.GetResolutionOrDefault(); + + Texture2D mainTex = null; + if (renderData.ExportMode == MaterialImportMode.Dynamic) + { + if (!m.TryGetMainTex(out mainTex)) + { + renderData.ExportMode = MaterialImportMode.FixedSize; + Debug.LogWarning($"Couldn't find a Main Texture for material \"{m.name}\"," + + "falling back to legacy render mode." + + "Make sure the shader has a texture marked as [Main Texture] or" + + "a texture named _MainTex, _BaseColor, or _Color."); + } + + if (mainTex && !renderData.IsResolutionOverridden) + { + res = new(mainTex.width, mainTex.height); + } + } + + TexturePair tex = GetOrCreateTexturePair(res); + + // Do not remove - these are used in HDRP + bool createdTempMaterial = false; + Material tempMaterial = null; + + switch (renderData.ExportMode) + { + case MaterialImportMode.FixedSize: + // Set up RT and material - we have to save it for HDRP + createdTempMaterial = TryCreateUnlitCopy(m, out tempMaterial, renderData.ExportMode); + +#if HDRP_INSTALLED && UNITY_EDITOR + if (createdTempMaterial) + { + string tempName = Path.GetFileNameWithoutExtension(AssetDatabase.GetAssetPath(m)) + "_TrembleTemp.mat"; + string tempPath = Path.Combine("Assets", tempName); + AssetDatabase.CreateAsset(tempMaterial, tempPath); + } +#endif + + m_Renderer.material = tempMaterial ? tempMaterial : m; + + // Render once + m_Camera.targetTexture = tex.RenderTexture; + m_Camera.Render(); + + if (RenderTexture.active != tex.RenderTexture) + RenderTexture.active = tex.RenderTexture; + + // Copy texture from RT + tex.Texture.ReadPixels(new(0, 0, res.x, res.y), 0, 0); + File.WriteAllBytes(outPath, tex.Texture.EncodeToPNG()); + + break; + case MaterialImportMode.Dynamic: +#if UNITY_EDITOR + string path = AssetDatabase.GetAssetPath(mainTex); + + //TODO(jwf): colourise by main colour? + + // Is it a PNG, and we're not overriding resolution? Just copy it directly + if (!renderData.IsResolutionOverridden && path.EndsWithInvariant(".png")) + { + File.Copy(Application.dataPath + path.Remove(0, 6), outPath, true); + return; + } +#endif + + // Else we make a copy to resize + m_Camera.targetTexture = null; + GL.sRGBWrite = true; + Graphics.Blit(mainTex, tex.RenderTexture); + + RenderTexture.active = tex.RenderTexture; + + // Copy texture from RT + tex.Texture.ReadPixels(new(0, 0, res.x, res.y), 0, 0); + File.WriteAllBytes(outPath, tex.Texture.EncodeToPNG()); + break; + } + + // Delete temp material, if we made one +#if HDRP_INSTALLED && UNITY_EDITOR + if (createdTempMaterial) + { + AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(tempMaterial)); + } +#endif + } + + private static readonly Dictionary s_ShaderRemaps = new() + { + { "Standard", "Legacy Shaders/Diffuse" }, // or Particles/Standard Unlit? + { "Universal Render Pipeline/Lit", "Universal Render Pipeline/Unlit" }, + { "HDRP/Lit", "HDRP/Unlit" } + }; + + private bool TryCreateUnlitCopy(Material material, out Material newMaterial, MaterialImportMode mode) + { + // No lights in the scene. Assume we don't need to tweak materials as they're using ambient colour + if (mode is MaterialImportMode.Dynamic || (m_Lights.Count == 0 && mode is MaterialImportMode.FixedSize)) + { + newMaterial = material; + return false; + } + +#if UNITY_EDITOR + foreach ((string originalShader, string remapShader) in s_ShaderRemaps) + { + if (!material.shader.name.Equals(originalShader)) + continue; + + newMaterial = mode is MaterialImportMode.FixedSize ? new(Shader.Find(remapShader)) : new(Shader.Find(originalShader)); + CopyMaterialProperties_Recursive(material, newMaterial); + + // Ensure colours/textures set properly + newMaterial.color = material.color; + newMaterial.mainTexture = material.mainTexture; + + // Render after post-processing (mostly for HDRP) + newMaterial.renderQueue = 2501; + + return true; + } +#endif + + newMaterial = material; + return false; + } + + [Conditional("UNITY_EDITOR")] + private static void CopyMaterialProperties_Recursive(Material from, Material to) + { +#if UNITY_EDITOR + +#if UNITY_2022_1_OR_NEWER + if (from.parent) + { + // If parent, copy that one first! + CopyMaterialProperties_Recursive(from.parent, to); + } +#endif + + // Copy shader keywords + to.shaderKeywords = from.shaderKeywords; + + // Iterate over all properties of the material + Shader shader = from.shader; + +#if UNITY_6000_5_OR_NEWER + int propertyCount = shader.GetPropertyCount(); + + for (int i = 0; i < propertyCount; i++) + { + // Get the property type and name + ShaderPropertyType propertyType = shader.GetPropertyType(i); + string propertyName = shader.GetPropertyName(i); + + // Copy the property value based on its type + switch (propertyType) + { + case ShaderPropertyType.Color: + to.SetColor(propertyName, from.GetColor(propertyName)); + break; + case ShaderPropertyType.Vector: + to.SetVector(propertyName, from.GetVector(propertyName)); + break; + case ShaderPropertyType.Float: + case ShaderPropertyType.Range: + to.SetFloat(propertyName, from.GetFloat(propertyName)); + break; + case ShaderPropertyType.Texture: + to.SetTexture(propertyName, from.GetTexture(propertyName)); + to.SetTextureOffset(propertyName, from.GetTextureOffset(propertyName)); + to.SetTextureScale(propertyName, from.GetTextureScale(propertyName)); + break; + } + } +#else + int propertyCount = ShaderUtil.GetPropertyCount(shader); + + for (int i = 0; i < propertyCount; i++) + { + // Get the property type and name + ShaderUtil.ShaderPropertyType propertyType = ShaderUtil.GetPropertyType(shader, i); + string propertyName = ShaderUtil.GetPropertyName(shader, i); + + // Copy the property value based on its type + switch (propertyType) + { + case ShaderUtil.ShaderPropertyType.Color: + to.SetColor(propertyName, from.GetColor(propertyName)); + break; + case ShaderUtil.ShaderPropertyType.Vector: + to.SetVector(propertyName, from.GetVector(propertyName)); + break; + case ShaderUtil.ShaderPropertyType.Float: + case ShaderUtil.ShaderPropertyType.Range: + to.SetFloat(propertyName, from.GetFloat(propertyName)); + break; + case ShaderUtil.ShaderPropertyType.TexEnv: + to.SetTexture(propertyName, from.GetTexture(propertyName)); + to.SetTextureOffset(propertyName, from.GetTextureOffset(propertyName)); + to.SetTextureScale(propertyName, from.GetTextureScale(propertyName)); + break; + } + } +#endif + + // Copy render queue and other settings + to.renderQueue = from.renderQueue; + to.enableInstancing = from.enableInstancing; + to.doubleSidedGI = from.doubleSidedGI; +#endif + } + + + private void SetupGameObjects(float lightIntensity, float lightAngle) + { + m_SceneRoot = new("Scene Root"); + + // Set up gameobjects + GameObject snapCamera = new("Camera"); + snapCamera.transform.SetParent(m_SceneRoot.transform, false); + snapCamera.transform.localPosition = new(0f, 0f, -0.1f); + + m_Camera = snapCamera.AddComponent(); + m_Camera.orthographic = true; + m_Camera.allowHDR = false; + m_Camera.orthographicSize = 0.5f; + m_Camera.nearClipPlane = 0.01f; + m_Camera.farClipPlane = 0.5f; + m_Camera.backgroundColor = Color.black; + m_Camera.clearFlags = CameraClearFlags.Color; + + Vector3 lightDirection = Vector3.Lerp(Vector3.right, Vector3.forward, lightAngle); + + GameObject snapLight = new("Light"); + snapLight.transform.SetParent(m_SceneRoot.transform, false); + snapLight.transform.localPosition = new(0f, 0f, -0.1f); + snapLight.transform.rotation = Quaternion.LookRotation(lightDirection); + m_StudioLight = snapLight.AddComponent(); + m_StudioLight.type = LightType.Directional; + m_StudioLight.intensity = lightIntensity; + m_StudioLight.shadows = LightShadows.None; + m_StudioLight.color = Color.white; + + GameObject snapQuad = new("Quad"); + snapQuad.transform.SetParent(m_SceneRoot.transform, false); + snapQuad.transform.localPosition = Vector3.zero; + + MeshFilter meshFilter = snapQuad.AddComponent(); + meshFilter.sharedMesh = CreateQuadMesh(); + + m_Renderer = snapQuad.AddComponent(); + } + + private Mesh CreateQuadMesh() + { + Mesh quadMesh = new() + { + name = "Quad", + vertices = new Vector3[] + { + new(-0.5f, -0.5f, 0f), + new(-0.5f, +0.5f, 0f), + new(+0.5f, +0.5f, 0f), + new(+0.5f, -0.5f, 0f), + }, + normals = new Vector3[] + { + new(0f, 0f, -1f), + new(0f, 0f, -1f), + new(0f, 0f, -1f), + new(0f, 0f, -1f), + }, + uv = new Vector2[] + { + new(0f, 0f), + new(0f, 1f), + new(1f, 1f), + new(1f, 0f), + }, + }; + + List indices = new() { 0, 1, 2, 0, 2, 3 }; + quadMesh.SetIndices(indices, MeshTopology.Triangles, 0); + return quadMesh; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/MapTextureSnapshotter.cs.meta b/Assets/Tremble/Utils/MapTextureSnapshotter.cs.meta new file mode 100644 index 0000000..3dd612d --- /dev/null +++ b/Assets/Tremble/Utils/MapTextureSnapshotter.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: cd6405c6b01049ba9a15b8f11f80f46d +timeCreated: 1707139093 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/MapTextureSnapshotter.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/MeshBuilder.cs b/Assets/Tremble/Utils/MeshBuilder.cs new file mode 100644 index 0000000..4e9a261 --- /dev/null +++ b/Assets/Tremble/Utils/MeshBuilder.cs @@ -0,0 +1,451 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering; + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace TinyGoose.Tremble +{ + public class MeshBuilder + { + public delegate Material FindMaterialFunc(string name); + + // ----------------------------------------------------------------------------------------------------------------------------- + // Setup + // ----------------------------------------------------------------------------------------------------------------------------- + private readonly TrembleMapImportSettings m_ImportSettings; + private readonly string m_WorldspawnName; + private readonly float m_SmoothingAngle; + private readonly float m_MaxMeshSurfaceArea; + private readonly FindMaterialFunc m_MaterialFinder; + + // ----------------------------------------------------------------------------------------------------------------------------- + // State + // ----------------------------------------------------------------------------------------------------------------------------- + private int m_MeshCounter; + + private readonly List m_FaceIndicesBuffer = new(); + private readonly List m_MeshVerticesBuffer = new(2048); + private readonly List m_MeshSubmeshesBuffer = new(16); + private readonly Dictionary m_BaseIndexToIndex = new(2048); + + public MeshBuilder(TrembleMapImportSettings importSettings, FindMaterialFunc materialFinder, string worldspawnName, float smoothingAngle, float maxMeshSurfaceArea) + { + m_ImportSettings = importSettings; + m_WorldspawnName = worldspawnName; + m_SmoothingAngle = smoothingAngle; + m_MaxMeshSurfaceArea = maxMeshSurfaceArea; + m_MaterialFinder = materialFinder; + } + + private static readonly HashSet s_InnerFaceList = new(2048); + public void BuildMesh_Recursive(MapBsp mapBsp, Transform parent, int nodeID, HashSet faceList, float importScale, int unityLayer, List intoListOrNull = null) + { + // Not a leaf - recurse unless smol + if (nodeID >= 0) + { + bool subdivide = TrembleSyncSettings.Get().SubdivideAllLeafs; + ref BspNode node = ref mapBsp.Nodes[nodeID]; + + if (!subdivide) + { + float sqrSurfArea = 0; + BspParser.GetSurfaceAreaSqr(mapBsp, node, ref sqrSurfArea, faceList); + + subdivide = (sqrSurfArea > m_MaxMeshSurfaceArea * m_MaxMeshSurfaceArea); + } + + if (subdivide) + { + s_InnerFaceList.Clear(); + BuildMesh_Recursive(mapBsp, parent, node.Child1, s_InnerFaceList, importScale, unityLayer, intoListOrNull); + BuildMesh_Recursive(mapBsp, parent, node.Child2, s_InnerFaceList, importScale, unityLayer, intoListOrNull); + + // Don't build this one + return; + } + } + + // This is a leaf, or as small as we want to go - create! + Bounds bounds = new(); + if (nodeID < 0) + { + bounds.min = new Vector3(mapBsp.Leaves[-nodeID - 1].Min.x, mapBsp.Leaves[-nodeID - 1].Min.z, mapBsp.Leaves[-nodeID - 1].Min.y) * importScale; + bounds.max = new Vector3(mapBsp.Leaves[-nodeID - 1].Max.x, mapBsp.Leaves[-nodeID - 1].Max.z, mapBsp.Leaves[-nodeID - 1].Max.y) * importScale; + } + else + { + bounds.min = new Vector3(mapBsp.Nodes[nodeID].Min.x, mapBsp.Nodes[nodeID].Min.z, mapBsp.Nodes[nodeID].Min.y) * importScale; + bounds.max = new Vector3(mapBsp.Nodes[nodeID].Max.x, mapBsp.Nodes[nodeID].Max.z, mapBsp.Nodes[nodeID].Max.y) * importScale; + } + + GameObject meshGo = BuildMesh(mapBsp, parent, nodeID, true, m_WorldspawnName, true, bounds.center, true); + if (meshGo) + { + meshGo.layer = unityLayer; + intoListOrNull?.Add(meshGo); + } + } + + public GameObject BuildMesh(MapBsp mapBsp, Transform parent, int sourceID, bool isBspRoot, string modelName, bool isFromNode, Vector3 origin, bool isStatic, Quaternion? rotation = null, float smoothingAngleOverride = -1f) + { + // Thank you again John Evans. This method would have been awful to figure out by myself! + + // Collect face indices + m_FaceIndicesBuffer.Clear(); + if (isFromNode) + { + if (sourceID < 0) + { + BspParser.GetFaceList(mapBsp, mapBsp.Leaves[-sourceID - 1], m_FaceIndicesBuffer); + } + else + { + BspParser.GetFaceList(mapBsp, mapBsp.Nodes[sourceID], m_FaceIndicesBuffer); + } + } + else + { + for (int i = 0; i < mapBsp.Models[sourceID].NumFaces; i++) + { + m_FaceIndicesBuffer.Add(mapBsp.Models[sourceID].StartFaceIdx + i); + } + } + + if (m_FaceIndicesBuffer.Count == 0) + return null; + + // Gather vertices and submeshes + m_MeshVerticesBuffer.Clear(); + m_MeshSubmeshesBuffer.Clear(); + m_BaseIndexToIndex.Clear(); + + // Get faces for this mesh + foreach (BspFace face in m_FaceIndicesBuffer.Select(faceIdx => mapBsp.Faces[faceIdx])) + { + // Get each vertex for this face + for (int faceVertIdx = face.MeshVertexStartIdx; faceVertIdx < face.MeshVertexStartIdx + face.NumMeshVertices; faceVertIdx++) + { + int baseIdx = face.VertexStartIdx + mapBsp.MeshVertices[faceVertIdx]; + + // Find or add a vertex to this mesh + int localVertIndex = FindOrAddVertexForBaseIndex(baseIdx, mapBsp, origin, rotation); + AddVertexToSubmeshWithTexID(m_MeshSubmeshesBuffer, face.TexID, localVertIndex); + } + } + + // Discover and apply materials + List meshMaterials = new(m_MeshSubmeshesBuffer.Count); + { + for (int materialIdx = 0; materialIdx < m_MeshSubmeshesBuffer.Count; materialIdx++) + { + string matName = mapBsp.TexInfos[m_MeshSubmeshesBuffer[materialIdx].TexID].Name; + + // Skip? Skip! + if (matName.ContainsInvariant(TBConsts.SKIP_TEXTURE, caseSensitive: true)) + { + m_MeshSubmeshesBuffer.RemoveAt(materialIdx); + materialIdx--; + + continue; + } + + Material foundMaterial = m_MaterialFinder.Invoke(matName); + meshMaterials.Add(foundMaterial); + + if (foundMaterial) + { + m_ImportSettings.AddDependency(foundMaterial); + } + } + } + + // Create Unity mesh + Mesh mesh = CreateUnityMesh(isBspRoot, ref modelName, m_MeshVerticesBuffer, m_MeshSubmeshesBuffer, smoothingAngleOverride); + + bool isTinyMesh = mesh.triangles.Length == 0 || Mathf.Max(mesh.bounds.extents.x, mesh.bounds.extents.y, mesh.bounds.extents.z) < 0.1f; + if (isTinyMesh) + return null; + + m_ImportSettings.SaveObjectInMap(mesh.name, mesh); + + // Create model GameObject and attach mesh + GameObject modelObject = new(modelName); + modelObject.transform.parent = parent; + modelObject.transform.position = origin; + modelObject.AddComponent().mesh = mesh; + modelObject.AddComponent().sharedMaterials = meshMaterials.ToArray(); + + TrembleSyncSettings syncSettings = TrembleSyncSettings.Get(); + + // Generate mesh collider + Mesh collisionMesh; + if (syncSettings.PipelineSimplifyCollisionMeshes) + { + using TrembleTimerScope _ = new(TrembleTimer.Context.SimplifyCollisionMeshes); + collisionMesh = GenerateSimplifiedUnityCollisionMesh(mesh); + } + else + { + collisionMesh = Mesh.Instantiate(mesh); + } + + collisionMesh.name = mesh.name.Replace("_mesh", "_collision"); + + m_ImportSettings.SaveObjectInMap(collisionMesh.name, collisionMesh); + modelObject.AddComponent().sharedMesh = collisionMesh; + + // Calculate lightmap UVs +#if UNITY_EDITOR + if (isStatic && syncSettings.PipelineUnwrapUV2) + { + using TrembleTimerScope _ = new(TrembleTimer.Context.GenerateUV2); + Unwrapping.GenerateSecondaryUVSet(mesh, new() + { + hardAngle = 70.0f, + angleError = 8.0f, + areaError = 15.0f, + packMargin = mapBsp.Options.UV2Padding, + }); + } +#endif + + modelObject.isStatic = isStatic; + return modelObject; + } + + private Mesh CreateUnityMesh(bool isBspRoot, ref string modelName, List meshVertices, List meshSubmeshes, float smoothingAngleOverride) + { + IndexFormat meshFormat = IndexFormat.UInt16; + foreach (BspSubMesh submesh in meshSubmeshes) + { + if (submesh.Triangles.Count * 3 > 65535) + { + Debug.Log($"Note: Mesh '{modelName}' using 32-bit indices due to high index count. Render performance may be reduced!"); + meshFormat = IndexFormat.UInt32; + break; + } + } + + // Create Unity mesh + Mesh mesh = new() + { + indexFormat = meshFormat, + subMeshCount = meshSubmeshes.Count, + vertices = meshVertices.Select(mv => mv.Position).ToArray(), + normals = meshVertices.Select(mv => mv.Normal).ToArray(), + uv = meshVertices.Select(mv => mv.UV).ToArray(), + }; + + for (int i = 0; i < meshSubmeshes.Count; i++) + { + mesh.SetTriangles(meshSubmeshes[i].Triangles.ToArray(), i); + } + mesh.RecalculateBounds(); + mesh.RecalculateTangents(); + + // Name the mesh + if (isBspRoot) + { + modelName += $"_{++m_MeshCounter}"; + mesh.name = $"{modelName}_mesh"; + } + else + { + mesh.name = $"{modelName}_{++m_MeshCounter}_mesh"; + } + + float smoothingAngle = m_SmoothingAngle; + if (smoothingAngleOverride >= 0f) + smoothingAngle = smoothingAngleOverride; + + // Smooth out normals if required + if (smoothingAngle > 0 && TrembleSyncSettings.Get().PipelineSmoothMeshNormals) + { + using TrembleTimerScope _ = new(TrembleTimer.Context.SmoothMeshNormals); + SmoothMeshNormals(mesh, smoothingAngle); + } + + return mesh; + } + + private int FindOrAddVertexForBaseIndex(int baseIdx, MapBsp mapBsp, Vector3 origin, Quaternion? rotation) + { + // Find existing value + if (m_BaseIndexToIndex.TryGetValue(baseIdx, out int currentMeshVertIdx)) + return currentMeshVertIdx; + + Vector3 position = mapBsp.Vertices[baseIdx].Position - origin; + Vector3 normal = mapBsp.Vertices[baseIdx].Normal; + + if (rotation != null) + { + position = rotation.Value * position; + normal = rotation.Value * normal; + } + + // Not found, add a new one + BspMeshVertex currentMeshVertex = new() + { + Position = position, + Normal = normal, + UV = mapBsp.Vertices[baseIdx].TexCoord + new Vector2(0.5f, 0.5f), + BaseIndex = baseIdx + }; + m_MeshVerticesBuffer.Add(currentMeshVertex); + m_BaseIndexToIndex.Add(baseIdx, m_MeshVerticesBuffer.Count - 1); + return m_MeshVerticesBuffer.Count - 1; + } + + private static void AddVertexToSubmeshWithTexID(List meshSubmeshes, int texID, int localVertexIdx) + { + // Find a submesh that uses this texture ID + foreach (BspSubMesh subMesh in meshSubmeshes) + { + if (texID != subMesh.TexID) + continue; + + subMesh.Triangles.Add(localVertexIdx); + return; + } + + // Not found, make a new submesh for this face + meshSubmeshes.Add(new() + { + TexID = texID, + Triangles = new() { localVertexIdx }, + }); + } + + // ----------------------------------------------------------------------------------------------------------------------------- + // Utilities + // ----------------------------------------------------------------------------------------------------------------------------- + private static void SmoothMeshNormals(Mesh mesh, float maxAngle = 45.0f) + { + Vector3[] newVertices = mesh.vertices; + Vector3[] newNormals = mesh.normals; + + Vector3[] originalNormals = new Vector3[newNormals.Length]; + Array.Copy(newNormals, originalNormals, newNormals.Length); + + float cosThreshold = Mathf.Cos(Mathf.Deg2Rad * maxAngle); + + for (int i = 0; i < newVertices.Length; i++) + { + int groupCount = 1; + Vector3 currentNormal = originalNormals[i]; + + for (int j = 0; j < newVertices.Length; j++) + { + if (i == j) + continue; + + // Inlined SqrMagnitude to avoid Vector3 .ctor + ref Vector3 from = ref newVertices[i]; + ref Vector3 to = ref newVertices[j]; + + float xDiff = from.x - to.x; + float yDiff = from.y - to.y; + float zDiff = from.z - to.z; + float sqrDistance = xDiff * xDiff + yDiff * yDiff + zDiff * zDiff; + + if (sqrDistance >= 0.01f * 0.01f) + continue; + + // Merge verts! + to = from; + + // Also inline AngleBetween and avoid Acos for speed up... these 3 changes reduce from 700ms to about 20ms ;) + float cosBetween = Vector3.Dot(originalNormals[i], originalNormals[j]); + + if (cosBetween > cosThreshold) + { + currentNormal += originalNormals[j]; + groupCount++; + } + } + + if (groupCount >= 2) + { + newNormals[i] = currentNormal / groupCount; + } + } + + mesh.vertices = newVertices; + mesh.normals = newNormals; + mesh.RecalculateBounds(); + mesh.RecalculateTangents(); + } + + private static Mesh GenerateSimplifiedUnityCollisionMesh(Mesh inputMesh, float threshold = 0.01f) + { + Mesh outputMesh = new() { name = inputMesh.name}; + + Vector3[] inputVertices = inputMesh.vertices; + int inputVertexCount = inputMesh.vertexCount; + int[] inputTriangles = inputMesh.triangles; + int[] vertexRemap = new int[inputVertexCount]; + + List newVertices = new() { inputVertices[0] }; + + float sqrThreshold = threshold * threshold; + + for (int inputVertIdx = 0; inputVertIdx < inputVertexCount; inputVertIdx++) + { + bool wasRemapped = false; + + float newVertCount = newVertices.Count; + for (int newVertIdx = 0; newVertIdx < newVertCount; newVertIdx++) + { + Vector3 from = inputVertices[inputVertIdx]; + Vector3 to = newVertices[newVertIdx]; + + float xDiff = from.x - to.x; + float yDiff = from.y - to.y; + float zDiff = from.z - to.z; + float sqrDistance = xDiff * xDiff + yDiff * yDiff + zDiff * zDiff; + + if (sqrDistance > sqrThreshold) + continue; + + vertexRemap[inputVertIdx] = newVertIdx; + wasRemapped = true; + break; + } + + if (!wasRemapped) + { + newVertices.Add(inputVertices[inputVertIdx]); + vertexRemap[inputVertIdx] = newVertices.Count - 1; + } + } + + // Create triangles array + int[] newTriangles = new int[inputTriangles.Length]; + int triPtr = 0; + + for (int i = 0; i < inputTriangles.Length; i += 3) + { + if (vertexRemap[inputTriangles[i]] == vertexRemap[inputTriangles[i + 1]] || vertexRemap[inputTriangles[i]] == vertexRemap[inputTriangles[i + 2]] || vertexRemap[inputTriangles[i + 1]] == vertexRemap[inputTriangles[i + 2]]) + continue; + + newTriangles[triPtr++] = vertexRemap[inputTriangles[i + 0]]; + newTriangles[triPtr++] = vertexRemap[inputTriangles[i + 1]]; + newTriangles[triPtr++] = vertexRemap[inputTriangles[i + 2]]; + } + + outputMesh.vertices = newVertices.ToArray(); + outputMesh.triangles = newTriangles; + return outputMesh; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/MeshBuilder.cs.meta b/Assets/Tremble/Utils/MeshBuilder.cs.meta new file mode 100644 index 0000000..de190b3 --- /dev/null +++ b/Assets/Tremble/Utils/MeshBuilder.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 61078239862345b09915cb704095f22d +timeCreated: 1709824324 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/MeshBuilder.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/NamingConventionUtil.cs b/Assets/Tremble/Utils/NamingConventionUtil.cs new file mode 100644 index 0000000..ca606a5 --- /dev/null +++ b/Assets/Tremble/Utils/NamingConventionUtil.cs @@ -0,0 +1,157 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Text; + +namespace TinyGoose.Tremble +{ + public static class NamingConventionUtil + { + public static string ToNamingConvention(this string input, NamingConvention convention) + { + switch (convention) + { + case NamingConvention.SnakeCase: + return input.ToSnakeCase(); + case NamingConvention.UpperCamelCase: + return CapitaliseFirstLetter(input, true); + case NamingConvention.LowerCamelCase: + return CapitaliseFirstLetter(input, false); + case NamingConvention.HumanFriendly: + return ToHuman(input); + case NamingConvention.PreserveExact: + return input; + } + + return input; + } + + private static readonly StringBuilder s_SnakeBuilder = new(128); + private static string ToSnakeCase(this string inString) + { + s_SnakeBuilder.Clear(); + + for (int i = 0; i < inString.Length; i++) + { + if (inString[i] == ' ') + { + s_SnakeBuilder.Append('_'); + continue; + } + + if (Char.IsUpper(inString[i]) && i > 0) + { + // Not if we just output an underscore! + if (s_SnakeBuilder[^1] != '_') + { + // If the previous character wasn't uppercase + if (!Char.IsUpper(inString[i - 1])) + { + s_SnakeBuilder.Append('_'); + } + // Or the next character isn't uppercase + else if (i < inString.Length - 1 && Char.IsLower(inString[i + 1])) + { + s_SnakeBuilder.Append('_'); + } + } + } + + s_SnakeBuilder.Append(Char.ToLowerInvariant(inString[i])); + } + return s_SnakeBuilder.ToString(); + } + + private static string ToHuman(this string inString) + { + s_SnakeBuilder.Clear(); + + int firstIndex = inString.IndexOf('_') + 1; + + for (int i = firstIndex; i < inString.Length; i++) + { + // Straight up convert underscores to spaces + if (inString[i] == '_') + { + s_SnakeBuilder.Append(' '); + continue; + } + + if (Char.IsUpper(inString[i]) && i > firstIndex) + { + // Not if we just output a space! + if (s_SnakeBuilder[^1] != ' ' && s_SnakeBuilder[^1] != '_') + { + // If the previous character wasn't uppercase + if (!Char.IsUpper(inString[i - 1])) + { + s_SnakeBuilder.Append(' '); + } + // Or the next character isn't uppercase + else if (i < inString.Length - 1 && Char.IsLower(inString[i + 1])) + { + s_SnakeBuilder.Append(' '); + } + } + } + + if (i == firstIndex || s_SnakeBuilder[^1] == ' ') + { + s_SnakeBuilder.Append(Char.ToUpperInvariant(inString[i])); + } + else + { + s_SnakeBuilder.Append(Char.ToLowerInvariant(inString[i])); + } + } + return s_SnakeBuilder.ToString(); + } + + public static string FromHuman(ReadOnlySpan inString) + { + s_SnakeBuilder.Clear(); + + int inBrackets = 0; + + for (int i = 0; i < inString.Length; i++) + { + if (inString[i] == '(') { inBrackets++; continue; } + if (inString[i] == ')') { inBrackets--; continue; } + + + if (!Char.IsLetter(inString[i]) && !Char.IsNumber(inString[i]) && inString[i] != '_') + continue; + + if (inBrackets > 0) + continue; + + if (i == 0 || inString[i - 1] == ' ') + { + s_SnakeBuilder.Append(Char.ToUpperInvariant(inString[i])); + } + else + { + s_SnakeBuilder.Append(inString[i]); + } + } + + return s_SnakeBuilder.ToString().Trim(); + } + public static string FromHuman(string inString) => FromHuman(inString.AsSpan()); + + private static string CapitaliseFirstLetter(string input, bool capitalise) + { + if (input.IsNullOrEmpty()) + return ""; + + if (input.Length == 1) + return capitalise ? input.ToUpperInvariant() : input.ToLowerInvariant(); + + return (capitalise ? Char.ToUpperInvariant(input[0]) : Char.ToLowerInvariant(input[0])) + + input.Substring(1); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/NamingConventionUtil.cs.meta b/Assets/Tremble/Utils/NamingConventionUtil.cs.meta new file mode 100644 index 0000000..d2602bf --- /dev/null +++ b/Assets/Tremble/Utils/NamingConventionUtil.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 795d7b8deadc141e6a5a75234bb0b0b8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/NamingConventionUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/PackedResourceUtil.cs b/Assets/Tremble/Utils/PackedResourceUtil.cs new file mode 100644 index 0000000..e51b46a --- /dev/null +++ b/Assets/Tremble/Utils/PackedResourceUtil.cs @@ -0,0 +1,49 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.IO; +using System.Threading.Tasks; +using UnityEngine; + + +namespace TinyGoose.Tremble +{ + public static class PackedResourceUtil + { +#if UNITY_EDITOR + public static async Task PackFolderIntoResource(string folderPath, string resourceName) + { + if (!Directory.Exists(folderPath)) + return null; + + string containingFolder = Path.Combine(Directory.GetCurrentDirectory(), "Assets", "StreamingAssets"); + string resourcePath = Path.Combine(containingFolder, resourceName + ".tpak"); + + DirectoryUtil.CreateAllDirectories(containingFolder); + File.Delete(resourcePath); + + TpakArchive tpak = new(resourcePath); + tpak.AddDirectory(folderPath); + await tpak.PackAsync(); + + return resourcePath; + } +#endif + + public static async Task UnpackResourceIntoFolder(string resourceName, string folderPath) + { + // Empty directory + DirectoryUtil.CreateAllDirectories(folderPath); + + string resourcePath = Path.Combine(Application.streamingAssetsPath, resourceName + ".tpak"); + if (!File.Exists(resourcePath)) + return false; + + TpakArchive tpak = new(resourcePath); + await tpak.UnpackAsync(folderPath); + return true; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/PackedResourceUtil.cs.meta b/Assets/Tremble/Utils/PackedResourceUtil.cs.meta new file mode 100644 index 0000000..990df58 --- /dev/null +++ b/Assets/Tremble/Utils/PackedResourceUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 309d4c10ad944b18a2e61762c8125acc +timeCreated: 1715783554 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/PackedResourceUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/PrefabUtil.cs b/Assets/Tremble/Utils/PrefabUtil.cs new file mode 100644 index 0000000..ba94e05 --- /dev/null +++ b/Assets/Tremble/Utils/PrefabUtil.cs @@ -0,0 +1,27 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using UnityEngine; + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace TinyGoose.Tremble +{ + public static class PrefabUtil + { + public static GameObject InstantiatePrefab(GameObject prefab, Transform parent = null) + { +#if UNITY_EDITOR + return Application.isPlaying + ? GameObject.Instantiate(prefab, parent) + : (GameObject)PrefabUtility.InstantiatePrefab(prefab, parent); +#else + return GameObject.Instantiate(prefab, parent); +#endif + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/PrefabUtil.cs.meta b/Assets/Tremble/Utils/PrefabUtil.cs.meta new file mode 100644 index 0000000..21b9c6e --- /dev/null +++ b/Assets/Tremble/Utils/PrefabUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: d9d995248a5748abbedb56c4af36f30b +timeCreated: 1715879939 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/PrefabUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/ProgressUtil.cs b/Assets/Tremble/Utils/ProgressUtil.cs new file mode 100644 index 0000000..14d5061 --- /dev/null +++ b/Assets/Tremble/Utils/ProgressUtil.cs @@ -0,0 +1,71 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +//#define USE_SYNC_PROGRESS + +using UnityEditor; + +namespace TinyGoose.Tremble +{ + public static class ProgressUtil + { + public static int Start(string taskName) + { +#if UNITY_EDITOR + #if USE_SYNC_PROGRESS + EditorUtility.DisplayProgressBar("Trembling...", taskName, 0f); + return -1; + #else + return Progress.Start(taskName, options: Progress.Options.Managed | Progress.Options.Sticky); + #endif +#else + return -1; +#endif + } + + public static void Succeed(int task) + { +#if UNITY_EDITOR + #if USE_SYNC_PROGRESS + EditorUtility.DisplayProgressBar("Trembling...", "done", 1f); + EditorUtility.ClearProgressBar(); + #else + if (task == 0) + return; + Progress.Finish(task); + #endif +#endif + } + + public static void Fail(int task) + { +#if UNITY_EDITOR + #if USE_SYNC_PROGRESS + EditorUtility.ClearProgressBar(); + #else + if (task == 0) + return; + Progress.Finish(task, Progress.Status.Failed); + #endif +#endif + } + + public static void Report(int task, int step, int totalSteps, string description) + { +#if UNITY_EDITOR + #if USE_SYNC_PROGRESS + float progress = (float)step / (float)totalSteps; + EditorUtility.DisplayProgressBar("Tremble", $"{description} ({step + 1}/{totalSteps} - {progress*100:F0}%)", progress); + #else + if (task == 0) + return; + + float progress = (float)step / (float)totalSteps; + Progress.Report(task, step, totalSteps, $"{description} ({step + 1}/{totalSteps} - {progress*100:F0}%)"); + #endif +#endif + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/ProgressUtil.cs.meta b/Assets/Tremble/Utils/ProgressUtil.cs.meta new file mode 100644 index 0000000..4b1e8f1 --- /dev/null +++ b/Assets/Tremble/Utils/ProgressUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 0bf65aab508f4d5a99f9f050ab34c9fd +timeCreated: 1715667825 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/ProgressUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/StreamWriterUtil.cs b/Assets/Tremble/Utils/StreamWriterUtil.cs new file mode 100644 index 0000000..23a8532 --- /dev/null +++ b/Assets/Tremble/Utils/StreamWriterUtil.cs @@ -0,0 +1,20 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.IO; + +namespace TinyGoose.Tremble +{ + public static class StreamWriterUtil + { + public static void WriteIndent(this StreamWriter sw, int indent) + { + for (int i = 0; i < indent; i++) + { + sw.Write('\t'); + } + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/StreamWriterUtil.cs.meta b/Assets/Tremble/Utils/StreamWriterUtil.cs.meta new file mode 100644 index 0000000..ab79583 --- /dev/null +++ b/Assets/Tremble/Utils/StreamWriterUtil.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 7fe95984a548d45aca3824cfa3d3d8e0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/StreamWriterUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/StringUtil.cs b/Assets/Tremble/Utils/StringUtil.cs new file mode 100644 index 0000000..4990763 --- /dev/null +++ b/Assets/Tremble/Utils/StringUtil.cs @@ -0,0 +1,131 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Text; + +namespace TinyGoose.Tremble +{ + public static class StringUtil + { + public static bool Split(this string input, char splitter, out string first, out string rest) + => Split(input.AsSpan(), splitter, out first, out rest); + + public static bool Split(this ReadOnlySpan input, char splitter, out string first, out string rest) + { + bool insideQuotes = false; + int index = -1; + for (int c = 0; c < input.Length; c++) + { + if (input[c] == '"') + { + insideQuotes = !insideQuotes; + } + + if (insideQuotes || input[c] != splitter) + continue; + + index = c; + break; + } + + if (index == -1) + { + first = null; + rest = input.ToString(); + return false; + } + + first = input[..index].ToString().Trim(); + rest = input[(index + 1)..].ToString().Trim(); + + return true; + } + + public static bool IsNullOrEmpty(this string input) => string.IsNullOrEmpty(input); + + public static bool EqualsInvariant(this string input, string other, bool caseSensitive = false) + { + StringComparison compareType = caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase; + return input.Equals(other, compareType); + } + public static bool ContainsInvariant(this string input, string other, bool caseSensitive = false) + { + StringComparison compareType = caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase; + return input.Contains(other, compareType); + } + + public static bool StartsWithInvariant(this string input, string other, bool caseSensitive = false) + { + StringComparison compareType = caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase; + return input.StartsWith(other, compareType); + } + public static bool EndsWithInvariant(this string input, string other, bool caseSensitive = false) + { + StringComparison compareType = caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase; + return input.EndsWith(other, compareType); + } + public static int IndexOfInvariant(this string input, string other, bool caseSensitive = false) + { + StringComparison compareType = caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase; + return input.IndexOf(other, compareType); + } + public static int LastIndexOfInvariant(this string input, string other, bool caseSensitive = false) + { + StringComparison compareType = caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase; + return input.LastIndexOf(other, compareType); + } + + public static bool EqualsInvariant(this ReadOnlySpan input, string other, bool caseSensitive = false) + { + StringComparison compareType = caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase; + return input.Equals( other, compareType); + } + public static bool ContainsInvariant(this ReadOnlySpan input, string other, bool caseSensitive = false) + { + StringComparison compareType = caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase; + return input.Contains( other, compareType); + } + + public static bool StartsWithInvariant(this ReadOnlySpan input, string other, bool caseSensitive = false) + { + StringComparison compareType = caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase; + return input.StartsWith( other, compareType); + } + public static bool EndsWithInvariant(this ReadOnlySpan input, string other, bool caseSensitive = false) + { + StringComparison compareType = caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase; + return input.EndsWith( other, compareType); + } + + private static readonly HashSet DEFAULT_ILLEGAL_CHARS = new() { '{', '}', ' ', '[', ']', '"', '\'', '.', ',' }; + public static string Sanitise(this string input, HashSet illegalCharacters = null, char? replacement = null) + { + if (input == null) + return null; + + illegalCharacters ??= DEFAULT_ILLEGAL_CHARS; + + StringBuilder newName = new(input.Length); + foreach (char c in input) + { + if (illegalCharacters.Contains(c)) + { + if (replacement.HasValue) + { + newName.Append(replacement.Value); + } + + continue; + } + + newName.Append(c); + } + + return newName.ToString(); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/StringUtil.cs.meta b/Assets/Tremble/Utils/StringUtil.cs.meta new file mode 100644 index 0000000..9465fb6 --- /dev/null +++ b/Assets/Tremble/Utils/StringUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 3a1e2c6b1ca3410bae79a376273f1e2f +timeCreated: 1712132630 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/StringUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/TextureUtil.cs b/Assets/Tremble/Utils/TextureUtil.cs new file mode 100644 index 0000000..4761861 --- /dev/null +++ b/Assets/Tremble/Utils/TextureUtil.cs @@ -0,0 +1,201 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System.Linq; +using UnityEngine; + +namespace TinyGoose.Tremble +{ + public static class TextureUtil + { + public static Texture2D GenerateColourTexture(Color32 colour) + { + int size = TrembleSyncSettings.Get().MaterialExportSize.ToIntSize(); + int sizeSqr = size * size; + + Texture2D texture = new(size, size); + + if (s_ColourBuffer == null || s_ColourBuffer.Length != sizeSqr) + { + s_ColourBuffer = new Color32[sizeSqr]; + } + + for (int i = 0; i < sizeSqr; i++) + { + s_ColourBuffer[i] = colour; + s_ColourBuffer[i].a = 0xFF; + } + + texture.SetPixels32(s_ColourBuffer); + return texture; + } + + public static Texture2D GenerateCheckerTexture(int checkerSize = 64) => GenerateCheckerTexture(Color.black, Color.white, checkerSize); + + public static Texture2D GenerateCheckerTexture(Color32 colour1, Color32 colour2, int checkerSize = 64) + { + int size = TrembleSyncSettings.Get().MaterialExportSize.ToIntSize(); + + Texture2D texture = new(size, size); + texture.SetPixels32(GenerateCheckerColours(size, colour1, colour2, checkerSize)); + return texture; + } + + public static Texture2D GenerateClipTexture(Color32 colour1, Color32 colour2, Color32 clipText, int checkerSize = 64) + { + int size = TrembleSyncSettings.Get().MaterialExportSize.ToIntSize(); + + Texture2D texture = new(size, size); + Color32[] image = GenerateCheckerColours(size, colour1, colour2, checkerSize); + ApplyClipTexture(image, size, clipText, checkerSize); + texture.SetPixels32(image); + + return texture; + } + + public static Texture2D GenerateSkipTexture(Color32 colour1, Color32 colour2, Color32 clipText, int checkerSize = 64) + { + int size = TrembleSyncSettings.Get().MaterialExportSize.ToIntSize(); + + Texture2D texture = new(size, size); + Color32[] image = GenerateCheckerColours(size, colour1, colour2, checkerSize); + ApplySkipTexture(image, size, clipText, checkerSize); + texture.SetPixels32(image); + + return texture; + } + + private static Color32[] s_ColourBuffer; + + private static Color32[] GenerateCheckerColours(int size, Color32 colour1, Color32 colour2, int checkerSize = 64) + { + int sizeSqr = size * size; + + if (s_ColourBuffer == null || s_ColourBuffer.Length != sizeSqr) + { + s_ColourBuffer = new Color32[sizeSqr]; + } + + for (int x = 0; x < size; x++) + { + for (int y = 0; y < size; y++) + { + int xCoord = x / checkerSize; + int yCoord = y / checkerSize; + + if ((xCoord + yCoord) % 2 == 0) + { + s_ColourBuffer[y * size + x] = colour1; + } + else + { + s_ColourBuffer[y * size + x] = colour2; + } + + s_ColourBuffer[y * size + x].a = 0xFF; + } + } + + return s_ColourBuffer; + } + + // Cheeky clip texture + private const char _ = ' '; + + private static readonly string[] s_ClipTexture = + { + "", "", // 2-line space + _ + "/--" + _ + "| " + _ + "|" + _ + "/-|" + _ + _ + _, + _ + "| " + _ + "| " + _ + " " + _ + "| |" + _ + _ + _, + _ + "| " + _ + "| " + _ + "|" + _ + "+_/" + _ + _ + _, + _ + "| " + _ + "| " + _ + "|" + _ + "| " + _ + _ + _, + _ + "|__" + _ + "|__" + _ + "|" + _ + "| " + _ + _ + _, + "", // 1-line space + }; + + private static readonly string[] s_SkipTexture = + { + "", "", // 2-line space + _ + "/--" + _ + "| |" + _ + "|" + _ + "/-|" + _ + _ + _, + _ + "| " + _ + "| /" + _ + " " + _ + "| |" + _ + _ + _, + _ + "---" + _ + "|/ " + _ + "|" + _ + "+-/" + _ + _ + _, + _ + " |" + _ + "|+ " + _ + "|" + _ + "| " + _ + _ + _, + _ + "--+" + _ + "| +" + _ + "|" + _ + "| " + _ + _ + _, + "", // 1-line space + }; + + private static void ApplyClipTexture(Color32[] image, int size, Color32 textColour, int checkerSize = 64) + => ApplyWordTexture(image, s_ClipTexture, size, textColour, checkerSize); + + private static void ApplySkipTexture(Color32[] image, int size, Color32 textColour, int checkerSize = 64) + => ApplyWordTexture(image, s_SkipTexture, size, textColour, checkerSize); + + private static void ApplyWordTexture(Color32[] image, string[] wordTexture, int size, Color32 textColour, int checkerSize = 64) + { + int clipWidth = 16; + float clipScale = (float)size / (float)checkerSize; + + for (int x = 0; x < size; x++) + { + for (int y = 0; y < size; y++) + { + // Offset every other row + int offset = ((y / checkerSize) & 1) == 0 ? 0 : checkerSize; + + // Scale the text + int scaledX = (int)((x + offset) / clipScale); + int scaledY = (int)(y / clipScale); + + // Flip rows (textures, amirite?!) + int row = size - scaledY - 1; + + // Pull the pixel data from the array + string wordRow = wordTexture[row % wordTexture.Length]; + char wordValue = wordRow.Length > 0 ? wordRow[scaledX % clipWidth] : _; + + if (wordValue != _) + { + // Write pixel if it's on + image[y * size + x] = textColour; + } + } + } + } + + // Account for weird custom choices for main texture names + private static readonly int[] LIKELY_MAIN_TEXTURE_IDS = + { + Shader.PropertyToID("_BaseColor"), + Shader.PropertyToID("_Color"), + Shader.PropertyToID("_maintex"), + Shader.PropertyToID("_Maintex"), + }; + public static bool TryGetMainTex(this Material material, out Texture2D mainTexture) + { + if (!material) + { + mainTexture = null; + return false; + } + + // First check for _MainTex or [MainTexture] + mainTexture = material.mainTexture as Texture2D; + + if (!mainTexture) + { + foreach (int name in LIKELY_MAIN_TEXTURE_IDS) + { + if (!material.HasTexture(name)) + continue; + + mainTexture = material.GetTexture(name) as Texture2D; + break; + } + } + + return mainTexture; + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/TextureUtil.cs.meta b/Assets/Tremble/Utils/TextureUtil.cs.meta new file mode 100644 index 0000000..eef7e52 --- /dev/null +++ b/Assets/Tremble/Utils/TextureUtil.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 90d10613740347268599188e50f56c1f +timeCreated: 1709808325 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/TextureUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/TrenchBroomUtil.cs b/Assets/Tremble/Utils/TrenchBroomUtil.cs new file mode 100644 index 0000000..0e102ad --- /dev/null +++ b/Assets/Tremble/Utils/TrenchBroomUtil.cs @@ -0,0 +1,237 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using UnityEngine; + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace TinyGoose.Tremble +{ + public static class TrenchBroomUtil + { + + private static string TrenchBroomPathFromPrefs + { +#if UNITY_EDITOR + get => EditorPrefs.GetString("Tremble_TBPath", null); + set => EditorPrefs.SetString("Tremble_TBPath", value); +#else + get => PlayerPrefs.GetString("Tremble_TBPath", null); + set => PlayerPrefs.SetString("Tremble_TBPath", value); +#endif + } + + public static string TrenchBroomPath + { + get + { + // First look for a running Trenchbroom + Process[] procs = Process.GetProcessesByName("trenchbroom"); + if (procs.Length > 0 && procs[0].MainModule != null) + { + TrenchBroomPathFromPrefs = procs[0].MainModule.FileName; + return procs[0].MainModule.FileName; + } + + // Not running - try a path we previously knew about + string path = TrenchBroomPathFromPrefs; + if (path != null && File.Exists(path)) + return path; + + return null; + } + + private set => TrenchBroomPathFromPrefs = value; + } + + public static bool IsTrenchBroomRunning + { + get + { + Process proc = Process.GetProcessesByName("trenchbroom").FirstOrDefault(); + if (proc == null) + return false; + + TrenchBroomPath = proc.MainModule.FileName; + + return true; + } + } + + public static bool DoesEnginePathExistInTrenchBroomPrefs() + { + string preferencesFile = Path.Combine(GetTrenchBroomConfigFolder(), "Preferences.json"); + string key = $"Games/{TrembleConsts.GAME_NAME}/Path"; + + if (!File.Exists(preferencesFile)) + return false; + + // Read in current config + foreach (string line in File.ReadLines(preferencesFile)) + { + string trimmedLine = line.Trim(' ', ','); + + // Ignore braces and empty lines + if (trimmedLine.IsNullOrEmpty() || trimmedLine is "{" or "}") + continue; + + // Existing path? - patch it! + if (trimmedLine.StartsWith($"\"{key}\"")) + return true; + } + + return false; + } + + public static async Task WriteEnginePathIntoTrenchBroomPrefs() + { + // I didn't want to import a JSON library so - this is it. + // Read each line into an array (ignore the braces) and remove the commas. + // Find if there's a current path - if so, patch it up. + // if not, add a new one at the end. + + string preferencesFile = Path.Combine(GetTrenchBroomConfigFolder(), "Preferences.json"); + string key = $"Games/{TrembleConsts.GAME_NAME}/Path"; + + string projectFolderUnix = Directory.GetCurrentDirectory().Replace('\\', '/'); + string entry = $"\"{key}\": \"{projectFolderUnix}\""; + + bool wasPatched = false; + List configLines = new(); + + if (File.Exists(preferencesFile)) + { + // Read in current config + foreach (string line in File.ReadLines(preferencesFile)) + { + string trimmedLine = line.Trim(' ', ','); + + // Ignore braces and empty lines + if (trimmedLine.IsNullOrEmpty() || trimmedLine is "{" or "}") + continue; + + // Existing path? - patch it! + if (trimmedLine.StartsWith($"\"{key}\"")) + { + configLines.Add(entry); + wasPatched = true; + + continue; + } + + configLines.Add(trimmedLine); + } + } + + if (!wasPatched) + { + // We didn't find the game - append to the end (before close brace) + configLines.Add(entry); + } + + // Write out new config + for (int lineIdx = 0; lineIdx < configLines.Count; lineIdx++) + { + // Indent + configLines[lineIdx] = $" {configLines[lineIdx]}"; + + // Add commas (not on the last one!) + if (lineIdx < configLines.Count - 1) + { + configLines[lineIdx] += ","; + } + } + + configLines.Insert(0, "{"); + configLines.Add("}"); + + DirectoryUtil.CreateAllDirectories(preferencesFile); + await File.WriteAllLinesAsync(preferencesFile, configLines); + + return !wasPatched; + } + + private static string GetTrenchBroomConfigFolder() => + Application.platform switch + { + RuntimePlatform.OSXEditor or RuntimePlatform.OSXPlayer + => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library", "Application Support", "TrenchBroom"), + RuntimePlatform.WindowsEditor or RuntimePlatform.WindowsPlayer + => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "TrenchBroom"), + RuntimePlatform.LinuxEditor or RuntimePlatform.LinuxPlayer + => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".TrenchBroom"), + _ => throw new ArgumentOutOfRangeException(nameof(Application.platform), "Unknown platform!") + }; + + public static string GetGameFolder() => Path.Combine(GetTrenchBroomConfigFolder(), "games", "Unity", Application.productName); + + public static void OpenWithTrenchBroom(string mapFile) + { + switch (Application.platform) + { + case RuntimePlatform.OSXEditor: + case RuntimePlatform.OSXPlayer: + RunCommand($"open -a TrenchBroom '{mapFile}'"); + break; + + case RuntimePlatform.WindowsEditor: + case RuntimePlatform.WindowsPlayer: + // Sad. On Windows, TB is mostly portable so we may have to just show the file in Explorer, lol + if (TrenchBroomPath != null) + { + RunCommand($"\"{TrenchBroomPath}\" \"{mapFile}\"", useShell: false); + } + else + { +#if UNITY_EDITOR + EditorUtility.DisplayDialog( + title: "Where's TrenchBroom?", + message: "Tremble could not find TrenchBroom. Ensure TrenchBroom is installed and " + + "running, and Tremble will make a note of where it's installed for next time." + + " For now, I'll show your map in Explorer.", "Okay"); +#endif + RunCommand($"explorer /select, \"{mapFile}\""); + } + break; + + case RuntimePlatform.LinuxEditor: + case RuntimePlatform.LinuxPlayer: + RunCommand($"/usr/bin/trenchbroom '{mapFile}'"); + break; + } + } + + private static void RunCommand(string command, bool useShell = true) + { + command.Split(' ', out string exe, out string args); + +#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN + // Windows Command Prompt + if (useShell) + { + args = $"/c \"{exe} {args}\""; + exe = "cmd.exe"; + } +#else + // Under macOS and Linux we assume /bin/sh is a thing + if (useShell) + { + args = $"-c \"{exe} {args}\""; + exe = "/bin/sh"; + } +#endif + + Process.Start(new ProcessStartInfo(exe, args) { WorkingDirectory = Directory.GetCurrentDirectory() }); + } + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/TrenchBroomUtil.cs.meta b/Assets/Tremble/Utils/TrenchBroomUtil.cs.meta new file mode 100644 index 0000000..b0be506 --- /dev/null +++ b/Assets/Tremble/Utils/TrenchBroomUtil.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: e7bf4a6e8c1404a21adc02ab38521201 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/TrenchBroomUtil.cs + uploadId: 939664 diff --git a/Assets/Tremble/Utils/TypeDatabase.cs b/Assets/Tremble/Utils/TypeDatabase.cs new file mode 100644 index 0000000..3c7a4a8 --- /dev/null +++ b/Assets/Tremble/Utils/TypeDatabase.cs @@ -0,0 +1,365 @@ +// +// This file is part of the Tremble package by Tiny Goose. +// Copyright (c) 2024-2026 TinyGoose Ltd., All Rights Reserved. +// + +//#define USE_TYPEDB_IN_EDITOR + +using System; +using System.Collections.Generic; + +#if !UNITY_EDITOR || USE_TYPEDB_IN_EDITOR +using System.Linq; +using UnityEngine; +#endif + +#if UNITY_EDITOR +using UnityEditor; +#endif + + +namespace TinyGoose.Tremble +{ + public static class TypeDatabase + { + private static Dictionary s_ClassLookup; + private static Dictionary s_ClassAttributes; + + public static Type GetType(string fullName) + { + if (fullName == null) + return null; + +#if UNITY_EDITOR && !USE_TYPEDB_IN_EDITOR + // Unsupported - but very fast! + return Unsupported.GetTypeFromFullName(fullName); +#else + if (s_ClassLookup == null) + { + GenerateClassLookup(); + } + + return s_ClassLookup.GetValueOrDefault(fullName); +#endif + } + + public static IList GetTypesWithAttribute() + where TAttribute : Attribute + { +#if UNITY_EDITOR && !USE_TYPEDB_IN_EDITOR + return TypeCache.GetTypesWithAttribute(); +#else + if (s_ClassLookup == null) + { + GenerateClassLookup(); + } + + List types = new(256); + foreach (KeyValuePair kvp in s_ClassAttributes) + { + foreach (object attribute in kvp.Value) + { + Type attributeType = attribute.GetType(); + + if (attributeType == typeof(TAttribute) || attributeType.IsSubclassOf(typeof(TAttribute))) + { + types.Add(kvp.Key); + } + } + } + + return types; +#endif + } + + +#if !UNITY_EDITOR || USE_TYPEDB_IN_EDITOR + private static readonly HashSet FORBIDDEN_ASSEMBLIES = new() + { + "mscorlib", + "UnityEngine", + "UnityEngine.AIModule", + "UnityEngine.AMDModule", + "UnityEngine.ARModule", + "UnityEngine.AccessibilityModule", + "UnityEngine.AndroidJNIModule", + "UnityEngine.AnimationModule", + "UnityEngine.AssetBundleModule", + "UnityEngine.AudioModule", + "UnityEngine.ClothModule", + "UnityEngine.ClusterInputModule", + "UnityEngine.ClusterRendererModule", + "UnityEngine.ContentLoadModule", + "UnityEngine.CoreModule", + "UnityEngine.CrashReportingModule", + "UnityEngine.DSPGraphModule", + "UnityEngine.DirectorModule", + "UnityEngine.GIModule", + "UnityEngine.GameCenterModule", + "UnityEngine.GraphicsStateCollectionSerializerModule", + "UnityEngine.GridModule", + "UnityEngine.HierarchyCoreModule", + "UnityEngine.HotReloadModule", + "UnityEngine.IMGUIModule", + "UnityEngine.ImageConversionModule", + "UnityEngine.InputModule", + "UnityEngine.InputForUIModule", + "UnityEngine.InputLegacyModule", + "UnityEngine.JSONSerializeModule", + "UnityEngine.LocalizationModule", + "UnityEngine.MarshallingModule", + "UnityEngine.MultiplayerModule", + "UnityEngine.NVIDIAModule", + "UnityEngine.ParticleSystemModule", + "UnityEngine.PerformanceReportingModule", + "UnityEngine.PhysicsModule", + "UnityEngine.Physics2DModule", + "UnityEngine.PropertiesModule", + "UnityEngine.RuntimeInitializeOnLoadManagerInitializerModule", + "UnityEngine.ScreenCaptureModule", + "UnityEngine.ShaderVariantAnalyticsModule", + "UnityEngine.SharedInternalsModule", + "UnityEngine.SpriteMaskModule", + "UnityEngine.SpriteShapeModule", + "UnityEngine.StreamingModule", + "UnityEngine.SubstanceModule", + "UnityEngine.SubsystemsModule", + "UnityEngine.TLSModule", + "UnityEngine.TerrainModule", + "UnityEngine.TerrainPhysicsModule", + "UnityEngine.TextCoreFontEngineModule", + "UnityEngine.TextCoreTextEngineModule", + "UnityEngine.TextRenderingModule", + "UnityEngine.TilemapModule", + "UnityEngine.UIModule", + "UnityEngine.UIElementsModule", + "UnityEngine.UmbraModule", + "UnityEngine.UnityAnalyticsModule", + "UnityEngine.UnityAnalyticsCommonModule", + "UnityEngine.UnityConnectModule", + "UnityEngine.UnityCurlModule", + "UnityEngine.UnityTestProtocolModule", + "UnityEngine.UnityWebRequestModule", + "UnityEngine.UnityWebRequestAssetBundleModule", + "UnityEngine.UnityWebRequestAudioModule", + "UnityEngine.UnityWebRequestTextureModule", + "UnityEngine.UnityWebRequestWWWModule", + "UnityEngine.VFXModule", + "UnityEngine.VRModule", + "UnityEngine.VehiclesModule", + "UnityEngine.VideoModule", + "UnityEngine.VirtualTexturingModule", + "UnityEngine.WindModule", + "UnityEngine.XRModule", + "UnityEditor", + "UnityEditor.AccessibilityModule", + "UnityEditor.AdaptivePerformanceModule", + "UnityEditor.BuildProfileModule", + "UnityEditor.CoreBusinessMetricsModule", + "UnityEditor.CoreModule", + "UnityEditor.DeviceSimulatorModule", + "UnityEditor.DiagnosticsModule", + "UnityEditor.EditorToolbarModule", + "UnityEditor.GIModule", + "UnityEditor.GraphViewModule", + "UnityEditor.GraphicsStateCollectionSerializerModule", + "UnityEditor.GridAndSnapModule", + "UnityEditor.GridModule", + "UnityEditor.MultiplayerModule", + "UnityEditor.Physics2DModule", + "UnityEditor.PhysicsModule", + "UnityEditor.PresetsUIModule", + "UnityEditor.PropertiesModule", + "UnityEditor.QuickSearchModule", + "UnityEditor.SafeModeModule", + "UnityEditor.SceneTemplateModule", + "UnityEditor.SceneViewModule", + "UnityEditor.ShaderFoundryModule", + "UnityEditor.SketchUpModule", + "UnityEditor.SpriteMaskModule", + "UnityEditor.SpriteShapeModule", + "UnityEditor.SubstanceModule", + "UnityEditor.TerrainModule", + "UnityEditor.TextCoreFontEngineModule", + "UnityEditor.TextCoreTextEngineModule", + "UnityEditor.TextRenderingModule", + "UnityEditor.TilemapModule", + "UnityEditor.TreeModule", + "UnityEditor.UIAutomationModule", + "UnityEditor.UIBuilderModule", + "UnityEditor.UIElementsModule", + "UnityEditor.UIElementsSamplesModule", + "UnityEditor.UmbraModule", + "UnityEditor.UnityConnectModule", + "UnityEditor.VFXModule", + "UnityEditor.VideoModule", + "UnityEditor.XRModule", + "netstandard", + "System.Core", + "System", + "Mono.Security", + "System.Configuration", + "System.Xml", + "System.Numerics", + "System.Data", + "System.Transactions", + "System.EnterpriseServices", + "System.Runtime.Serialization", + "System.ServiceModel.Internals", + "System.Xml.Linq", + "Unity.Cecil", + "Bee.BeeDriver2", + "Bee.BinLog", + "UnityEditor.Graphs", + "UnityEditor.OSXStandalone.Extensions", + "UnityEditor.iOS.Extensions.Xcode", + "Autodesk.Fbx.BuildTestAssets", + "Autodesk.Fbx", + "Autodesk.Fbx.Editor", + "PPv2URPConverters", + "Unity.Addressables", + "Unity.Addressables.Editor", + "Unity.AI.Navigation", + "Unity.AI.Navigation.Editor.ConversionSystem", + "Unity.AI.Navigation.Editor", + "Unity.AI.Navigation.Updater", + "Unity.Bindings.OpenImageIO.Editor", + "Unity.Burst.CodeGen", + "Unity.Burst", + "Unity.Burst.Editor", + "Unity.Cinemachine", + "Unity.Cinemachine.Editor", + "Unity.CollabProxy.Editor", + "Unity.Collections.CodeGen", + "Unity.Collections", + "Unity.Collections.Editor", + "Unity.EditorCoroutines.Editor", + "Unity.Formats.Fbx.Editor", + "Unity.Formats.Fbx.Runtime", + "Unity.InputSystem", + "Unity.InputSystem.ForUI", + "Unity.InputSystem.TestFramework", + "Unity.Mathematics", + "Unity.Mathematics.Editor", + "Unity.MemoryProfiler", + "Unity.MemoryProfiler.Editor", + "Unity.MemoryProfiler.Editor.MemoryProfilerModule", + "Unity.PerformanceTesting", + "Unity.PerformanceTesting.Editor", + "Unity.PlasticSCM.Editor", + "Unity.Profiling.Core", + "Unity.Recorder.Base", + "Unity.Recorder", + "Unity.Recorder.Editor", + "Unity.Rendering.LightTransport.Editor", + "Unity.Rendering.LightTransport.Runtime", + "Unity.RenderPipeline.Universal.ShaderLibrary", + "Unity.RenderPipelines.Core.Editor", + "Unity.RenderPipelines.Core.Editor.Shared", + "Unity.RenderPipelines.Core.Runtime", + "Unity.RenderPipelines.Core.Runtime.Shared", + "Unity.RenderPipelines.Core.ShaderLibrary", + "Unity.RenderPipelines.GPUDriven.Runtime", + "Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary", + "Unity.RenderPipelines.Universal.2D.Runtime", + "Unity.RenderPipelines.Universal.Config.Runtime", + "Unity.RenderPipelines.Universal.Editor", + "Unity.RenderPipelines.Universal.Runtime", + "Unity.RenderPipelines.Universal.Shaders", + "Unity.ResourceManager", + "Unity.Rider.Editor", + "Unity.ScriptableBuildPipeline", + "Unity.ScriptableBuildPipeline.Editor", + "Unity.Searcher.Editor", + "Unity.Serialization", + "Unity.Serialization.Editor", + "Unity.Services.Authentication", + "Unity.Services.Authentication.Editor", + "Unity.Services.Authentication.Editor.Shared", + "Unity.Services.Authentication.PlayerAccounts", + "Unity.Services.Authentication.PlayerAccounts.Editor", + "Unity.Services.Core.Analytics", + "Unity.Services.Core.Configuration", + "Unity.Services.Core.Configuration.Editor", + "Unity.Services.Core.Device", + "Unity.Services.Core", + "Unity.Services.Core.Editor", + "Unity.Services.Core.Environments", + "Unity.Services.Core.Environments.Editor", + "Unity.Services.Core.Environments.Internal", + "Unity.Services.Core.Internal", + "Unity.Services.Core.Networking", + "Unity.Services.Core.Registration", + "Unity.Services.Core.Scheduler", + "Unity.Services.Core.Telemetry", + "Unity.Services.Core.Threading", + "Unity.Services.Ugc", + "Unity.Services.Ugc.DocCodeSamples", + "Unity.Services.Ugc.Internal.Generated", + "Unity.Settings.Editor", + "Unity.ShaderGraph.Editor", + "Unity.ShaderGraph.Utilities", + "Unity.Splines", + "Unity.Splines.Editor", + "Unity.TextMeshPro", + "Unity.TextMeshPro.Editor", + "Unity.Timeline", + "Unity.Timeline.Editor", + "UnityEditor.TestRunner", + "UnityEditor.UI", + "UnityEngine.TestRunner", + "UnityEngine.UI", + "Mono.Cecil.Pdb", + "SingularityGroup.HotReload.RuntimeDependencies", + "Unity.Burst.Cecil.Pdb", + "Unity.Collections.LowLevel.ILSupport", + "nunit.framework", + "SingularityGroup.HotReload.EditorDependencies", + "unityplastic", + "Unity.Plastic.Antlr3.Runtime", + "Unity.Burst.Cecil.Mdb", + "Unity.Burst.Cecil", + "SingularityGroup.HotReload.RuntimeDependencies2020", + "DOTweenEditor", + "Mono.Cecil.Mdb", + "Unity.Plastic.Newtonsoft.Json", + "Unity.Burst.Unsafe", + "Mono.Cecil.Rocks", + "Mono.Cecil", + "Unity.Burst.Cecil.Rocks", + "System.Net.Http", + "Unity.CompilationPipeline.Common", + "System.Drawing", + "System.Runtime", + "Mono.Posix", + "System.Web", + "Microsoft.GeneratedCode", + "JetBrains.Rider.Unity.Editor.Plugin.Net46.Repacked", + "ExCSS.Unity", + "Microsoft.GeneratedCode", + }; + + public static void GenerateClassLookup() + { + s_ClassLookup = new(1024); + s_ClassAttributes = new(1024); + + IEnumerable types = AppDomain.CurrentDomain + .GetAssemblies() + .Where(ass => !FORBIDDEN_ASSEMBLIES.Contains(ass.GetName().Name)) + .SelectMany(ass => ass.GetTypes()) + .Where(t => t.FullName != null); + + foreach (Type availableType in types) + { + s_ClassLookup[availableType.FullName] = availableType; + + if (availableType.IsSubclassOf(typeof(MonoBehaviour)) || availableType.IsSubclassOf(typeof(TrembleFieldConverter))) + { + s_ClassAttributes.Add(availableType, availableType.GetCustomAttributes(true)); + } + } + } +#endif + } +} \ No newline at end of file diff --git a/Assets/Tremble/Utils/TypeDatabase.cs.meta b/Assets/Tremble/Utils/TypeDatabase.cs.meta new file mode 100644 index 0000000..ebcf660 --- /dev/null +++ b/Assets/Tremble/Utils/TypeDatabase.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 5e121f8ff98d4f5f98898fd968b7d827 +timeCreated: 1715667413 +AssetOrigin: + serializedVersion: 1 + productId: 277805 + packageName: Tremble - Map Importer + packageVersion: 1.11.1 + assetPath: Assets/Tremble/Utils/TypeDatabase.cs + uploadId: 939664 diff --git a/ProjectSettings/NavMeshAreas.asset b/ProjectSettings/NavMeshAreas.asset index 3b0b7c3..a5e48ab 100644 --- a/ProjectSettings/NavMeshAreas.asset +++ b/ProjectSettings/NavMeshAreas.asset @@ -69,9 +69,9 @@ NavMeshProjectSettings: cost: 1 - name: cost: 1 - m_LastAgentTypeID: -887442657 + m_LastAgentTypeID: -1372625422 m_Settings: - - serializedVersion: 2 + - serializedVersion: 3 agentTypeID: 0 agentRadius: 0.5 agentHeight: 2 @@ -84,7 +84,9 @@ NavMeshProjectSettings: cellSize: 0.16666667 manualTileSize: 0 tileSize: 256 - accuratePlacement: 0 + buildHeightMesh: 0 + maxJobWorkers: 0 + preserveTilesOutsideBounds: 0 debug: m_Flags: 0 m_SettingNames: diff --git a/ProjectSettings/Packages/com.unity.probuilder/Settings.json b/ProjectSettings/Packages/com.unity.probuilder/Settings.json index c308320..b2d07bb 100644 --- a/ProjectSettings/Packages/com.unity.probuilder/Settings.json +++ b/ProjectSettings/Packages/com.unity.probuilder/Settings.json @@ -35,6 +35,16 @@ "type": "System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "key": "editor.backFaceSelectEnabled", "value": "{\"m_Value\":false}" + }, + { + "type": "System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", + "key": "ShapeComponent.ResetSettings", + "value": "{\"m_Value\":false}" + }, + { + "type": "System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", + "key": "lightmapping.autoUnwrapLightmapUV", + "value": "{\"m_Value\":true}" } ] }