diff --git a/Assets/Editor/Presets/GeomCache/game.cbc b/Assets/Editor/Presets/GeomCache/game.cbc
deleted file mode 100644
index 9b98f3460f..0000000000
--- a/Assets/Editor/Presets/GeomCache/game.cbc
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Assets/Editor/Presets/GeomCache/game_lz4hc.cbc b/Assets/Editor/Presets/GeomCache/game_lz4hc.cbc
deleted file mode 100644
index dbd0499175..0000000000
--- a/Assets/Editor/Presets/GeomCache/game_lz4hc.cbc
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Assets/Editor/Presets/GeomCache/game_z_up.cbc b/Assets/Editor/Presets/GeomCache/game_z_up.cbc
deleted file mode 100644
index ec2555a3e3..0000000000
--- a/Assets/Editor/Presets/GeomCache/game_z_up.cbc
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Assets/Editor/Presets/GeomCache/game_z_up_lz4hc.cbc b/Assets/Editor/Presets/GeomCache/game_z_up_lz4hc.cbc
deleted file mode 100644
index c2e30a6386..0000000000
--- a/Assets/Editor/Presets/GeomCache/game_z_up_lz4hc.cbc
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Assets/Editor/Presets/GeomCache/prerendered.cbc b/Assets/Editor/Presets/GeomCache/prerendered.cbc
deleted file mode 100644
index c09785111d..0000000000
--- a/Assets/Editor/Presets/GeomCache/prerendered.cbc
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Assets/Editor/Presets/GeomCache/prerendered_z_up.cbc b/Assets/Editor/Presets/GeomCache/prerendered_z_up.cbc
deleted file mode 100644
index e42a915e58..0000000000
--- a/Assets/Editor/Presets/GeomCache/prerendered_z_up.cbc
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Assets/Editor/Presets/GeomCache/rigids_only.cbc b/Assets/Editor/Presets/GeomCache/rigids_only.cbc
deleted file mode 100644
index e8620bc11e..0000000000
--- a/Assets/Editor/Presets/GeomCache/rigids_only.cbc
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Assets/Editor/Presets/GeomCache/rigids_only_z_up.cbc b/Assets/Editor/Presets/GeomCache/rigids_only_z_up.cbc
deleted file mode 100644
index d1f8bc2db3..0000000000
--- a/Assets/Editor/Presets/GeomCache/rigids_only_z_up.cbc
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Assets/Editor/Presets/GeomCache/uncompressed.cbc b/Assets/Editor/Presets/GeomCache/uncompressed.cbc
deleted file mode 100644
index e21d52d9d1..0000000000
--- a/Assets/Editor/Presets/GeomCache/uncompressed.cbc
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Assets/Editor/Presets/GeomCache/uncompressed_z_up.cbc b/Assets/Editor/Presets/GeomCache/uncompressed_z_up.cbc
deleted file mode 100644
index 273ce1fbb1..0000000000
--- a/Assets/Editor/Presets/GeomCache/uncompressed_z_up.cbc
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.abc b/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.abc
deleted file mode 100644
index 8ca759d342..0000000000
--- a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.abc
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:9c36d7bc993ddf616f478115a123efabda5b4b833a4e6524312f43c228ae0902
-size 487003
diff --git a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.cbc b/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.cbc
deleted file mode 100644
index 3c99ab1627..0000000000
--- a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.cbc
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.ma b/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.ma
deleted file mode 100644
index 65aade11a0..0000000000
--- a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.ma
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:96a21446422b834ea90a5d38eaaca309fdee31dc3cc03c0e9c094b39ec3a459d
-size 4715164
diff --git a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.mtl b/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.mtl
deleted file mode 100644
index 05dfe70b09..0000000000
--- a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.mtl
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake
index 4d5680a30d..f9d1e60dda 100644
--- a/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake
+++ b/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake
@@ -8,3 +8,8 @@
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
+
+set(GEM_DEPENDENCIES
+ Gem::Atom_RHI_Metal.Private
+ Gem::Atom_RHI_Null.Private
+)
\ No newline at end of file
diff --git a/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake
index 4d5680a30d..ee7be9ac6d 100644
--- a/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake
+++ b/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake
@@ -8,3 +8,10 @@
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
+
+set(GEM_DEPENDENCIES
+ Gem::Atom_RHI_Null.Private
+ Gem::Atom_RHI_Null.Builders
+ Gem::Atom_RHI_Metal.Private
+ Gem::Atom_RHI_Metal.Builders
+)
\ No newline at end of file
diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CryMaterialsCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CryMaterialsCommands_test.py
deleted file mode 100755
index 41ae0608a4..0000000000
--- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CryMaterialsCommands_test.py
+++ /dev/null
@@ -1,75 +0,0 @@
-"""
-All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
-its licensors.
-
-For complete copyright and license terms please see the LICENSE at the root of this
-distribution (the "License"). All use of this software is governed by the License,
-or, if provided, by the license below or the license accompanying this file. Do not
-remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-"""
-
-#
-# This is a pytest module to test the in-Editor Python API from ViewPane.h
-#
-import pytest
-pytest.importorskip('ly_test_tools')
-
-import sys
-import os
-sys.path.append(os.path.dirname(__file__))
-from hydra_utils import launch_test_case
-
-
-@pytest.mark.SUITE_sandbox
-@pytest.mark.parametrize('launcher_platform', ['windows_editor'])
-@pytest.mark.parametrize('project', ['AutomatedTesting'])
-@pytest.mark.parametrize('level', ['auto_test'])
-class TestLegacyCryMaterialsCommandsAutomation(object):
-
- def test_Legacy_CryMaterials(self, request, editor, level, launcher_platform):
-
- unexpected_lines=[]
- expected_lines = [
- # "Material Settings/Shader updated correctly", # Disabled, SPEC-3590
- # "Material Settings/Surface Type updated correctly", # Disabled, SPEC-3590
- "Texture Maps/Diffuse/Tiling/IsTileU updated correctly",
- "Texture Maps/Diffuse/Tiling/TileU updated correctly",
- "Texture Maps/Diffuse/Rotator/Type updated correctly",
- "Texture Maps/Diffuse/Rotator/Amplitude updated correctly",
- "Texture Maps/Diffuse/Oscillator/AmplitudeU updated correctly",
- "Opacity Settings/Opacity updated correctly",
- "Opacity Settings/AlphaTest updated correctly",
- "Opacity Settings/Additive updated correctly",
- "Lighting Settings/Diffuse Color updated correctly",
- "Lighting Settings/Specular Color updated correctly",
- "Lighting Settings/Emissive Intensity updated correctly",
- "Lighting Settings/Emissive Color updated correctly",
- "Advanced/Allow layer activation updated correctly",
- "Advanced/2 Sided updated correctly",
- "Advanced/No Shadow updated correctly",
- "Advanced/Use Scattering updated correctly",
- "Advanced/Hide After Breaking updated correctly",
- "Advanced/Fog Volume Shading Quality High updated correctly",
- "Advanced/Blend Terrain Color updated correctly",
- "Advanced/Voxel Coverage updated correctly",
- "Advanced/Propagate Opacity Settings updated correctly",
- "Advanced/Propagate Lighting Settings updated correctly",
- "Advanced/Propagate Advanced Settings updated correctly",
- "Advanced/Propagate Texture Maps updated correctly",
- "Advanced/Propagate Shader Params updated correctly",
- "Advanced/Propagate Shader Generation updated correctly",
- "Advanced/Propagate Vertex Deformation updated correctly",
- # "Shader Params/Blend Factor updated correctly", # Disabled, SPEC-3590
- # "Shader Params/Indirect bounce color updated correctly", # Disabled, SPEC-3590
- "Vertex Deformation/Type updated correctly",
- "Vertex Deformation/Wave Length X updated correctly",
- "Vertex Deformation/Wave X/Level updated correctly",
- "Vertex Deformation/Wave X/Amplitude updated correctly",
- "Vertex Deformation/Wave X/Phase updated correctly",
- "Vertex Deformation/Wave X/Frequency updated correctly"
- ]
-
- test_case_file = os.path.join(os.path.dirname(__file__), 'CryMaterialsCommands_test_case.py')
- launch_test_case(editor, test_case_file, expected_lines, unexpected_lines)
-
diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CryMaterialsCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CryMaterialsCommands_test_case.py
deleted file mode 100755
index 913b1ace24..0000000000
--- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CryMaterialsCommands_test_case.py
+++ /dev/null
@@ -1,116 +0,0 @@
-"""
-All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
-its licensors.
-
-For complete copyright and license terms please see the LICENSE at the root of this
-distribution (the "License"). All use of this software is governed by the License,
-or, if provided, by the license below or the license accompanying this file. Do not
-remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-"""
-
-# Tests the legacy Python API for CryMaterials while the Editor is running
-
-import azlmbr.bus as bus
-import azlmbr.editor as editor
-import azlmbr.legacy.material as material
-import azlmbr.math as math
-
-materialName = 'materials/ter_layer_green'
-print(f'Starting CryMaterial test case using material {materialName}')
-
-
-def MaterialPropertyTest(property, value, doReset=True):
- try:
- # get old value and attempt to set new value
- oldValue = material.get_property(materialName, property)
- if oldValue == value:
- print(f'>>> `{property}` already set to {oldValue}')
- return
- material.set_property(materialName, property, value)
-
- # test that the set new value worked
- newValue = material.get_property(materialName, property)
- if oldValue != newValue:
- print(f"{property} updated correctly")
-
- # reset back to old value
- if doReset:
- material.set_property(materialName, property, oldValue)
- except:
- print(f'!!! hit an exception when setting `{property}` to {value}')
-
-
-color = math.Color()
-color.r = 255.0
-color.g = 128.0
-color.b = 64.0
-color.a = 0.0
-
-# Material Settings
-# MaterialPropertyTest("Material Settings/Shader", "Geometrybeam") # Disabled, SPEC-3590
-# MaterialPropertyTest("Material Settings/Surface Type", "grass") # Disabled, SPEC-3590
-
-# Texture Maps
-MaterialPropertyTest("Texture Maps/Diffuse/Tiling/IsTileU", False)
-MaterialPropertyTest("Texture Maps/Diffuse/Tiling/IsTileV", False)
-MaterialPropertyTest("Texture Maps/Diffuse/Tiling/TileU", 0.42)
-MaterialPropertyTest("Texture Maps/Diffuse/Rotator/Type", 'Oscillated Rotation')
-MaterialPropertyTest("Texture Maps/Diffuse/Rotator/Amplitude", 42.0)
-MaterialPropertyTest("Texture Maps/Diffuse/Oscillator/TypeU", 'Fixed Moving')
-MaterialPropertyTest("Texture Maps/Diffuse/Oscillator/AmplitudeU", 42.0)
-
-# Vertex Deformation
-MaterialPropertyTest("Vertex Deformation/Type", 'Sin Wave')
-MaterialPropertyTest("Vertex Deformation/Wave Length X", 42.0)
-MaterialPropertyTest("Vertex Deformation/Type", 'Perlin 3D')
-MaterialPropertyTest("Vertex Deformation/Noise Scale", math.Vector3(1.1, 2.2, 3.3))
-
-# Opacity Settings
-MaterialPropertyTest("Opacity Settings/Opacity", 42)
-MaterialPropertyTest("Opacity Settings/AlphaTest", 2)
-MaterialPropertyTest("Opacity Settings/Additive", True)
-
-# Lighting Settings
-MaterialPropertyTest("Lighting Settings/Diffuse Color", color)
-MaterialPropertyTest("Lighting Settings/Specular Color", color)
-MaterialPropertyTest("Lighting Settings/Emissive Intensity", 42.0)
-MaterialPropertyTest("Lighting Settings/Emissive Color", color)
-MaterialPropertyTest("Lighting Settings/Specular Level", 2.0)
-
-# Advanced
-MaterialPropertyTest("Advanced/Allow layer activation", False)
-MaterialPropertyTest("Advanced/2 Sided", True)
-MaterialPropertyTest("Advanced/No Shadow", True)
-MaterialPropertyTest("Advanced/Use Scattering", True)
-MaterialPropertyTest("Advanced/Hide After Breaking", True)
-MaterialPropertyTest("Advanced/Fog Volume Shading Quality High", True)
-MaterialPropertyTest("Advanced/Blend Terrain Color", True)
-MaterialPropertyTest("Advanced/Voxel Coverage", 0.42)
-# --- MaterialPropertyTest("Advanced/Link to Material", "materials/ter_layer_blue") # Works, but clears on UI refresh
-MaterialPropertyTest("Advanced/Propagate Opacity Settings", True)
-MaterialPropertyTest("Advanced/Propagate Lighting Settings", True)
-MaterialPropertyTest("Advanced/Propagate Advanced Settings", True)
-MaterialPropertyTest("Advanced/Propagate Texture Maps", True)
-MaterialPropertyTest("Advanced/Propagate Shader Params", True)
-MaterialPropertyTest("Advanced/Propagate Shader Generation", True)
-MaterialPropertyTest("Advanced/Propagate Vertex Deformation", True)
-
-# Shader parameters vary with each Shader, just testing a couple of them...
-# MaterialPropertyTest("Shader Params/Blend Factor", 7.0, False) # Disabled, SPEC-3590
-# MaterialPropertyTest("Shader Params/Indirect bounce color", color, False) # Disabled, SPEC-3590
-
-### These values are reset to False when set. Left them here commented for reference.
-# MaterialPropertyTest("Shader Generation Params/Dust & Turbulence", True)
-# MaterialPropertyTest("Shader Generation Params/Receive Shadows", True)
-# MaterialPropertyTest("Shader Generation Params/UV Vignetting", True)
-
-# Vertex Deformation
-MaterialPropertyTest("Vertex Deformation/Type", "Sin Wave")
-MaterialPropertyTest("Vertex Deformation/Wave Length X", 42.0)
-MaterialPropertyTest("Vertex Deformation/Wave X/Level", 42.0)
-MaterialPropertyTest("Vertex Deformation/Wave X/Amplitude", 42.0)
-MaterialPropertyTest("Vertex Deformation/Wave X/Phase", 42.0)
-MaterialPropertyTest("Vertex Deformation/Wave X/Frequency", 42.0)
-
-editor.EditorToolsApplicationRequestBus(bus.Broadcast, 'ExitNoPrompt')
diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py
index 062c449ab7..e701ff8d16 100644
--- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py
+++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py
@@ -161,20 +161,6 @@ def run():
# Deletion/Undo/Redo test
verify_deletion_undo_redo(self.component_name, entity_obj)
- # Area Light Component
- area_light = "Area Light"
- ComponentTests(
- area_light, lambda entity_obj: verify_required_component_addition(
- entity_obj, ["Capsule Shape"], area_light))
-
- # Decal Component
- material_asset_path = os.path.join("AutomatedTesting", "Materials", "basic_grey.material")
- material_asset = asset.AssetCatalogRequestBus(
- bus.Broadcast, "GetAssetIdByPath", material_asset_path, math.Uuid(), False)
- ComponentTests(
- "Decal (Atom)", lambda entity_obj: verify_set_property(
- entity_obj, "Controller|Configuration|Material", material_asset))
-
# DepthOfField Component
camera_entity = hydra.Entity("camera_entity")
camera_entity.create_entity(math.Vector3(512.0, 512.0, 34.0), ["Camera"])
@@ -185,6 +171,14 @@ def run():
lambda entity_obj: verify_set_property(
entity_obj, "Controller|Configuration|Camera Entity", camera_entity.id))
+ # Decal Component
+ material_asset_path = os.path.join("AutomatedTesting", "Materials", "basic_grey.material")
+ material_asset = asset.AssetCatalogRequestBus(
+ bus.Broadcast, "GetAssetIdByPath", material_asset_path, math.Uuid(), False)
+ ComponentTests(
+ "Decal (Atom)", lambda entity_obj: verify_set_property(
+ entity_obj, "Controller|Configuration|Material", material_asset))
+
# Directional Light Component
ComponentTests(
"Directional Light",
@@ -213,9 +207,6 @@ def run():
# Physical Sky Component
ComponentTests("Physical Sky")
- # Point Light Component
- ComponentTests("Point Light")
-
# PostFX Layer Component
ComponentTests("PostFX Layer")
diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py
index 16139e3f66..aafa2ff9b7 100644
--- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py
+++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py
@@ -27,194 +27,6 @@ TEST_DIRECTORY = os.path.join(os.path.dirname(__file__), "atom_hydra_scripts")
@pytest.mark.parametrize("level", ["auto_test"])
class TestAtomEditorComponentsMain(object):
- @pytest.mark.test_case_id(
- "C32078117", # Area Light
- "C32078130", # Display Mapper
- "C32078129", # Light
- "C32078131", # Radius Weight Modifier
- "C32078127", # PostFX Layer
- "C32078126", # Point Light
- "C32078125", # Physical Sky
- "C32078115", # Global Skylight (IBL)
- "C32078121", # Exposure Control
- "C32078120", # Directional Light
- "C32078119", # DepthOfField
- "C32078118") # Decal
- def test_AtomEditorComponents_AddedToEntity(self, request, editor, level, workspace, project, launcher_platform):
- cfg_args = [level]
-
- expected_lines = [
- # Area Light Component
- "Area Light Entity successfully created",
- "Area Light_test: Component added to the entity: True",
- "Area Light_test: Component removed after UNDO: True",
- "Area Light_test: Component added after REDO: True",
- "Area Light_test: Entered game mode: True",
- "Area Light_test: Entity enabled after adding required components: True",
- "Area Light_test: Entity is hidden: True",
- "Area Light_test: Entity is shown: True",
- "Area Light_test: Entity deleted: True",
- "Area Light_test: UNDO entity deletion works: True",
- "Area Light_test: REDO entity deletion works: True",
- # Decal Component
- "Decal (Atom) Entity successfully created",
- "Decal (Atom)_test: Component added to the entity: True",
- "Decal (Atom)_test: Component removed after UNDO: True",
- "Decal (Atom)_test: Component added after REDO: True",
- "Decal (Atom)_test: Entered game mode: True",
- "Decal (Atom)_test: Exit game mode: True",
- "Decal (Atom) Controller|Configuration|Material: SUCCESS",
- "Decal (Atom)_test: Entity is hidden: True",
- "Decal (Atom)_test: Entity is shown: True",
- "Decal (Atom)_test: Entity deleted: True",
- "Decal (Atom)_test: UNDO entity deletion works: True",
- "Decal (Atom)_test: REDO entity deletion works: True",
- # DepthOfField Component
- "DepthOfField Entity successfully created",
- "DepthOfField_test: Component added to the entity: True",
- "DepthOfField_test: Component removed after UNDO: True",
- "DepthOfField_test: Component added after REDO: True",
- "DepthOfField_test: Entered game mode: True",
- "DepthOfField_test: Exit game mode: True",
- "DepthOfField_test: Entity disabled initially: True",
- "DepthOfField_test: Entity enabled after adding required components: True",
- "DepthOfField Controller|Configuration|Camera Entity: SUCCESS",
- "DepthOfField_test: Entity is hidden: True",
- "DepthOfField_test: Entity is shown: True",
- "DepthOfField_test: Entity deleted: True",
- "DepthOfField_test: UNDO entity deletion works: True",
- "DepthOfField_test: REDO entity deletion works: True",
- # Directional Light Component
- "Directional Light Entity successfully created",
- "Directional Light_test: Component added to the entity: True",
- "Directional Light_test: Component removed after UNDO: True",
- "Directional Light_test: Component added after REDO: True",
- "Directional Light_test: Entered game mode: True",
- "Directional Light_test: Exit game mode: True",
- "Directional Light Controller|Configuration|Shadow|Camera: SUCCESS",
- "Directional Light_test: Entity is hidden: True",
- "Directional Light_test: Entity is shown: True",
- "Directional Light_test: Entity deleted: True",
- "Directional Light_test: UNDO entity deletion works: True",
- "Directional Light_test: REDO entity deletion works: True",
- # Exposure Control Component
- "Exposure Control Entity successfully created",
- "Exposure Control_test: Component added to the entity: True",
- "Exposure Control_test: Component removed after UNDO: True",
- "Exposure Control_test: Component added after REDO: True",
- "Exposure Control_test: Entered game mode: True",
- "Exposure Control_test: Exit game mode: True",
- "Exposure Control_test: Entity disabled initially: True",
- "Exposure Control_test: Entity enabled after adding required components: True",
- "Exposure Control_test: Entity is hidden: True",
- "Exposure Control_test: Entity is shown: True",
- "Exposure Control_test: Entity deleted: True",
- "Exposure Control_test: UNDO entity deletion works: True",
- "Exposure Control_test: REDO entity deletion works: True",
- # Global Skylight (IBL) Component
- "Global Skylight (IBL) Entity successfully created",
- "Global Skylight (IBL)_test: Component added to the entity: True",
- "Global Skylight (IBL)_test: Component removed after UNDO: True",
- "Global Skylight (IBL)_test: Component added after REDO: True",
- "Global Skylight (IBL)_test: Entered game mode: True",
- "Global Skylight (IBL)_test: Exit game mode: True",
- "Global Skylight (IBL) Controller|Configuration|Diffuse Image: SUCCESS",
- "Global Skylight (IBL) Controller|Configuration|Specular Image: SUCCESS",
- "Global Skylight (IBL)_test: Entity is hidden: True",
- "Global Skylight (IBL)_test: Entity is shown: True",
- "Global Skylight (IBL)_test: Entity deleted: True",
- "Global Skylight (IBL)_test: UNDO entity deletion works: True",
- "Global Skylight (IBL)_test: REDO entity deletion works: True",
- # Physical Sky Component
- "Physical Sky Entity successfully created",
- "Physical Sky component was added to entity",
- "Entity has a Physical Sky component",
- "Physical Sky_test: Component added to the entity: True",
- "Physical Sky_test: Component removed after UNDO: True",
- "Physical Sky_test: Component added after REDO: True",
- "Physical Sky_test: Entered game mode: True",
- "Physical Sky_test: Exit game mode: True",
- "Physical Sky_test: Entity is hidden: True",
- "Physical Sky_test: Entity is shown: True",
- "Physical Sky_test: Entity deleted: True",
- "Physical Sky_test: UNDO entity deletion works: True",
- "Physical Sky_test: REDO entity deletion works: True",
- # Point Light Component
- "Point Light Entity successfully created",
- "Point Light_test: Component added to the entity: True",
- "Point Light_test: Component removed after UNDO: True",
- "Point Light_test: Component added after REDO: True",
- "Point Light_test: Entered game mode: True",
- "Point Light_test: Exit game mode: True",
- "Point Light_test: Entity is hidden: True",
- "Point Light_test: Entity is shown: True",
- "Point Light_test: Entity deleted: True",
- "Point Light_test: UNDO entity deletion works: True",
- "Point Light_test: REDO entity deletion works: True",
- # PostFX Layer Component
- "PostFX Layer Entity successfully created",
- "PostFX Layer_test: Component added to the entity: True",
- "PostFX Layer_test: Component removed after UNDO: True",
- "PostFX Layer_test: Component added after REDO: True",
- "PostFX Layer_test: Entered game mode: True",
- "PostFX Layer_test: Exit game mode: True",
- "PostFX Layer_test: Entity is hidden: True",
- "PostFX Layer_test: Entity is shown: True",
- "PostFX Layer_test: Entity deleted: True",
- "PostFX Layer_test: UNDO entity deletion works: True",
- "PostFX Layer_test: REDO entity deletion works: True",
- # Radius Weight Modifier Component
- "Radius Weight Modifier Entity successfully created",
- "Radius Weight Modifier_test: Component added to the entity: True",
- "Radius Weight Modifier_test: Component removed after UNDO: True",
- "Radius Weight Modifier_test: Component added after REDO: True",
- "Radius Weight Modifier_test: Entered game mode: True",
- "Radius Weight Modifier_test: Exit game mode: True",
- "Radius Weight Modifier_test: Entity is hidden: True",
- "Radius Weight Modifier_test: Entity is shown: True",
- "Radius Weight Modifier_test: Entity deleted: True",
- "Radius Weight Modifier_test: UNDO entity deletion works: True",
- "Radius Weight Modifier_test: REDO entity deletion works: True",
- # Light Component
- "Light Entity successfully created",
- "Light_test: Component added to the entity: True",
- "Light_test: Component removed after UNDO: True",
- "Light_test: Component added after REDO: True",
- "Light_test: Entered game mode: True",
- "Light_test: Exit game mode: True",
- "Light_test: Entity is hidden: True",
- "Light_test: Entity is shown: True",
- "Light_test: Entity deleted: True",
- "Light_test: UNDO entity deletion works: True",
- "Light_test: REDO entity deletion works: True",
- # Display Mapper Component
- "Display Mapper Entity successfully created",
- "Display Mapper_test: Component added to the entity: True",
- "Display Mapper_test: Component removed after UNDO: True",
- "Display Mapper_test: Component added after REDO: True",
- "Display Mapper_test: Entered game mode: True",
- "Display Mapper_test: Exit game mode: True",
- "Display Mapper_test: Entity is hidden: True",
- "Display Mapper_test: Entity is shown: True",
- "Display Mapper_test: Entity deleted: True",
- "Display Mapper_test: UNDO entity deletion works: True",
- "Display Mapper_test: REDO entity deletion works: True",
- ]
-
- unexpected_lines = [
- "failed to open",
- "Traceback (most recent call last):",
- ]
-
- hydra.launch_and_validate_results(
- request,
- TEST_DIRECTORY,
- editor,
- "hydra_AtomEditorComponents_AddedToEntity.py",
- timeout=EDITOR_TIMEOUT,
- expected_lines=expected_lines,
- unexpected_lines=unexpected_lines,
- halt_on_unexpected=True,
- null_renderer=True,
- cfg_args=cfg_args,
- )
+ # It requires at least one test
+ def test_Dummy(self, request, editor, level, workspace, project, launcher_platform):
+ pass
diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_SandboxSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_SandboxSuite.py
index 0fb873e677..8ca5b5aa31 100644
--- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_SandboxSuite.py
+++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_SandboxSuite.py
@@ -19,6 +19,170 @@ import pytest
@pytest.mark.parametrize("level", ["auto_test"])
class TestAtomEditorComponentsSandbox(object):
- # It requires at least one test
- def test_Dummy(self, request, editor, level, workspace, project, launcher_platform):
- pass
+ @pytest.mark.test_case_id(
+ "C32078117", # Area Light
+ "C32078130", # Display Mapper
+ "C32078129", # Light
+ "C32078131", # Radius Weight Modifier
+ "C32078127", # PostFX Layer
+ "C32078126", # Point Light
+ "C32078125", # Physical Sky
+ "C32078115", # Global Skylight (IBL)
+ "C32078121", # Exposure Control
+ "C32078120", # Directional Light
+ "C32078119", # DepthOfField
+ "C32078118") # Decal
+ def test_AtomEditorComponents_AddedToEntity(self, request, editor, level, workspace, project, launcher_platform):
+ cfg_args = [level]
+
+ expected_lines = [
+ # Decal Component
+ "Decal (Atom) Entity successfully created",
+ "Decal (Atom)_test: Component added to the entity: True",
+ "Decal (Atom)_test: Component removed after UNDO: True",
+ "Decal (Atom)_test: Component added after REDO: True",
+ "Decal (Atom)_test: Entered game mode: True",
+ "Decal (Atom)_test: Exit game mode: True",
+ "Decal (Atom) Controller|Configuration|Material: SUCCESS",
+ "Decal (Atom)_test: Entity is hidden: True",
+ "Decal (Atom)_test: Entity is shown: True",
+ "Decal (Atom)_test: Entity deleted: True",
+ "Decal (Atom)_test: UNDO entity deletion works: True",
+ "Decal (Atom)_test: REDO entity deletion works: True",
+ # DepthOfField Component
+ "DepthOfField Entity successfully created",
+ "DepthOfField_test: Component added to the entity: True",
+ "DepthOfField_test: Component removed after UNDO: True",
+ "DepthOfField_test: Component added after REDO: True",
+ "DepthOfField_test: Entered game mode: True",
+ "DepthOfField_test: Exit game mode: True",
+ "DepthOfField_test: Entity disabled initially: True",
+ "DepthOfField_test: Entity enabled after adding required components: True",
+ "DepthOfField Controller|Configuration|Camera Entity: SUCCESS",
+ "DepthOfField_test: Entity is hidden: True",
+ "DepthOfField_test: Entity is shown: True",
+ "DepthOfField_test: Entity deleted: True",
+ "DepthOfField_test: UNDO entity deletion works: True",
+ "DepthOfField_test: REDO entity deletion works: True",
+ # Directional Light Component
+ "Directional Light Entity successfully created",
+ "Directional Light_test: Component added to the entity: True",
+ "Directional Light_test: Component removed after UNDO: True",
+ "Directional Light_test: Component added after REDO: True",
+ "Directional Light_test: Entered game mode: True",
+ "Directional Light_test: Exit game mode: True",
+ "Directional Light Controller|Configuration|Shadow|Camera: SUCCESS",
+ "Directional Light_test: Entity is hidden: True",
+ "Directional Light_test: Entity is shown: True",
+ "Directional Light_test: Entity deleted: True",
+ "Directional Light_test: UNDO entity deletion works: True",
+ "Directional Light_test: REDO entity deletion works: True",
+ # Exposure Control Component
+ "Exposure Control Entity successfully created",
+ "Exposure Control_test: Component added to the entity: True",
+ "Exposure Control_test: Component removed after UNDO: True",
+ "Exposure Control_test: Component added after REDO: True",
+ "Exposure Control_test: Entered game mode: True",
+ "Exposure Control_test: Exit game mode: True",
+ "Exposure Control_test: Entity disabled initially: True",
+ "Exposure Control_test: Entity enabled after adding required components: True",
+ "Exposure Control_test: Entity is hidden: True",
+ "Exposure Control_test: Entity is shown: True",
+ "Exposure Control_test: Entity deleted: True",
+ "Exposure Control_test: UNDO entity deletion works: True",
+ "Exposure Control_test: REDO entity deletion works: True",
+ # Global Skylight (IBL) Component
+ "Global Skylight (IBL) Entity successfully created",
+ "Global Skylight (IBL)_test: Component added to the entity: True",
+ "Global Skylight (IBL)_test: Component removed after UNDO: True",
+ "Global Skylight (IBL)_test: Component added after REDO: True",
+ "Global Skylight (IBL)_test: Entered game mode: True",
+ "Global Skylight (IBL)_test: Exit game mode: True",
+ "Global Skylight (IBL) Controller|Configuration|Diffuse Image: SUCCESS",
+ "Global Skylight (IBL) Controller|Configuration|Specular Image: SUCCESS",
+ "Global Skylight (IBL)_test: Entity is hidden: True",
+ "Global Skylight (IBL)_test: Entity is shown: True",
+ "Global Skylight (IBL)_test: Entity deleted: True",
+ "Global Skylight (IBL)_test: UNDO entity deletion works: True",
+ "Global Skylight (IBL)_test: REDO entity deletion works: True",
+ # Physical Sky Component
+ "Physical Sky Entity successfully created",
+ "Physical Sky component was added to entity",
+ "Entity has a Physical Sky component",
+ "Physical Sky_test: Component added to the entity: True",
+ "Physical Sky_test: Component removed after UNDO: True",
+ "Physical Sky_test: Component added after REDO: True",
+ "Physical Sky_test: Entered game mode: True",
+ "Physical Sky_test: Exit game mode: True",
+ "Physical Sky_test: Entity is hidden: True",
+ "Physical Sky_test: Entity is shown: True",
+ "Physical Sky_test: Entity deleted: True",
+ "Physical Sky_test: UNDO entity deletion works: True",
+ "Physical Sky_test: REDO entity deletion works: True",
+ # PostFX Layer Component
+ "PostFX Layer Entity successfully created",
+ "PostFX Layer_test: Component added to the entity: True",
+ "PostFX Layer_test: Component removed after UNDO: True",
+ "PostFX Layer_test: Component added after REDO: True",
+ "PostFX Layer_test: Entered game mode: True",
+ "PostFX Layer_test: Exit game mode: True",
+ "PostFX Layer_test: Entity is hidden: True",
+ "PostFX Layer_test: Entity is shown: True",
+ "PostFX Layer_test: Entity deleted: True",
+ "PostFX Layer_test: UNDO entity deletion works: True",
+ "PostFX Layer_test: REDO entity deletion works: True",
+ # Radius Weight Modifier Component
+ "Radius Weight Modifier Entity successfully created",
+ "Radius Weight Modifier_test: Component added to the entity: True",
+ "Radius Weight Modifier_test: Component removed after UNDO: True",
+ "Radius Weight Modifier_test: Component added after REDO: True",
+ "Radius Weight Modifier_test: Entered game mode: True",
+ "Radius Weight Modifier_test: Exit game mode: True",
+ "Radius Weight Modifier_test: Entity is hidden: True",
+ "Radius Weight Modifier_test: Entity is shown: True",
+ "Radius Weight Modifier_test: Entity deleted: True",
+ "Radius Weight Modifier_test: UNDO entity deletion works: True",
+ "Radius Weight Modifier_test: REDO entity deletion works: True",
+ # Light Component
+ "Light Entity successfully created",
+ "Light_test: Component added to the entity: True",
+ "Light_test: Component removed after UNDO: True",
+ "Light_test: Component added after REDO: True",
+ "Light_test: Entered game mode: True",
+ "Light_test: Exit game mode: True",
+ "Light_test: Entity is hidden: True",
+ "Light_test: Entity is shown: True",
+ "Light_test: Entity deleted: True",
+ "Light_test: UNDO entity deletion works: True",
+ "Light_test: REDO entity deletion works: True",
+ # Display Mapper Component
+ "Display Mapper Entity successfully created",
+ "Display Mapper_test: Component added to the entity: True",
+ "Display Mapper_test: Component removed after UNDO: True",
+ "Display Mapper_test: Component added after REDO: True",
+ "Display Mapper_test: Entered game mode: True",
+ "Display Mapper_test: Exit game mode: True",
+ "Display Mapper_test: Entity is hidden: True",
+ "Display Mapper_test: Entity is shown: True",
+ "Display Mapper_test: Entity deleted: True",
+ "Display Mapper_test: UNDO entity deletion works: True",
+ "Display Mapper_test: REDO entity deletion works: True",
+ ]
+
+ unexpected_lines = [
+ "failed to open",
+ "Traceback (most recent call last):",
+ ]
+
+ hydra.launch_and_validate_results(
+ request,
+ TEST_DIRECTORY,
+ editor,
+ "hydra_AtomEditorComponents_AddedToEntity.py",
+ timeout=EDITOR_TIMEOUT,
+ expected_lines=expected_lines,
+ unexpected_lines=unexpected_lines,
+ halt_on_unexpected=True,
+ null_renderer=True,
+ cfg_args=cfg_args,
+ )
diff --git a/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py b/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py
index d8e0a6769c..60fa9dc44d 100755
--- a/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py
+++ b/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py
@@ -20,7 +20,10 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
class Tests():
enter_game_mode = ("Entered game mode", "Failed to enter game mode")
find_cylinder = ("Cylinder entity found", "Cylinder entity not found")
- find_terrain = ("Terrain found", "Terrain not found")
+ create_terrain = ("Terrain entity created successfully", "Failed to create Terrain Entity")
+ find_terrain = ("Terrain entity found", "Terrain entity not found")
+ add_physx_shape_collider = ("Added PhysX Shape Collider", "Failed to add PhysX Shape Collider")
+ add_box_shape = ("Added Box Shape", "Failed to add Box Shape")
cylinder_above_terrain = ("Cylinder position above ground", "Cylinder is not above the ground")
time_out = ("No time out occurred", "A time out occurred, please validate level setup")
touched_ground = ("Touched ground before time out", "Did not touch ground before time out")
@@ -40,11 +43,12 @@ def C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain():
Once game mode is entered, the cylinder should fall toward and collide with the terrain.
Steps:
- 1) Open level and enter game mode
- 2) Retrieve entities and positions
- 3) Wait for cylinder to collide with terrain OR time out
- 4) Exit game mode
- 5) Close the editor
+ 1) Open level and create terrain Entity.
+ 2) Enter Game Mode.
+ 3) Retrieve entities and positions
+ 4) Wait for cylinder to collide with terrain OR time out
+ 5) Exit game mode
+ 6) Close the editor
:return:
"""
@@ -54,29 +58,48 @@ def C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain():
import ImportPathHelper as imports
imports.init()
-
+ from editor_python_test_tools.editor_entity_utils import EditorEntity
import azlmbr.legacy.general as general
import azlmbr.bus
+ import azlmbr.math as math
from editor_python_test_tools.utils import Report
from editor_python_test_tools.utils import TestHelper as helper
# Global time out
TIME_OUT = 1.0
- # 1) Open level / Enter game mode
+ # 1) Open level
helper.init_idle()
helper.open_level("Physics", "C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain")
+
+ # Create terrain entity
+ terrain = EditorEntity.create_editor_entity_at([30.0, 30.0, 33.96], "Terrain")
+ Report.result(Tests.create_terrain, terrain.id.IsValid())
+
+ terrain.add_component("PhysX Shape Collider")
+ Report.result(Tests.add_physx_shape_collider, terrain.has_component("PhysX Shape Collider"))
+
+ box_shape_component = terrain.add_component("Box Shape")
+ Report.result(Tests.add_box_shape, terrain.has_component("Box Shape"))
+
+ box_shape_component.set_component_property_value("Box Shape|Box Configuration|Dimensions",
+ math.Vector3(1024.0, 1024.0, 0.01))
+
+ # 2)Enter game mode
helper.enter_game_mode(Tests.enter_game_mode)
- # 2) Retrieve entities and positions
+ # 3) Retrieve entities and positions
cylinder_id = general.find_game_entity("PhysX_Cylinder")
Report.critical_result(Tests.find_cylinder, cylinder_id.IsValid())
+
+
+ terrain_id = general.find_game_entity("Terrain")
+ Report.critical_result(Tests.find_terrain, terrain_id.IsValid())
- terrain_id = general.find_game_entity("PhysX_Terrain")
- Report.critical_result(Tests.find_terrain, terrain_id.IsValid())
- cylinder_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTM", cylinder_id).GetPosition()
- terrain_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTM", terrain_id).GetPosition()
+ cylinder_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", cylinder_id)
+ #Cylinder position is 64,84,35
+ terrain_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", terrain_id)
Report.info_vector3(cylinder_pos, "Cylinder:")
Report.info_vector3(terrain_pos, "Terrain:")
Report.critical_result(
@@ -104,13 +127,13 @@ def C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain():
handler.connect(cylinder_id)
handler.add_callback("OnCollisionBegin", on_collision_begin)
- # 3) Wait for the cylinder to hit the ground OR time out
+ # 4) Wait for the cylinder to hit the ground OR time out
test_completed = helper.wait_for_condition((lambda: TouchGround.value), TIME_OUT)
Report.critical_result(Tests.time_out, test_completed)
Report.result(Tests.touched_ground, TouchGround.value)
- # 4) Exit game mode
+ # 5) Exit game mode
helper.exit_game_mode(Tests.exit_game_mode)
diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py
index 67e855a00e..f81445fe03 100644
--- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py
+++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py
@@ -34,4 +34,61 @@ class TestAutomation(TestAutomationBase):
def test_C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC(self, request, workspace, editor, launcher_platform):
from . import C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ def test_C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies(self, request, workspace, editor, launcher_platform):
+ from . import C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ def test_C4044459_Material_DynamicFriction(self, request, workspace, editor, launcher_platform):
+ from . import C4044459_Material_DynamicFriction as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ def test_C15425929_Undo_Redo(self, request, workspace, editor, launcher_platform):
+ from . import C15425929_Undo_Redo as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ def test_C4976243_Collision_SameCollisionGroupDiffCollisionLayers(self, request, workspace, editor,
+ launcher_platform):
+ from . import C4976243_Collision_SameCollisionGroupDiffCollisionLayers as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ def test_C14654881_CharacterController_SwitchLevels(self, request, workspace, editor, launcher_platform):
+ from . import C14654881_CharacterController_SwitchLevels as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ def test_C17411467_AddPhysxRagdollComponent(self, request, workspace, editor, launcher_platform):
+ from . import C17411467_AddPhysxRagdollComponent as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ def test_C12712453_ScriptCanvas_MultipleRaycastNode(self, request, workspace, editor, launcher_platform):
+ from . import C12712453_ScriptCanvas_MultipleRaycastNode as test_module
+ # Fixme: unexpected_lines = ["Assert"] + test_module.Lines.unexpected
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ @fm.file_override('physxsystemconfiguration.setreg','C4982593_PhysXCollider_CollisionLayer.setreg', 'AutomatedTesting/Registry')
+ def test_C4982593_PhysXCollider_CollisionLayerTest(self, request, workspace, editor, launcher_platform):
+ from . import C4982593_PhysXCollider_CollisionLayerTest as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ def test_C18243586_Joints_HingeLeadFollowerCollide(self, request, workspace, editor, launcher_platform):
+ from . import C18243586_Joints_HingeLeadFollowerCollide as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ def test_C4982803_Enable_PxMesh_Option(self, request, workspace, editor, launcher_platform):
+ from . import C4982803_Enable_PxMesh_Option as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ def test_C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain(self, request, workspace, editor, launcher_platform):
+ from . import C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain as test_module
self._run_test(request, workspace, editor, test_module)
\ No newline at end of file
diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py
index 39ed85a65a..4f91f539ee 100755
--- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py
+++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py
@@ -52,11 +52,6 @@ class TestAutomation(TestAutomationBase):
from . import C4976207_PhysXRigidBodies_KinematicBehavior as test_module
self._run_test(request, workspace, editor, test_module)
- @revert_physics_config
- def test_C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies(self, request, workspace, editor, launcher_platform):
- from . import C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies as test_module
- self._run_test(request, workspace, editor, test_module)
-
@revert_physics_config
def test_C5932042_PhysXForceRegion_LinearDamping(self, request, workspace, editor, launcher_platform):
from . import C5932042_PhysXForceRegion_LinearDamping as test_module
@@ -92,11 +87,6 @@ class TestAutomation(TestAutomationBase):
from . import C4976194_RigidBody_PhysXComponentIsValid as test_module
self._run_test(request, workspace, editor, test_module)
- @revert_physics_config
- def test_C4044459_Material_DynamicFriction(self, request, workspace, editor, launcher_platform):
- from . import C4044459_Material_DynamicFriction as test_module
- self._run_test(request, workspace, editor, test_module)
-
@revert_physics_config
def test_C5932045_ForceRegion_Spline(self, request, workspace, editor, launcher_platform):
from . import C5932045_ForceRegion_Spline as test_module
@@ -208,26 +198,11 @@ class TestAutomation(TestAutomationBase):
from . import C18981526_Material_RestitutionCombinePriority as test_module
self._run_test(request, workspace, editor, test_module)
- @revert_physics_config
- def test_C15425929_Undo_Redo(self, request, workspace, editor, launcher_platform):
- from . import C15425929_Undo_Redo as test_module
- self._run_test(request, workspace, editor, test_module)
-
- @revert_physics_config
- def test_C15308217_NoCrash_LevelSwitch(self, request, workspace, editor, launcher_platform):
- from . import C15308217_NoCrash_LevelSwitch as test_module
- self._run_test(request, workspace, editor, test_module)
-
@revert_physics_config
def test_C12868580_ForceRegion_SplineModifiedTransform(self, request, workspace, editor, launcher_platform):
from . import C12868580_ForceRegion_SplineModifiedTransform as test_module
self._run_test(request, workspace, editor, test_module)
- @revert_physics_config
- def test_C4976243_Collision_SameCollisionGroupDiffCollisionLayers(self, request, workspace, editor, launcher_platform):
- from . import C4976243_Collision_SameCollisionGroupDiffCollisionLayers as test_module
- self._run_test(request, workspace, editor, test_module)
-
@revert_physics_config
def test_C12712455_ScriptCanvas_ShapeCastVerification(self, request, workspace, editor, launcher_platform):
from . import C12712455_ScriptCanvas_ShapeCastVerification as test_module
@@ -248,17 +223,6 @@ class TestAutomation(TestAutomationBase):
from . import C6131473_StaticSlice_OnDynamicSliceSpawn as test_module
self._run_test(request, workspace, editor, test_module)
- @revert_physics_config
- def test_C4982798_Collider_ColliderRotationOffset(self, request, workspace, editor, launcher_platform):
- from . import C4982798_Collider_ColliderRotationOffset as test_module
- self._run_test(request, workspace, editor, test_module)
-
- @revert_physics_config
- def test_C12712453_ScriptCanvas_MultipleRaycastNode(self, request, workspace, editor, launcher_platform):
- from . import C12712453_ScriptCanvas_MultipleRaycastNode as test_module
- # Fixme: unexpected_lines = ["Assert"] + test_module.Lines.unexpected
- self._run_test(request, workspace, editor, test_module)
-
@revert_physics_config
def test_C5959808_ForceRegion_PositionOffset(self, request, workspace, editor, launcher_platform):
from . import C5959808_ForceRegion_PositionOffset as test_module
@@ -275,7 +239,7 @@ class TestAutomation(TestAutomationBase):
def test_C13895144_Ragdoll_ChangeLevel(self, request, workspace, editor, launcher_platform):
from . import C13895144_Ragdoll_ChangeLevel as test_module
self._run_test(request, workspace, editor, test_module)
-
+
@revert_physics_config
def test_C5968759_ForceRegion_ExertsSeveralForcesOnRigidBody(self, request, workspace, editor, launcher_platform):
from . import C5968759_ForceRegion_ExertsSeveralForcesOnRigidBody as test_module
@@ -305,11 +269,6 @@ class TestAutomation(TestAutomationBase):
from . import C5296614_PhysXMaterial_ColliderShape as test_module
self._run_test(request, workspace, editor, test_module)
- @revert_physics_config
- def test_C6090547_ForceRegion_ParentChildForceRegions(self, request, workspace, editor, launcher_platform):
- from . import C6090547_ForceRegion_ParentChildForceRegions as test_module
- self._run_test(request, workspace, editor, test_module)
-
@revert_physics_config
def test_C4982595_Collider_TriggerDisablesCollision(self, request, workspace, editor, launcher_platform):
from . import C4982595_Collider_TriggerDisablesCollision as test_module
@@ -320,11 +279,6 @@ class TestAutomation(TestAutomationBase):
from . import C14976307_Gravity_SetGravityWorks as test_module
self._run_test(request, workspace, editor, test_module)
- @revert_physics_config
- def test_C14654881_CharacterController_SwitchLevels(self, request, workspace, editor, launcher_platform):
- from . import C14654881_CharacterController_SwitchLevels as test_module
- self._run_test(request, workspace, editor, test_module)
-
@revert_physics_config
def test_C15556261_PhysXMaterials_CharacterControllerMaterialAssignment(self, request, workspace, editor, launcher_platform):
from . import C15556261_PhysXMaterials_CharacterControllerMaterialAssignment as test_module
@@ -374,18 +328,6 @@ class TestAutomation(TestAutomationBase):
from . import C4044461_Material_Restitution as test_module
self._run_test(request, workspace, editor, test_module)
- @revert_physics_config
- @fm.file_override('physxsystemconfiguration.setreg','C4982593_PhysXCollider_CollisionLayer.setreg', 'AutomatedTesting/Registry')
- def test_C4982593_PhysXCollider_CollisionLayerTest(self, request, workspace, editor, launcher_platform):
- from . import C4982593_PhysXCollider_CollisionLayerTest as test_module
- self._run_test(request, workspace, editor, test_module)
-
- @revert_physics_config
- @fm.file_override('physxsystemconfiguration.setreg','C3510644_Collider_CollisionGroups.setreg', 'AutomatedTesting/Registry')
- def test_C3510644_Collider_CollisionGroups(self, request, workspace, editor, launcher_platform):
- from . import C3510644_Collider_CollisionGroups as test_module
- self._run_test(request, workspace, editor, test_module)
-
@revert_physics_config
@fm.file_override('physxdefaultsceneconfiguration.setreg','C14902097_ScriptCanvas_PreUpdateEvent.setreg', 'AutomatedTesting/Registry')
def test_C14902097_ScriptCanvas_PreUpdateEvent(self, request, workspace, editor, launcher_platform):
@@ -415,11 +357,6 @@ class TestAutomation(TestAutomationBase):
from . import C18243589_Joints_BallSoftLimitsConstrained as test_module
self._run_test(request, workspace, editor, test_module)
- @revert_physics_config
- def test_C18243586_Joints_HingeLeadFollowerCollide(self, request, workspace, editor, launcher_platform):
- from . import C18243586_Joints_HingeLeadFollowerCollide as test_module
- self._run_test(request, workspace, editor, test_module)
-
@revert_physics_config
def test_C18243591_Joints_BallLeadFollowerCollide(self, request, workspace, editor, launcher_platform):
from . import C18243591_Joints_BallLeadFollowerCollide as test_module
@@ -441,21 +378,11 @@ class TestAutomation(TestAutomationBase):
from . import C14861500_DefaultSetting_ColliderShape as test_module
self._run_test(request, workspace, editor, test_module)
- @revert_physics_config
- def test_C19578021_ShapeCollider_CanBeAdded(self, request, workspace, editor, launcher_platform):
- from . import C19578021_ShapeCollider_CanBeAdded as test_module
- self._run_test(request, workspace, editor, test_module)
-
@revert_physics_config
def test_C19723164_ShapeCollider_WontCrashEditor(self, request, workspace, editor, launcher_platform):
from . import C19723164_ShapeColliders_WontCrashEditor as test_module
self._run_test(request, workspace, editor, test_module)
- @revert_physics_config
- def test_C4982803_Enable_PxMesh_Option(self, request, workspace, editor, launcher_platform):
- from . import C4982803_Enable_PxMesh_Option as test_module
- self._run_test(request, workspace, editor, test_module)
-
@revert_physics_config
def test_C4982800_PhysXColliderShape_CanBeSelected(self, request, workspace, editor, launcher_platform):
from . import C4982800_PhysXColliderShape_CanBeSelected as test_module
@@ -471,10 +398,6 @@ class TestAutomation(TestAutomationBase):
from . import C4982802_PhysXColliderShape_CanBeSelected as test_module
self._run_test(request, workspace, editor, test_module)
- def test_C17411467_AddPhysxRagdollComponent(self, request, workspace, editor, launcher_platform):
- from . import C17411467_AddPhysxRagdollComponent as test_module
- self._run_test(request, workspace, editor, test_module)
-
def test_C12905528_ForceRegion_WithNonTriggerCollider(self, request, workspace, editor, launcher_platform):
from . import C12905528_ForceRegion_WithNonTriggerCollider as test_module
# Fixme: expected_lines = ["[Warning] (PhysX Force Region) - Please ensure collider component marked as trigger exists in entity"]
@@ -522,4 +445,35 @@ class TestAutomation(TestAutomationBase):
def test_C100000_RigidBody_EnablingGravityWorksPoC(self, request, workspace, editor, launcher_platform):
from . import C100000_RigidBody_EnablingGravityWorksPoC as test_module
- self._run_test(request, workspace, editor, test_module)
\ No newline at end of file
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ @fm.file_override('physxsystemconfiguration.setreg','C3510644_Collider_CollisionGroups.setreg', 'AutomatedTesting/Registry')
+ def test_C3510644_Collider_CollisionGroups(self, request, workspace, editor, launcher_platform):
+ from . import C3510644_Collider_CollisionGroups as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ def test_C4982798_Collider_ColliderRotationOffset(self, request, workspace, editor, launcher_platform):
+ from . import C4982798_Collider_ColliderRotationOffset as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ def test_C15308217_NoCrash_LevelSwitch(self, request, workspace, editor, launcher_platform):
+ from . import C15308217_NoCrash_LevelSwitch as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ def test_C6090547_ForceRegion_ParentChildForceRegions(self, request, workspace, editor, launcher_platform):
+ from . import C6090547_ForceRegion_ParentChildForceRegions as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ def test_C19578021_ShapeCollider_CanBeAdded(self, request, workspace, editor, launcher_platform):
+ from . import C19578021_ShapeCollider_CanBeAdded as test_module
+ self._run_test(request, workspace, editor, test_module)
+
+ @revert_physics_config
+ def test_C15425929_Undo_Redo(self, request, workspace, editor, launcher_platform):
+ from . import C15425929_Undo_Redo as test_module
+ self._run_test(request, workspace, editor, test_module)
diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py
index 39bc4c8188..e829726ba9 100755
--- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py
+++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py
@@ -1,49 +1,49 @@
-"""
-All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
-its licensors.
-
-For complete copyright and license terms please see the LICENSE at the root of this
-distribution (the "License"). All use of this software is governed by the License,
-or, if provided, by the license below or the license accompanying this file. Do not
-remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-
-"""
-
-# This suite consists of all test cases that are passing and have been verified.
-
-import pytest
-import os
-import sys
-
-from .FileManagement import FileManagement as fm
-from ly_test_tools import LAUNCHERS
-
-sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared')
-
-from base import TestAutomationBase
-
-
-revert_physics_config = fm.file_revert_list(['physxdebugconfiguration.setreg', 'physxdefaultsceneconfiguration.setreg', 'physxsystemconfiguration.setreg'], 'AutomatedTesting/Registry')
-
-
-@pytest.mark.SUITE_sandbox
-@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
-@pytest.mark.parametrize("project", ["AutomatedTesting"])
-class TestAutomation(TestAutomationBase):
-
- ## Seems to be flaky, need to investigate
- def test_C19536274_GetCollisionName_PrintsName(self, request, workspace, editor, launcher_platform):
- from . import C19536274_GetCollisionName_PrintsName as test_module
- # Fixme: expected_lines=["Layer Name: Right"]
- self._run_test(request, workspace, editor, test_module)
-
- ## Seems to be flaky, need to investigate
- def test_C19536277_GetCollisionName_PrintsNothing(self, request, workspace, editor, launcher_platform):
- from . import C19536277_GetCollisionName_PrintsNothing as test_module
- # All groups present in the PhysX Collider that could show up in test
- # Fixme: collision_groups = ["All", "None", "All_NoTouchBend", "All_3", "None_1", "All_NoTouchBend_1", "All_2", "None_1_1", "All_NoTouchBend_1_1", "All_1", "None_1_1_1", "All_NoTouchBend_1_1_1", "All_4", "None_1_1_1_1", "All_NoTouchBend_1_1_1_1", "GroupLeft", "GroupRight"]
- # Fixme: for group in collision_groups:
- # Fixme: unexpected_lines.append(f"GroupName: {group}")
- # Fixme: expected_lines=["GroupName: "]
- self._run_test(request, workspace, editor, test_module)
\ No newline at end of file
+"""
+All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
+its licensors.
+
+For complete copyright and license terms please see the LICENSE at the root of this
+distribution (the "License"). All use of this software is governed by the License,
+or, if provided, by the license below or the license accompanying this file. Do not
+remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+
+"""
+
+# This suite consists of all test cases that are passing and have been verified.
+
+import pytest
+import os
+import sys
+
+from .FileManagement import FileManagement as fm
+from ly_test_tools import LAUNCHERS
+
+sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared')
+
+from base import TestAutomationBase
+
+
+revert_physics_config = fm.file_revert_list(['physxdebugconfiguration.setreg', 'physxdefaultsceneconfiguration.setreg', 'physxsystemconfiguration.setreg'], 'AutomatedTesting/Registry')
+
+
+@pytest.mark.SUITE_sandbox
+@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
+@pytest.mark.parametrize("project", ["AutomatedTesting"])
+class TestAutomation(TestAutomationBase):
+
+ ## Seems to be flaky, need to investigate
+ def test_C19536274_GetCollisionName_PrintsName(self, request, workspace, editor, launcher_platform):
+ from . import C19536274_GetCollisionName_PrintsName as test_module
+ # Fixme: expected_lines=["Layer Name: Right"]
+ self._run_test(request, workspace, editor, test_module)
+
+ ## Seems to be flaky, need to investigate
+ def test_C19536277_GetCollisionName_PrintsNothing(self, request, workspace, editor, launcher_platform):
+ from . import C19536277_GetCollisionName_PrintsNothing as test_module
+ # All groups present in the PhysX Collider that could show up in test
+ # Fixme: collision_groups = ["All", "None", "All_NoTouchBend", "All_3", "None_1", "All_NoTouchBend_1", "All_2", "None_1_1", "All_NoTouchBend_1_1", "All_1", "None_1_1_1", "All_NoTouchBend_1_1_1", "All_4", "None_1_1_1_1", "All_NoTouchBend_1_1_1_1", "GroupLeft", "GroupRight"]
+ # Fixme: for group in collision_groups:
+ # Fixme: unexpected_lines.append(f"GroupName: {group}")
+ # Fixme: expected_lines=["GroupName: "]
+ self._run_test(request, workspace, editor, test_module)
diff --git a/AutomatedTesting/Levels/Physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.ly b/AutomatedTesting/Levels/Physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.ly
index ba141251d5..d618bf1873 100644
--- a/AutomatedTesting/Levels/Physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.ly
+++ b/AutomatedTesting/Levels/Physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.ly
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:231d5ac32c95334eeb1cbf77ea0bceae1d8010de3290dfdbd991abb46d18bae6
-size 6844
+oid sha256:83af66a6db4ff2b4df7212099b661a96668cfb326d8984e41b16506ec0062141
+size 5844
diff --git a/AutomatedTesting/Registry/assets_scan_folders.setreg b/AutomatedTesting/Registry/assets_scan_folders.setreg
index 5394d381a3..91061f3337 100644
--- a/AutomatedTesting/Registry/assets_scan_folders.setreg
+++ b/AutomatedTesting/Registry/assets_scan_folders.setreg
@@ -38,6 +38,13 @@
"Gems/PrimitiveAssets"
]
},
+ "MaterialEditor":
+ {
+ "SourcePaths":
+ [
+ "Gems/Atom/Tools/MaterialEditor"
+ ]
+ },
"UiBasics":
{
"SourcePaths":
diff --git a/AutomatedTesting/ShaderLib/raytracingscenesrg.srgi b/AutomatedTesting/ShaderLib/raytracingscenesrg.srgi
deleted file mode 100644
index ac1d663bb8..0000000000
--- a/AutomatedTesting/ShaderLib/raytracingscenesrg.srgi
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
-* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
-* its licensors.
-*
-* For complete copyright and license terms please see the LICENSE at the root of this
-* distribution (the "License"). All use of this software is governed by the License,
-* or, if provided, by the license below or the license accompanying this file. Do not
-* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-*
-*/
-
-#pragma once
-
-// Please read README.md for an explanation on why scenesrg.srgi and viewsrg.srgi are
-// located in this folder (And how you can optionally customize your own scenesrg.srgi
-// and viewsrg.srgi in your game project).
-
-#include
-
-partial ShaderResourceGroup RayTracingSceneSrg : SRG_RayTracingScene
-{
-/* Intentionally Empty. Helps define the SrgSemantic for RayTracingSceneSrg once.*/
-};
-
-#define AZ_COLLECTING_PARTIAL_SRGS
-#include
-#undef AZ_COLLECTING_PARTIAL_SRGS
diff --git a/CMakeLists.txt b/CMakeLists.txt
index cefbcf2ef4..ae8a7a05f8 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -75,7 +75,9 @@ foreach(restricted_platform ${PAL_RESTRICTED_PLATFORMS})
endif()
endforeach()
-add_subdirectory(scripts)
+if(NOT INSTALLED_ENGINE)
+ add_subdirectory(scripts)
+endif()
# SPEC-1417 will investigate and fix this
if(NOT PAL_PLATFORM_NAME STREQUAL "Mac")
@@ -125,5 +127,5 @@ if(NOT INSTALLED_ENGINE)
ly_setup_o3de_install()
# IMPORTANT: must be included last
- include(cmake/CPack.cmake)
+ include(cmake/Packaging.cmake)
endif()
diff --git a/Code/CryEngine/CMakeLists.txt b/Code/CryEngine/CMakeLists.txt
index 38fcbf4a27..96f6427268 100644
--- a/Code/CryEngine/CMakeLists.txt
+++ b/Code/CryEngine/CMakeLists.txt
@@ -10,5 +10,4 @@
#
add_subdirectory(CryCommon)
-add_subdirectory(CryFont)
add_subdirectory(CrySystem)
diff --git a/Code/CryEngine/Cry3DEngine/3DEngineLight.cpp b/Code/CryEngine/Cry3DEngine/3DEngineLight.cpp
deleted file mode 100644
index 054620003c..0000000000
--- a/Code/CryEngine/Cry3DEngine/3DEngineLight.cpp
+++ /dev/null
@@ -1,733 +0,0 @@
-/*
-* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
-* its licensors.
-*
-* For complete copyright and license terms please see the LICENSE at the root of this
-* distribution (the "License"). All use of this software is governed by the License,
-* or, if provided, by the license below or the license accompanying this file. Do not
-* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-*
-*/
-// Original file Copyright Crytek GMBH or its affiliates, used under license.
-
-// Description : Light sources manager
-
-
-#include "Cry3DEngine_precompiled.h"
-
-#include "3dEngine.h"
-#include "ObjMan.h"
-#include "VisAreas.h"
-#include "AABBSV.h"
-#include "LightEntity.h"
-#include "ObjectsTree.h"
-#include "ClipVolumeManager.h"
-
-ILightSource* C3DEngine::CreateLightSource()
-{
- // construct new object
- CLightEntity* pLightEntity = new CLightEntity();
-
- m_lstStaticLights.Add(pLightEntity);
-
- return pLightEntity;
-}
-
-void C3DEngine::DeleteLightSource(ILightSource* pLightSource)
-{
- if (m_lstStaticLights.Delete((CLightEntity*)pLightSource) || pLightSource == m_pSun)
- {
- if (pLightSource == m_pSun)
- {
- m_pSun = NULL;
- }
-
- delete pLightSource;
- }
- else
- {
- assert(!"Light object not found");
- }
-}
-
-void CLightEntity::Release(bool)
-{
- Get3DEngine()->UnRegisterEntityDirect(this);
- Get3DEngine()->DeleteLightSource(this);
-}
-
-void CLightEntity::SetLightProperties(const CDLight& light)
-{
- C3DEngine* engine = Get3DEngine();
-
- m_light = light;
-
- m_bShadowCaster = (m_light.m_Flags & DLF_CASTSHADOW_MAPS) != 0;
-
- m_light.m_fBaseRadius = m_light.m_fRadius;
- m_light.m_fLightFrustumAngle = CLAMP(m_light.m_fLightFrustumAngle, 0.f, (LIGHT_PROJECTOR_MAX_FOV / 2.f));
-
- if (!(m_light.m_Flags & (DLF_PROJECT | DLF_AREA_LIGHT)))
- {
- m_light.m_fLightFrustumAngle = 90.f / 2.f;
- }
-
- m_light.m_pOwner = this;
-
- if (m_light.m_Flags & DLF_ATTACH_TO_SUN)
- {
- m_dwRndFlags |= ERF_RENDER_ALWAYS | ERF_HUD;
- }
-
- engine->GetLightEntities()->Delete((ILightSource*)this);
-
- PodArray& lightEntities = *engine->GetLightEntities();
-
- //on consoles we force all lights (except sun) to be deferred
- if (GetCVars()->e_DynamicLightsForceDeferred && !(m_light.m_Flags & (DLF_SUN | DLF_POST_3D_RENDERER)))
- {
- m_light.m_Flags |= DLF_DEFERRED_LIGHT;
- }
-
- if (light.m_Flags & DLF_DEFERRED_LIGHT)
- {
- lightEntities.Add((ILightSource*)this);
- }
- else
- {
- lightEntities.InsertBefore((ILightSource*)this, 0);
- }
-}
-
-void C3DEngine::ResetCasterCombinationsCache()
-{
- for (int nSunInUse = 0; nSunInUse < 2; nSunInUse++)
- {
- // clear user counters
- for (ShadowFrustumListsCacheUsers::iterator it = m_FrustumsCacheUsers[nSunInUse].begin(); it != m_FrustumsCacheUsers[nSunInUse].end(); ++it)
- {
- it->second = 0;
- }
- }
-}
-
-void C3DEngine::DeleteAllStaticLightSources()
-{
- for (int i = 0; i < m_lstStaticLights.Count(); i++)
- {
- delete m_lstStaticLights[i];
- }
- m_lstStaticLights.Reset();
-
- m_pSun = NULL;
-}
-
-void C3DEngine::InitShadowFrustums(const SRenderingPassInfo& passInfo)
-{
- assert(passInfo.IsGeneralPass());
- FUNCTION_PROFILER_3DENGINE_LEGACYONLY;
- AZ_TRACE_METHOD();
-
- if (m_pSun)
- {
- CDLight* pLight = &m_pSun->GetLightProperties();
- CLightEntity* pLightEntity = (CLightEntity*)pLight->m_pOwner;
-
- if (passInfo.RenderShadows() && (pLight->m_Flags & DLF_CASTSHADOW_MAPS) && pLight->m_Id >= 0)
- {
- pLightEntity->UpdateGSMLightSourceShadowFrustum(passInfo);
-
- if (pLightEntity->m_pShadowMapInfo)
- {
- pLight->m_pShadowMapFrustums = pLightEntity->m_pShadowMapInfo->pGSM;
- }
- }
-
- _smart_ptr pMat = pLightEntity->GetMaterial();
- if (pMat)
- {
- pLight->m_Shader = pMat->GetShaderItem();
- }
-
- // update copy of light ion the renderer
- if (pLight->m_Id >= 0)
- {
- CDLight* pRndLight = NULL;
- GetRenderer()->EF_Query(EFQ_LightSource, pLight->m_Id, pRndLight);
- assert(pLight->m_Id == pRndLight->m_Id);
- pRndLight->m_pShadowMapFrustums = pLight->m_pShadowMapFrustums;
- pRndLight->m_Shader = pLight->m_Shader;
- pRndLight->m_Flags = pLight->m_Flags;
- }
-
- // add per object shadow frustums
- m_nCustomShadowFrustumCount = 0;
- if (passInfo.RenderShadows() && GetCVars()->e_ShadowsPerObject > 0)
- {
- const uint nFrustumCount = m_lstPerObjectShadows.size();
- if (nFrustumCount > m_lstCustomShadowFrustums.size())
- {
- m_lstCustomShadowFrustums.resize(nFrustumCount);
- }
-
- for (uint i = 0; i < nFrustumCount; ++i)
- {
- if (m_lstPerObjectShadows[i].pCaster)
- {
- ShadowMapFrustum* pFr = &m_lstCustomShadowFrustums[i];
- pFr->m_eFrustumType = ShadowMapFrustum::e_PerObject;
-
- CLightEntity::ProcessPerObjectFrustum(pFr, &m_lstPerObjectShadows[i], m_pSun, passInfo);
- ++m_nCustomShadowFrustumCount;
- }
- }
- }
- }
-
- if (passInfo.RenderShadows())
- {
- ResetCasterCombinationsCache();
- }
-}
-
-void C3DEngine::AddPerObjectShadow(IShadowCaster* pCaster, float fConstBias, float fSlopeBias, float fJitter, const Vec3& vBBoxScale, uint nTexSize)
-{
- SPerObjectShadow* pOS = GetPerObjectShadow(pCaster);
- if (!pOS)
- {
- pOS = &m_lstPerObjectShadows.AddNew();
- }
-
- pOS->pCaster = pCaster;
- pOS->fConstBias = fConstBias;
- pOS->fSlopeBias = fSlopeBias;
- pOS->fJitter = fJitter;
- pOS->vBBoxScale = vBBoxScale;
- pOS->nTexSize = nTexSize;
-}
-
-void C3DEngine::RemovePerObjectShadow(IShadowCaster* pCaster)
-{
- SPerObjectShadow* pOS = GetPerObjectShadow(pCaster);
- if (pOS)
- {
- FRAME_PROFILER("C3DEngine::RemovePerObjectShadow", GetSystem(), PROFILE_3DENGINE);
-
- size_t nIndex = (size_t)(pOS - m_lstPerObjectShadows.begin());
- m_lstPerObjectShadows.Delete(nIndex);
- }
-}
-
-struct SPerObjectShadow* C3DEngine::GetPerObjectShadow(IShadowCaster* pCaster)
-{
- for (int i = 0; i < m_lstPerObjectShadows.Count(); ++i)
- {
- if (m_lstPerObjectShadows[i].pCaster == pCaster)
- {
- return &m_lstPerObjectShadows[i];
- }
- }
-
- return NULL;
-}
-
-void C3DEngine::GetCustomShadowMapFrustums(ShadowMapFrustum*& arrFrustums, int& nFrustumCount)
-{
- arrFrustums = m_lstCustomShadowFrustums.begin();
- nFrustumCount = m_nCustomShadowFrustumCount;
-}
-
-// delete pLight->m_pProjCamera;
-//pLight->m_pProjCamera=0;
-//if(pLight->m_pShader)
-// SAFE_RELEASE(pLight->m_pShader);
-namespace
-{
- static inline bool CmpCastShadowFlag(const CDLight* p1, const CDLight* p2)
- {
- // move sun first
- if ((p1->m_Flags & DLF_SUN) > (p2->m_Flags & DLF_SUN))
- {
- return true;
- }
- else if ((p1->m_Flags & DLF_SUN) < (p2->m_Flags & DLF_SUN))
- {
- return false;
- }
-
- // move shadow casters first
- if ((p1->m_Flags & DLF_CASTSHADOW_MAPS) > (p2->m_Flags & DLF_CASTSHADOW_MAPS))
- {
- return true;
- }
- else if ((p1->m_Flags & DLF_CASTSHADOW_MAPS) < (p2->m_Flags & DLF_CASTSHADOW_MAPS))
- {
- return false;
- }
-
- // get some sorting consistency for shadow casters
- if (p1->m_pOwner > p2->m_pOwner)
- {
- return true;
- }
- else if (p1->m_pOwner < p2->m_pOwner)
- {
- return false;
- }
-
- return false;
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-void C3DEngine::SubmitSun(const SRenderingPassInfo& passInfo)
-{
- assert(passInfo.IsGeneralPass());
- FUNCTION_PROFILER_3DENGINE_LEGACYONLY;
- AZ_TRACE_METHOD();
-
- if (m_pSun)
- {
- CDLight* light = &m_pSun->GetLightProperties();
-
- GetRenderer()->EF_ADDDlight(light, passInfo);
- }
-}
-
-void C3DEngine::RemoveEntityLightSources(IRenderNode* pEntity)
-{
- for (int i = 0; i < m_lstStaticLights.Count(); i++)
- {
- if (m_lstStaticLights[i] == pEntity)
- {
- m_lstStaticLights.Delete(i);
- if (pEntity == m_pSun)
- {
- m_pSun = NULL;
- }
- i--;
- }
- }
-}
-
-ILightSource* C3DEngine::GetSunEntity()
-{
- return m_pSun;
-}
-
-void C3DEngine::OnCasterDeleted(IShadowCaster* pCaster)
-{
- FUNCTION_PROFILER(gEnv->pSystem, PROFILE_3DENGINE);
- { // make sure pointer to object will not be used somewhere in the renderer
- if (m_pSun)
- {
- m_pSun->OnCasterDeleted(pCaster);
- }
-
- if (GetRenderer()->GetActiveGPUCount() > 1)
- {
- if (ShadowFrustumMGPUCache* pFrustumCache = GetRenderer()->GetShadowFrustumMGPUCache())
- {
- pFrustumCache->DeleteFromCache(pCaster);
- }
- }
-
- // remove from per object shadows list
- RemovePerObjectShadow(pCaster);
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////
-
-void CLightVolumesMgr::Init()
-{
- m_bUpdateLightVolumes = false;
- for (int i = 0; i < RT_COMMAND_BUF_COUNT; ++i)
- {
- m_pLightVolumes[i].reserve(LV_MAX_COUNT);
- m_pLightVolsInfo[i].reserve(LV_MAX_COUNT);
- }
- memset(m_nWorldCells, 0, sizeof(m_nWorldCells));
- memset(m_pWorldLightCells, 0, sizeof(m_pWorldLightCells));
-}
-
-void CLightVolumesMgr::Reset()
-{
- for (int i = 0; i < RT_COMMAND_BUF_COUNT; ++i)
- {
- stl::free_container(m_pLightVolumes[i]);
- }
-
- m_bUpdateLightVolumes = false;
- memset(m_nWorldCells, 0, sizeof(m_nWorldCells));
- memset(m_pWorldLightCells, 0, sizeof(m_pWorldLightCells));
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-uint16 CLightVolumesMgr::RegisterVolume(const Vec3& vPos, f32 fRadius, uint8 nClipVolumeRef, const SRenderingPassInfo& passInfo)
-{
- DynArray& lightVolsInfo = m_pLightVolsInfo[passInfo.ThreadID()];
-
- IF ((m_bUpdateLightVolumes && (lightVolsInfo.size() < LV_MAX_COUNT)) && fRadius < 256.0f, 1)
- {
- FUNCTION_PROFILER_3DENGINE;
-
- int32 nPosx = (int32)(floorf(vPos.x * LV_CELL_RSIZEX));
- int32 nPosy = (int32)(floorf(vPos.y * LV_CELL_RSIZEY));
- int32 nPosz = (int32)(floorf(vPos.z * LV_CELL_RSIZEZ));
-
- // Check if world cell has any light volume, else add new one
- uint16 nHashIndex = GetWorldHashBucketKey(nPosx, nPosy, nPosz);
- uint16* pCurrentVolumeID = &m_nWorldCells[nHashIndex];
-
- while (*pCurrentVolumeID != 0)
- {
- SLightVolInfo& sVolInfo = *lightVolsInfo[*pCurrentVolumeID - 1];
-
- int32 nVolumePosx = (int32)(floorf(sVolInfo.vVolume.x * LV_CELL_RSIZEX));
- int32 nVolumePosy = (int32)(floorf(sVolInfo.vVolume.y * LV_CELL_RSIZEY));
- int32 nVolumePosz = (int32)(floorf(sVolInfo.vVolume.z * LV_CELL_RSIZEZ));
-
- if (nPosx == nVolumePosx &&
- nPosy == nVolumePosy &&
- nPosz == nVolumePosz &&
- nClipVolumeRef == sVolInfo.nClipVolumeID)
- {
- return (uint16) * pCurrentVolumeID;
- }
-
- pCurrentVolumeID = &sVolInfo.nNextVolume;
- }
-
- // create new volume
- SLightVolInfo* pLightVolInfo = new SLightVolInfo(vPos, fRadius, nClipVolumeRef);
- lightVolsInfo.push_back(pLightVolInfo);
- *pCurrentVolumeID = lightVolsInfo.size();
-
- return *pCurrentVolumeID;
- }
-
- return 0;
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-void CLightVolumesMgr::RegisterLight(const CDLight& pDL, uint32 nLightID, [[maybe_unused]] const SRenderingPassInfo& passInfo)
-{
- IF ((m_bUpdateLightVolumes && !(pDL.m_Flags & LV_DLF_LIGHTVOLUMES_MASK)), 1)
- {
- FUNCTION_PROFILER_3DENGINE;
-
- const f32 fColCheck = (f32) fsel(pDL.m_Color.r + pDL.m_Color.g + pDL.m_Color.b - 0.333f, 1.0f, 0.0f); //light color > threshold
- const f32 fRadCheck = (f32) fsel(pDL.m_fRadius - 0.5f, 1.0f, 0.0f); //light radius > threshold
- if (fColCheck * fRadCheck)
- {
- //if the radius is large than certain value, all the the world light cells will be lighted anyway. So we just add the light to all the cells
- //the input radius restriction will be added too
- if(floorf(pDL.m_fRadius*LV_LIGHT_CELL_R_SIZE) > LV_LIGHTS_WORLD_BUCKET_SIZE)
- {
- for (int32 idx = 0; idx < LV_LIGHTS_WORLD_BUCKET_SIZE; idx++)
- {
- SLightCell& lightCell = m_pWorldLightCells[idx];
- CryPrefetch(&lightCell);
- if (lightCell.nLightCount < LV_LIGHTS_MAX_COUNT)
- {
- lightCell.nLightID[lightCell.nLightCount] = nLightID;
- lightCell.nLightCount += 1;
- }
- }
- }
- else
- {
- int32 nMiny = (int32)(floorf((pDL.m_Origin.y - pDL.m_fRadius) * LV_LIGHT_CELL_R_SIZE));
- int32 nMaxy = (int32)(floorf((pDL.m_Origin.y + pDL.m_fRadius) * LV_LIGHT_CELL_R_SIZE));
- int32 nMinx = (int32)(floorf((pDL.m_Origin.x - pDL.m_fRadius) * LV_LIGHT_CELL_R_SIZE));
- int32 nMaxx = (int32)(floorf((pDL.m_Origin.x + pDL.m_fRadius) * LV_LIGHT_CELL_R_SIZE));
-
- // Register light into all cells touched by light radius
- for (int32 y = nMiny, ymax = nMaxy; y <= ymax; ++y)
- {
- for (int32 x = nMinx, xmax = nMaxx; x <= xmax; ++x)
- {
- SLightCell& lightCell = m_pWorldLightCells[GetWorldHashBucketKey(x, y, 1, LV_LIGHTS_WORLD_BUCKET_SIZE)];
- CryPrefetch(&lightCell);
- if (lightCell.nLightCount < LV_LIGHTS_MAX_COUNT)
- {
- //only if the las light added to the cell wasn't the same light
- if (!(lightCell.nLightCount > 0 && lightCell.nLightID[lightCell.nLightCount - 1] == nLightID))
- {
- lightCell.nLightID[lightCell.nLightCount] = nLightID;
- lightCell.nLightCount += 1;
- }
- }
- }
- }
- }
- }
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-void CLightVolumesMgr::AddLight(const SRenderLight& pLight, const SLightVolInfo* __restrict pVolInfo, SLightVolume& pVolume)
-{
- // Check for clip volume
- if (pLight.m_nStencilRef[0] == pVolInfo->nClipVolumeID || pLight.m_nStencilRef[1] == pVolInfo->nClipVolumeID ||
- pLight.m_nStencilRef[0] == CClipVolumeManager::AffectsEverythingStencilRef)
- {
- const Vec4* __restrict vLight = (Vec4*) &pLight.m_Origin.x;
- const Vec4& vVolume = pVolInfo->vVolume;
- const f32 fDimCheck = (f32) fsel(vLight->w - vVolume.w * 0.1f, 1.0f, 0.0f); //light radius not more than 10x smaller than volume radius
- const f32 fOverlapCheck = (f32) fsel(sqr(vVolume.x - vLight->x) + sqr(vVolume.y - vLight->y) + sqr(vVolume.z - vLight->z) - sqr(vVolume.w + vLight->w), 0.0f, 1.0f);// touches volumes
- if (fDimCheck * fOverlapCheck)
- {
- float fAttenuationBulbSize = pLight.m_fAttenuationBulbSize;
- Vec3 lightColor = *((Vec3*)&pLight.m_Color);
-
- // Adjust light intensity so that the intended brightness is reached 1 meter from the light's surface
- IF (!(pLight.m_Flags & (DLF_AREA_LIGHT | DLF_AMBIENT)), 1)
- {
- fAttenuationBulbSize = max(fAttenuationBulbSize, 0.001f);
-
- // Solve I * 1 / (1 + d/lightsize)^2 = 1
- float intensityMul = 1.0f + 1.0f / fAttenuationBulbSize;
- intensityMul *= intensityMul;
- lightColor *= intensityMul;
- }
-
- pVolume.pData.push_back();
- SLightVolume::SLightData& lightData = pVolume.pData[pVolume.pData.size() - 1];
- lightData.vPos = *vLight;
- lightData.vColor = Vec4(lightColor, fAttenuationBulbSize);
- lightData.vParams = Vec4(0.f, 0.f, 0.f, 0.f);
-
- IF (pLight.m_Flags & DLF_PROJECT, 1)
- {
- lightData.vParams = Vec4(pLight.m_ObjMatrix.GetColumn0(), cos_tpl(DEG2RAD(pLight.m_fLightFrustumAngle)));
- }
- }
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-void CLightVolumesMgr::Update(const SRenderingPassInfo& passInfo)
-{
- uint32 nThreadID = passInfo.ThreadID();
- DynArray& lightVolsInfo = m_pLightVolsInfo[nThreadID];
-
- if (!m_bUpdateLightVolumes || lightVolsInfo.empty())
- {
- return;
- }
-
- FUNCTION_PROFILER_3DENGINE;
- TArray* pLights = GetRenderer()->EF_GetDeferredLights(passInfo);
- const uint32 nLightCount = pLights->size();
-
- uint32 nLightVols = lightVolsInfo.size();
- LightVolumeVector& lightVols = m_pLightVolumes[nThreadID];
- uint32 existingLightVolsCount = 0; //This is 0, that just means we will be overwriting all existing light volumes
-
- //If this is a recursive pass (not the first time that this is called this frame), we're just going to be adding on new light volumes to the existing collection
- if (passInfo.IsRecursivePass())
- {
- existingLightVolsCount = lightVols.size();
-
- //If no new light volumes have been added, don't bother updating
- if (nLightVols == existingLightVolsCount)
- {
- return;
- }
- }
-
- lightVols.resize(nLightVols);
-
- if (!nLightCount)
- {
- //Start out existingLightVolsCount to avoid clearing out existing light volumes when we don't need to
- for (uint32 v = existingLightVolsCount; v < nLightVols; ++v)
- {
- lightVols[v].pData.resize(0);
- }
-
- return;
- }
-
- const int MAX_NUM_LIGHTS_FOR_LIGHT_VOLUME_UPDATE = 1024;
-
- if (nLightCount > MAX_NUM_LIGHTS_FOR_LIGHT_VOLUME_UPDATE)
- {
- CryWarning(VALIDATOR_MODULE_3DENGINE, VALIDATOR_WARNING, "More lights in the scene (%d) than supported by the Light Volume Update function (%d). Extra lights will be ignored.",
- nLightCount, MAX_NUM_LIGHTS_FOR_LIGHT_VOLUME_UPDATE);
- }
-
- //This can be a uint8 array because nLightVols should never be greater than 256(LV_MAX_COUNT)
- assert(LV_MAX_COUNT <= 256);
- uint8 lightProcessedStateArray[MAX_NUM_LIGHTS_FOR_LIGHT_VOLUME_UPDATE];
-
- //Start at the number of light volumes that already exist so that we don't end up re-updating light volumes unnecessarily.
- for (uint32 v = existingLightVolsCount; v < nLightVols; ++v)
- {
- const Vec4* __restrict vBVol = &lightVolsInfo[v]->vVolume;
- int32 nMiny = (int32)(floorf((vBVol->y - vBVol->w) * LV_LIGHT_CELL_R_SIZE));
- int32 nMaxy = (int32)(floorf((vBVol->y + vBVol->w) * LV_LIGHT_CELL_R_SIZE));
- int32 nMinx = (int32)(floorf((vBVol->x - vBVol->w) * LV_LIGHT_CELL_R_SIZE));
- int32 nMaxx = (int32)(floorf((vBVol->x + vBVol->w) * LV_LIGHT_CELL_R_SIZE));
-
- lightVols[v].pData.resize(0);
-
- // Loop through active light cells touching bounding volume (~avg 2 cells)
- for (int32 y = nMiny, ymax = nMaxy; y <= ymax; ++y)
- {
- for (int32 x = nMinx, xmax = nMaxx; x <= xmax; ++x)
- {
- const SLightCell& lightCell = m_pWorldLightCells[GetWorldHashBucketKey(x, y, 1, LV_LIGHTS_WORLD_BUCKET_SIZE)];
- CryPrefetch(&lightCell);
-
- const SRenderLight& pFirstDL = (*pLights)[lightCell.nLightID[0]];
- CryPrefetch(&pFirstDL);
- CryPrefetch(&pFirstDL.m_ObjMatrix);
- for (uint32 l = 0; (l < lightCell.nLightCount) & (lightVols[v].pData.size() < LIGHTVOLUME_MAXLIGHTS); ++l)
- {
- const int32 nLightId = lightCell.nLightID[l];
-
- //Only allow IDs < MAX_NUM_LIGHTS_FOR_LIGHT_VOLUME_UPDATE to continue or else we'll overflow access to
- //lightProcessedStateArray[MAX_NUM_LIGHTS_FOR_LIGHT_VOLUME_UPDATE]. Skipping the extra lights shouldn't really matter
- //since A) folks won't be using that many lights, and B) for the case of light emitting particles, they tend to be grouped
- //so that the individual contributions tend to bleed together anyway.
- if (nLightId >= MAX_NUM_LIGHTS_FOR_LIGHT_VOLUME_UPDATE)
- {
- continue;
- }
-
- if (static_cast(nLightId) < nLightCount)
- {
- const SRenderLight& pDL = (*pLights)[nLightId];
- const int32 nNextLightId = lightCell.nLightID[(l + 1) & (LIGHTVOLUME_MAXLIGHTS - 1)];
- const SRenderLight& pNextDL = (*pLights)[nNextLightId];
- CryPrefetch(&pNextDL);
- CryPrefetch(&pNextDL.m_ObjMatrix);
-
- IF(lightProcessedStateArray[nLightId] != v + 1, 1)
- {
- lightProcessedStateArray[nLightId] = v + 1;
- AddLight(pDL, &*lightVolsInfo[v], lightVols[v]);
- }
- }
- }
- }
- }
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-void CLightVolumesMgr::Clear(const SRenderingPassInfo& passInfo)
-{
- DynArray& lightVolsInfo = m_pLightVolsInfo[passInfo.ThreadID()];
-
- m_bUpdateLightVolumes = false;
- if (GetCVars()->e_LightVolumes && passInfo.IsGeneralPass() && GetCVars()->e_DynamicLights)
- {
- memset(m_nWorldCells, 0, sizeof(m_nWorldCells));
- memset(m_pWorldLightCells, 0, sizeof(m_pWorldLightCells));
-
- //Clean up volume info data
- for (size_t i = 0; i < lightVolsInfo.size(); ++i)
- {
- delete lightVolsInfo[i];
- }
-
- m_pLightVolsInfo[passInfo.ThreadID()].clear();
- m_bUpdateLightVolumes = (GetCVars()->e_LightVolumes == 1) ? true : false;
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-void CLightVolumesMgr::GetLightVolumes(threadID nThreadID, SLightVolume*& pLightVols, uint32& nNumVols)
-{
- pLightVols = 0;
- nNumVols = 0;
- if (GetCVars()->e_LightVolumes == 1 && GetCVars()->e_DynamicLights && !m_pLightVolumes[nThreadID].empty())
- {
- pLightVols = &m_pLightVolumes[nThreadID][0];
- nNumVols = m_pLightVolumes[nThreadID].size();
- }
-}
-
-
-void C3DEngine::GetLightVolumes(threadID nThreadID, SLightVolume*& pLightVols, uint32& nNumVols)
-{
- m_LightVolumesMgr.GetLightVolumes(nThreadID, pLightVols, nNumVols);
-}
-
-uint16 C3DEngine::RegisterVolumeForLighting(const Vec3& vPos, f32 fRadius, uint8 nClipVolumeRef, const SRenderingPassInfo& passInfo)
-{
- return m_LightVolumesMgr.RegisterVolume(vPos, fRadius, nClipVolumeRef, passInfo);
-}
-
-//////////////////////////////////////////////////////////////////////////
-#ifndef _RELEASE
-void CLightVolumesMgr::DrawDebug(const SRenderingPassInfo& passInfo)
-{
- DynArray& lightVolsInfo = m_pLightVolsInfo[passInfo.ThreadID()];
-
- IRenderer* pRenderer = GetRenderer();
- IRenderAuxGeom* pAuxGeom = GetRenderer()->GetIRenderAuxGeom();
- if (!pAuxGeom || !passInfo.IsGeneralPass())
- {
- return;
- }
-
- ColorF cWhite = ColorF(1, 1, 1, 1);
- ColorF cBad = ColorF(1.0f, 0.0, 0.0f, 1.0f);
- ColorF cWarning = ColorF(1.0f, 1.0, 0.0f, 1.0f);
- ColorF cGood = ColorF(0.0f, 0.5, 1.0f, 1.0f);
- ColorF cSingleCell = ColorF(0.0f, 1.0, 0.0f, 1.0f);
-
- const uint32 nLightVols = lightVolsInfo.size();
- LightVolumeVector& lightVols = m_pLightVolumes[passInfo.ThreadID()];
- const Vec3 vCamPos = passInfo.GetCamera().GetPosition();
-
- float fYLine = 8.0f, fYStep = 20.0f;
- GetRenderer()->Draw2dLabel(8.0f, fYLine += fYStep, 2.0f, (float*)&cWhite.r, false, "Light Volumes Info (count %d)", nLightVols);
-
- for (uint32 v = 0; v < nLightVols; ++v) // draw each light volume
- {
- SLightVolume& lv = lightVols[v];
- SLightVolInfo& lvInfo = *lightVolsInfo[v];
-
- ColorF& cCol = (lv.pData.size() >= 10) ? cBad : ((lv.pData.size() >= 5) ? cWarning : cGood);
- const Vec3 vPos = Vec3(lvInfo.vVolume.x, lvInfo.vVolume.y, lvInfo.vVolume.z);
- const float fCamDistSq = (vPos - vCamPos).len2();
- cCol.a = max(0.25f, min(1.0f, 1024.0f / (fCamDistSq + 1e-6f)));
-
- pRenderer->DrawLabelEx(vPos, 1.3f, (float*)&cCol.r, true, true, "Id: %d\nPos: %.2f %.2f %.2f\nRadius: %.2f\nLights: %d\nOutLights: %d",
- v, vPos.x, vPos.y, vPos.z, lvInfo.vVolume.w, lv.pData.size(), (*(int32*)&lvInfo.vVolume.w) & (1 << 31) ? 1 : 0);
-
- if (GetCVars()->e_LightVolumesDebug == 2)
- {
- const float fSideSize = 0.707f * sqrtf(lvInfo.vVolume.w * lvInfo.vVolume.w * 2);
- pAuxGeom->DrawAABB(AABB(vPos - Vec3(fSideSize), vPos + Vec3(fSideSize)), false, cCol, eBBD_Faceted);
- }
-
- if (GetCVars()->e_LightVolumesDebug == 3)
- {
- cBad.a = 1.0f;
- const Vec3 vCellPos = Vec3(floorf((lvInfo.vVolume.x) * LV_CELL_RSIZEX) * LV_CELL_SIZEX,
- floorf((lvInfo.vVolume.y) * LV_CELL_RSIZEY) * LV_CELL_SIZEY,
- floorf((lvInfo.vVolume.z) * LV_CELL_RSIZEZ) * LV_CELL_SIZEZ);
-
- const Vec3 vMin = vCellPos;
- const Vec3 vMax = vMin + Vec3(LV_CELL_SIZEX, LV_CELL_SIZEY, LV_CELL_SIZEZ);
- pAuxGeom->DrawAABB(AABB(vMin, vMax), false, cBad, eBBD_Faceted);
- }
- }
-}
-#endif
diff --git a/Code/CryEngine/Cry3DEngine/3DEngineMemory.cpp b/Code/CryEngine/Cry3DEngine/3DEngineMemory.cpp
deleted file mode 100644
index 65cb53d0b1..0000000000
--- a/Code/CryEngine/Cry3DEngine/3DEngineMemory.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
-* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
-* its licensors.
-*
-* For complete copyright and license terms please see the LICENSE at the root of this
-* distribution (the "License"). All use of this software is governed by the License,
-* or, if provided, by the license below or the license accompanying this file. Do not
-* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-*
-*/
-// Original file Copyright Crytek GMBH or its affiliates, used under license.
-
-#include "Cry3DEngine_precompiled.h"
-#include "3DEngineMemory.h"
-
-// Static CTemporaryPool instance
-CTemporaryPool* CTemporaryPool::s_Instance = NULL;
-
-namespace util
-{
- void* pool_allocate(size_t nSize)
- {
- return CTemporaryPool::Get()->Allocate(nSize, 8);
- }
- void pool_free(void* ptr)
- {
- return CTemporaryPool::Get()->Free(ptr);
- }
-}
diff --git a/Code/CryEngine/Cry3DEngine/3DEngineMemory.h b/Code/CryEngine/Cry3DEngine/3DEngineMemory.h
deleted file mode 100644
index 143aeccab2..0000000000
--- a/Code/CryEngine/Cry3DEngine/3DEngineMemory.h
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
-* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
-* its licensors.
-*
-* For complete copyright and license terms please see the LICENSE at the root of this
-* distribution (the "License"). All use of this software is governed by the License,
-* or, if provided, by the license below or the license accompanying this file. Do not
-* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-*
-*/
-// Original file Copyright Crytek GMBH or its affiliates, used under license.
-
-#ifndef CRYINCLUDE_CRY3DENGINE_3DENGINEMEMORY_H
-#define CRYINCLUDE_CRY3DENGINE_3DENGINEMEMORY_H
-#pragma once
-
-// The type of pool responsible for temporary allocations within the 3dengine
-//
-// Note: The header is included here for reasons of devirtualization. If
-// included directly from the precompiled header in 3dEngine, the gamedll will
-// fail to compile!
-#include
-#include
-
-using NCryPoolAlloc::CFirstFit; // speed of allocations are crucial, so simply use the first fitting free allocation
-using NCryPoolAlloc::CInPlace; //
-using NCryPoolAlloc::CMemoryDynamic; // the pool itself will be dynamically allocated
-using NCryPoolAlloc::CListItemInPlace; // use inplace items
-
-// Tempororary Pool Holder
-class CTemporaryPool
-{
-private:
- // Access granted for 3dEngine to create, destroy and maintain the temporary
- // pool for the 3d engine
- friend class C3DEngine;
-
- // The static pool instance - one pool to rule them all (temp allocations at least)
- static CTemporaryPool* s_Instance;
-
- // The type of the backing temporary pool
- typedef CFirstFit, CListItemInPlace> TTemporaryPool;
- TTemporaryPool Pool;
-
- // A non-recursive critical section guards the pool against concurrent access
- typedef CryCriticalSectionNonRecursive TTemporaryPoolLock;
- TTemporaryPoolLock Lock;
-
- // Initialize the pool manager.
- //
- // Allocates the backing storage and initializes the temporary pool
- // itself. The backing storage is aligned to 16 bytes to reduce the amount of
- // cachelines crossed by the temporary pool
- static bool Initialize(size_t poolSize)
- {
- // Create the object instance
- s_Instance = new CTemporaryPool();
- if (!s_Instance)
- {
- CryFatalError("CTemporaryPool::Init(): could not create an instance of CTemporaryPool");
- return false;
- }
-
- // Allocate the backing storage
- uint8* tempPool = reinterpret_cast(CryModuleMemalign(poolSize, 16));
- if (!tempPool)
- {
- CryFatalError("CTemporaryPool::Init(): could not allocate %" PRISIZE_T " bytes for temportary pool", poolSize);
- return false;
- }
-
- // Initialize the actual pool
- s_Instance->Pool.InitMem(poolSize, tempPool);
- return true;
- }
-
- // Shutdown the temporary pool manager.
- //
- // Frees the temporary pool
- static bool Shutdown()
- {
- if (s_Instance == NULL)
- {
- CryFatalError("CTemporaryPool::Shutdown(): no temporary pool instance present");
- return false;
- }
-
- bool error = false;
- CTemporaryPool& instance = *s_Instance;
- if (instance.Pool.Data())
- {
- CryModuleMemalignFree(instance.Pool.Data());
- }
- else
- {
- error = true;
- }
-
- delete s_Instance;
- s_Instance = NULL;
- return !error;
- }
-
- // Templated construct helper member function using an inplace factory
- //
- // Called from the templated New function below. Returns a typed
- // pointer to the inplace constructed object.
- template
- T* Construct(const InPlaceFactory& factory, void* storage)
- {
- return reinterpret_cast(factory.template apply(storage));
- }
-
- // Templated destruct helper member function.
- //
- // Calls the object's destructor and returns a void pointer to the storage
- template
- void* Destruct(T* obj)
- {
- obj->~T();
- return reinterpret_cast(obj);
- }
-
- // Empty private constructor/destructors to prevent clients from creating and
- // destroying instances of CTemporaryPool (there should only be one instance
- // in the 3DEngine).
- CTemporaryPool() {};
- ~CTemporaryPool() {};
-
-public:
-
- // Allocate a block of memory with the given size and alignment
- void* Allocate(size_t size, size_t align)
- {
- AUTO_LOCK_T(CryCriticalSectionNonRecursive, Lock);
- void* pData = Pool.Allocate(size, align);
- if (pData == NULL)
- {
- CryFatalError("**** could not allocate %" PRISIZE_T " bytes from temporary pool", size);
- }
- return Pool.Resolve(pData);
- };
-
- // Allocates memory and constructs object of type 'T'
- //
- // Note: This method is respects the alignment of 'T' via C99 alignof()
- template
- T* New(const Expr& expr)
- {
- AUTO_LOCK_T(CryCriticalSectionNonRecursive, Lock);
- void* pObjStorage = Pool.Allocate(sizeof(T), alignof(T));
- if (pObjStorage == NULL)
- {
- CryFatalError("**** could not allocate %d bytes from temporary pool",
- (int)sizeof (T));
- }
- return Construct(expr, pObjStorage);
- };
-
- // Allocates memory and constructs object of type 'T'
- //
- // Note: This method is respects the alignment of 'T' via C99 alignof()
- template
- T* New()
- {
- AUTO_LOCK_T(CryCriticalSectionNonRecursive, Lock);
- void* pObjStorage = Pool.Allocate(sizeof(T), alignof(T));
- if (pObjStorage == NULL)
- {
- CryFatalError("**** could not allocate %d bytes from temporary pool",
- (int)sizeof (T));
- }
- return Construct(InplaceFactory(), pObjStorage);
- };
-
- // Frees a block of memory from the temporary pool
- //
- void Free(void* ptr)
- {
- AUTO_LOCK_T(CryCriticalSectionNonRecursive, Lock);
- Pool.Free(ptr);
- }
-
-
- // Destroys an object of type 'T' and frees the underlying block of memory
- template
- void Delete(T* ptr)
- {
- AUTO_LOCK_T(CryCriticalSectionNonRecursive, Lock);
- Pool.Free(Destruct(ptr));
- }
-
- // Static function to retrieve the static instance of CTemporaryPool
- static CTemporaryPool* Get() { return s_Instance; };
-
- void GetMemoryUsage(ICrySizer* pSizer) const
- {
- pSizer->AddObject(Pool.Data(), Pool.MemSize());
- }
-};
-
-// A stl compliant scratch allocator that uses the given temporary pool.
-template
-class scratch_allocator
-{
-public:
- typedef Type value_type;
- typedef value_type* pointer;
- typedef const value_type* const_pointer;
- typedef value_type& reference;
- typedef const value_type& const_reference;
- typedef size_t size_type;
- typedef ptrdiff_t difference_type;
-
- template
- struct rebind
- {
- typedef scratch_allocator other;
- };
-
- scratch_allocator() {}
- template
- scratch_allocator(const scratch_allocator&) {}
- scratch_allocator(const scratch_allocator&) {}
- ~scratch_allocator() {}
-
- pointer address(reference x) const {return &x; }
- const_pointer address(const_reference x) const { return &x; }
-
- // Note: size can be zero - return value will be null in that case
- value_type* allocate(size_type n, const void* = 0)
- {
- if (n != 0)
- {
- size_type buf_size = n * sizeof(value_type);
-
- void* ret = CTemporaryPool::Get()->Allocate(
- buf_size,
- alignof(value_type));
-
- return reinterpret_cast(ret);
- }
- return 0;
- }
-
- // Note: size can be zero.
- void deallocate(pointer p, [[maybe_unused]] size_type n)
- {
- if (p != NULL)
- {
- CTemporaryPool::Get()->Free(p);
- }
- }
-
- size_type max_size() const { return size_t(-1) / sizeof(value_type); }
-
- void construct(pointer p, const_reference val)
- { new (reinterpret_cast(p))value_type(val); }
-
- void destroy(pointer p) { p->~value_type(); }
-
- void cleanup() {}
-
- size_t get_heap_size() { return 0; }
-
- size_t get_wasted_in_allocation() { return 0; }
-
- size_t get_wasted_in_blocks() { return 0; }
-};
-
-
-// A scratch vector type to use the stl vector
-template
-class scratch_vector
- : public std::vector >
-{
-};
-
-namespace util
-{
- extern void* pool_allocate(size_t nSize);
- extern void pool_free(void* ptr);
-}
-
-#endif // CRYINCLUDE_CRY3DENGINE_3DENGINEMEMORY_H
diff --git a/Code/CryEngine/Cry3DEngine/3DEngineRender.cpp b/Code/CryEngine/Cry3DEngine/3DEngineRender.cpp
deleted file mode 100644
index 26c731aca4..0000000000
--- a/Code/CryEngine/Cry3DEngine/3DEngineRender.cpp
+++ /dev/null
@@ -1,3932 +0,0 @@
-
-/*
-* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
-* its licensors.
-*
-* For complete copyright and license terms please see the LICENSE at the root of this
-* distribution (the "License"). All use of this software is governed by the License,
-* or, if provided, by the license below or the license accompanying this file. Do not
-* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-*
-*/
-// Original file Copyright Crytek GMBH or its affiliates, used under license.
-
-// Description : rendering
-
-
-#include "Cry3DEngine_precompiled.h"
-
-#include "3dEngine.h"
-#include "ObjMan.h"
-#include "VisAreas.h"
-#include "Ocean.h"
-#include
-#include
-#include "DecalManager.h"
-#include "SkyLightManager.h"
-
-#include "CullBuffer.h"
-#include "LightEntity.h"
-#include "FogVolumeRenderNode.h"
-#include "ObjectsTree.h"
-#include "CloudsManager.h"
-#include "MatMan.h"
-#include "VolumeObjectRenderNode.h"
-#include "CryPath.h"
-#include "ILocalMemoryUsage.h"
-#include "BitFiddling.h"
-#include "ObjMan.h"
-#include "GeomCacheManager.h"
-#include "ClipVolumeManager.h"
-#include "ITimeOfDay.h"
-#include "Environment/OceanEnvironmentBus.h"
-
-#include
-
-
-
-#ifdef GetCharWidth
-#undef GetCharWidth
-#endif //GetCharWidth
-
-
-#ifdef WIN32
-#include
-#endif
-
-#include
-#include
-#include
-#include // for AZ_MAX_PATH_LEN
-#include
-#include "../RenderDll/Common/Memory/VRAMDrillerBus.h"
-
-////////////////////////////////////////////////////////////////////////////////////////
-// RenderScene
-////////////////////////////////////////////////////////////////////////////////////////
-#define FREE_MEMORY_YELLOW_LIMIT (30)
-#define FREE_MEMORY_RED_LIMIT (10)
-#define DISPLAY_INFO_SCALE (1.25f)
-#define DISPLAY_INFO_SCALE_SMALL (1.1f)
-#define STEP_SMALL_DIFF (2.f)
-
-#if defined(WIN32) || defined(WIN64) || defined(MAC)
-// for panorama screenshots
-class CStitchedImage
- : public Cry3DEngineBase
-{
-public:
- CStitchedImage(C3DEngine& rEngine,
- const uint32 dwWidth,
- const uint32 dwHeight,
- const uint32 dwVirtualWidth,
- const uint32 dwVirtualHeight,
- const uint32 dwSliceCount,
- const f32 fTransitionSize,
- const bool bMetaData = false)
- : m_rEngine(rEngine)
- , m_dwWidth(dwWidth)
- , m_dwHeight(dwHeight)
- , m_fInvWidth(1.f / static_cast(dwWidth))
- , m_fInvHeight(1.f / static_cast(dwHeight))
- , m_dwVirtualWidth(dwVirtualWidth)
- , m_dwVirtualHeight(dwVirtualHeight)
- , m_fInvVirtualWidth(1.f / static_cast(dwVirtualWidth))
- , m_fInvVirtualHeight(1.f / static_cast(dwVirtualHeight))
- , m_nFileId(0)
- , m_dwSliceCount(dwSliceCount)
- , m_fHorizFOV(2 * gf_PI / dwSliceCount)
- , m_bFlipY(false)
- , m_fTransitionSize(fTransitionSize)
- , m_bMetaData(bMetaData)
- {
- assert(dwWidth);
- assert(dwHeight);
-
- m_RGB.resize(m_dwWidth * 3 * m_dwHeight);
-
- // ratio between width and height defines angle 1 (angle from mid to cylinder edges)
- float fVert1Frac = (2 * gf_PI * m_dwHeight) / m_dwWidth;
-
- // slice count defines angle 2
- float fHorizFrac = tanf(GetHorizFOVWithBorder() * 0.5f);
- float fVert2Frac = 2.0f * fHorizFrac / rEngine.GetRenderer()->GetWidth() * rEngine.GetRenderer()->GetHeight();
- // float fVert2Frac = 2.0f * fHorizFrac / rEngine.GetRenderer()->GetWidth() * rEngine.GetRenderer()->GetHeight();
-
- // the bigger one defines the needed angle
- float fVertFrac = max(fVert1Frac, fVert2Frac);
-
- // planar image becomes a barrel after projection and we need to zoom in to only utilize the usable part (inner rect)
- // this is not always needed - for quality with low slice count we could be save some quality here
- fVertFrac /= cosf(GetHorizFOVWithBorder() * 0.5f);
-
- // compute FOV from Frac
- float fVertFOV = 2 * atanf(0.5f * fVertFrac);
-
- m_fPanoramaShotVertFOV = fabsf(fVertFOV);
-
- CryLog("RenderFov = %f degrees (%f = max(%f,%f)*fix)", RAD2DEG(m_fPanoramaShotVertFOV), fVertFrac, fVert1Frac, fVert2Frac);
- Clear();
- }
-
- void Clear()
- {
- memset(&m_RGB[0], 0, m_dwWidth * m_dwHeight * 3);
- }
-
- // szDirectory + "/" + file_id + "." + extension
- // logs errors in the case there are problems
- bool SaveImage(const char* szDirectory)
- {
- assert(szDirectory);
-
- const char* szExtension = m_rEngine.GetCVars()->e_ScreenShotFileFormat->GetString();
-
- if (azstricmp(szExtension, "dds") != 0 &&
- azstricmp(szExtension, "tga") != 0 &&
- azstricmp(szExtension, "jpg") != 0)
- {
- gEnv->pLog->LogError("Format e_ScreenShotFileFormat='%s' not supported", szExtension);
- return false;
- }
-
- const char* sRequestedName = m_rEngine.GetCVars()->e_ScreenShotFileName->GetString();
-
- char sFileName[AZ_MAX_PATH_LEN];
-
- if (azstricmp(sRequestedName, "") != 0)
- {
- AZStd::string folderPath;
- AZStd::string fileName;
- AzFramework::StringFunc::Path::Split(sRequestedName, nullptr, &folderPath, &fileName);
- gEnv->pFileIO->CreatePath((AZStd::string("@user@/ScreenShots/") + folderPath).c_str());
- azsnprintf(sFileName, sizeof(sFileName), "@user@/ScreenShots/%s.%s", sRequestedName, szExtension);
- }
- else
- {
- azsnprintf(sFileName, sizeof(sFileName), "@user@/ScreenShots/%s", szDirectory);
- gEnv->pFileIO->CreatePath(sFileName);
-
- // find free file id
- for (;; )
- {
- azsnprintf(sFileName, sizeof(sFileName), "@user@/ScreenShots/%s/%.5d.%s", szDirectory, m_nFileId, szExtension);
-
- AZ::IO::HandleType fileHandle = gEnv->pCryPak->FOpen(sFileName, "rb");
-
- if (fileHandle == AZ::IO::InvalidHandle)
- {
- break; // file doesn't exist
- }
-
- gEnv->pCryPak->FClose(fileHandle);
- m_nFileId++;
- }
- }
-
- bool bOk;
-
- if (azstricmp(szExtension, "dds") == 0)
- {
- bOk = gEnv->pRenderer->WriteDDS((byte*)&m_RGB[0], m_dwWidth, m_dwHeight, 3, sFileName, eTF_BC3, 1);
- }
- else
- if (azstricmp(szExtension, "tga") == 0)
- {
- bOk = gEnv->pRenderer->WriteTGA((byte*)&m_RGB[0], m_dwWidth, m_dwHeight, sFileName, 24, 24);
- }
- else
- {
- bOk = gEnv->pRenderer->WriteJPG((byte*)&m_RGB[0], m_dwWidth, m_dwHeight, sFileName, 24);
- }
-
- if (!bOk)
- {
- gEnv->pLog->LogError("Failed to write '%s' (not supported on this platform?)", sFileName);
- }
- else //write meta data
- {
- if (m_bMetaData)
- {
- const f32 fSizeX = GetCVars()->e_ScreenShotMapSizeX;
- const f32 fSizeY = GetCVars()->e_ScreenShotMapSizeY;
- const f32 fTLX = GetCVars()->e_ScreenShotMapCenterX - fSizeX;
- const f32 fTLY = GetCVars()->e_ScreenShotMapCenterY - fSizeY;
- const f32 fBRX = GetCVars()->e_ScreenShotMapCenterX + fSizeX;
- const f32 fBRY = GetCVars()->e_ScreenShotMapCenterY + fSizeY;
-
- snprintf(sFileName, sizeof(sFileName), "@user@/ScreenShots/%s/%.5d.%s", szDirectory, m_nFileId, "xml");
-
- AZ::IO::HandleType metaFileHandle = gEnv->pCryPak->FOpen(sFileName, "wt");
- if (metaFileHandle != AZ::IO::InvalidHandle)
- {
- char sFileData[1024];
- snprintf(sFileData, sizeof(sFileData), "",
- m_nFileId, szExtension, fTLX, fTLY, fBRX, fBRY);
- string data(sFileData);
- gEnv->pCryPak->FWrite(data.c_str(), data.size(), metaFileHandle);
- gEnv->pCryPak->FClose(metaFileHandle);
- }
- }
- }
-
- // reset filename when done so user doesn't overwrite other screen shots (unless they want to)
- // this is done here as there is no callback for standard screenshots to allow the user to clear
- // this when done with the screen shot, so I decided to just always clear it when done
- m_rEngine.GetCVars()->e_ScreenShotFileName->Set("");
-
- return bOk;
- }
-
- // rasterize rectangle
- // Arguments:
- // x0 - x0, excluding
- // y1 - >y0, excluding
- void RasterizeRect(const uint32* pRGBAImage,
- const uint32 dwWidth,
- const uint32 dwHeight,
- const uint32 dwSliceX,
- const uint32 dwSliceY,
- const f32 fTransitionSize,
- const bool bFadeBordersX,
- const bool bFadeBordersY)
- {
- {
- //calculate rect inside the whole image
- const int32 OrgX0 = static_cast(static_cast((dwSliceX * dwWidth) * m_dwWidth) * m_fInvVirtualWidth);
- const int32 OrgY0 = static_cast(static_cast((dwSliceY * dwHeight) * m_dwHeight) * m_fInvVirtualHeight);
- const int32 OrgX1 = min(static_cast(static_cast(((dwSliceX + 1) * dwWidth) * m_dwWidth) * m_fInvVirtualWidth), static_cast(m_dwWidth)) - (m_rEngine.GetCVars()->e_ScreenShotDebug == 1 ? 1 : 0);
- const int32 OrgY1 = min(static_cast(static_cast(((dwSliceY + 1) * dwHeight) * m_dwHeight) * m_fInvVirtualHeight), static_cast(m_dwHeight)) - (m_rEngine.GetCVars()->e_ScreenShotDebug == 1 ? 1 : 0);
- //expand bounds for borderblending
- const int32 CenterX = (OrgX0 + OrgX1) / 2;
- const int32 CenterY = (OrgY0 + OrgY1) / 2;
- const int32 X0 = static_cast(static_cast(OrgX0 - CenterX) * (1.f + fTransitionSize)) + CenterX;
- const int32 Y0 = static_cast(static_cast(OrgY0 - CenterY) * (1.f + fTransitionSize)) + CenterY;
- const int32 X1 = static_cast(static_cast(OrgX1 - CenterX) * (1.f + fTransitionSize)) + CenterX;
- const int32 Y1 = static_cast(static_cast(OrgY1 - CenterY) * (1.f + fTransitionSize)) + CenterY;
- const f32 InvBlendX = 1.f / max(static_cast(X1 - OrgX1), 0.01f);//0.5 is here because the border is two times wider then the border of the single segment in total
- const f32 InvBlendY = 1.f / max(static_cast(Y1 - OrgY1), 0.01f);
- const int32 DebugScale = (m_rEngine.GetCVars()->e_ScreenShotDebug == 2) ? 65536 : 0;
- for (int32 y = max(Y0, 0); y < Y1 && y < (int)m_dwHeight; y++)
- {
- const f32 WeightY = bFadeBordersY ? min(1.f, static_cast(min(y - Y0, Y1 - y)) * InvBlendY) : 1.f;
- for (int32 x = max(X0, 0); x < X1 && x < (int)m_dwWidth; x++)
- {
- uint8* pDst = &m_RGB[m_bFlipY ? 3 * (x + (m_dwHeight - y - 1) * m_dwWidth) : 3 * (x + y * m_dwWidth)];
- const f32 WeightX = bFadeBordersX ? min(1.f, static_cast(min(x - X0, X1 - x)) * InvBlendX) : 1.f;
- GetBilinearFilteredBlend(static_cast(static_cast(x - X0) / static_cast(X1 - X0) * static_cast(dwWidth) * 16.f),
- static_cast(static_cast(y - Y0) / static_cast(Y1 - Y0) * static_cast(dwHeight) * 16.f),
- pRGBAImage, dwWidth, dwHeight,
- max(static_cast(WeightX * WeightY * 65536.f), DebugScale), pDst);
- }
- }
- }
- }
-
- void RasterizeCylinder(const uint32* pRGBAImage,
- const uint32 dwWidth,
- const uint32 dwHeight,
- const uint32 dwSlice,
- const bool bFadeBorders)
- {
- float fSrcAngleMin = GetSliceAngle(dwSlice - 1);
- float fFractionVert = tanf(m_fPanoramaShotVertFOV * 0.5f);
- float fFractionHoriz = fFractionVert * gEnv->pRenderer->GetCamera().GetProjRatio();
- float fInvFractionHoriz = 1.0f / fFractionHoriz;
-
- // for soft transition
- float fFadeOutFov = GetHorizFOVWithBorder();
- float fFadeInFov = GetHorizFOV();
-
- int x0 = 0, y0 = 0, x1 = m_dwWidth, y1 = m_dwHeight;
-
- float fScaleX = 1.0f / m_dwWidth;
- float fScaleY = 0.5f * fInvFractionHoriz / (m_dwWidth / (2 * gf_PI)) / dwHeight * dwWidth; // this value is not correctly computed yet - but using many slices reduced the problem
-
- if (m_bFlipY)
- {
- fScaleY = -fScaleY;
- }
-
-
- // it's more efficient to process colums than lines
- for (int x = x0; x < x1; ++x)
- {
- uint8* pDst = &m_RGB[3 * (x + y0 * m_dwWidth)];
- float fSrcX = x * fScaleX - 0.5f; // -0.5 .. 0.5
- float fSrcAngleX = fSrcAngleMin + 2 * gf_PI * fSrcX;
-
- if (fSrcAngleX > gf_PI)
- {
- fSrcAngleX -= 2 * gf_PI;
- }
- if (fSrcAngleX < -gf_PI)
- {
- fSrcAngleX += 2 * gf_PI;
- }
-
- if (fabs(fSrcAngleX) > fFadeOutFov * 0.5f)
- {
- continue; // clip away curved parts of the barrel
- }
- float fScrPosX = (tanf(fSrcAngleX) * 0.5f * fInvFractionHoriz + 0.5f) * dwWidth;
- // float fInvCosSrcX = 1.0f / cos(fSrcAngleX);
- float fInvCosSrcX = 1.0f / cosf(fSrcAngleX);
-
- if (fScrPosX >= 0 && fScrPosX <= (float)dwWidth) // this is an optimization - but it could be done even more efficient
- {
- if (fInvCosSrcX > 0) // don't render the viewer opposing direction
- {
- int iSrcPosX16 = (int)(fScrPosX * 16.0f);
-
- float fYOffset = 16 * 0.5f * dwHeight - 16 * 0.5f * m_dwHeight * fScaleY * fInvCosSrcX * dwHeight;
- float fYMul = 16 * fScaleY * fInvCosSrcX * dwHeight;
-
- float fSrcY = y0 * fYMul + fYOffset;
-
- uint32 dwLerp64k = 256 * 256 - 1;
-
- if (!bFadeBorders)
- {
- // first pass - every second image without soft borders
- for (int y = y0; y < y1; ++y, fSrcY += fYMul, pDst += m_dwWidth * 3)
- {
- GetBilinearFiltered(iSrcPosX16, (int)fSrcY, pRGBAImage, dwWidth, dwHeight, pDst);
- }
- }
- else
- {
- // second pass - do all the inbetween with soft borders
- float fOffSlice = fabs(fSrcAngleX / fFadeInFov) - 0.5f;
-
- if (fOffSlice < 0)
- {
- fOffSlice = 0; // no transition in this area
- }
- float fBorder = (fFadeOutFov - fFadeInFov) * 0.5f;
-
- if (fBorder < 0.001f)
- {
- fBorder = 0.001f; // we do not have border
- }
- float fFade = 1.0f - fOffSlice * fFadeInFov / fBorder;
-
- if (fFade < 0.0f)
- {
- fFade = 0.0f; // don't use this slice here
- }
- dwLerp64k = (uint32)(fFade * (256.0f * 256.0f - 1.0f)); // 0..64k
-
- if (dwLerp64k) // optimization
- {
- for (int y = y0; y < y1; ++y, fSrcY += fYMul, pDst += m_dwWidth * 3)
- {
- GetBilinearFilteredBlend(iSrcPosX16, (int)fSrcY, pRGBAImage, dwWidth, dwHeight, dwLerp64k, pDst);
- }
- }
- }
- }
- }
- }
- }
-
- // fast, rgb only
- static inline ColorB lerp(const ColorB x, const ColorB y, const uint32 a, const uint32 dwBase)
- {
- const int32 b = dwBase - a;
- const int32 RC = dwBase / 2;//rounding correction
-
-
- return ColorB(((int)x.r * b + (int)y.r * a + RC) / dwBase,
- ((int)x.g * b + (int)y.g * a + RC) / dwBase,
- ((int)x.b * b + (int)y.b * a + RC) / dwBase);
- }
-
- static inline ColorB Mul(const ColorB x, const int32 a, const int32 dwBase)
- {
- return ColorB(((int)x.r * (int)a) / dwBase,
- ((int)x.g * (int)a) / dwBase,
- ((int)x.b * (int)a) / dwBase);
- }
- static inline ColorB MadSaturate(const ColorB x, const int32 a, const int32 dwBase, const ColorB y)
- {
- const int32 MAX_COLOR = 0xff;
- const ColorB PreMuled = Mul(x, a, dwBase);
- return ColorB(min((int)PreMuled.r + (int)y.r, MAX_COLOR),
- min((int)PreMuled.g + (int)y.g, MAX_COLOR),
- min((int)PreMuled.b + (int)y.b, MAX_COLOR));
- }
-
- // bilinear filtering in fixpoint,
- // 4bit fractional part -> multiplier 16
- // --lookup outside of the image is not defined
- // lookups outside the image are now clamped, needed due to some float inaccuracy while rasterizing a rect-screenshot
- // Arguments:
- // iX16 - fX mul 16
- // iY16 - fY mul 16
- // result - [0]=red, [1]=green, [2]=blue
- static inline bool GetBilinearFilteredRaw(const int iX16, const int iY16,
- const uint32* pRGBAImage,
- const uint32 dwWidth, const uint32 dwHeight,
- ColorB& result)
- {
- int iLocalX = min(max(iX16 / 16, 0), static_cast(dwWidth - 1));
- int iLocalY = min(max(iY16 / 16, 0), static_cast(dwHeight - 1));
-
- int iLerpX = iX16 & 0xf; // 0..15
- int iLerpY = iY16 & 0xf; // 0..15
-
- ColorB colS[4];
-
- const uint32* pRGBA = &pRGBAImage[iLocalX + iLocalY * dwWidth];
-
- colS[0] = pRGBA[0];
- colS[1] = pRGBA[1];
- colS[2] = pRGBA[iLocalY + 1uL < dwHeight ? dwWidth : 0];
- colS[3] = pRGBA[(iLocalX + 1uL < dwWidth ? 1 : 0) + (iLocalY + 1uL < dwHeight ? dwWidth : 0)];
-
- ColorB colTop, colBottom;
-
- colTop = lerp(colS[0], colS[1], iLerpX, 16);
- colBottom = lerp(colS[2], colS[3], iLerpX, 16);
-
- result = lerp(colTop, colBottom, iLerpY, 16);
- return true;
- }
-
-
- // blend with background
- static inline bool GetBilinearFiltered(const int iX16, const int iY16,
- const uint32* pRGBAImage,
- const uint32 dwWidth, const uint32 dwHeight,
- uint8 result[3])
- {
- ColorB colFiltered;
- if (GetBilinearFilteredRaw(iX16, iY16, pRGBAImage, dwWidth, dwHeight, colFiltered))
- {
- result[0] = colFiltered.r;
- result[1] = colFiltered.g;
- result[2] = colFiltered.b;
- return true;
- }
- return false;
- }
-
- static inline bool GetBilinearFilteredBlend(const int iX16, const int iY16,
- const uint32* pRGBAImage,
- const uint32 dwWidth, const uint32 dwHeight,
- const uint32 dwLerp64k,
- uint8 result[3])
- {
- ColorB colFiltered;
- if (GetBilinearFilteredRaw(iX16, iY16, pRGBAImage, dwWidth, dwHeight, colFiltered))
- {
- ColorB colRet = lerp(ColorB(result[0], result[1], result[2]), colFiltered, dwLerp64k, 256 * 256);
-
- result[0] = colRet.r;
- result[1] = colRet.g;
- result[2] = colRet.b;
- return true;
- }
- return false;
- }
-
- static inline bool GetBilinearFilteredAdd(const int iX16, const int iY16,
- const uint32* pRGBAImage,
- const uint32 dwWidth, const uint32 dwHeight,
- const uint32 dwLerp64k,
- uint8 result[3])
- {
- ColorB colFiltered;
- if (GetBilinearFilteredRaw(iX16, iY16, pRGBAImage, dwWidth, dwHeight, colFiltered))
- {
- ColorB colRet = MadSaturate(colFiltered, dwLerp64k, 256 * 256, ColorB(result[0], result[1], result[2]));
-
- result[0] = colRet.r;
- result[1] = colRet.g;
- result[2] = colRet.b;
- return true;
- }
- return false;
- }
-
-
- float GetSliceAngle(const uint32 dwSlice) const
- {
- uint32 dwAlternatingSlice = (dwSlice * 2) % m_dwSliceCount;
-
- float fAngleStep = m_fHorizFOV;
-
- float fRet = fAngleStep * dwAlternatingSlice;
-
- if (dwSlice * 2 >= m_dwSliceCount)
- {
- fRet += fAngleStep;
- }
-
- return fRet;
- }
-
- float GetHorizFOV() const
- {
- return m_fHorizFOV;
- }
-
- float GetHorizFOVWithBorder() const
- {
- return m_fHorizFOV * (1.0f + m_fTransitionSize);
- }
-
- void* GetBuffer(){ return &m_RGB[0]; }
- uint32 GetWidth() { return m_dwWidth; }
- uint32 GetHeight() { return m_dwHeight; }
-
-
- //private: // -------------------------------------------------------------------
-
- uint32 m_dwWidth; // >0
- uint32 m_dwHeight; // >0
- f32 m_fInvWidth; // >0
- f32 m_fInvHeight; // >0
- uint32 m_dwVirtualWidth; // >0
- uint32 m_dwVirtualHeight; // >0
- f32 m_fInvVirtualWidth; // >0
- f32 m_fInvVirtualHeight; // >0
- std::vector m_RGB; // [channel + x*3 + m_dwWidth*3*y], channel=0..2, xe_ScreenShotWidth);
- const uint32 dwPanHeight = max(1, GetCVars()->e_ScreenShotHeight);
- const f32 fTransitionSize = min(1.f, abs(GetCVars()->e_ScreenShotQuality) * 0.01f);
-
- const uint32 widthSlices = (dwPanWidth + GetRenderer()->GetWidth() - 1) / GetRenderer()->GetWidth();
- const uint32 heightSlices = (dwPanHeight + GetRenderer()->GetHeight() - 1) / GetRenderer()->GetHeight();
- uint32 MinSlices = max(widthSlices, heightSlices);
- MinSlices = max(MinSlices, (uint32)GetCVars()->e_ScreenShotMinSlices);
-
- const uint32 dwVirtualWidth = GetRenderer()->GetWidth() * MinSlices;
- const uint32 dwVirtualHeight = GetRenderer()->GetHeight() * MinSlices;
-
- GetRenderer()->StartScreenShot(GetCVars()->e_ScreenShot);
-
- switch (abs(GetCVars()->e_ScreenShot))
- {
- case ESST_HIGHRES:
- GetConsole()->ShowConsole(false);
-
- MinSlices = max(MinSlices, 1u);
- pStitchedImage = new CStitchedImage(*this, dwPanWidth, dwPanHeight, dwVirtualWidth, dwVirtualHeight, MinSlices, fTransitionSize);
-
- ScreenShotHighRes(pStitchedImage, nRenderFlags, passInfo, MinSlices, fTransitionSize);
- pStitchedImage->SaveImage("HiRes");
- pStitchedImage->Clear(); // good for debugging
- delete pStitchedImage;
- if (GetCVars()->e_ScreenShot > 0) // <0 is used for multiple frames (videos)
- {
- GetCVars()->e_ScreenShot = 0;
- }
- break;
- case ESST_PANORAMA:
- GetConsole()->ShowConsole(false);
-
- // Panorama screenshots will exhibit artifacts if insufficient slices are used to render them
- // 20 slices yields great quality.
- MinSlices = max(MinSlices, 20u);
- pStitchedImage = new CStitchedImage(*this, dwPanWidth, dwPanHeight, dwVirtualWidth, dwVirtualHeight, MinSlices, fTransitionSize);
-
- ScreenShotPanorama(pStitchedImage, nRenderFlags, passInfo, MinSlices, fTransitionSize);
- pStitchedImage->SaveImage("Panorama");
- pStitchedImage->Clear(); // good for debugging
- delete pStitchedImage;
- if (GetCVars()->e_ScreenShot > 0) // <0 is used for multiple frames (videos)
- {
- GetCVars()->e_ScreenShot = 0;
- }
- break;
- case ESST_MAP_DELAYED:
- {
- GetCVars()->e_ScreenShot = sgn(GetCVars()->e_ScreenShot) * ESST_MAP; // sgn() to keep sign bit , <0 is used for multiple frames (videos)
- }
- break;
- case ESST_SWMAP_DELAYED:
- {
- GetCVars()->e_ScreenShot = sgn(GetCVars()->e_ScreenShot) * ESST_SWMAP; // sgn() to keep sign bit , <0 is used for multiple frames (videos)
- }
- break;
- case ESST_SWMAP:
- case ESST_MAP:
- {
- static const unsigned int nMipMapSnapshotSize = 2048;
- GetRenderer()->ChangeViewport(0, 0, nMipMapSnapshotSize, nMipMapSnapshotSize);
- uint32 TmpHeight, TmpWidth, TmpVirtualHeight, TmpVirtualWidth;
- TmpHeight = TmpWidth = TmpVirtualHeight = TmpVirtualWidth = 1;
-
- while ((TmpHeight << 1) <= dwPanHeight)
- {
- TmpHeight <<= 1;
- }
- while ((TmpWidth << 1) <= dwPanWidth)
- {
- TmpWidth <<= 1;
- }
- const uint32 TmpMinSlices = max(max(1, GetCVars()->e_ScreenShotMinSlices),
- max(static_cast((TmpWidth + nMipMapSnapshotSize - 1) / nMipMapSnapshotSize),
- static_cast((TmpHeight + nMipMapSnapshotSize - 1) / nMipMapSnapshotSize)));
- while ((TmpVirtualHeight << 1) <= TmpMinSlices * nMipMapSnapshotSize)
- {
- TmpVirtualHeight <<= 1;
- }
- while ((TmpVirtualWidth << 1) <= TmpMinSlices * nMipMapSnapshotSize)
- {
- TmpVirtualWidth <<= 1;
- }
-
- GetConsole()->ShowConsole(false);
- pStitchedImage = new CStitchedImage(*this, TmpWidth, TmpHeight, TmpVirtualWidth, TmpVirtualHeight, TmpMinSlices, fTransitionSize, true);
- ScreenShotMap(pStitchedImage, nRenderFlags, passInfo, TmpMinSlices, fTransitionSize);
- if (abs(GetCVars()->e_ScreenShot) == ESST_MAP)
- {
- pStitchedImage->SaveImage("Map");
- }
-
- if (m_pScreenshotCallback)
- {
- const f32 fSizeX = GetCVars()->e_ScreenShotMapSizeX;
- const f32 fSizeY = GetCVars()->e_ScreenShotMapSizeY;
- const f32 fTLX = GetCVars()->e_ScreenShotMapCenterX - fSizeX;
- const f32 fTLY = GetCVars()->e_ScreenShotMapCenterY - fSizeY;
- const f32 fBRX = GetCVars()->e_ScreenShotMapCenterX + fSizeX;
- const f32 fBRY = GetCVars()->e_ScreenShotMapCenterY + fSizeY;
-
- m_pScreenshotCallback->SendParameters(pStitchedImage->GetBuffer(), pStitchedImage->GetWidth(), pStitchedImage->GetHeight(), fTLX, fTLY, fBRX, fBRY);
- }
-
- pStitchedImage->Clear(); // good for debugging
- delete pStitchedImage;
- }
- if (GetCVars()->e_ScreenShot > 0) // <0 is used for multiple frames (videos)
- {
- GetCVars()->e_ScreenShot = 0;
- }
-
- break;
- default:
- GetCVars()->e_ScreenShot = 0;
- }
-
- GetRenderer()->EndScreenShot(GetCVars()->e_ScreenShot);
-
-#endif //#if defined(WIN32) || defined(WIN64)
-}
-
-
-
-struct SDebugFrustrum
-{
- Vec3 m_vPos[8];
- const char* m_szName;
- CTimeValue m_TimeStamp;
- ColorB m_Color;
- float m_fQuadDist; // < 0 if not used
-};
-
-static StaticInstance> g_DebugFrustrums;
-
-void C3DEngine::DebugDraw_Draw()
-{
-#ifndef _RELEASE
- if (m_DebugDrawListMgr.IsEnabled())
- {
- m_DebugDrawListMgr.Update();
- }
-
- CTimeValue CurrentTime = gEnv->pTimer->GetFrameStartTime();
-
- IRenderAuxGeom* pAux = GetRenderer()->GetIRenderAuxGeom();
-
- SAuxGeomRenderFlags oldFlags = pAux->GetRenderFlags();
- SAuxGeomRenderFlags newFlags;
- newFlags.SetAlphaBlendMode(e_AlphaBlended);
- newFlags.SetCullMode(e_CullModeNone);
- newFlags.SetDepthWriteFlag(e_DepthWriteOff);
- pAux->SetRenderFlags(newFlags);
- std::vector::iterator it;
-
- for (it = g_DebugFrustrums.begin(); it != g_DebugFrustrums.end(); )
- {
- SDebugFrustrum& ref = *it;
-
- float fRatio = (CurrentTime - ref.m_TimeStamp).GetSeconds() * 2.0f;
-
- if (fRatio > 1.0f)
- {
- it = g_DebugFrustrums.erase(it);
- continue;
- }
-
- vtx_idx pnInd[8] = { 0, 4, 1, 5, 2, 6, 3, 7 };
-
- float fRadius = ((ref.m_vPos[0] + ref.m_vPos[1] + ref.m_vPos[2] + ref.m_vPos[3]) - (ref.m_vPos[4] + ref.m_vPos[5] + ref.m_vPos[6] + ref.m_vPos[7])).GetLength() * 0.25f;
- float fDistance = min(fRadius, 33.0f); // in meters
-
- float fRenderRatio = fRatio * fDistance / fRadius;
-
- if (ref.m_fQuadDist > 0)
- {
- fRenderRatio = ref.m_fQuadDist / fRadius;
- }
-
- Vec3 vPos[4];
-
- for (uint32 i = 0; i < 4; ++i)
- {
- vPos[i] = ref.m_vPos[i] * fRenderRatio + ref.m_vPos[i + 4] * (1.0f - fRenderRatio);
- }
-
- Vec3 vMid = (vPos[0] + vPos[1] + vPos[2] + vPos[3]) * 0.25f;
-
- ColorB col = ref.m_Color;
-
- if (ref.m_fQuadDist <= 0)
- {
- for (uint32 i = 0; i < 4; ++i)
- {
- vPos[i] = vPos[i] * 0.95f + vMid * 0.05f;
- }
-
- // quad
- if (ref.m_fQuadDist != -999.f)
- {
- pAux->DrawTriangle(vPos[0], col, vPos[2], col, vPos[1], col);
- pAux->DrawTriangle(vPos[2], col, vPos[0], col, vPos[3], col);
- }
- // projection lines
- pAux->DrawLines(ref.m_vPos, 8, pnInd, 2, RGBA8(0xff, 0xff, 0x1f, 0xff));
- pAux->DrawLines(ref.m_vPos, 8, pnInd + 2, 2, RGBA8(0xff, 0xff, 0x1f, 0xff));
- pAux->DrawLines(ref.m_vPos, 8, pnInd + 4, 2, RGBA8(0xff, 0xff, 0x1f, 0xff));
- pAux->DrawLines(ref.m_vPos, 8, pnInd + 6, 2, RGBA8(0xff, 0xff, 0x1f, 0xff));
- }
- else
- {
- // rectangle
- pAux->DrawPolyline(vPos, 4, true, RGBA8(0xff, 0xff, 0x1f, 0xff));
- }
-
- ++it;
- }
-
- pAux->SetRenderFlags(oldFlags);
-
-
- if (GetCVars()->e_DebugDraw == 16)
- {
- DebugDraw_UpdateDebugNode();
- }
- else
- {
- GetRenderer()->SetDebugRenderNode(NULL);
- }
-
-#endif //_RELEASE
-}
-
-void C3DEngine::DebugDraw_UpdateDebugNode()
-{
-#ifndef _RELEASE
-
-
-#endif //_RELEASE
-}
-
-void C3DEngine::RenderWorld(const int nRenderFlags, const SRenderingPassInfo& passInfo, const char* szDebugName)
-{
- AZ_TRACE_METHOD();
-
- if (nRenderFlags & SHDF_ALLOW_AO)
- {
- SVOGILegacyRequestBus::Broadcast(&SVOGILegacyRequests::OnFrameStart, passInfo);
- }
-
- if (m_szLevelFolder[0] != 0)
- {
- m_nFramesSinceLevelStart++;
- }
-
- assert(szDebugName);
-
- if (!GetCVars()->e_Render)
- {
- return;
- }
-
- IF (!m_bEditor && (m_bInShutDown || m_bInUnload) && !GetRenderer()->IsPost3DRendererEnabled(), 0)
- {
- // Do not render during shutdown/unloading (should never reach here, unless something wrong with game/editor code)
- return;
- }
-
- FUNCTION_PROFILER_3DENGINE;
-
- if (GetCVars()->e_ScreenShot)
- {
- ScreenshotDispatcher(nRenderFlags, passInfo);
- // screenshots can mess up the frame ids, be safe and recreate the rendering passinfo object after a screenshot
- const_cast(passInfo) = SRenderingPassInfo::CreateGeneralPassRenderingInfo(passInfo.GetCamera());
- }
-
- if (GetCVars()->e_DefaultMaterial)
- {
- _smart_ptr pMat = GetMaterialManager()->LoadMaterial("Materials/material_default");
- _smart_ptr pTerrainMat = GetMaterialManager()->LoadMaterial("Materials/material_terrain_default");
- GetRenderer()->SetDefaultMaterials(pMat, pTerrainMat);
- }
- else
- {
- GetRenderer()->SetDefaultMaterials(NULL, NULL);
- }
-
- // skip rendering if camera is invalid
- if (IsCameraAnd3DEngineInvalid(passInfo, szDebugName))
- {
- return;
- }
-
- // this will also set the camera in passInfo for the General Pass (done here to support e_camerafreeze)
- UpdateRenderingCamera(szDebugName, passInfo);
-
- RenderInternal(nRenderFlags, passInfo, szDebugName);
-
-#if !defined(_RELEASE)
- PrintDebugInfo(passInfo);
-#endif
-}
-
-void C3DEngine::RenderInternal(const int nRenderFlags, const SRenderingPassInfo& passInfo, [[maybe_unused]] const char* szDebugName)
-{
- assert(m_pObjManager);
-
-
- if (AZ::Interface::Get())
- {
- GetRenderer()->EF_EndEf3D(
- IsShadersSyncLoad() ? (nRenderFlags | SHDF_NOASYNC | SHDF_STREAM_SYNC) : nRenderFlags,
- GetObjManager()->GetUpdateStreamingPrioriryRoundId(),
- GetObjManager()->GetUpdateStreamingPrioriryRoundIdFast(),
- passInfo);
- }
- else
- {
- UpdatePreRender(passInfo);
- RenderScene(nRenderFlags, passInfo);
- UpdatePostRender(passInfo);
- }
-}
-
-
-void C3DEngine::PreWorldStreamUpdate(const CCamera& cam)
-{
- if (m_szLevelFolder[0] != 0)
- {
- m_nStreamingFramesSinceLevelStart++;
- }
-
- // force preload terrain data if camera was teleported more than 32 meters
- if (!IsAreaActivationInUse() || m_bLayersActivated)
- {
- float fDistance = m_vPrevMainFrameCamPos.GetDistance(cam.GetPosition());
-
- if (m_vPrevMainFrameCamPos != Vec3(-1000000.f, -1000000.f, -1000000.f))
- {
- m_vAverageCameraMoveDir = m_vAverageCameraMoveDir * .75f + (cam.GetPosition() - m_vPrevMainFrameCamPos) / max(0.01f, GetTimer()->GetFrameTime()) * .25f;
- if (m_vAverageCameraMoveDir.GetLength() > 10.f)
- {
- m_vAverageCameraMoveDir.SetLength(10.f);
- }
-
- float fNewSpeed = fDistance / max(0.001f, gEnv->pTimer->GetFrameTime());
- if (fNewSpeed > m_fAverageCameraSpeed)
- {
- m_fAverageCameraSpeed = fNewSpeed * .20f + m_fAverageCameraSpeed * .80f;
- }
- else
- {
- m_fAverageCameraSpeed = fNewSpeed * .02f + m_fAverageCameraSpeed * .98f;
- }
- m_fAverageCameraSpeed = CLAMP(m_fAverageCameraSpeed, 0, 10.f);
- }
-
- // Adjust streaming mip bias based on camera speed and depending on installed on HDD or not
- bool bStreamingFromHDD = gEnv->pSystem->GetStreamEngine()->IsStreamDataOnHDD();
- if (GetCVars()->e_StreamAutoMipFactorSpeedThreshold)
- {
- if (m_fAverageCameraSpeed > GetCVars()->e_StreamAutoMipFactorSpeedThreshold)
- {
- GetRenderer()->SetTexturesStreamingGlobalMipFactor(bStreamingFromHDD ? GetCVars()->e_StreamAutoMipFactorMax * .5f : GetCVars()->e_StreamAutoMipFactorMax);
- }
- else
- {
- GetRenderer()->SetTexturesStreamingGlobalMipFactor(bStreamingFromHDD ? GetCVars()->e_StreamAutoMipFactorMin * .5f : GetCVars()->e_StreamAutoMipFactorMin);
- }
- }
- else
- {
- if (bStreamingFromHDD)
- {
- GetRenderer()->SetTexturesStreamingGlobalMipFactor(0);
- }
- else
- {
- GetRenderer()->SetTexturesStreamingGlobalMipFactor(GetCVars()->e_StreamAutoMipFactorMaxDVD);
- }
- }
-
- if (GetCVars()->e_AutoPrecacheCameraJumpDist && fDistance > GetCVars()->e_AutoPrecacheCameraJumpDist)
- {
- m_bContentPrecacheRequested = true;
-
- // Invalidate existing precache info
- m_pObjManager->IncrementUpdateStreamingPrioriryRoundIdFast(8);
- m_pObjManager->IncrementUpdateStreamingPrioriryRoundId(8);
- }
-
- m_vPrevMainFrameCamPos = cam.GetPosition();
- }
-}
-
-void C3DEngine::WorldStreamUpdate()
-{
-#if defined(STREAMENGINE_ENABLE_STATS)
- static uint32 nCurrentRequestCount = 0;
- static uint64 nCurrentBytesRead = 0;
- if (m_nStreamingFramesSinceLevelStart == 1)
- {
- // store current streaming stats
- SStreamEngineStatistics& fullStats = gEnv->pSystem->GetStreamEngine()->GetStreamingStatistics();
- nCurrentBytesRead = fullStats.nTotalBytesRead;
- nCurrentRequestCount = fullStats.nTotalRequestCount;
- }
-#endif
-
- static float fTestStartTime = 0;
- if (m_nStreamingFramesSinceLevelStart == 1)
- {
- fTestStartTime = GetCurAsyncTimeSec();
- gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_FIRST_FRAME, 0, 0);
- }
-
- // Simple streaming performance test: Wait until all startup texture streaming jobs finish and print a message
- if (!m_bEditor)
- {
- if (!m_bPreCacheEndEventSent)
- {
- IStreamEngine* pSE = gEnv->pSystem->GetStreamEngine();
- SStreamEngineOpenStats openStats;
- pSE->GetStreamingOpenStatistics(openStats);
- bool bStarted =
- (openStats.nOpenRequestCountByType[eStreamTaskTypeTexture] > 0) ||
- (openStats.nOpenRequestCountByType[eStreamTaskTypeGeometry] > 0);
-
- float fTime = GetCurAsyncTimeSec() - fTestStartTime;
-
- switch (m_nStreamingFramesSinceLevelStart)
- {
- case 1:
- pSE->PauseStreaming(true, (1 << eStreamTaskTypeTexture) | (1 << eStreamTaskTypeGeometry));
- break;
- case 4:
- pSE->PauseStreaming(false, (1 << eStreamTaskTypeGeometry));
- break;
- case 8:
- pSE->PauseStreaming(false, (1 << eStreamTaskTypeTexture));
- break;
- }
-
- int nGlobalSystemState = gEnv->pSystem->GetSystemGlobalState();
-
- if ((nGlobalSystemState != ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_COMPLETE && (!bStarted || fTime >= 10.0f)) && m_nStreamingFramesSinceLevelStart > 16)
- {
- gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_COMPLETE);
-
- if (!bStarted)
- {
- PrintMessage("Textures startup streaming finished in %.1f sec", fTime);
- }
- else
- {
- PrintMessage("Textures startup streaming timed out after %.1f sec", fTime);
- }
-
- m_fTimeStateStarted = fTime;
- }
-
- if (nGlobalSystemState == ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_COMPLETE && (fTime - m_fTimeStateStarted) > 0.4f)
- {
- pSE->PauseStreaming(false, (1 << eStreamTaskTypeTexture) | (1 << eStreamTaskTypeGeometry));
-
- m_bPreCacheEndEventSent = true;
- gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_RUNNING);
- gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_END, 0, 0);
-
- fTestStartTime = 0.f;
-
-#if defined(STREAMENGINE_ENABLE_STATS)
- SStreamEngineStatistics& fullStats = pSE->GetStreamingStatistics();
- uint64 nBytesRead = fullStats.nTotalBytesRead - nCurrentBytesRead;
- uint32 nRequestCount = fullStats.nTotalRequestCount - nCurrentRequestCount;
-
- uint32 nOverallFileReadKB = (uint32)(nBytesRead / 1024);
- uint32 nOverallFileReadNum = nRequestCount;
- uint32 nBlockSize = (uint32)(nBytesRead / max((uint32)1, nRequestCount));
- float fReadBandwidthMB = (float)fullStats.nTotalSessionReadBandwidth / (1024 * 1024);
-
- PrintMessage("Average block size: %d KB, Average throughput: %.1f MB/sec, Jobs processed: %d (%.1f MB), File IO Bandwidth: %.2fMB/s",
- (nBlockSize) / 1024, (float)(nOverallFileReadKB / max(fTime, 1.f)) / 1024.f,
- nOverallFileReadNum, (float)nOverallFileReadKB / 1024.f,
- fReadBandwidthMB);
-
- if (GetCVars()->e_StreamSaveStartupResultsIntoXML)
- {
- const char* testResultsFile = "@usercache@/TestResults/Streaming_Level_Start_Throughput.xml";
-
- AZ::IO::HandleType resultsFile = gEnv->pCryPak->FOpen(testResultsFile, "wb");
- if (resultsFile != AZ::IO::InvalidHandle)
- {
- AZ::IO::Print(resultsFile,
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n",
- fTime,
- (nOverallFileReadKB / nOverallFileReadNum),
- (float)nOverallFileReadKB / max(fTime, 1.f) / 1024.f,
- nOverallFileReadNum,
- (float)nOverallFileReadKB / 1024.f);
- gEnv->pCryPak->FClose(resultsFile);
- }
- }
-#endif
- // gEnv->pCryPak->GetFileReadSequencer()->EndSection(); // STREAMING
- }
- else if (m_szLevelFolder[0])
- {
- ProposeContentPrecache();
- }
- }
- }
- else
- {
- if (!m_bPreCacheEndEventSent && m_nStreamingFramesSinceLevelStart == 4)
- {
- m_bPreCacheEndEventSent = true;
- gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_RUNNING);
- gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_END, 0, 0);
- }
- }
-}
-
-void C3DEngine::PrintDebugInfo(const SRenderingPassInfo& passInfo)
-{
- if (GetCVars()->e_DebugDraw)
- {
- f32 fColor[4] = {1, 1, 0, 1};
-
- float fYLine = 8.0f, fYStep = 20.0f;
-
- GetRenderer()->Draw2dLabel(8.0f, fYLine += fYStep, 2.0f, fColor, false, "e_DebugDraw = %d", GetCVars()->e_DebugDraw);
-
- const char* szMode = "";
-
- switch (static_cast(GetCVars()->e_DebugDraw))
- {
- case -1:
- szMode = "Showing bounding boxes";
- break;
- case 1:
- szMode = "bounding boxes, name of the used cgf, polycount, used LOD";
- break;
- case -2:
- case 2:
- szMode = "color coded polygon count(red,yellow,green,turqoise, blue)";
- break;
- case -3:
- szMode = "show color coded LODs count, flashing color indicates LOD.";
- break;
- case 3:
- szMode = "show color coded LODs count, flashing color indicates LOD.\nFormat: (Current LOD [Min LOD; Max LOD] (LOD Ratio / Distance to camera)";
- break;
- case -4:
- case 4:
- szMode = "object texture memory usage in KB";
- break;
- case -5:
- case 5:
- szMode = "number of render materials (color coded)";
- break;
- case 6:
- szMode = "ambient color (R,G,B,A)";
- break;
- case 7:
- szMode = "triangle count, number of render materials, texture memory in KB";
- break;
- case 8:
- szMode = "Free slot";
- break;
- case 9:
- szMode = "Free slot";
- break;
- case 10:
- szMode = "Deprecated option, use \"r_showlines 2\" instead";
- break;
- case 11:
- szMode = "Free slot";
- break;
- case 12:
- szMode = "Free slot";
- break;
- case 13:
- szMode = "occlusion amount (used during AO computations)";
- break;
- // case 14: szMode="";break;
- case 15:
- szMode = "display helpers";
- break;
- case 16:
- szMode = "Debug Gun";
- break;
- case 17:
- szMode = "streaming: buffer sizes (black: geometry, blue: texture)";
- if (gEnv->pLocalMemoryUsage)
- {
- gEnv->pLocalMemoryUsage->OnRender(GetRenderer(), &passInfo.GetCamera());
- }
- break;
- case 18:
- szMode = "Free slot";
- break;
- case 19:
- szMode = "physics proxy triangle count";
- break;
- case 20:
- szMode = "Character attachments texture memory usage";
- break;
- case 21:
- szMode = "Display animated objects distance to camera";
- break;
- case -22:
- case 22:
- szMode = "object's current LOD vertex count";
- break;
- case 23:
- szMode = "Display shadow casters in red";
- break;
- case 24:
- szMode = "Objects without LODs.\n name - (triangle count)\n draw calls - zpass/general/transparent/shadows/misc";
- break;
- case 25:
- szMode = "Objects without LODs (Red). Objects that need more LODs (Blue)\n name - (triangle count)\n draw calls - zpass/general/transparent/shadows/misc";
- break;
-
- default:
- assert(0);
- }
-
- GetRenderer()->Draw2dLabel(8.0f, fYLine += fYStep, 2.0f, fColor, false, " %s", szMode);
-
- if (GetCVars()->e_DebugDraw == 17)
- {
- GetRenderer()->Draw2dLabel(8.0f, fYLine += fYStep, 2.0f, fColor, false, " StatObj geometry used: %.2fMb / %dMb", CObjManager::s_nLastStreamingMemoryUsage / (1024.f * 1024.f), GetCVars()->e_StreamCgfPoolSize);
-
- ICVar* cVar = GetConsole()->GetCVar("r_TexturesStreaming");
- if (!cVar || !cVar->GetIVal())
- {
- GetRenderer()->Draw2dLabel(8.0f, fYLine += fYStep, 2.0f, fColor, false, " You have to set r_TexturesStreaming = 1 to see texture information!");
- }
- }
- }
-
- float fTextPosX = 10, fTextPosY = 10, fTextStepY = 12;
-
- // print list of streamed meshes
- if (m_pObjManager && GetCVars()->e_StreamCgf && GetCVars()->e_StreamCgfDebug >= 3)
- {
- // overall status
- {
- static char szCGFStreaming[256] = "";
- static SObjectsStreamingStatus objectsStreamingStatus = {0};
-
- {
- m_pObjManager->GetObjectsStreamingStatus(objectsStreamingStatus);
- sprintf_s(szCGFStreaming, 256, "CgfStrm: Loaded:%d InProg:%d All:%d Act:%d MemUsed:%2.2f MemReq:%2.2f Pool:%d",
- objectsStreamingStatus.nReady, objectsStreamingStatus.nInProgress, objectsStreamingStatus.nTotal, objectsStreamingStatus.nActive, float(objectsStreamingStatus.nAllocatedBytes) / 1024 / 1024, float(objectsStreamingStatus.nMemRequired) / 1024 / 1024, GetCVars()->e_StreamCgfPoolSize);
- }
-
- bool bOutOfMem((float(objectsStreamingStatus.nMemRequired) / 1024 / 1024) > GetCVars()->e_StreamCgfPoolSize);
- bool bCloseToOutOfMem((float(objectsStreamingStatus.nMemRequired) / 1024 / 1024) > GetCVars()->e_StreamCgfPoolSize * 90 / 100);
-
- ColorF color = Col_White;
- if (bOutOfMem)
- {
- color = Col_Red;
- }
- else if (bCloseToOutOfMem)
- {
- color = Col_Orange;
- }
-
- DrawTextLeftAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, color, szCGFStreaming);
- fTextPosY += fTextStepY;
- }
-
- DrawTextLeftAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, Col_White, "------------------- List of meshes bigger than %d KB -------------------", GetCVars()->e_StreamCgfDebugMinObjSize);
-
- for (int nObjId = 0; nObjId < m_pObjManager->GetArrStreamableObjects().Count(); nObjId++)
- {
- CStatObj* pStatObj = (CStatObj*)m_pObjManager->GetArrStreamableObjects()[nObjId].GetStreamAbleObject();
-
- int nKB = pStatObj->GetStreamableContentMemoryUsage() >> 10;
- int nSel = (pStatObj->m_nSelectedFrameId >= passInfo.GetMainFrameID() - 2);
-
- string sName;
- pStatObj->GetStreamableName(sName);
-
- if ((nKB >= GetCVars()->e_StreamCgfDebugMinObjSize && strstr(sName.c_str(), GetCVars()->e_StreamCgfDebugFilter->GetString())) || nSel)
- {
- const char* pComment = 0;
-
- if (!pStatObj->m_bCanUnload)
- {
- pComment = "NO_STRM";
- }
- else if (pStatObj->m_pLod0)
- {
- pComment = " LOD_X";
- }
- else if (!pStatObj->m_bLodsAreLoadedFromSeparateFile && pStatObj->m_nLoadedLodsNum > 1)
- {
- pComment = " SINGLE";
- }
- else if (pStatObj->m_nLoadedLodsNum > 1)
- {
- pComment = " LOD_0";
- }
- else
- {
- pComment = "NO_LODS";
- }
-
- int nDiff = SATURATEB(int(float(nKB - GetCVars()->e_StreamCgfDebugMinObjSize) / max(1, (int)GetCVars()->e_StreamCgfDebugMinObjSize) * 255));
- ColorB col(nDiff, 255 - nDiff, 0, 255);
- if (nSel && (1 & (int)(GetCurTimeSec() * 5.f)))
- {
- col = Col_Yellow;
- }
- ColorF fColor(col[0] / 255.f, col[1] / 255.f, col[2] / 255.f, col[3] / 255.f);
-
- const char* pStatusText = "Unload";
- if (pStatObj->m_eStreamingStatus == ecss_Ready)
- {
- pStatusText = "Ready ";
- }
- else if (pStatObj->m_eStreamingStatus == ecss_InProgress)
- {
- pStatusText = "InProg";
- }
-
- DrawTextLeftAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, fColor, "%1.2f mb, %s, %s, %s",
- 1.f / 1024.f * nKB, pComment, pStatusText, sName.c_str());
-
- if (fTextPosY > (float)gEnv->pRenderer->GetHeight())
- {
- break;
- }
- }
- }
- }
-
- if (m_arrProcessStreamingLatencyTestResults.Count())
- {
- float fAverTime = 0;
- for (int i = 0; i < m_arrProcessStreamingLatencyTestResults.Count(); i++)
- {
- fAverTime += m_arrProcessStreamingLatencyTestResults[i];
- }
- fAverTime /= m_arrProcessStreamingLatencyTestResults.Count();
-
- int nAverTexNum = 0;
- for (int i = 0; i < m_arrProcessStreamingLatencyTexNum.Count(); i++)
- {
- nAverTexNum += m_arrProcessStreamingLatencyTexNum[i];
- }
- nAverTexNum /= m_arrProcessStreamingLatencyTexNum.Count();
-
- DrawTextLeftAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, Col_Yellow, "------ SQT Average Time = %.1f, TexNum = %d ------", fAverTime, nAverTexNum);
-
- for (int i = 0; i < m_arrProcessStreamingLatencyTestResults.Count(); i++)
- {
- DrawTextLeftAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, Col_Yellow, "Run %d: Time = %.1f, TexNum = %d",
- i, m_arrProcessStreamingLatencyTestResults[i], m_arrProcessStreamingLatencyTexNum[i]);
- }
- }
-
-#if defined(USE_GEOM_CACHES)
-#ifndef _RELEASE
- if (GetCVars()->e_GeomCacheDebug)
- {
- m_pGeomCacheManager->DrawDebugInfo();
- }
- else
- {
- m_pGeomCacheManager->ResetDebugInfo();
- }
-#endif
-#endif
-}
-
-void C3DEngine::UpdatePreRender(const SRenderingPassInfo& passInfo)
-{
- AZ_TRACE_METHOD();
- FUNCTION_PROFILER(GetISystem(), PROFILE_3DENGINE);
-
- assert(passInfo.IsGeneralPass());
-
- // Compute global shadow cascade parameters.
- {
- m_fGsmRange = GetCVars()->e_GsmRange;
- m_fGsmRangeStep = GetCVars()->e_GsmRangeStep;
-
- //!!!also formulas for computing biases per gsm needs to be changed
- m_fShadowsConstBias = GetCVars()->e_ShadowsConstBias;
- m_fShadowsSlopeBias = GetCVars()->e_ShadowsSlopeBias;
-
- if (m_eShadowMode == ESM_HIGHQUALITY)
- {
- m_fGsmRange = min(0.15f, GetCVars()->e_GsmRange);
- m_fGsmRangeStep = min(2.8f, GetCVars()->e_GsmRangeStep);
-
- m_fShadowsConstBias = min(GetCVars()->e_ShadowsConstBiasHQ, GetCVars()->e_ShadowsConstBias);
- m_fShadowsSlopeBias = min(GetCVars()->e_ShadowsSlopeBiasHQ, GetCVars()->e_ShadowsSlopeBias);
- }
-
- const int nCascadeCount = Get3DEngine()->GetShadowsCascadeCount(NULL);
- m_pObjManager->SetGSMMaxDistance(Get3DEngine()->m_fGsmRange * powf(Get3DEngine()->m_fGsmRangeStep, (float)nCascadeCount));
- }
-
- // (bethelz) This has to happen before particle updates.
- m_PhysicsAreaUpdates.Update();
-
- if (passInfo.RenderClouds())
- {
- if (m_pCloudsManager)
- {
- m_pCloudsManager->MoveClouds();
- }
-
- CVolumeObjectRenderNode::MoveVolumeObjects();
- }
-
- UpdateSun(passInfo);
-
- // Set traceable fog volume areas
- CFogVolumeRenderNode::SetTraceableArea(AABB(passInfo.GetCamera().GetPosition(), 1024.0f), passInfo);
-}
-
-void C3DEngine::UpdatePostRender(const SRenderingPassInfo& passInfo)
-{
- AZ_TRACE_METHOD();
- FUNCTION_PROFILER(GetISystem(), PROFILE_3DENGINE);
-
- assert (m_pObjManager);
-
- m_pObjManager->CheckTextureReadyFlag();
- if (GetCVars()->e_StreamCgf)
- {
- static Array2d memUsage;
-
- int nArrayDim = 256;
-#ifndef CONSOLE_CONST_CVAR_MODE
- if (GetCVars()->e_StreamCgfDebugHeatMap == 1)
- {
- memUsage.Allocate(nArrayDim);
- CCamera camOld = passInfo.GetCamera();
-
- PrintMessage("Computing mesh streaming heat map");
-
- //The assumption is that this is called on Main Thread, otherwise the loop
- //Should be wrapped inside a EnumerateHandlers lambda.
- auto terrain = AzFramework::Terrain::TerrainDataRequestBus::FindFirstHandler();
- const float defaultTerrainHeight = AzFramework::Terrain::TerrainDataRequests::GetDefaultTerrainHeight();
-
- const AZ::Aabb terrainAabb = terrain ? terrain->GetTerrainAabb() : AZ::Aabb::CreateFromPoint(AZ::Vector3::CreateZero());
- const int nTerrainSizeX = static_cast(terrainAabb.GetXExtent());
- const int nTerrainSizeY = static_cast(terrainAabb.GetYExtent());
- const int nStepX = nTerrainSizeX / nArrayDim;
- const int nStepY = nTerrainSizeY / nArrayDim;
-
- for (int x = 0; x < nTerrainSizeX; x += nStepX)
- {
- for (int y = 0; y < nTerrainSizeY; y += nStepY)
- {
- CCamera camTmp = camOld;
- float terrainHeight = terrain ? terrain->GetHeightFromFloats((float)x, (float)y) : defaultTerrainHeight;
- camTmp.SetPosition(Vec3((float)x + (float)nStepX / 2.f, (float)y + (float)nStepY / 2.f, terrainHeight));
- //SetCamera(camTmp);
- m_pObjManager->ProcessObjectsStreaming(passInfo);
-
- SObjectsStreamingStatus objectsStreamingStatus;
- m_pObjManager->GetObjectsStreamingStatus(objectsStreamingStatus);
-
- memUsage[x / nStepX][y / nStepY] = objectsStreamingStatus.nMemRequired;
- }
-
- if (!((x / nStepX) & 31))
- {
- PrintMessage(" working ...");
- }
- }
-
- PrintMessage(" done");
-
- GetCVars()->e_StreamCgfDebugHeatMap = 2;
- //SetCamera(camOld);
- }
- else if (GetCVars()->e_StreamCgfDebugHeatMap == 2)
- {
- auto terrain = AzFramework::Terrain::TerrainDataRequestBus::FindFirstHandler();
- const float defaultTerrainHeight = AzFramework::Terrain::TerrainDataRequests::GetDefaultTerrainHeight();
-
- const AZ::Aabb terrainAabb = terrain ? terrain->GetTerrainAabb() : AZ::Aabb::CreateFromPoint(AZ::Vector3::CreateZero());
- const float terrainSizeX = terrainAabb.GetXExtent();
- const float terrainSizeY = terrainAabb.GetYExtent();
- const float fStepX = terrainSizeX / nArrayDim;
- const float fStepY = terrainSizeY / nArrayDim;
-
- for (int x = 0; x < memUsage.GetSize(); x++)
- {
- for (int y = 0; y < memUsage.GetSize(); y++)
- {
- float terrainHeight = terrain ? terrain->GetHeightFromFloats((float)x * fStepX, (float)y * fStepY) : defaultTerrainHeight;
- Vec3 v0((float)x* fStepX, (float)y* fStepY, terrainHeight);
- Vec3 v1((float)x* fStepX + fStepX, (float)y* fStepY + fStepY, v0.z + fStepX);
- v0 += Vec3(.25f, .25f, .25f);
- v1 -= Vec3(.25f, .25f, .25f);
- AABB box(v0, v1);
- if (!passInfo.GetCamera().IsAABBVisible_F(box))
- {
- continue;
- }
-
- int nMemUsageMB = memUsage[(int)(x)][(int)(y)] / 1024 / 1024;
-
- int nOverLoad = nMemUsageMB - GetCVars()->e_StreamCgfPoolSize;
-
- ColorB col = Col_Red;
-
- if (nOverLoad < GetCVars()->e_StreamCgfPoolSize / 2)
- {
- col = Col_Yellow;
- }
-
- if (nOverLoad < 0)
- {
- col = Col_Green;
- }
-
- DrawBBox(box, col);
- }
- }
- }
-#endif //CONSOLE_CONST_CVAR_MODE
- m_pObjManager->ProcessObjectsStreaming(passInfo);
- }
- else
- {
- m_pObjManager->GetStreamPreCacheCameras()[0].vPosition = passInfo.GetCamera().GetPosition();
- if (Distance::Point_AABBSq(m_pObjManager->GetStreamPreCacheCameras()[0].vPosition, m_pObjManager->GetStreamPreCacheCameras()[0].bbox) > 0.0f)
- {
- m_pObjManager->GetStreamPreCacheCameras()[0].bbox = AABB(m_pObjManager->GetStreamPreCacheCameras()[0].vPosition, GetCVars()->e_StreamPredictionBoxRadius);
- }
- m_pObjManager->UpdateObjectsStreamingPriority(false, passInfo);
- }
-
- // (bethelz) Per-frame precache request handled by streaming systems.
- m_bContentPrecacheRequested = false;
-}
-
-int __cdecl C3DEngine__Cmp_SRNInfo(const void* v1, const void* v2)
-{
- SRNInfo* p1 = (SRNInfo*)v1;
- SRNInfo* p2 = (SRNInfo*)v2;
-
- float fViewDist1 = p1->fMaxViewDist - p1->objSphere.radius;
- float fViewDist2 = p2->fMaxViewDist - p2->objSphere.radius;
-
- // if same - give closest sectors higher priority
- if (fViewDist1 > fViewDist2)
- {
- return 1;
- }
- else if (fViewDist1 < fViewDist2)
- {
- return -1;
- }
-
- return 0;
-}
-
-void C3DEngine::SetSkyMaterialPath(const string& skyMatName)
-{
- m_skyMatName = skyMatName;
- m_pSkyMat = nullptr;
-}
-
-void C3DEngine::SetSkyLowSpecMaterialPath(const string& skyLowSpecMatName)
-{
- m_skyLowSpecMatName = skyLowSpecMatName;
- m_pSkyLowSpecMat = nullptr;
-}
-
-void C3DEngine::LoadSkyMaterial()
-{
- const int skyType = GetCVars()->e_SkyType;
- if (skyType == 0)
- {
- if (!m_pSkyLowSpecMat)
- {
- m_pSkyLowSpecMat = m_skyLowSpecMatName.empty() ? nullptr : m_pMatMan->LoadMaterial(m_skyLowSpecMatName.c_str(), false, false, MTL_FLAG_IS_SKY);
- AZ_Warning("3DEngine", m_pSkyLowSpecMat, "Missing low spec sky material: %s", m_skyLowSpecMatName.c_str());
- }
- }
- else
- {
- if (!m_pSkyMat)
- {
- m_pSkyMat = m_skyMatName.empty() ? nullptr : m_pMatMan->LoadMaterial(m_skyMatName.c_str(), false, false, MTL_FLAG_IS_SKY);
- AZ_Warning("3DEngine", m_pSkyMat, "Missing sky material: %s", m_skyMatName.c_str());
- }
- }
- m_previousSkyType = skyType;
-}
-
-_smart_ptr C3DEngine::GetSkyMaterial()
-{
- const int skyType = GetCVars()->e_SkyType;
-
- // If e_SkyType has changed, then we may need to load a different sky material.
- if (skyType != m_previousSkyType)
- {
- LoadSkyMaterial();
- }
-
- return (skyType == 0) ? m_pSkyLowSpecMat : m_pSkyMat;
-}
-
-void C3DEngine::SetSkyMaterial(_smart_ptr pSkyMat)
-{
- m_pSkyMat = pSkyMat;
-}
-
-bool C3DEngine::IsHDRSkyMaterial(_smart_ptr pMat) const
-{
- return pMat && !azstricmp(pMat->GetSafeSubMtl(0)->GetShaderItem().m_pShader->GetName(), "SkyHDR");
-}
-
-void C3DEngine::RenderScene(const int nRenderFlags, const SRenderingPassInfo& passInfo)
-{
- FUNCTION_PROFILER_3DENGINE_LEGACYONLY;
- AZ_TRACE_METHOD();
- CRY_ASSERT(passInfo.IsGeneralPass());
- CRY_ASSERT(m_pVisAreaManager);
- CRY_ASSERT(m_pClipVolumeManager);
- CRY_ASSERT(m_pDecalManager);
-
- GetObjManager()->GetCullThread().SetActive(true);
-
- if (GetCVars()->e_CoverageBuffer)
- {
- m_pCoverageBuffer->BeginFrame(passInfo);
- }
-
- if (m_pVisAreaManager != nullptr)
- {
- m_pVisAreaManager->DrawOcclusionAreasIntoCBuffer(m_pCoverageBuffer, passInfo);
- m_pVisAreaManager->CheckVis(passInfo);
- }
-
- if (m_pClipVolumeManager)
- {
- m_pClipVolumeManager->PrepareVolumesForRendering(passInfo);
- }
-
- if (m_pObjManager)
- {
- m_pObjManager->RenderAllObjectDebugInfo();
- }
- SRendItemSorter rendItemSorter = SRendItemSorter::CreateRendItemSorter(passInfo);
-
- // make sure all jobs from the previous frame have finished
- threadID nPrevThreadID = 0;
- gEnv->pRenderer->EF_Query(EFQ_RenderThreadList, nPrevThreadID);
- gEnv->pRenderer->GetFinalizeRendItemJobExecutor(nPrevThreadID)->WaitForCompletion();
- gEnv->pRenderer->GetFinalizeShadowRendItemJobExecutor(nPrevThreadID)->WaitForCompletion();
-
- GetRenderer()->EF_ClearSkinningDataPool();
- GetRenderer()->BeginSpawningGeneratingRendItemJobs(passInfo.ThreadID());
-
- GetRenderer()->EF_StartEf(passInfo);
-
- m_bIsInRenderScene = true;
- COctreeNode::ReleaseEmptyNodes();
-
- m_LightVolumesMgr.Clear(passInfo);
-
- SubmitSun(passInfo);
-
- if (GetCVars()->e_StatObjBufferRenderTasks && m_pObjManager != nullptr)
- {
- m_pObjManager->BeginOcclusionCulling(passInfo);
- }
-
- if (m_pVisAreaManager != nullptr)
- {
- m_pVisAreaManager->DrawVisibleSectors(passInfo, rendItemSorter);
- }
- m_nOceanRenderFlags &= ~OCR_OCEANVOLUME_VISIBLE;
-
- if (IsOutdoorVisible() || GetRenderer()->IsPost3DRendererEnabled())
- {
- if (m_pVisAreaManager != nullptr && m_pVisAreaManager->m_lstOutdoorPortalCameras.Count() &&
- (m_pVisAreaManager->m_pCurArea || m_pVisAreaManager->m_pCurPortal))
- { // enable multi-camera culling
- const_cast(passInfo.GetCamera()).m_pMultiCamera = &m_pVisAreaManager->m_lstOutdoorPortalCameras;
- }
-
- if (IsOutdoorVisible())
- {
- RenderSkyBox(GetSkyMaterial(), passInfo);
- }
-
- rendItemSorter.IncreaseOctreeCounter();
- {
- FRAME_PROFILER_LEGACYONLY("COctreeNode::Render_____", GetSystem(), PROFILE_3DENGINE);
- AZ_TRACE_METHOD_NAME("COctreeNode::Render");
- if (m_pObjectsTree != nullptr)
- {
- m_pObjectsTree->Render_Object_Nodes(false, OCTREENODE_RENDER_FLAG_OBJECTS, passInfo, rendItemSorter);
- }
- }
- rendItemSorter.IncreaseGroupCounter();
- }
- else if (m_pVisAreaManager && m_pVisAreaManager->IsSkyVisible())
- {
- RenderSkyBox(GetSkyMaterial(), passInfo);
- }
-
- // Outdoor is not visible, that means there is no SkyBox to render.
- // So we want to clear the GBuffer RT/background in order to avoid artifacts.
- GetRenderer()->SetClearBackground(!IsOutdoorVisible());
-
- if (nRenderFlags & SHDF_ALLOW_AO)
- {
- SVOGILegacyRequestBus::Broadcast(&SVOGILegacyRequests::UpdateRenderData);
- }
-
- {
- FRAME_PROFILER_LEGACYONLY("COctreeNode::Render_Object_Nodes_NEAR", GetSystem(), PROFILE_3DENGINE);
- AZ_TRACE_METHOD_NAME("COctreeNode::Render_Object_Nodes_NEAR");
- rendItemSorter.IncreaseOctreeCounter();
- if (GetCVars()->e_PortalsBigEntitiesFix)
- {
- if (!IsOutdoorVisible() && GetVisAreaManager() != nullptr && GetVisAreaManager()->GetCurVisArea())
- {
- if (GetVisAreaManager()->GetCurVisArea()->IsConnectedToOutdoor())
- {
- CCamera cam = passInfo.GetCamera();
- cam.SetFrustum(cam.GetViewSurfaceX(), cam.GetViewSurfaceZ(), cam.GetFov(), min(cam.GetNearPlane(), 1.f), 2.f, cam.GetPixelAspectRatio());
- m_pObjectsTree->Render_Object_Nodes(false, OCTREENODE_RENDER_FLAG_OBJECTS | OCTREENODE_RENDER_FLAG_OBJECTS_ONLY_ENTITIES, SRenderingPassInfo::CreateTempRenderingInfo(cam, passInfo), rendItemSorter);
- }
- }
- }
- }
- rendItemSorter.IncreaseGroupCounter();
-
- // render special objects like laser beams intersecting entire level
- for (int i = 0; i < m_lstAlwaysVisible.Count(); i++)
- {
- IRenderNode* pObj = m_lstAlwaysVisible[i];
- const AABB& objBox = pObj->GetBBox();
- // don't frustum cull the HUD. When e.g. zooming the FOV for this camera is very different to the
- // fixed HUD FOV, and this can cull incorrectly.
- const unsigned int dwRndFlags = pObj->GetRndFlags();
- if (dwRndFlags & ERF_HUD || passInfo.GetCamera().IsAABBVisible_E(objBox))
- {
- FRAME_PROFILER_LEGACYONLY("C3DEngine::RenderScene_DrawAlwaysVisible", GetSystem(), PROFILE_3DENGINE);
- AZ_TRACE_METHOD_NAME("COctreeNode::RenderScene_DrawAlwaysVisible");
-
- Vec3 vCamPos = passInfo.GetCamera().GetPosition();
- float fEntDistance = sqrt_tpl(Distance::Point_AABBSq(vCamPos, objBox)) * passInfo.GetZoomFactor();
- assert(fEntDistance >= 0 && _finite(fEntDistance));
- if (fEntDistance < pObj->m_fWSMaxViewDist && GetObjManager() != nullptr)
- {
- GetObjManager()->RenderObject(pObj, objBox, fEntDistance, pObj->GetRenderNodeType(), passInfo, rendItemSorter);
- }
- }
- }
- rendItemSorter.IncreaseGroupCounter();
-
- if (m_pOcean)
- {
- ProcessOcean(passInfo);
- }
-
- if (passInfo.RenderDecals() && m_pDecalManager != nullptr)
- {
- m_pDecalManager->Render(passInfo);
- }
-
- // tell the occlusion culler that no new work will be submitted
- if (GetCVars()->e_StatObjBufferRenderTasks == 1 && GetObjManager() != nullptr)
- {
- GetObjManager()->PushIntoCullQueue(SCheckOcclusionJobData::CreateQuitJobData());
- }
-
- // fill shadow list here to allow more time between starting and waiting for the occlusion buffer
- InitShadowFrustums(passInfo);
-
- gEnv->pSystem->DoWorkDuringOcclusionChecks();
-
- if (GetCVars()->e_StatObjBufferRenderTasks && m_pObjManager != nullptr)
- {
- m_pObjManager->RenderBufferedRenderMeshes(passInfo);
- }
-
- // don't start shadow jobs if we aren't generating shadows
- if ((nRenderFlags & SHDF_NO_SHADOWGEN) == 0)
- {
- GetRenderer()->EF_InvokeShadowMapRenderJobs(IsShadersSyncLoad() ? (nRenderFlags | SHDF_NOASYNC | SHDF_STREAM_SYNC) : nRenderFlags);
- }
-
- m_LightVolumesMgr.Update(passInfo);
-
- SetupDistanceFog();
-
- SetupClearColor();
-
- {
- FRAME_PROFILER("Renderer::EF_EndEf3D", GetSystem(), PROFILE_RENDERER);
- // TODO: separate SHDF_NOASYNC and SHDF_STREAM_SYNC flags
- GetRenderer()->EF_EndEf3D(IsShadersSyncLoad() ? (nRenderFlags | SHDF_NOASYNC | SHDF_STREAM_SYNC) : nRenderFlags, GetObjManager()->GetUpdateStreamingPrioriryRoundId(), GetObjManager()->GetUpdateStreamingPrioriryRoundIdFast(), passInfo);
- }
-
- GetRenderer()->EnableFog(false);
-
- bool bIsMultiThreadedRenderer = false;
- gEnv->pRenderer->EF_Query(EFQ_RenderMultithreaded, bIsMultiThreadedRenderer);
- if (bIsMultiThreadedRenderer)
- {
- gEnv->pRenderer->EndSpawningGeneratingRendItemJobs();
- }
-
- m_bIsInRenderScene = false;
-
-#ifndef _RELEASE
- IF (GetCVars()->e_LightVolumesDebug, 0)
- {
- m_LightVolumesMgr.DrawDebug(passInfo);
- }
-#endif
-}
-
-void C3DEngine::WaitForCullingJobsCompletion()
-{
- const bool waitForOcclusionJobCompletion = true;
- m_pObjManager->EndOcclusionCulling(waitForOcclusionJobCompletion);
- COctreeNode::WaitForContentJobCompletion();
-}
-
-void C3DEngine::RenderSceneReflection(const int nRenderFlags, const SRenderingPassInfo& passInfo)
-{
- FUNCTION_PROFILER_3DENGINE_LEGACYONLY;
- AZ_TRACE_METHOD();
- CRY_ASSERT(passInfo.IsRecursivePass());
- CRY_ASSERT(passInfo.GetRecursiveLevel() < MAX_RECURSION_LEVELS);
- CRY_ASSERT(m_pVisAreaManager);
- CRY_ASSERT(m_pClipVolumeManager);
- CRY_ASSERT(m_pDecalManager);
-
- if (!GetCVars()->e_Recursion)
- {
- return;
- }
-
- if (m_pVisAreaManager != nullptr)
- {
- m_pVisAreaManager->CheckVis(passInfo);
- }
-
- if (m_pClipVolumeManager != nullptr)
- {
- m_pClipVolumeManager->PrepareVolumesForRendering(passInfo);
- }
- ////////////////////////////////////////////////////////////////////////////////////////
- // From here we add render elements of main scene
- ////////////////////////////////////////////////////////////////////////////////////////
- SRendItemSorter rendItemSorter = SRendItemSorter::CreateRendItemSorter(passInfo);
-
- GetRenderer()->EF_StartEf(passInfo);
-
- if (m_pVisAreaManager != nullptr)
- {
- m_pVisAreaManager->DrawVisibleSectors(passInfo, rendItemSorter);
- }
-
- if (IsOutdoorVisible() || GetRenderer()->IsPost3DRendererEnabled())
- {
- if (m_pVisAreaManager != nullptr && m_pVisAreaManager->m_lstOutdoorPortalCameras.Count() &&
- (m_pVisAreaManager->m_pCurArea || m_pVisAreaManager->m_pCurPortal))
- { // enable multi-camera culling
- const_cast(passInfo.GetCamera()).m_pMultiCamera = &m_pVisAreaManager->m_lstOutdoorPortalCameras;
- }
-
- if (IsOutdoorVisible())
- {
- RenderSkyBox(GetSkyMaterial(), passInfo);
- }
-
- {
- rendItemSorter.IncreaseOctreeCounter();
- FRAME_PROFILER("COctreeNode::Render_____", GetSystem(), PROFILE_3DENGINE);
- if (m_pObjectsTree != nullptr)
- {
- m_pObjectsTree->Render_Object_Nodes(false, OCTREENODE_RENDER_FLAG_OBJECTS, passInfo, rendItemSorter);
- }
- }
- rendItemSorter.IncreaseGroupCounter();
- }
- else if (m_pVisAreaManager != nullptr && m_pVisAreaManager->IsSkyVisible())
- {
- RenderSkyBox(GetSkyMaterial(), passInfo);
- }
-
- {
- FRAME_PROFILER("COctreeNode::Render_Object_Nodes_NEAR", GetSystem(), PROFILE_3DENGINE);
- rendItemSorter.IncreaseOctreeCounter();
- if (GetCVars()->e_PortalsBigEntitiesFix)
- {
- if (!IsOutdoorVisible() && GetVisAreaManager() != nullptr && GetVisAreaManager()->GetCurVisArea())
- {
- if (GetVisAreaManager()->GetCurVisArea()->IsConnectedToOutdoor())
- {
- CCamera cam = passInfo.GetCamera();
- cam.SetFrustum(cam.GetViewSurfaceX(), cam.GetViewSurfaceZ(), cam.GetFov(), min(cam.GetNearPlane(), 1.f), 2.f, cam.GetPixelAspectRatio());
- if (m_pObjectsTree != nullptr)
- {
- m_pObjectsTree->Render_Object_Nodes(false, OCTREENODE_RENDER_FLAG_OBJECTS | OCTREENODE_RENDER_FLAG_OBJECTS_ONLY_ENTITIES, SRenderingPassInfo::CreateTempRenderingInfo(cam, passInfo), rendItemSorter);
- }
- }
- }
- }
- }
- rendItemSorter.IncreaseGroupCounter();
-
- // render special objects like laser beams intersecting entire level
- for (int i = 0; i < m_lstAlwaysVisible.Count(); i++)
- {
- IRenderNode* pObj = m_lstAlwaysVisible[i];
- const AABB& objBox = pObj->GetBBox();
- // don't frustum cull the HUD. When e.g. zooming the FOV for this camera is very different to the
- // fixed HUD FOV, and this can cull incorrectly.
- const unsigned int dwRndFlags = pObj->GetRndFlags();
- if (dwRndFlags & ERF_HUD || passInfo.GetCamera().IsAABBVisible_E(objBox))
- {
- FRAME_PROFILER("C3DEngine::RenderScene_DrawAlwaysVisible", GetSystem(), PROFILE_3DENGINE);
-
- Vec3 vCamPos = passInfo.GetCamera().GetPosition();
- float fEntDistance = sqrt_tpl(Distance::Point_AABBSq(vCamPos, objBox)) * passInfo.GetZoomFactor();
- assert(fEntDistance >= 0 && _finite(fEntDistance));
- if (fEntDistance < pObj->m_fWSMaxViewDist)
- {
- GetObjManager()->RenderObject(pObj, objBox, fEntDistance, pObj->GetRenderNodeType(), passInfo, rendItemSorter);
- }
- }
- }
- rendItemSorter.IncreaseGroupCounter();
-
- if (m_pOcean)
- {
- ProcessOcean(passInfo);
- }
-
- //Update light volumes again. Processing particles may have resulted in an increase in the number of light volumes.
- m_LightVolumesMgr.Update(passInfo);
-
- if (passInfo.RenderDecals() && m_pDecalManager != nullptr)
- {
- m_pDecalManager->Render(passInfo);
- }
-
- {
- FRAME_PROFILER("Renderer::EF_EndEf3D", GetSystem(), PROFILE_RENDERER);
- GetRenderer()->EF_EndEf3D(IsShadersSyncLoad() ? (nRenderFlags | SHDF_NOASYNC | SHDF_STREAM_SYNC) : nRenderFlags, GetObjManager()->GetUpdateStreamingPrioriryRoundId(), GetObjManager()->GetUpdateStreamingPrioriryRoundIdFast(), passInfo);
- }
-}
-
-void C3DEngine::ProcessOcean(const SRenderingPassInfo& passInfo)
-{
- FUNCTION_PROFILER_3DENGINE_LEGACYONLY;
- AZ_TRACE_METHOD();
-
- AZ_Assert(m_pOcean != nullptr, "Ocean pointer must be validated before calling ProcessOcean");
-
- if (GetOceanRenderFlags() & OCR_NO_DRAW || !GetVisAreaManager() || GetCVars()->e_DefaultMaterial)
- {
- return;
- }
-
- bool bOceanIsForcedByVisAreaFlags = GetVisAreaManager()->IsOceanVisible();
-
- if (!IsOutdoorVisible() && !bOceanIsForcedByVisAreaFlags)
- {
- return;
- }
-
- bool bOceanVisible = false;
- if (OceanToggle::IsActive())
- {
- bOceanVisible = OceanRequest::OceanIsEnabled();
- }
- else
- {
- bOceanVisible = true;
- }
-
- if (bOceanVisible && passInfo.RenderWaterOcean() && m_bOcean)
- {
- Vec3 vCamPos = passInfo.GetCamera().GetPosition();
- float fWaterPlaneSize = passInfo.GetCamera().GetFarPlane();
- const float fOceanLevel = OceanToggle::IsActive() ? OceanRequest::GetOceanLevel(): m_pOcean->GetWaterLevel();
-
- AABB boxOcean(Vec3(vCamPos.x - fWaterPlaneSize, vCamPos.y - fWaterPlaneSize, std::numeric_limits::lowest()),
- Vec3(vCamPos.x + fWaterPlaneSize, vCamPos.y + fWaterPlaneSize, fOceanLevel + 0.5f));
-
- if ((!bOceanIsForcedByVisAreaFlags && passInfo.GetCamera().IsAABBVisible_EM(boxOcean)) ||
- (bOceanIsForcedByVisAreaFlags && passInfo.GetCamera().IsAABBVisible_E (boxOcean)))
- {
- bool bOceanIsVisibleFromIndoor = true;
- if (class PodArray* pMultiCamera = passInfo.GetCamera().m_pMultiCamera)
- {
- for (int i = 0; i < pMultiCamera->Count(); i++)
- {
- CVisArea* pExitPortal = (CVisArea*)(pMultiCamera->Get(i))->m_pPortal;
- float fMinZ = pExitPortal->GetAABBox()->min.z;
- float fMaxZ = pExitPortal->GetAABBox()->max.z;
-
- if (!bOceanIsForcedByVisAreaFlags)
- {
- if (fMinZ > fOceanLevel && vCamPos.z < fMinZ)
- {
- bOceanIsVisibleFromIndoor = false;
- }
-
- if (fMaxZ < fOceanLevel && vCamPos.z > fMaxZ)
- {
- bOceanIsVisibleFromIndoor = false;
- }
- }
- }
- }
-
- if (bOceanIsVisibleFromIndoor)
- {
- m_pOcean->Update(passInfo);
-
- if ((GetOceanRenderFlags() & OCR_OCEANVOLUME_VISIBLE))
- {
- if (passInfo.RenderWaterOcean())
- {
- m_pOcean->Render(passInfo);
- m_pOcean->SetLastFov(passInfo.GetCamera().GetFov());
- }
- }
- }
- }
- }
-
- if (GetCVars()->e_WaterRipplesDebug > 0)
- {
- GetRenderer()->EF_DrawWaterSimHits();
- }
-}
-
-void C3DEngine::RenderSkyBox(_smart_ptr pMat, const SRenderingPassInfo& passInfo)
-{
- FUNCTION_PROFILER_3DENGINE_LEGACYONLY;
- AZ_TRACE_METHOD();
-
- if (!Get3DEngine()->GetCoverageBuffer()->IsOutdooVisible())
- {
- return;
- }
-
- const float fForceDrawLastSortOffset = 100000.0f;
-
- // hdr sky dome
- // TODO: temporary workaround to force the right sky dome for the selected shader
- if (m_pREHDRSky && IsHDRSkyMaterial(pMat))
- {
- if (GetCVars()->e_SkyBox)
- {
-#ifndef CONSOLE_CONST_CVAR_MODE
- if (GetCVars()->e_SkyQuality < 1)
- {
- GetCVars()->e_SkyQuality = 1;
- }
- else if (GetCVars()->e_SkyQuality > 2)
- {
- GetCVars()->e_SkyQuality = 2;
- }
-#endif
- m_pSkyLightManager->SetQuality(GetCVars()->e_SkyQuality);
-
- // set sky light incremental update rate and perform update
- if (GetCVars()->e_SkyUpdateRate <= 0.0f)
- {
- GetCVars()->e_SkyUpdateRate = 0.01f;
- }
- m_pSkyLightManager->IncrementalUpdate(GetCVars()->e_SkyUpdateRate, passInfo);
-
- // prepare render object
- CRenderObject* pObj = GetRenderer()->EF_GetObject_Temp(passInfo.ThreadID());
- if (!pObj)
- {
- return;
- }
- pObj->m_II.m_Matrix.SetTranslationMat(passInfo.GetCamera().GetPosition());
- pObj->m_pRenderNode = 0;//m_pREHDRSky;
- pObj->m_fSort = fForceDrawLastSortOffset; // force sky to draw last
-
- /* if( 0 == m_nRenderStackLevel )
- {
- // set scissor rect
- pObj->m_nScissorX1 = GetCamera().m_ScissorInfo.x1;
- pObj->m_nScissorY1 = GetCamera().m_ScissorInfo.y1;
- pObj->m_nScissorX2 = GetCamera().m_ScissorInfo.x2;
- pObj->m_nScissorY2 = GetCamera().m_ScissorInfo.y2;
- }*/
-
- m_pREHDRSky->m_pRenderParams = m_pSkyLightManager->GetRenderParams();
- m_pREHDRSky->m_moonTexId = m_nNightMoonTexId;
-
- // add sky dome to render list
- SRendItemSorter rendItemSorter = SRendItemSorter::CreateRendItemSorter(passInfo);
- GetRenderer()->EF_AddEf(m_pREHDRSky, pMat->GetSafeSubMtl(0)->GetShaderItem(), pObj, passInfo, EFSLIST_GENERAL, 1, rendItemSorter);
- }
- }
- // skybox
- else
- {
- if (pMat && m_pRESky && GetCVars()->e_SkyBox)
- {
- CRenderObject* pObj = GetRenderer()->EF_GetObject_Temp(passInfo.ThreadID());
- if (!pObj)
- {
- return;
- }
- pObj->m_II.m_Matrix.SetTranslationMat(passInfo.GetCamera().GetPosition());
- pObj->m_II.m_Matrix = pObj->m_II.m_Matrix * Matrix33::CreateRotationZ(DEG2RAD(m_fSkyBoxAngle));
- pObj->m_fSort = fForceDrawLastSortOffset; // force sky to draw last
-
- if (OceanToggle::IsActive())
- {
- m_pRESky->m_fTerrainWaterLevel = OceanRequest::GetOceanLevelOrDefault(-100000.0f);
- }
- else
- {
- const float waterLevel = m_pOcean ? m_pOcean->GetWaterLevel() : 0.0f;
- m_pRESky->m_fTerrainWaterLevel = max(0.0f, waterLevel);
- }
- m_pRESky->m_fSkyBoxStretching = m_fSkyBoxStretching;
-
- SRendItemSorter rendItemSorter = SRendItemSorter::CreateRendItemSorter(passInfo);
- GetRenderer()->EF_AddEf(m_pRESky, pMat->GetSafeSubMtl(0)->GetShaderItem(), pObj, passInfo, EFSLIST_GENERAL, 1, rendItemSorter);
- }
- }
-}
-
-void C3DEngine::DrawTextRightAligned(const float x, const float y, const char* format, ...)
-{
- va_list args;
- va_start(args, format);
-
- SDrawTextInfo ti;
- ti.flags = eDrawText_FixedSize | eDrawText_Right | eDrawText_2D | eDrawText_Monospace;
- ti.xscale = ti.yscale = DISPLAY_INFO_SCALE;
- GetRenderer()->DrawTextQueued(Vec3(x, y, 1.0f), ti, format, args);
-
- va_end(args);
-}
-
-void C3DEngine::DrawTextAligned(int flags, const float x, const float y, const float scale, const ColorF& color, const char* format, ...)
-{
- va_list args;
- va_start(args, format);
-
- SDrawTextInfo ti;
- ti.flags = flags;
- ti.color[0] = color[0];
- ti.color[1] = color[1];
- ti.color[2] = color[2];
- ti.color[3] = color[3];
- ti.xscale = ti.yscale = scale;
- GetRenderer()->DrawTextQueued(Vec3(x, y, 1.0f), ti, format, args);
-
- va_end(args);
-}
-
-void C3DEngine::DrawTextLeftAligned(const float x, const float y, const float scale, const ColorF& color, const char* format, ...)
-{
- va_list args;
- va_start(args, format);
-
- SDrawTextInfo ti;
- ti.flags = eDrawText_FixedSize | eDrawText_2D | eDrawText_Monospace;
- ti.color[0] = color[0];
- ti.color[1] = color[1];
- ti.color[2] = color[2];
- ti.color[3] = color[3];
- ti.xscale = ti.yscale = scale;
- GetRenderer()->DrawTextQueued(Vec3(x, y, 1.0f), ti, format, args);
-
- va_end(args);
-}
-
-void C3DEngine::DrawTextRightAligned(const float x, const float y, const float scale, const ColorF& color, const char* format, ...)
-{
- va_list args;
- va_start(args, format);
-
- SDrawTextInfo ti;
- ti.flags = eDrawText_FixedSize | eDrawText_Right | eDrawText_2D | eDrawText_Monospace;
- ti.color[0] = color[0];
- ti.color[1] = color[1];
- ti.color[2] = color[2];
- ti.color[3] = color[3];
- ti.xscale = ti.yscale = scale;
- GetRenderer()->DrawTextQueued(Vec3(x, y, 1.0f), ti, format, args);
-
- va_end(args);
-}
-
-int __cdecl C3DEngine__Cmp_FPS(const void* v1, const void* v2)
-{
- float f1 = *(float*)v1;
- float f2 = *(float*)v2;
-
- if (f1 > f2)
- {
- return 1;
- }
- else if (f1 < f2)
- {
- return -1;
- }
-
- return 0;
-}
-
-inline void Blend(float& Stat, float StatCur, float fBlendCur)
-{
- Stat = Stat * (1.f - fBlendCur) + StatCur * fBlendCur;
-}
-
-inline void Blend(float& Stat, int& StatCur, float fBlendCur)
-{
- Blend(Stat, float(StatCur), fBlendCur);
- StatCur = int_round(Stat);
-}
-
-#ifdef ENABLE_LW_PROFILERS
-static void AppendString(char*& szEnd, const char* szToAppend)
-{
- assert(szToAppend);
-
- while (*szToAppend)
- {
- *szEnd++ = *szToAppend++;
- }
-
- *szEnd++ = ' ';
- *szEnd = 0;
-}
-#endif
-
-void C3DEngine::DisplayInfo([[maybe_unused]] float& fTextPosX, [[maybe_unused]] float& fTextPosY, [[maybe_unused]] float& fTextStepY, [[maybe_unused]] const bool bEnhanced)
-{
-#ifdef ENABLE_LW_PROFILERS
- // FUNCTION_PROFILER_3DENGINE; causes 0 fps in stats
- static ICVar* pDisplayInfo = GetConsole()->GetCVar("r_DisplayInfo");
- assert(pDisplayInfo);
- if (pDisplayInfo && pDisplayInfo->GetIVal() == 0)
- {
- return;
- }
-
- if (gEnv->IsDedicated())
- {
- return;
- }
-
-#if defined(INFO_FRAME_COUNTER)
- static int frameCounter = 0;
-#endif
- GetRenderer()->SetState(GS_NODEPTHTEST);
-
- fTextPosY = -10;
- fTextStepY = 13;
- fTextPosX = (float)GetRenderer()->GetOverlayWidth() - 5.0f;
-
- const char* description = GetRenderer()->GetRenderDescription();
- if (description && description[0] != 0)
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, 1.5f, ColorF(1.0f, 1.0f, 0.5f, 1.0f),
- "%s", description);
- }
-
- // If stat averaging is on, compute blend amount for current stats.
- float fFPS = GetTimer()->GetFrameRate();
-
- // Limit the FPS history for a single level to ~1 hour.
- // This vector is cleared on each level load, but during a soak test this continues to grow every frame
- const AZStd::size_t maxFPSEntries = 60 * 60 * 60; // 60ms * 60s * 60min
- if (arrFPSforSaveLevelStats.size() < maxFPSEntries)
- {
- arrFPSforSaveLevelStats.push_back(SATURATEB((int)fFPS));
- }
-
- float fBlendTime = GetTimer()->GetCurrTime();
- int iBlendMode = 0;
- float fBlendCur = GetTimer()->GetProfileFrameBlending(&fBlendTime, &iBlendMode);
-
- if (pDisplayInfo && pDisplayInfo->GetIVal() == 3)
- {
- static float fCurrentFPS, fCurrentFrameTime;
- Blend(fCurrentFPS, fFPS, fBlendCur);
- Blend(fCurrentFrameTime, GetTimer()->GetRealFrameTime() * 1000.0f, fBlendCur);
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, 1.5f, ColorF(1.0f, 1.0f, 0.5f, 1.0f),
- "FPS %.1f - %.1fms", fCurrentFPS, fCurrentFrameTime);
- return;
- }
-
- // make level name
- char szLevelName[128];
-
- *szLevelName = 0;
- {
- int ii;
- for (ii = strlen(m_szLevelFolder) - 2; ii > 0; ii--)
- {
- if (m_szLevelFolder[ii] == '\\' || m_szLevelFolder[ii] == '/')
- {
- break;
- }
- }
-
- if (ii >= 0)
- {
- cry_strcpy(szLevelName, &m_szLevelFolder[ii + 1]);
-
- for (int i = strlen(szLevelName) - 1; i > 0; i--)
- {
- if (szLevelName[i] == '\\' || szLevelName[i] == '/')
- {
- szLevelName[i] = 0;
- }
- }
- }
- }
-
- Matrix33 m = Matrix33(GetRenderingCamera().GetMatrix());
- //m.OrthonormalizeFast(); // why is that needed? is it?
- Ang3 aAng = RAD2DEG(Ang3::GetAnglesXYZ(m));
- Vec3 vPos = GetRenderingCamera().GetPosition();
-
- // Time of day info
- int hours = 0;
- int minutes = 0;
- ITimeOfDay* timeOfDay = GetTimeOfDay();
- if (timeOfDay)
- {
- float time = timeOfDay->GetTime();
- hours = (int)time;
- minutes = (int)((time - hours) * 60);
- }
-
- // display out of memory message if an allocation failed
- IF (gEnv->bIsOutOfMemory, 0)
- {
- ColorF fColor(1.0f, 0.0f, 0.0f, 1.0f);
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, 4.0f, fColor, "**** Out of Memory ****");
- fTextPosY += 40.0f;
- }
- // display out of memory message if an allocation failed
- IF (gEnv->bIsOutOfVideoMemory, 0)
- {
- ColorF fColor(1.0f, 0.0f, 0.0f, 1.0f);
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, 4.0f, fColor, "**** Out of Video Memory ****");
- fTextPosY += 40.0f;
- }
-
- float fogCullDist = 0.0f;
- Vec2 vViewportScale = Vec2(0.0f, 0.0f);
- m_pRenderer->EF_Query(EFQ_GetFogCullDistance, fogCullDist);
- m_pRenderer->EF_Query(EFQ_GetViewportDownscaleFactor, vViewportScale);
-
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "CamPos=%.2f %.2f %.2f Angl=%3d %2d %3d ZN=%.2f ZF=%d",
- vPos.x, vPos.y, vPos.z, (int)aAng.x, (int)aAng.y, (int)aAng.z,
- GetRenderingCamera().GetNearPlane(), (int)GetRenderingCamera().GetFarPlane());
-
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "Cam FC=%.2f VS=%.2f,%.2f Zoom=%.2f Speed=%1.2f TimeOfDay=%02d:%02d",
- fogCullDist, vViewportScale.x, vViewportScale.y,
- GetZoomFactor(), GetAverageCameraSpeed(), hours, minutes);
-
- // get version
- const SFileVersion& ver = GetSystem()->GetFileVersion();
- //char sVersion[128];
- //ver.ToString(sVersion);
-
- // Get memory usage.
- static IMemoryManager::SProcessMemInfo processMemInfo;
- {
- static int nGetMemInfoCount = 0;
- if ((nGetMemInfoCount & 0x1F) == 0 && GetISystem()->GetIMemoryManager())
- {
- // Only get mem stats every 32 frames.
- GetISystem()->GetIMemoryManager()->GetProcessMemInfo(processMemInfo);
- }
- nGetMemInfoCount++;
- }
-
- bool bMultiGPU;
- m_pRenderer->EF_Query(EFQ_MultiGPUEnabled, bMultiGPU);
-
- const char* pRenderType(0);
-
- if (AZ::Interface::Get())
- {
- pRenderType = "DX11";
- }
- else
- {
- switch (gEnv->pRenderer->GetRenderType())
- {
- case eRT_OpenGL:
- pRenderType = "GL";
- break;
- case eRT_DX11:
- pRenderType = "DX11";
- break;
- case eRT_DX12:
- pRenderType = "DX12";
- break;
- case eRT_Jasper:
- pRenderType = "Jasper";
- break;
- case eRT_Provo:
- pRenderType = "Provo";
- break;
- case eRT_Metal:
- pRenderType = "Metal";
- break;
- case eRT_Null:
- pRenderType = "Null";
- break;
- case eRT_Undefined:
- default:
- assert(0);
- pRenderType = "Undefined";
- break;
- }
- }
- assert(gEnv->pSystem);
- bool bTextureStreamingEnabled = false;
- m_pRenderer->EF_Query(EFQ_TextureStreamingEnabled, bTextureStreamingEnabled);
- const bool bCGFStreaming = GetCVars()->e_StreamCgf && m_pObjManager;
- const bool bTexStreaming = gEnv->pSystem->GetStreamEngine() && bTextureStreamingEnabled;
- char szFlags[128], * szFlagsEnd = szFlags;
-
-#ifndef _RELEASE
- ESystemConfigSpec spec = GetISystem()->GetConfigSpec();
- switch (spec)
- {
- case CONFIG_AUTO_SPEC:
- AppendString(szFlagsEnd, "Auto");
- break;
- case CONFIG_LOW_SPEC:
- AppendString(szFlagsEnd, "LowSpec");
- break;
- case CONFIG_MEDIUM_SPEC:
- AppendString(szFlagsEnd, "MedSpec");
- break;
- case CONFIG_HIGH_SPEC:
- AppendString(szFlagsEnd, "HighSpec");
- break;
- case CONFIG_VERYHIGH_SPEC:
- AppendString(szFlagsEnd, "VeryHighSpec");
- break;
- default:
- assert(0);
- }
-#endif
-#ifndef CONSOLE_CONST_CVAR_MODE
- static ICVar* pMultiThreaded = GetConsole()->GetCVar("r_MultiThreaded");
- if (pMultiThreaded && pMultiThreaded->GetIVal() > 0)
-#endif
- AppendString(szFlagsEnd, "MT");
-
- char* sAAMode = NULL;
- m_pRenderer->EF_Query(EFQ_AAMode, sAAMode);
- AppendString(szFlagsEnd, sAAMode);
-
- if (IsAreaActivationInUse())
- {
- AppendString(szFlagsEnd, "LA");
- }
-
- if (bMultiGPU)
- {
- AppendString(szFlagsEnd, "MGPU");
- }
-
- if (gEnv->pSystem->IsDevMode())
- {
- AppendString(szFlagsEnd, gEnv->IsEditor() ? "DevMode (Editor)" : "DevMode");
- }
-
- if (bCGFStreaming || bTexStreaming)
- {
- if (bCGFStreaming && !bTexStreaming)
- {
- AppendString(szFlagsEnd, "StG");
- }
- if (bTexStreaming && !bCGFStreaming)
- {
- AppendString(szFlagsEnd, "StT");
- }
- if (bTexStreaming && bCGFStreaming)
- {
- AppendString(szFlagsEnd, "StGT");
- }
- }
-
- // remove last space
- if (szFlags != szFlagsEnd)
- {
- *(szFlagsEnd - 1) = 0;
- }
-#ifdef _RELEASE
- const char* mode = "Release";
-#else
- const char* mode = "Profile";
-#endif
-
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "%s %s %dbit %s %s [%d.%d]",
- pRenderType, mode, (int)sizeof(char*) * 8, szFlags, szLevelName, ver.v[1], ver.v[0]);
-
- // Polys in scene
- int nPolygons, nShadowPolygons;
- GetRenderer()->GetPolyCount(nPolygons, nShadowPolygons);
- int nDrawCalls, nShadowGenDrawCalls;
- GetRenderer()->GetCurrentNumberOfDrawCalls(nDrawCalls, nShadowGenDrawCalls);
-
- int nGeomInstances = GetRenderer()->GetNumGeomInstances();
- int nGeomInstanceDrawCalls = GetRenderer()->GetNumGeomInstanceDrawCalls();
-
- if (fBlendCur != 1.f)
- {
- // Smooth over time.
- static float fPolygons, fShadowVolPolys, fDrawCalls, fShadowGenDrawCalls, fGeomInstances, fGeomInstanceDrawCalls;
- Blend(fPolygons, nPolygons, fBlendCur);
- Blend(fShadowVolPolys, nShadowPolygons, fBlendCur);
- Blend(fDrawCalls, nDrawCalls, fBlendCur);
- Blend(fShadowGenDrawCalls, nShadowGenDrawCalls, fBlendCur);
- Blend(fGeomInstances, nGeomInstances, fBlendCur);
- Blend(fGeomInstanceDrawCalls, nGeomInstanceDrawCalls, fBlendCur);
- }
-
- //
- static float m_lastAverageDPTime = -FLT_MAX;
- float curTime = gEnv->pTimer->GetAsyncCurTime();
- static int lastDrawCalls = 0;
- static int lastShadowGenDrawCalls = 0;
- static int avgPolys = 0;
- static int avgShadowPolys = 0;
- static int sumPolys = 0;
- static int sumShadowPolys = 0;
- static int nPolysFrames = 0;
- if (curTime < m_lastAverageDPTime)
- {
- m_lastAverageDPTime = curTime;
- }
- if (curTime - m_lastAverageDPTime > 1.0f)
- {
- lastDrawCalls = nDrawCalls;
- lastShadowGenDrawCalls = nShadowGenDrawCalls;
- m_lastAverageDPTime = curTime;
- avgPolys = nPolysFrames ? sumPolys / nPolysFrames : 0;
- avgShadowPolys = nPolysFrames ? sumShadowPolys / nPolysFrames : 0;
- sumPolys = nPolygons;
- sumShadowPolys = nShadowPolygons;
- nPolysFrames = 1;
- }
- else
- {
- nPolysFrames++;
- sumPolys += nPolygons;
- sumShadowPolys += nShadowPolygons;
- }
- //
-
- int nMaxDrawCalls = GetCVars()->e_MaxDrawCalls <= 0 ? 2000 : GetCVars()->e_MaxDrawCalls;
- bool bInRed = (nDrawCalls + nShadowGenDrawCalls) > nMaxDrawCalls;
-
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, bInRed ? Col_Red : Col_White, "DP: %04d (%04d) ShadowGen:%04d (%04d) - Total: %04d Instanced: %04d",
- nDrawCalls, lastDrawCalls, nShadowGenDrawCalls, lastShadowGenDrawCalls, nDrawCalls + nShadowGenDrawCalls, nDrawCalls + nShadowGenDrawCalls - nGeomInstances + nGeomInstanceDrawCalls);
-#if defined(MOBILE)
- bInRed = nPolygons > 500000;
-#else
- bInRed = nPolygons > 1500000;
-#endif
-
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, bInRed ? Col_Red : Col_White, "Polys: %03d,%03d (%03d,%03d) Shadow:%03d,%03d (%03d,%03d)",
- nPolygons / 1000, nPolygons % 1000, avgPolys / 1000, avgPolys % 1000,
- nShadowPolygons / 1000, nShadowPolygons % 1000, avgShadowPolys / 1000, avgShadowPolys % 1000);
-
- {
- SShaderCacheStatistics stats;
- m_pRenderer->EF_Query(EFQ_GetShaderCacheInfo, stats);
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, Col_White, "ShaderCache: %d GCM | %d Async Reqs | Compile: %s",
- (int)stats.m_nGlobalShaderCacheMisses, (int)stats.m_nNumShaderAsyncCompiles, stats.m_bShaderCompileActive ? "On" : "Off");
- }
- }
-
- // print stats about CGF's streaming
- if (bCGFStreaming)
- {
- static char szCGFStreaming[256] = "";
- static SObjectsStreamingStatus objectsStreamingStatus = {0};
-
- if (!(GetRenderer()->GetFrameID(false) & 15) || !szCGFStreaming[0] || GetCVars()->e_StreamCgfDebug)
- {
- m_pObjManager->GetObjectsStreamingStatus(objectsStreamingStatus);
- sprintf_s(szCGFStreaming, 256, "CgfStrm: Loaded:%d InProg:%d All:%d Act:%d PcP:%d MemUsed:%2.2f MemReq:%2.2f Pool:%d",
- objectsStreamingStatus.nReady, objectsStreamingStatus.nInProgress, objectsStreamingStatus.nTotal, objectsStreamingStatus.nActive,
- (int)m_pObjManager->GetStreamPreCachePointDefs().size(),
- float(objectsStreamingStatus.nAllocatedBytes) / 1024 / 1024, float(objectsStreamingStatus.nMemRequired) / 1024 / 1024, GetCVars()->e_StreamCgfPoolSize);
- }
-
- bool bOutOfMem((float(objectsStreamingStatus.nMemRequired) / 1024 / 1024) > GetCVars()->e_StreamCgfPoolSize);
- bool bCloseToOutOfMem((float(objectsStreamingStatus.nMemRequired) / 1024 / 1024) > GetCVars()->e_StreamCgfPoolSize * 90 / 100);
-
- ColorF color = Col_White;
- if (bOutOfMem)
- {
- color = Col_Red;
- }
- else if (bCloseToOutOfMem)
- {
- color = Col_Orange;
- }
- // if(bTooManyRequests)
- // color = Col_Magenta;
-
- if ((pDisplayInfo->GetIVal() == 2 || GetCVars()->e_StreamCgfDebug) || bOutOfMem || bCloseToOutOfMem)
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, color, szCGFStreaming);
- }
- }
-
- // print stats about textures' streaming
- if (bTexStreaming)
- {
- static char szTexStreaming[256] = "";
- static bool bCloseToOutOfMem = false;
- static bool bOutOfMem = false;
- static bool bTooManyRequests = false;
- static bool bOverloadedPool = false;
- static uint32 nTexCount = 0;
- static uint32 nTexSize = 0;
-
- float fTexBandwidthRequired = 0.f;
- m_pRenderer->GetBandwidthStats(&fTexBandwidthRequired);
-
- if (!(GetRenderer()->GetFrameID(false) % 30) || !szTexStreaming[0])
- {
- STextureStreamingStats stats(!(GetRenderer()->GetFrameID(false) % 120));
- m_pRenderer->EF_Query(EFQ_GetTexStreamingInfo, stats);
-
- if (!(GetRenderer()->GetFrameID(false) % 120))
- {
- bOverloadedPool = stats.bPoolOverflowTotally;
- nTexCount = stats.nRequiredStreamedTexturesCount;
- nTexSize = stats.nRequiredStreamedTexturesSize;
- }
-
- int nPlatformSize = nTexSize;
-
- const int iPercentage = int((float)stats.nCurrentPoolSize / stats.nMaxPoolSize * 100.f);
- const int iStaticPercentage = int((float)stats.nStaticTexturesSize / stats.nMaxPoolSize * 100.f);
- sprintf_s(szTexStreaming, "TexStrm: TexRend: %u NumTex: %u Req:%.1fMB Mem(strm/stat/tot):%.1f/%.1f/%.1fMB(%d%%/%d%%) PoolSize:%" PRISIZE_T "MB PoolFrag:%.1f%%",
- stats.nNumTexturesPerFrame, nTexCount, (float)nPlatformSize / 1024 / 1024,
- (float)stats.nStreamedTexturesSize / 1024 / 1024, (float)stats.nStaticTexturesSize / 1024 / 1024, (float)stats.nCurrentPoolSize / 1024 / 1024,
- iPercentage, iStaticPercentage, stats.nMaxPoolSize / 1024 / 1024,
- stats.fPoolFragmentation * 100.0f
- );
- bOverloadedPool |= stats.bPoolOverflowTotally;
-
- bCloseToOutOfMem = iPercentage >= 90;
- bOutOfMem = stats.bPoolOverflow;
- }
-
- if (pDisplayInfo->GetIVal() == 2 || bCloseToOutOfMem || bTooManyRequests || bOverloadedPool)
- {
- ColorF color = Col_White;
- if (bOutOfMem)
- {
- color = Col_Red;
- }
- else if (bCloseToOutOfMem)
- {
- color = Col_Orange;
- }
- if (bTooManyRequests)
- {
- color = Col_Magenta;
- }
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, color, "%s", szTexStreaming);
- }
-
- if (pDisplayInfo->GetIVal() > 0 && bOverloadedPool)
- {
- DrawTextLeftAligned(0, 10, 2.3f, Col_Red, "Texture pool totally overloaded!");
- }
- }
-
-
-
- {
- static char szMeshPoolUse[256] = "";
- static unsigned nFlushFrameId = 0U;
- static unsigned nFallbackFrameId = 0U;
- static SMeshPoolStatistics lastStats;
- static SMeshPoolStatistics stats;
-
- const unsigned nMainFrameId = GetRenderer()->GetFrameID(false);
- m_pRenderer->EF_Query(EFQ_GetMeshPoolInfo, stats);
- const int iPercentage = int((float)stats.nPoolInUse / (stats.nPoolSize ? stats.nPoolSize : 1U) * 100.f);
- const int iVolatilePercentage = int((float)stats.nInstancePoolInUse / (stats.nInstancePoolSize ? stats.nInstancePoolSize : 1U) * 100.f);
- nFallbackFrameId = lastStats.nFallbacks < stats.nFallbacks ? nMainFrameId : nFallbackFrameId;
- nFlushFrameId = lastStats.nFlushes < stats.nFlushes ? nMainFrameId : nFlushFrameId;
- const bool bOverflow = nMainFrameId - nFlushFrameId < 50;
- const bool bFallback = nMainFrameId - nFallbackFrameId < 50;
-
- sprintf_s(szMeshPoolUse,
- "Mesh Pool: MemUsed:%.2fKB(%d%%%%) Peak %.fKB PoolSize:%" PRISIZE_T "KB Flushes %" PRISIZE_T " Fallbacks %.3fKB %s",
- (float)stats.nPoolInUse / 1024,
- iPercentage,
- (float)stats.nPoolInUsePeak / 1024,
- stats.nPoolSize / 1024,
- stats.nFlushes,
- (float)stats.nFallbacks / 1024.0f,
- (bFallback ? "FULL!" : bOverflow ? "OVERFLOW" : ""));
-
- if (stats.nPoolSize && (pDisplayInfo->GetIVal() == 2 || bOverflow || bFallback))
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE,
- bFallback ? Col_Red : bOverflow ? Col_Orange : Col_White,
- szMeshPoolUse);
- }
- if (stats.nPoolSize && pDisplayInfo->GetIVal() == 2)
- {
- char szVolatilePoolsUse[256];
- sprintf_s(szVolatilePoolsUse,
- "Mesh Instance Pool: MemUsed:%.2fKB(%d%%%%) Peak %.fKB PoolSize:%" PRISIZE_T "KB Fallbacks %.3fKB",
- (float)stats.nInstancePoolInUse / 1024,
- iVolatilePercentage,
- (float)stats.nInstancePoolInUsePeak / 1024,
- stats.nInstancePoolSize / 1024,
- (float)stats.nInstanceFallbacks / 1024.0f);
-
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE,
- Col_White, szVolatilePoolsUse);
- }
-
- memcpy(&lastStats, &stats, sizeof(lastStats));
- }
-
- // streaming info
- {
- IStreamEngine* pSE = gEnv->pSystem->GetStreamEngine();
- if (pSE)
- {
- SStreamEngineStatistics& stats = pSE->GetStreamingStatistics();
- SStreamEngineOpenStats openStats;
- pSE->GetStreamingOpenStatistics(openStats);
-
- static char szStreaming[128] = "";
- if (!(GetRenderer()->GetFrameID(false) & 7))
- {
- if (pDisplayInfo->GetIVal() == 2)
- {
- sprintf_s(szStreaming, "Streaming IO: ACT: %3dmsec, Jobs:%2d Total:%5d",
- (uint32)stats.fAverageCompletionTime, openStats.nOpenRequestCount, stats.nTotalStreamingRequestCount);
- }
- else
- {
- sprintf_s(szStreaming, "Streaming IO: ACT: %3dmsec, Jobs:%2d",
- (uint32)stats.fAverageCompletionTime, openStats.nOpenRequestCount);
- }
- }
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, szStreaming);
-
- if (stats.bTempMemOutOfBudget)
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, 1.3f, Col_Red, "Temporary Streaming Memory Pool Out of Budget!");
- }
- }
-
- if (pDisplayInfo && pDisplayInfo->GetIVal() == 2) // more streaming info
- {
- SStreamEngineStatistics& stats = gEnv->pSystem->GetStreamEngine()->GetStreamingStatistics();
-
- { // HDD stats
- static char szStreaming[512] = "";
- sprintf_s(szStreaming, "HDD: BW:%1.2f|%1.2fMb/s (Eff:%2.1f|%2.1fMb/s) - Seek:%1.2fGB - Active:%2.1f%%%%",
- (float)stats.hddInfo.nCurrentReadBandwidth / (1024 * 1024), (float)stats.hddInfo.nSessionReadBandwidth / (1024 * 1024),
- (float)stats.hddInfo.nActualReadBandwidth / (1024 * 1024), (float)stats.hddInfo.nAverageActualReadBandwidth / (1024 * 1024),
- (float)stats.hddInfo.nAverageSeekOffset / (1024 * 1024), stats.hddInfo.fAverageActiveTime);
-
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, szStreaming);
- }
- }
- }
-
- //////////////////////////////////////////////////////////////////////////
- // Display Info about dynamic lights.
- //////////////////////////////////////////////////////////////////////////
- {
- {
-#ifndef _RELEASE
- // Checkpoint loading information
- if (!gEnv->bMultiplayer)
- {
- ISystem::ICheckpointData data;
- gEnv->pSystem->GetCheckpointData(data);
-
- if (data.m_loadOrigin != ISystem::eLLO_Unknown)
- {
- static const char* loadStates[] =
- {
- "",
- "New Level",
- "Level to Level",
- "Resumed Game",
- "Map Command",
- };
-
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, 1.3f, Col_White, "%s, Checkpoint loads: %i", loadStates[(int)data.m_loadOrigin], (int)data.m_totalLoads);
- }
- }
-#endif
-
- int nPeakMemMB = (int)(processMemInfo.PeakPagefileUsage >> 20);
- int nVirtMemMB = (int)(processMemInfo.PagefileUsage >> 20);
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "Mem=%d Peak=%d DLights=(%d)", nVirtMemMB, nPeakMemMB, m_nRealLightsNum + m_nDeferredLightsNum);
-
- uint32 nShadowFrustums = 0;
- uint32 nShadowAllocs = 0;
- uint32 nShadowMaskChannels = 0;
- m_pRenderer->EF_Query(EFQ_GetShadowPoolFrustumsNum, nShadowFrustums);
- m_pRenderer->EF_Query(EFQ_GetShadowPoolAllocThisFrameNum, nShadowAllocs);
- m_pRenderer->EF_Query(EFQ_GetShadowMaskChannelsNum, nShadowMaskChannels);
- bool bThrash = (nShadowAllocs & 0x80000000) ? true : false;
- nShadowAllocs &= ~0x80000000;
- uint32 nAvailableShadowMaskChannels = nShadowMaskChannels >> 16;
- uint32 nUsedShadowMaskChannels = nShadowMaskChannels & 0xFFFF;
- bool bTooManyLights = nUsedShadowMaskChannels > nAvailableShadowMaskChannels ? true : false;
-
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, (nShadowFrustums || nShadowAllocs) ? Col_Yellow : Col_White, "%d Shadow Mask Channels, %3d Shadow Frustums, %3d Frustum Renders This Frame",
- nUsedShadowMaskChannels, nShadowFrustums, nShadowAllocs);
-
- if (bThrash)
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, Col_Red, "SHADOW POOL THRASHING!!!");
- }
-
- if (bTooManyLights)
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, Col_Red, "TOO MANY SHADOW CASTING LIGHTS (%d/%d)!!!", nUsedShadowMaskChannels, nAvailableShadowMaskChannels);
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, Col_Red, "Consider increasing 'r_ShadowCastingLightsMaxCount'");
- }
-
-#ifndef _RELEASE
- uint32 numTiledShadingSkippedLights;
- m_pRenderer->EF_Query(EFQ_GetTiledShadingSkippedLightsNum, numTiledShadingSkippedLights);
- if (numTiledShadingSkippedLights > 0)
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, Col_Red, "TILED SHADING: SKIPPED %d LIGHTS", numTiledShadingSkippedLights);
- }
-
- if (GetCVars()->e_levelStartupFrameNum)
- {
- static float startupAvgFPS = 0.f;
- static float levelStartupTime = 0;
- static int levelStartupFrameEnd = GetCVars()->e_levelStartupFrameNum + GetCVars()->e_levelStartupFrameDelay;
- int curFrameID = GetRenderer()->GetFrameID(false);
-
- if (curFrameID >= GetCVars()->e_levelStartupFrameDelay)
- {
- if (curFrameID == GetCVars()->e_levelStartupFrameDelay)
- {
- levelStartupTime = gEnv->pTimer->GetAsyncCurTime();
- }
- if (curFrameID == levelStartupFrameEnd)
- {
- startupAvgFPS = (float)GetCVars()->e_levelStartupFrameNum / (gEnv->pTimer->GetAsyncCurTime() - levelStartupTime);
- }
- if (curFrameID >= levelStartupFrameEnd)
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, 2.f, Col_Red, "Startup AVG FPS: %.2f", startupAvgFPS);
- fTextPosY += fTextStepY;
- }
- }
- }
-#endif //_RELEASE
- }
-
- m_nDeferredLightsNum = 0;
- }
-
- assert(pDisplayInfo);
- if (bEnhanced)
- {
-#define CONVX(x) (((x) / (float)gUpdateTimesNum))
-#define CONVY(y) (1.f - ((y) / 720.f))
-#define TICKS_TO_MS(t) (1000.f * gEnv->pTimer->TicksToSeconds(t))
-# define MAX_PHYS_TIME 32.f
-# define MAX_PLE_TIME 4.f
- uint32 gUpdateTimeIdx = 0, gUpdateTimesNum = 0;
- const sUpdateTimes* gUpdateTimes = gEnv->pSystem->GetUpdateTimeStats(gUpdateTimeIdx, gUpdateTimesNum);
- if (pDisplayInfo->GetIVal() >= 5)
- {
- const SAuxGeomRenderFlags flags = gEnv->pRenderer->GetIRenderAuxGeom()->GetRenderFlags();
- SAuxGeomRenderFlags newFlags(flags);
- newFlags.SetAlphaBlendMode(e_AlphaNone);
- newFlags.SetMode2D3DFlag(e_Mode2D);
- newFlags.SetCullMode(e_CullModeNone);
- newFlags.SetDepthWriteFlag(e_DepthWriteOff);
- newFlags.SetDepthTestFlag(e_DepthTestOff);
- newFlags.SetFillMode(e_FillModeSolid);
- gEnv->pRenderer->GetIRenderAuxGeom()->SetRenderFlags(newFlags);
- const ColorF colorPhysFull = Col_Blue;
- const ColorF colorSysFull = Col_Green;
- const ColorF colorRenFull = Col_Red;
- const ColorF colorPhysHalf = colorPhysFull * 0.15f;
- const ColorF colorSysHalf = colorSysFull * 0.15f;
- const ColorF colorRenHalf = colorRenFull * 0.15f;
- float phys = (TICKS_TO_MS(gUpdateTimes[0].PhysStepTime) / 66.f) * 720.f;
- float sys = (TICKS_TO_MS(gUpdateTimes[0].SysUpdateTime) / 66.f) * 720.f;
- float ren = (TICKS_TO_MS(gUpdateTimes[0].RenderTime) / 66.f) * 720.f;
- float _lerp = ((float)(max((int)gUpdateTimeIdx - (int)0, 0) / (float)gUpdateTimesNum));
- ColorB colorPhysLast;
- colorPhysLast.lerpFloat(colorPhysFull, colorPhysHalf, _lerp);
- ColorB colorSysLast;
- colorSysLast.lerpFloat(colorSysFull, colorSysHalf, _lerp);
- ColorB colorRenLast;
- colorRenLast.lerpFloat(colorRenFull, colorRenHalf, _lerp);
- Vec3 lastPhys(CONVX(0), CONVY(phys), 1.f);
- Vec3 lastSys(CONVX(0), CONVY(sys), 1.f);
- Vec3 lastRen(CONVX(0), CONVY(ren), 1.f);
- for (uint32 i = 0; i < gUpdateTimesNum; ++i)
- {
- const float x = (float)i;
- _lerp = ((float)(max((int)gUpdateTimeIdx - (int)i, 0) / (float)gUpdateTimesNum));
- const sUpdateTimes& sample = gUpdateTimes[i];
- phys = (TICKS_TO_MS(sample.PhysStepTime) / 66.f) * 720.f;
- sys = (TICKS_TO_MS(sample.SysUpdateTime) / 66.f) * 720.f;
- ren = (TICKS_TO_MS(sample.RenderTime) / 66.f) * 720.f;
- Vec3 curPhys(CONVX(x), CONVY(phys), 1.f);
- Vec3 curSys(CONVX(x), CONVY(sys), 1.f);
- Vec3 curRen(CONVX(x), CONVY(ren), 1.f);
- ColorB colorPhys;
- colorPhys.lerpFloat(colorPhysFull, colorPhysHalf, _lerp);
- ColorB colorSys;
- colorSys.lerpFloat(colorSysFull, colorSysHalf, _lerp);
- ColorB colorRen;
- colorRen.lerpFloat(colorRenFull, colorRenHalf, _lerp);
- gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(lastPhys, colorPhysLast, curPhys, colorPhys);
- gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(lastSys, colorSysLast, curSys, colorSys);
- gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(lastRen, colorRenLast, curRen, colorRen);
- lastPhys = curPhys;
- colorPhysLast = colorPhys;
- lastSys = curSys;
- colorSysLast = colorSys;
- lastRen = curRen;
- colorRenLast = colorRen;
- }
- gEnv->pRenderer->GetIRenderAuxGeom()->SetRenderFlags(flags);
- }
- const float curPhysTime = TICKS_TO_MS(gUpdateTimes[gUpdateTimeIdx].PhysStepTime);
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE_SMALL, curPhysTime > MAX_PHYS_TIME ? Col_Red : Col_White, "%3.1f ms Phys", curPhysTime);
- const float curPhysWaitTime = TICKS_TO_MS(gUpdateTimes[gUpdateTimeIdx].physWaitTime);
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE_SMALL, curPhysTime > MAX_PHYS_TIME ? Col_Red : Col_White, "%3.1f ms WaitPhys", curPhysWaitTime);
-
- float partTicks = 0;
-
- //3dengine stats from RenderWorld
- {
-#if defined(MOBILE)
- const float maxVal = 12.f;
-#else
- const float maxVal = 50.f;
-#endif
- float fTimeMS = TICKS_TO_MS(m_nRenderWorldUSecs) - partTicks;
- DrawTextRightAligned(fTextPosX, fTextPosY += (fTextStepY - STEP_SMALL_DIFF), DISPLAY_INFO_SCALE_SMALL, fTimeMS > maxVal ? Col_Red : Col_White, "%.2f ms RendWorld", fTimeMS);
- }
-
- {
- SStreamEngineStatistics stat = gEnv->pSystem->GetStreamEngine()->GetStreamingStatistics();
-
- float fTimeMS = 1000.0f * gEnv->pTimer->TicksToSeconds(stat.nMainStreamingThreadWait);
- DrawTextRightAligned(fTextPosX, fTextPosY += (fTextStepY - STEP_SMALL_DIFF),
- DISPLAY_INFO_SCALE_SMALL, Col_White, "%3.1f ms StreamFin", fTimeMS);
- }
- }
-
-#undef MAX_PHYS_TIME
-#undef TICKS_TO_MS
-#undef CONVY
-#undef CONVX
-
- //////////////////////////////////////////////////////////////////////////
- // Display Thermal information of the device (if supported)
- //////////////////////////////////////////////////////////////////////////
-
- if (ThermalInfoRequestsBus::GetTotalNumOfEventHandlers())
- {
- const int thermalSensorCount = static_cast(ThermalSensorType::Count);
- const char* sensorStrings[thermalSensorCount] = { "CPU", "GPU", "Battery" };
- for (int i = 0; i < thermalSensorCount; ++i)
- {
- float temperature = 0.f;
- ThermalSensorType sensor = static_cast(i);
- EBUS_EVENT_RESULT(temperature, ThermalInfoRequestsBus, GetSensorTemp, sensor);
- AZStd::string tempText;
- ColorF tempColor;
- if (temperature > 0.f)
- {
- float overheatingTemp = 0.f;
- EBUS_EVENT_RESULT(overheatingTemp, ThermalInfoRequestsBus, GetSensorOverheatingTemp, sensor);
- tempText = AZStd::string::format(" %.1f C", temperature);
- tempColor = temperature >= overheatingTemp ? Col_Red : Col_White;
- }
- else
- {
- tempText = "N/A";
- tempColor = Col_White;
- }
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE, tempColor, "%s Temp %s", sensorStrings[i], tempText.c_str());
- }
- }
-
- //////////////////////////////////////////////////////////////////////////
- // Display Current fps
- //////////////////////////////////////////////////////////////////////////
-
- if (iBlendMode)
- {
- // Track FPS frequency, report min/max.
- Blend(m_fAverageFPS, fFPS, fBlendCur);
-
- Blend(m_fMinFPSDecay, fFPS, fBlendCur);
- if (fFPS <= m_fMinFPSDecay)
- {
- m_fMinFPS = m_fMinFPSDecay = fFPS;
- }
-
- Blend(m_fMaxFPSDecay, fFPS, fBlendCur);
- if (fFPS >= m_fMaxFPSDecay)
- {
- m_fMaxFPS = m_fMaxFPSDecay = fFPS;
- }
-
- const char* sMode = "";
- switch (iBlendMode)
- {
- case 1:
- sMode = "frame avg";
- break;
- case 2:
- sMode = "time avg";
- break;
- case 3:
- sMode = "peak hold";
- break;
- }
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, 1.5f, ColorF(1.0f, 1.0f, 0.5f, 1.0f),
- "FPS %.1f [%.0f..%.0f], %s over %.1f s",
- m_fAverageFPS, m_fMinFPS, m_fMaxFPS, sMode, fBlendTime);
- }
- else
- {
- const int nHistorySize = 16;
- static float arrfFrameRateHistory[nHistorySize] = {0};
-
- static int nFrameId = 0;
- nFrameId++;
- int nSlotId = nFrameId % nHistorySize;
- assert(nSlotId >= 0 && nSlotId < nHistorySize);
- arrfFrameRateHistory[nSlotId] = min(9999.f, GetTimer()->GetFrameRate());
-
- float fMinFPS = 9999.0f;
- float fMaxFPS = 0;
- for (int i = 0; i < nHistorySize; i++)
- {
- if (arrfFrameRateHistory[i] < fMinFPS)
- {
- fMinFPS = arrfFrameRateHistory[i];
- }
- if (arrfFrameRateHistory[i] > fMaxFPS)
- {
- fMaxFPS = arrfFrameRateHistory[i];
- }
- }
-
- float fFrameRate = 0;
- float fValidFrames = 0;
- for (int i = 0; i < nHistorySize; i++)
- {
- int s = (nFrameId - i) % nHistorySize;
- fFrameRate += arrfFrameRateHistory[s];
- fValidFrames++;
- }
- fFrameRate /= fValidFrames;
-
- m_fAverageFPS = fFrameRate;
- m_fMinFPS = m_fMinFPSDecay = fMinFPS;
- m_fMaxFPS = m_fMaxFPSDecay = fMaxFPS;
-
-
- //only difference to r_DisplayInfo 1, need ms for GPU time
- float fMax = (int(GetCurTimeSec() * 2) & 1) ? 999.f : 888.f;
- if (bEnhanced)
- {
- /* DrawTextRightAligned( fTextPosX, fTextPosY+=fTextStepY, "%6.2f ~%6.2f ms (%6.2f..%6.2f) CPU",
- GetTimer()->GetFrameTime()*1000.0f, 1000.0f/max(0.0001f,fFrameRate),
- 1000.0f/max(0.0001f,fMinFPS),
- 1000.0f/max(0.0001f,fMaxFPS));
- */
- const RPProfilerStats* pFrameRPPStats = GetRenderer()->GetRPPStats(eRPPSTATS_OverallFrame);
- float gpuTime = pFrameRPPStats ? pFrameRPPStats->gpuTime : 0.0f;
- static float sGPUTime = 0.f;
- if (gpuTime < 1000.f && gpuTime > 0.01f)
- {
- sGPUTime = gpuTime; //catch sporadic jumps
- }
- if (sGPUTime > 0.01f)
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, DISPLAY_INFO_SCALE_SMALL, (gpuTime >= 40.f) ? Col_Red : Col_White, "%3.1f ms GPU", sGPUTime);
- }
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, 1.4f, ColorF(1.0f, 1.0f, 0.2f, 1.0f), "FPS %5.1f (%3d..%3d)(%3.1f ms)",
- min(fMax, fFrameRate), (int)min(fMax, fMinFPS), (int)min(fMax, fMaxFPS), GetTimer()->GetFrameTime() * 1000.0f);
- }
- else
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, 1.4f, ColorF(1.0f, 1.0f, 0.2f, 1.0f), "FPS %5.1f (%3d..%3d)",
- min(fMax, fFrameRate), (int)min(fMax, fMinFPS), (int)min(fMax, fMaxFPS));
- }
- }
-
-#ifndef _RELEASE
- if (GetCVars()->e_GsmStats)
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "--------------- GSM Stats ---------------");
-
- if (m_pSun && m_pSun->m_pShadowMapInfo)
- {
- CLightEntity::ShadowMapInfo* pSMI = m_pSun->m_pShadowMapInfo;
- int arrGSMCastersCount[MAX_GSM_LODS_NUM];
- memset(arrGSMCastersCount, 0, sizeof(arrGSMCastersCount));
- char szText[256] = "Objects count per shadow map: ";
- for (int nLod = 0; nLod < Get3DEngine()->GetShadowsCascadeCount(NULL) && nLod < MAX_GSM_LODS_NUM; nLod++)
- {
- ShadowMapFrustum*& pLsource = pSMI->pGSM[nLod];
- if (nLod)
- {
- azstrcat(szText, AZ_ARRAY_SIZE(szText), ", ");
- }
-
- char* pstr = szText + strlen(szText);
- sprintf_s(pstr, sizeof(szText) - (pstr - szText), "%d", pLsource->m_castersList.Count());
- }
-
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, szText);
- }
-
- for (int nSunInUse = 0; nSunInUse < 2; nSunInUse++)
- {
- if (nSunInUse)
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "WithSun ListId FrNum UserNum");
- }
- else
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "NoSun ListId FrNum UserNum");
- }
-
- // TODO: For Nick, check if needed anymore
- //for(ShadowFrustumListsCache::iterator it = m_FrustumsCache[nSunInUse].begin(); it != m_FrustumsCache[nSunInUse].end(); ++it)
- //{
- // int nListId = (int)it->first;
- // PodArray * pList = it->second;
-
- // DrawTextRightAligned( fTextPosX, fTextPosY+=fTextStepY,
- // "%8d %8d %8d",
- // nListId,
- // pList->Count(), m_FrustumsCacheUsers[nSunInUse][nListId]);
- //}
- }
- }
-
- // objects counter
- if (GetCVars()->e_ObjStats)
- {
-#define DRAW_OBJ_STATS(_var) DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "%s: %d", (#_var), GetInstCount(_var))
-
- DRAW_OBJ_STATS(eERType_NotRenderNode);
- DRAW_OBJ_STATS(eERType_Light);
- DRAW_OBJ_STATS(eERType_Cloud);
- DRAW_OBJ_STATS(eERType_FogVolume);
- DRAW_OBJ_STATS(eERType_Decal);
- DRAW_OBJ_STATS(eERType_WaterVolume);
- DRAW_OBJ_STATS(eERType_DistanceCloud);
- DRAW_OBJ_STATS(eERType_VolumeObject);
- DRAW_OBJ_STATS(eERType_Rope);
- DRAW_OBJ_STATS(eERType_PrismObject);
- DRAW_OBJ_STATS(eERType_RenderComponent);
- DRAW_OBJ_STATS(eERType_StaticMeshRenderComponent);
- DRAW_OBJ_STATS(eERType_DynamicMeshRenderComponent);
- DRAW_OBJ_STATS(eERType_SkinnedMeshRenderComponent);
- DRAW_OBJ_STATS(eERType_GameEffect);
- DRAW_OBJ_STATS(eERType_BreakableGlass);
-
- if (IsObjectTreeReady())
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "--- By list type: ---");
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, " Main: %d", m_pObjectsTree->GetObjectsCount(eMain));
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "Caster: %d", m_pObjectsTree->GetObjectsCount(eCasters));
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "LigAll: %d", m_lstStaticLights.Count());
- }
-
- int nFree = m_LTPRootFree.Count();
- int nUsed = m_LTPRootUsed.Count();
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "RNTmpData(Used+Free): %d + %d = %d (%d KB)",
- nUsed, nFree, nUsed + nFree, (nUsed + nFree) * (int)sizeof(CRNTmpData) / 1024);
-
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "COctreeNode::m_arrEmptyNodes.Count() = %d", COctreeNode::m_arrEmptyNodes.Count());
- }
-
- CCullBuffer* pCB = GetCoverageBuffer();
- if (pCB && GetCVars()->e_CoverageBuffer && GetCVars()->e_CoverageBufferDebug && pCB->TrisWritten())
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY,
- "CB: Write:%3d/%2d Test:%4d/%4d/%3d ZFarM:%.2f ZNearM:%.2f Res:%d OI:%s",
- pCB->TrisWritten(), pCB->ObjectsWritten(),
- pCB->TrisTested(), pCB->ObjectsTested(), pCB->ObjectsTestedAndRejected(),
- pCB->GetZFarInMeters(), pCB->GetZNearInMeters(), pCB->SelRes(),
- pCB->IsOutdooVisible() ? "Out" : "In");
- }
-
-#if defined(INFO_FRAME_COUNTER)
- ++frameCounter;
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "Frame #%d", frameCounter);
-#endif
-
- ITimeOfDay* pTimeOfDay = Get3DEngine()->GetTimeOfDay();
- if (GetCVars()->e_TimeOfDayDebug && pTimeOfDay)
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "---------------------------------------");
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "------------ Time of Day -------------");
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, " ");
-
- int nVarCount = pTimeOfDay->GetVariableCount();
- for (int v = 0; v < nVarCount; ++v)
- {
- ITimeOfDay::SVariableInfo pVar;
- pTimeOfDay->GetVariableInfo(v, pVar);
-
- if (pVar.type == ITimeOfDay::TYPE_FLOAT)
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, " %s: %.9f", pVar.displayName, pVar.fValue[0]);
- }
- else
- {
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, " %s: %.3f %.3f %.3f", pVar.displayName, pVar.fValue[0], pVar.fValue[1], pVar.fValue[2]);
- }
- }
- DrawTextRightAligned(fTextPosX, fTextPosY += fTextStepY, "---------------------------------------");
- }
-
-#endif
- // We only show memory usage in dev mode.
- if (gEnv->pSystem->IsDevMode())
- {
- if (GetCVars()->e_DisplayMemoryUsageIcon)
- {
- uint64 nAverageMemoryUsage(0);
- uint64 nHighMemoryUsage(0);
- uint64 nCurrentMemoryUsage(0);
- const uint64 nMegabyte(1024 * 1024);
-
- // Copied from D3DDriver.cpp, function CD3D9Renderer::RT_EndFrame().
- int nIconSize = 16;
-
- nCurrentMemoryUsage = processMemInfo.TotalPhysicalMemory - processMemInfo.FreePhysicalMemory;
-
-#if defined(_WIN64) || defined(WIN64) || defined(MAC) || defined(LINUX64)
- nAverageMemoryUsage = 3000;
- nHighMemoryUsage = 6000;
- // This is the same value as measured in the editor.
- nCurrentMemoryUsage = processMemInfo.PagefileUsage / nMegabyte;
-#elif defined(_WIN32) || defined(LINUX32)
- nAverageMemoryUsage = 800;
- nHighMemoryUsage = 1200;
- // This is the same value as measured in the editor.
- nCurrentMemoryUsage = processMemInfo.PagefileUsage / nMegabyte;
-#endif //_WIN32
-
- ITexture* pRenderTexture(m_ptexIconAverageMemoryUsage);
- if (nCurrentMemoryUsage > nHighMemoryUsage)
- {
- pRenderTexture = m_ptexIconHighMemoryUsage;
- }
- else if (nCurrentMemoryUsage < nAverageMemoryUsage)
- {
- pRenderTexture = m_ptexIconLowMemoryUsage;
- }
-
- if (pRenderTexture && gEnv->pRenderer)
- {
- float vpWidth = (float)gEnv->pRenderer->GetOverlayWidth(), vpHeight = (float)gEnv->pRenderer->GetOverlayHeight();
- float iconWidth = (float)nIconSize / vpWidth * 800.0f;
- float iconHeight = (float)nIconSize / vpHeight * 600.0f;
- gEnv->pRenderer->Push2dImage((fTextPosX / vpWidth) * 800.0f - iconWidth, ((fTextPosY += nIconSize + 3) / vpHeight) * 600.0f,
- iconWidth, iconHeight, pRenderTexture->GetTextureID(), 0, 1.0f, 1.0f, 0);
- }
- }
- }
-#endif
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////////////////////
-static const float DISPLAY_MEMORY_ROW_MARGIN = 16.0f;
-static const float DISPLAY_MEMORY_ROW_HEIGHT = 32.0f;
-static const float DISPLAY_MEMORY_ROW_NUMBER_WIDTH = 128.0f;
-static const float DISPLAY_MEMORY_ROW_FONT_SCALE = 1.5f;
-static const float DISPLAY_MEMORY_COL_LABEL_FONT_SCALE = 1.0f;
-
-static inline void AdjustDisplayMemoryParameters(float& yPos, float& columnInset, float columnWidth, float screenHeight)
-{
- int column = (int)(yPos + DISPLAY_MEMORY_ROW_HEIGHT) / (int)screenHeight;
- columnInset += columnWidth * column;
- yPos -= screenHeight * column;
-}
-
-static void DisplayMemoryRow(C3DEngine& engine, float columnWidth, float screenHeight, float yPos, float valueA, float valueB, const char* valueBFormat, const ColorF& color, const char* categoryName, const char* subcategoryName = nullptr)
-{
- float columnInset = columnWidth - DISPLAY_MEMORY_ROW_MARGIN;
- AdjustDisplayMemoryParameters(yPos, columnInset, columnWidth, screenHeight);
- if (valueA != -1.0f)
- {
- engine.DrawTextRightAligned(columnInset - DISPLAY_MEMORY_ROW_NUMBER_WIDTH, yPos, DISPLAY_MEMORY_ROW_FONT_SCALE, color, "%.1fMB", valueA);
- }
- if (valueB != -1.0f)
- {
- engine.DrawTextRightAligned(columnInset, yPos, DISPLAY_MEMORY_ROW_FONT_SCALE, color, valueBFormat, valueB);
- }
-
- if (subcategoryName)
- {
- static const float MAIN_TEXT_SCALE = 1.5f;
- static const float SUB_TEXT_SCALE = 1.0f;
- static const float SUB_LINE_OFFSET_Y = 16.0f;
-
- engine.DrawTextLeftAligned(columnInset - DISPLAY_MEMORY_ROW_NUMBER_WIDTH * 4, yPos, MAIN_TEXT_SCALE, color, "%s", categoryName);
- engine.DrawTextLeftAligned(columnInset - DISPLAY_MEMORY_ROW_NUMBER_WIDTH * 4, yPos + SUB_LINE_OFFSET_Y, SUB_TEXT_SCALE, color, "%s", subcategoryName);
- }
- else
- {
- engine.DrawTextLeftAligned(columnInset - DISPLAY_MEMORY_ROW_NUMBER_WIDTH * 4, yPos, DISPLAY_MEMORY_ROW_FONT_SCALE, color, "%s", categoryName);
- }
-}
-
-void C3DEngine::DisplayMemoryStatistics()
-{
- const ColorF headerColor = ColorF(0.4f, 0.9f, 0.3f, 1.0f);
- const ColorF statisticColor = ColorF(0.4f, 0.9f, 0.9f, 1.0f);
- const ColorF subtotalColor = ColorF(0.4f, 0.3f, 0.9f, 1.0f);
- const ColorF totalColor = ColorF(0.9f, 0.9f, 0.9f, 1.0f);
- const ColorF labelColor = ColorF(0.4f, 0.3f, 0.3f, 1.0f);
-
- const float screenHeight = (float)m_pRenderer->GetHeight();
-
- if (GetCVars()->e_MemoryProfiling == 1)
- {
- const float columnWidth = (float)(m_pRenderer->GetWidth() / 2);
- float columnInset = columnWidth - DISPLAY_MEMORY_ROW_MARGIN;
-
- float memoryYPos = DISPLAY_MEMORY_ROW_HEIGHT;
- float memoryYPosStepSize = DISPLAY_MEMORY_ROW_HEIGHT;
-
- // Add column labels and header
- this->DrawTextRightAligned(columnInset - DISPLAY_MEMORY_ROW_NUMBER_WIDTH, memoryYPos, DISPLAY_MEMORY_COL_LABEL_FONT_SCALE, labelColor, "Allocated");
- this->DrawTextRightAligned(columnInset, memoryYPos, DISPLAY_MEMORY_COL_LABEL_FONT_SCALE, labelColor, "No. Allocations");
- DisplayMemoryRow(*this, columnWidth, screenHeight, memoryYPos, -1.0f, -1.0f, "%.1fMB", headerColor, "VRAM Usage");
- memoryYPos += (memoryYPosStepSize * 0.5f);
-
- float totalTrackedGPUAlloc = 0.0f;
-
- // Print the memory usage of each major VRAM category and each subcategory
- for (int category = 0; category < Render::Debug::VRAM_CATEGORY_NUMBER_CATEGORIES; ++category)
- {
- float categorySubTotal = 0.0f;
- AZStd::string categoryName;
-
- for (int subcategory = 0; subcategory < Render::Debug::VRAM_SUBCATEGORY_NUMBER_SUBCATEGORIES; ++subcategory)
- {
- AZStd::string subcategoryName;
- size_t numberBytesAllocated = 0;
- size_t numberAllocations = 0;
- EBUS_EVENT(Render::Debug::VRAMDrillerBus, GetCurrentVRAMStats, static_cast(category),
- static_cast(subcategory), categoryName, subcategoryName, numberBytesAllocated, numberAllocations);
-
- if (numberAllocations != 0)
- {
- float numMBallocated = numberBytesAllocated / (1024.0f * 1024.0f);
- DisplayMemoryRow(*this, columnWidth, screenHeight, memoryYPos, numMBallocated, (float)numberAllocations, "%.0f", statisticColor, categoryName.c_str(), subcategoryName.c_str());
-
- memoryYPos += memoryYPosStepSize;
- totalTrackedGPUAlloc += numMBallocated;
- categorySubTotal += numMBallocated;
- }
- }
- if (categorySubTotal > 0.0f)
- {
- float yPos = memoryYPos;
- AdjustDisplayMemoryParameters(yPos, columnInset, columnWidth, screenHeight);
- DrawTextLeftAligned(columnInset - DISPLAY_MEMORY_ROW_NUMBER_WIDTH * 4, yPos, DISPLAY_MEMORY_ROW_FONT_SCALE, subtotalColor, "%s Subtotal", categoryName.c_str());
- DrawTextRightAligned(columnInset - DISPLAY_MEMORY_ROW_NUMBER_WIDTH, yPos, DISPLAY_MEMORY_ROW_FONT_SCALE, subtotalColor, "%.1fMB", categorySubTotal);
- memoryYPos += (memoryYPosStepSize * 0.5f);
- }
- }
-
- float allocatedVideoMemoryMB = -1.0f, reservedVideoMemoryMB = -1.0f;
-
-#if defined(AZ_PLATFORM_PROVO)
- size_t allocatedVideoMemoryBytes = 0, reservedVideoMemoryBytes = 0;
- VirtualAllocator::QueryVideoMemory(allocatedVideoMemoryBytes, reservedVideoMemoryBytes);
- allocatedVideoMemoryMB = static_cast(allocatedVideoMemoryBytes) / (1024.0f * 1024.0f);
- reservedVideoMemoryMB = static_cast(reservedVideoMemoryBytes) / (1024.0f * 1024.0f);
-#else
- // Non PROVO platforms just sum up the tracked allocations
- allocatedVideoMemoryMB = totalTrackedGPUAlloc;
-#endif
-
- DrawTextLeftAligned(columnInset - DISPLAY_MEMORY_ROW_NUMBER_WIDTH * 4, memoryYPos, DISPLAY_MEMORY_ROW_FONT_SCALE, totalColor, "Total");
- if (reservedVideoMemoryMB != -1.0f)
- {
- DrawTextRightAligned(columnInset - DISPLAY_MEMORY_ROW_NUMBER_WIDTH * 1, memoryYPos, DISPLAY_MEMORY_ROW_FONT_SCALE, totalColor, "%.1fMB/%.1fMB", allocatedVideoMemoryMB, reservedVideoMemoryMB);
- memoryYPos += (memoryYPosStepSize * 0.5f);
- }
- else
- {
- DrawTextRightAligned(columnInset - DISPLAY_MEMORY_ROW_NUMBER_WIDTH * 1, memoryYPos, DISPLAY_MEMORY_ROW_FONT_SCALE, totalColor, "%.1fMB", allocatedVideoMemoryMB);
- memoryYPos += (memoryYPosStepSize * 0.5f);
- }
-
- // Spacer
- memoryYPos += (memoryYPosStepSize * 0.5f);
-
- // Add column labels and header
- this->DrawTextRightAligned(columnInset - DISPLAY_MEMORY_ROW_NUMBER_WIDTH, memoryYPos, DISPLAY_MEMORY_COL_LABEL_FONT_SCALE, labelColor, "Allocated");
- this->DrawTextRightAligned(columnInset, memoryYPos, DISPLAY_MEMORY_COL_LABEL_FONT_SCALE, labelColor, "Capacity");
- DisplayMemoryRow(*this, columnWidth, screenHeight, memoryYPos, -1.0f, -1.0f, "%.1fMB", headerColor, "CPU Memory Usage");
- memoryYPos += (memoryYPosStepSize * 0.5f);
-
- float totalTrackedCPUAlloc = 0.0f;
- float totalCapacityCPUAlloc = 0.0f;
-
- AZ::AllocatorManager& allocatorManager = AZ::AllocatorManager::Instance();
- const size_t allocatorCount = allocatorManager.GetNumAllocators();
- AZStd::map existingAllocators;
- AZStd::map sourcesToAllocators;
-
- // Build a mapping of original allocator sources to their allocators
- for (int i = 0; i < allocatorCount; ++i)
- {
- AZ::IAllocator* allocator = allocatorManager.GetAllocator(i);
- sourcesToAllocators.emplace(allocator->GetOriginalAllocationSource(), allocator);
- }
-
- // Group up any allocators under this size
- static float smallAllocatorCapacityMaxMB = 10.0f;
- float smallAllocatorsTotalCapacityMB = 0.0f;
- float smallAllocatorsTotalAllocatedMB = 0.0f;
-
- for (int i = 0; i < allocatorCount; ++i)
- {
- AZ::IAllocator* allocator = allocatorManager.GetAllocator(i);
- AZ::IAllocatorAllocate* source = allocator->GetAllocationSource();
- AZ::IAllocatorAllocate* originalSource = allocator->GetOriginalAllocationSource();
- AZ::IAllocatorAllocate* schema = allocator->GetSchema();
- AZ::IAllocator* alias = (source != originalSource) ? sourcesToAllocators[source] : nullptr;
-
- if (schema && !alias)
- {
- // Check to see if this allocator's source maps to another allocator
- // Need to check both the schema and the allocator itself, as either one might be used as the alias depending on how it's implemented
- AZStd::array checkAllocators = { { schema, allocator->GetAllocationSource() } };
-
- for (AZ::IAllocatorAllocate* check : checkAllocators)
- {
- auto existing = existingAllocators.emplace(check, allocator);
-
- if (!existing.second)
- {
- alias = existing.first->second;
- // Do not break out of the loop as we need to add to the map for all entries
- }
- }
- }
-
- if (!alias)
- {
- static const AZ::IAllocator* OS_ALLOCATOR = &AZ::AllocatorInstance::GetAllocator();
- float allocatedMB = (float)source->NumAllocatedBytes() / (1024.0f * 1024.0f);
- float capacityMB = (float)source->Capacity() / (1024.0f * 1024.0f);
-
- totalTrackedCPUAlloc += allocatedMB;
- totalCapacityCPUAlloc += capacityMB;
-
- // Skip over smaller allocators so the display is readable.
- if (capacityMB < smallAllocatorCapacityMaxMB)
- {
- smallAllocatorsTotalCapacityMB += capacityMB;
- smallAllocatorsTotalAllocatedMB += allocatedMB;
- continue;
- }
-
- if (allocator == OS_ALLOCATOR)
- {
- // Need to special case the OS allocator because its capacity is a made-up number. Better to just use the allocated amount, it will hopefully be small anyway.
- capacityMB = allocatedMB;
- }
-
- DisplayMemoryRow(*this, columnWidth, screenHeight, memoryYPos, allocatedMB, capacityMB, "%.1fMB", statisticColor, allocator->GetName(), allocator->GetDescription());
-
- memoryYPos += memoryYPosStepSize;
- }
- }
-
- if (smallAllocatorCapacityMaxMB > 0.0f)
- {
- AZStd::string subText = AZStd::string::format("Allocators smaller than %.0f MB", smallAllocatorCapacityMaxMB);
- DisplayMemoryRow(*this, columnWidth, screenHeight, memoryYPos, smallAllocatorsTotalAllocatedMB, smallAllocatorsTotalCapacityMB, "%.1fMB", statisticColor, "All Small Allocators", subText.c_str());
- memoryYPos += memoryYPosStepSize;
- }
-
- DisplayMemoryRow(*this, columnWidth, screenHeight, memoryYPos, totalTrackedCPUAlloc, totalCapacityCPUAlloc, "%.1fMB", totalColor, "Total");
- memoryYPos += (memoryYPosStepSize * 0.5f);
- }
- else if (GetCVars()->e_MemoryProfiling == 2)
- {
- const float columnWidth = (float)(m_pRenderer->GetWidth() / 2);
-
- float memoryYPos = DISPLAY_MEMORY_ROW_HEIGHT;
- float memoryYPosStepSize = DISPLAY_MEMORY_ROW_HEIGHT;
-
- AZ::AllocatorManager& allocatorManager = AZ::AllocatorManager::Instance();
- const size_t allocatorCount = allocatorManager.GetNumAllocators();
- AZStd::map existingAllocators;
- AZStd::map sourcesToAllocators;
-
- // Build a mapping of original allocator sources to their allocators
- for (int i = 0; i < allocatorCount; ++i)
- {
- AZ::IAllocator* allocator = allocatorManager.GetAllocator(i);
- sourcesToAllocators.emplace(allocator->GetOriginalAllocationSource(), allocator);
- }
-
- for (int i = 0; i < allocatorCount; ++i)
- {
- AZ::IAllocator* allocator = allocatorManager.GetAllocator(i);
- AZ::IAllocatorAllocate* source = allocator->GetAllocationSource();
- AZ::IAllocatorAllocate* originalSource = allocator->GetOriginalAllocationSource();
- AZ::IAllocatorAllocate* schema = allocator->GetSchema();
- AZ::IAllocator* alias = (source != originalSource) ? sourcesToAllocators[source] : nullptr;
-
- if (schema && !alias)
- {
- // Check to see if this allocator's source maps to another allocator
- // Need to check both the schema and the allocator itself, as either one might be used as the alias depending on how it's implemented
- AZStd::array checkAllocators = { { schema, allocator->GetAllocationSource() } };
-
- for (AZ::IAllocatorAllocate* check : checkAllocators)
- {
- auto existing = existingAllocators.emplace(check, allocator);
-
- if (!existing.second)
- {
- alias = existing.first->second;
- // Do not break out of the loop as we need to add to the map for all entries
- }
- }
- }
-
- if (alias)
- {
- float columnInset = columnWidth - DISPLAY_MEMORY_ROW_MARGIN;
- float yPos = memoryYPos;
- AdjustDisplayMemoryParameters(yPos, columnInset, columnWidth, screenHeight);
- DrawTextRightAligned(columnInset, yPos, DISPLAY_MEMORY_ROW_FONT_SCALE, statisticColor, "%s => %s", allocator->GetName(), alias->GetName());
- memoryYPos += (memoryYPosStepSize * 0.5f);
- }
- }
- }
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////////////////////
-
-void C3DEngine::SetupDistanceFog()
-{
- FUNCTION_PROFILER_3DENGINE;
-
- GetRenderer()->SetFogColor(ColorF(m_vFogColor.x, m_vFogColor.y, m_vFogColor.z, 1.0f));
- GetRenderer()->EnableFog(GetCVars()->e_Fog > 0);
-}
-
-void C3DEngine::ScreenShotHighRes([[maybe_unused]] CStitchedImage* pStitchedImage, [[maybe_unused]] const int nRenderFlags, [[maybe_unused]] const SRenderingPassInfo& passInfo, [[maybe_unused]] uint32 SliceCount, [[maybe_unused]] f32 fTransitionSize)
-{
-#if defined(WIN32) || defined(WIN64) || defined(MAC)
-
- //If the requested format is TGA we want the framebuffer in BGR format; otherwise we want RGB
- const char* szExtension = GetCVars()->e_ScreenShotFileFormat->GetString();
- bool BGRA = (azstricmp(szExtension, "tga") == 0) ? true : false;
-
- // finish frame started by system
- GetRenderer()->EndFrame();
-
- // The occlusion system does not like being restarted mid-frame like this. Disable it for
- // the screenshot system.
- AZ::s32 statObjBufferRenderTasks = GetCVars()->e_StatObjBufferRenderTasks;
- GetCVars()->e_StatObjBufferRenderTasks = 0;
-
- GetConsole()->SetScrollMax(0);
-
- const uint32 ScreenWidth = GetRenderer()->GetWidth();
- const uint32 ScreenHeight = GetRenderer()->GetHeight();
- uint32* pImage = new uint32[ScreenWidth * ScreenHeight];
- for (uint32 yy = 0; yy < SliceCount; yy++)
- {
- for (uint32 xx = 0; xx < SliceCount; xx++)
- {
- const int BlendX = (xx * 2) / SliceCount;
- const int BlendY = (yy * 2) / SliceCount;
- const int x = (((xx * 2) % SliceCount) & ~1) + BlendX;
- const int y = (((yy * 2) % SliceCount) & ~1) + BlendY;
- const int reverseX = SliceCount - 1 - x;
- const int reverseY = SliceCount - 1 - y;
-
- const float halfTransitionSize = fTransitionSize * 0.5f;
- const float sliceCountF = static_cast(SliceCount);
-
- // start new frame and define needed tile
- const f32 ScreenScale = 1.0f / ((1.0f / sliceCountF) * (1.0f + fTransitionSize));
-
- GetRenderer()->BeginFrame();
-
- // This has to happen after BeginFrame(), because BeginFrame increments the frame counter, and SRenderingPassInfo
- // pulls from that counter in the constructor. Individual render nodes track the frame they were last rendered with
- // and will bail if the same frame is rendered twice.
- SRenderingPassInfo screenShotPassInfo = SRenderingPassInfo::CreateGeneralPassRenderingInfo(passInfo.GetCamera());
- PrintMessage("Rendering tile %d of %d ... ", xx + yy * SliceCount + 1, SliceCount * SliceCount);
-
- const float normalizedX = ((static_cast(reverseX) - halfTransitionSize) / sliceCountF);
- const float normalizedY = ((static_cast(reverseY) - halfTransitionSize) / sliceCountF);
-
- GetRenderer()->SetRenderTile(
- ScreenScale * normalizedX,
- ScreenScale * normalizedY,
- ScreenScale, ScreenScale);
-
- UpdateRenderingCamera("ScreenShotHighRes", screenShotPassInfo);
-
- RenderInternal(nRenderFlags, screenShotPassInfo, "ScreenShotHighRes");
-
- // Make sure we've composited to the final back buffer.
- GetRenderer()->SwitchToNativeResolutionBackbuffer();
-
- GetRenderer()->EndFrame();
-
- PrintMessagePlus("reading frame buffer ... ");
-
- GetRenderer()->ReadFrameBufferFast(pImage, ScreenWidth, ScreenHeight, BGRA);
- pStitchedImage->RasterizeRect(pImage, ScreenWidth, ScreenHeight, x, y, fTransitionSize,
- fTransitionSize > 0.0001f && BlendX,
- fTransitionSize > 0.0001f && BlendY);
-
- PrintMessagePlus("ok");
- }
- }
- delete[] pImage;
-
- GetCVars()->e_StatObjBufferRenderTasks = statObjBufferRenderTasks;
-
- // re-start frame so system can safely finish it
- GetRenderer()->BeginFrame();
-
- // restore initial state
- GetRenderer()->SetViewport(0, 0, GetRenderer()->GetWidth(), GetRenderer()->GetHeight());
- GetConsole()->SetScrollMax(300);
- GetRenderer()->SetRenderTile();
-
- PrintMessagePlus(" ok");
-#endif // #if defined(WIN32) || defined(WIN64)
-}
-
-
-
-bool C3DEngine::ScreenShotMap([[maybe_unused]] CStitchedImage* pStitchedImage,
- [[maybe_unused]] const int nRenderFlags,
- [[maybe_unused]] const SRenderingPassInfo& passInfo,
- [[maybe_unused]] const uint32 SliceCount,
- [[maybe_unused]] const f32 fTransitionSize)
-{
-#if defined(WIN32) || defined(WIN64) || defined(MAC)
-
- const f32 fTLX = GetCVars()->e_ScreenShotMapCenterX - GetCVars()->e_ScreenShotMapSizeX + fTransitionSize * GetRenderer()->GetWidth();
- const f32 fTLY = GetCVars()->e_ScreenShotMapCenterY - GetCVars()->e_ScreenShotMapSizeY + fTransitionSize * GetRenderer()->GetHeight();
- const f32 fBRX = GetCVars()->e_ScreenShotMapCenterX + GetCVars()->e_ScreenShotMapSizeX + fTransitionSize * GetRenderer()->GetWidth();
- const f32 fBRY = GetCVars()->e_ScreenShotMapCenterY + GetCVars()->e_ScreenShotMapSizeY + fTransitionSize * GetRenderer()->GetHeight();
- const f32 Height = GetCVars()->e_ScreenShotMapCamHeight;
- const int Orient = GetCVars()->e_ScreenShotMapOrientation;
-
- const char* SettingsFileName = GetLevelFilePath("ScreenshotMap.Settings");
-
- AZ::IO::HandleType metaFileHandle = gEnv->pCryPak->FOpen(SettingsFileName, "wt");
- if (metaFileHandle != AZ::IO::InvalidHandle)
- {
- char Data[1024 * 8];
- snprintf(Data, sizeof(Data), "",
- GetCVars()->e_ScreenShotMapCenterX,
- GetCVars()->e_ScreenShotMapCenterY,
- GetCVars()->e_ScreenShotMapSizeX,
- GetCVars()->e_ScreenShotMapSizeY,
- GetCVars()->e_ScreenShotMapCamHeight,
- GetCVars()->e_ScreenShotQuality,
- GetCVars()->e_ScreenShotMapOrientation);
- string data(Data);
- gEnv->pCryPak->FWrite(data.c_str(), data.size(), metaFileHandle);
- gEnv->pCryPak->FClose(metaFileHandle);
- }
-
- // This bit is necessary because we don't have a way to render the world using an orthographic projection. This is doing
- // a hacky orthographic projection by shifting the camera up to a sufficient height to fake it. To preserve depth range
- // we define a maximum range then then fit the near / far planes to extend [-HeightRangeMax, HeightRangeMax] along Z (which is the up axis).
- const float HeightRangeMax = 4096;
- const float HeightRangeMaxDiv2 = HeightRangeMax / 2.0f;
-
- const float NearClip = max(Height - HeightRangeMaxDiv2, 1.0f);
- const float FarClip = max(Height + HeightRangeMaxDiv2, HeightRangeMax);
-
- CCamera cam = passInfo.GetCamera();
- Matrix34 tmX, tmY;
- float xrot = -gf_PI * 0.5f;
- float yrot = Orient == 0 ? -gf_PI * 0.5f : -0.0f;
- tmX.SetRotationX(xrot);
- tmY.SetRotationY(yrot);
- Matrix34 tm = tmX * tmY;
- tm.SetTranslation(Vec3((fTLX + fBRX) * 0.5f, (fTLY + fBRY) * 0.5f, Height));
- cam.SetMatrix(tm);
-
- const f32 AngleX = atanf(((fBRX - fTLX) * 0.5f) / Height);
- const f32 AngleY = atanf(((fBRY - fTLY) * 0.5f) / Height);
-
- ICVar* r_drawnearfov = GetConsole()->GetCVar("r_DrawNearFoV");
- assert(r_drawnearfov);
- const f32 drawnearfov_backup = r_drawnearfov->GetFVal();
- const f32 ViewingSize = (float)min(cam.GetViewSurfaceX(), cam.GetViewSurfaceZ());
- if (max(AngleX, AngleY) <= 0)
- {
- return false;
- }
- cam.SetFrustum((int)ViewingSize, (int)ViewingSize, max(0.001f, max(AngleX, AngleY) * 2.f), NearClip, FarClip);
- r_drawnearfov->Set(-1);
- ScreenShotHighRes(pStitchedImage, nRenderFlags, SRenderingPassInfo::CreateTempRenderingInfo(cam, passInfo), SliceCount, fTransitionSize);
- r_drawnearfov->Set(drawnearfov_backup);
-
- return true;
-#else // #if defined(WIN32) || defined(WIN64)
- return false;
-#endif // #if defined(WIN32) || defined(WIN64)
-}
-
-
-bool C3DEngine::ScreenShotPanorama([[maybe_unused]] CStitchedImage* pStitchedImage, [[maybe_unused]] const int nRenderFlags, [[maybe_unused]] const SRenderingPassInfo& passInfo, [[maybe_unused]] uint32 SliceCount, [[maybe_unused]] f32 fTransitionSize)
-{
-#if defined(WIN32) || defined(WIN64) || defined(MAC)
-
- //If the requested format is TGA we want the framebuffer in BGR format; otherwise we want RGB
- const char* szExtension = GetCVars()->e_ScreenShotFileFormat->GetString();
- bool BGRA = (azstricmp(szExtension, "tga") == 0) ? true : false;
-
- // finish frame started by system
- GetRenderer()->EndFrame();
-
- float r_drawnearfov_backup = -1;
- ICVar* r_drawnearfov = GetConsole()->GetCVar("r_DrawNearFoV");
- assert(r_drawnearfov);
-
- r_drawnearfov_backup = r_drawnearfov->GetFVal();
- r_drawnearfov->Set(-1); // means the fov override should be switched off
-
- // The occlusion system does not like being restarted mid-frame like this. Disable it for
- // the screenshot system.
- AZ::s32 statObjBufferRenderTasks = GetCVars()->e_StatObjBufferRenderTasks;
- GetCVars()->e_StatObjBufferRenderTasks = 0;
-
- GetTimer()->EnableTimer(false);
-
- uint32* pImage = new uint32[GetRenderer()->GetWidth() * GetRenderer()->GetHeight()];
-
- for (int iSlice = SliceCount - 1; iSlice >= 0; --iSlice)
- {
- if (iSlice == 0) // the last one should do eye adaption
- {
- GetTimer()->EnableTimer(true);
- }
-
- GetRenderer()->BeginFrame();
-
- Matrix33 rot;
- rot.SetIdentity();
-
- float fAngle = pStitchedImage->GetSliceAngle(iSlice);
-
- rot.SetRotationZ(fAngle);
-
- CCamera cam = passInfo.GetCamera();
-
- Matrix34 tm = cam.GetMatrix();
- tm = tm * rot;
- tm.SetTranslation(passInfo.GetCamera().GetPosition());
- cam.SetMatrix(tm);
-
- cam.SetFrustum(cam.GetViewSurfaceX(), cam.GetViewSurfaceZ(), pStitchedImage->m_fPanoramaShotVertFOV, cam.GetNearPlane(), cam.GetFarPlane(), cam.GetPixelAspectRatio());
-
- SRenderingPassInfo screenShotPassInfo = SRenderingPassInfo::CreateGeneralPassRenderingInfo(cam);
-
- UpdateRenderingCamera("ScreenShotPanorama", screenShotPassInfo);
-
- // render scene
- RenderInternal(nRenderFlags, screenShotPassInfo, "ScreenShotPanorama");
-
- // Make sure we've composited to the final back buffer.
- GetRenderer()->SwitchToNativeResolutionBackbuffer();
-
- GetRenderer()->ReadFrameBufferFast(pImage, GetRenderer()->GetWidth(), GetRenderer()->GetHeight(), BGRA);
-
- GetRenderer()->EndFrame(); // show last frame (from direction)
-
- const bool bFadeBorders = (iSlice + 1) * 2 <= (int)SliceCount;
-
- PrintMessage("PanoramaScreenShot %d/%d FadeBorders:%c (id: %d/%d)", iSlice + 1, SliceCount, bFadeBorders ? 't' : 'f', GetRenderer()->GetFrameID(false), GetRenderer()->GetFrameID(true));
-
- pStitchedImage->RasterizeCylinder(pImage, GetRenderer()->GetWidth(), GetRenderer()->GetHeight(), iSlice + 1, bFadeBorders);
-
- if (GetCVars()->e_ScreenShotQuality < 0) // to debug FadeBorders
- {
- if (iSlice * 2 == SliceCount)
- {
- pStitchedImage->Clear();
- PrintMessage("PanoramaScreenShot clear");
- }
- }
- }
- delete [] pImage;
-
- r_drawnearfov->Set(r_drawnearfov_backup);
- GetCVars()->e_StatObjBufferRenderTasks = statObjBufferRenderTasks;
-
- // re-start frame so system can safely finish it
- GetRenderer()->BeginFrame();
-
- return true;
-#else // #if defined(WIN32) || defined(WIN64)
- return false;
-#endif // #if defined(WIN32) || defined(WIN64)
-}
-
-
-
-void C3DEngine::SetupClearColor()
-{
- FUNCTION_PROFILER_3DENGINE;
-
- bool bCameraInOutdoors = m_pVisAreaManager && !m_pVisAreaManager->m_pCurArea && !(m_pVisAreaManager->m_pCurPortal && m_pVisAreaManager->m_pCurPortal->m_lstConnections.Count() > 1);
- GetRenderer()->SetClearColor(bCameraInOutdoors ? m_vFogColor : Vec3(0, 0, 0));
-}
-
-void C3DEngine::FillDebugFPSInfo(SDebugFPSInfo& info)
-{
- size_t c = 0;
- float average = 0.0f, min = 0.0f, max = 0.0f;
- const float clampFPS = 200.0f;
- for (size_t i = 0, end = arrFPSforSaveLevelStats.size(); i < end; ++i)
- {
- if (arrFPSforSaveLevelStats[i] > 1.0f && arrFPSforSaveLevelStats[i] < clampFPS)
- {
- ++c;
- average += arrFPSforSaveLevelStats[i];
- }
- }
-
- if (c)
- {
- average /= (float)c;
- }
-
- int minc = 0, maxc = 0;
- for (size_t i = 0, end = arrFPSforSaveLevelStats.size(); i < end; ++i)
- {
- if (arrFPSforSaveLevelStats[i] > average && arrFPSforSaveLevelStats[i] < clampFPS)
- {
- ++maxc;
- max += arrFPSforSaveLevelStats[i];
- }
-
- if (arrFPSforSaveLevelStats[i] < average && arrFPSforSaveLevelStats[i] < clampFPS)
- {
- ++minc;
- min += arrFPSforSaveLevelStats[i];
- }
- }
-
- if (minc == 0)
- {
- minc = 1;
- }
- if (maxc == 0)
- {
- maxc = 1;
- }
-
- info.fAverageFPS = average;
- info.fMinFPS = min / (float)minc;
- info.fMaxFPS = max / (float)maxc;
-}
diff --git a/Code/CryEngine/Cry3DEngine/3DEngine_Jobs.cpp b/Code/CryEngine/Cry3DEngine/3DEngine_Jobs.cpp
deleted file mode 100644
index a6beb77dda..0000000000
--- a/Code/CryEngine/Cry3DEngine/3DEngine_Jobs.cpp
+++ /dev/null
@@ -1,574 +0,0 @@
-/*
-* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
-* its licensors.
-*
-* For complete copyright and license terms please see the LICENSE at the root of this
-* distribution (the "License"). All use of this software is governed by the License,
-* or, if provided, by the license below or the license accompanying this file. Do not
-* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-*
-*/
-// Original file Copyright Crytek GMBH or its affiliates, used under license.
-
-// Description : Implementation of I3DEngine interface methods
-
-
-#include "Cry3DEngine_precompiled.h"
-#include
-
-#include "3dEngine.h"
-
-#include
-
-#include "VisAreas.h"
-#include "ObjMan.h"
-#include "Ocean.h"
-
-#include "DecalManager.h"
-#include "IndexedMesh.h"
-#include "AABBSV.h"
-
-#include "MatMan.h"
-
-#include "CullBuffer.h"
-#include "CGF/CGFLoader.h"
-#include "CGF/ReadOnlyChunkFile.h"
-
-#include "CloudRenderNode.h"
-#include "CloudsManager.h"
-#include "SkyLightManager.h"
-#include "FogVolumeRenderNode.h"
-#include "DecalRenderNode.h"
-#include "TimeOfDay.h"
-#include "LightEntity.h"
-#include "FogVolumeRenderNode.h"
-#include "ObjectsTree.h"
-#include "WaterVolumeRenderNode.h"
-#include "DistanceCloudRenderNode.h"
-#include "VolumeObjectRenderNode.h"
-#include "RenderMeshMerger.h"
-#include "DeferredCollisionEvent.h"
-#include "OpticsManager.h"
-#include "ClipVolumeManager.h"
-#include "Environment/OceanEnvironmentBus.h"
-
-
-#if !defined(EXCLUDE_DOCUMENTATION_PURPOSE)
-#include "PrismRenderNode.h"
-#endif // EXCLUDE_DOCUMENTATION_PURPOSE
-
-//Platform specific includes
-#if defined(WIN32) || defined(WIN64)
-#include "CryWindows.h"
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-void C3DEngine::CheckAddLight(CDLight* pLight, const SRenderingPassInfo& passInfo)
-{
- if (pLight->m_Id < 0)
- {
- GetRenderer()->EF_ADDDlight(pLight, passInfo);
- assert(pLight->m_Id >= 0);
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-float C3DEngine::GetLightAmount(CDLight* pLight, const AABB& objBox)
-{
- // find amount of light
- float fDist = sqrt_tpl(Distance::Point_AABBSq(pLight->m_Origin, objBox));
- float fLightAttenuation = (pLight->m_Flags & DLF_DIRECTIONAL) ? 1.f : 1.f - (fDist) / (pLight->m_fRadius);
- if (fLightAttenuation < 0)
- {
- fLightAttenuation = 0;
- }
-
- float fLightAmount =
- (pLight->m_Color.r + pLight->m_Color.g + pLight->m_Color.b) * 0.233f +
- (pLight->GetSpecularMult()) * 0.1f;
-
- return fLightAmount * fLightAttenuation;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-float C3DEngine::GetWaterLevel()
-{
- if (OceanToggle::IsActive())
- {
- return OceanRequest::GetOceanLevel();
- }
- return m_pOcean ? m_pOcean->GetWaterLevel() : WATER_LEVEL_UNKNOWN;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-bool C3DEngine::IsTessellationAllowed(const CRenderObject* pObj, const SRenderingPassInfo& passInfo, bool bIgnoreShadowPass) const
-{
-#ifdef MESH_TESSELLATION_ENGINE
- assert(pObj && GetCVars());
- bool rendererTessellation;
- GetRenderer()->EF_Query(EFQ_MeshTessellation, rendererTessellation);
- if (pObj->m_fDistance < GetCVars()->e_TessellationMaxDistance
- && GetCVars()->e_Tessellation
- && rendererTessellation
- && !(pObj->m_ObjFlags & FOB_DISSOLVE)) // dissolve is not working with tessellation for now
- {
- bool bAllowTessellation = true;
-
- // Check if rendering into shadow map and enable tessellation only if allowed
- if (!bIgnoreShadowPass && passInfo.IsShadowPass())
- {
- if (IsTessellationAllowedForShadowMap(passInfo))
- {
- // NOTE: This might be useful for game projects
- // Use tessellation only for objects visible in main view
- // Shadows will switch to non-tessellated when caster gets out of view
- IRenderNode* pRN = (IRenderNode*)pObj->m_pRenderNode;
- if (pRN)
- {
- bAllowTessellation = (pRN->IsRenderNode() && (pRN->GetDrawFrame() > passInfo.GetFrameID() - 10));
- }
- }
- else
- {
- bAllowTessellation = false;
- }
- }
-
- return bAllowTessellation;
- }
-#endif //#ifdef MESH_TESSELLATION_ENGINE
-
- return false;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-void C3DEngine::CreateRNTmpData(CRNTmpData** ppInfo, IRenderNode* pRNode, const SRenderingPassInfo& passInfo)
-{
- // m_checkCreateRNTmpData lock scope
- {
- AUTO_LOCK(m_checkCreateRNTmpData);
- FUNCTION_PROFILER_3DENGINE;
-
- if (*ppInfo)
- {
- return; // check if another thread already intialized ppInfo
- }
- // make sure element is allocated
- if (m_LTPRootFree.pNext == &m_LTPRootFree)
- {
- CRNTmpData* pNew = new CRNTmpData; //m_RNTmpDataPools.GetNewElement();
- pNew->Link(&m_LTPRootFree);
- }
-
- // move element from m_LTPRootFree to m_LTPRootUsed
- CRNTmpData* pElem = m_LTPRootFree.pNext;
- pElem->Unlink();
- pElem->Link(&m_LTPRootUsed);
-
- pElem->pOwnerRef = ppInfo;
- pElem->nFrameInfoId = GetFrameInfoId(ppInfo, passInfo.GetMainFrameID());
-
- assert(!pElem->pOwnerRef || !(*pElem->pOwnerRef));
- memset(&pElem->userData, 0, sizeof(pElem->userData));
-
-
- // Add a memory barrier that the write to nFrameInfoID is visible
- // before *ppInfo is written, else we have a race condtition in
- // CheckCreateRNTmpData as we don't use a lock there
- // for performance reasons
- MemoryBarrier();
-
- *ppInfo = pElem;
- }
-
- if (pRNode)
- {
- pRNode->OnRenderNodeBecomeVisible(passInfo); // Internally uses the just assigned RNTmpData pointer i.e IRenderNode::m_pRNTmpData ...
-
- if (IVisArea* pVisArea = pRNode->GetEntityVisArea())
- {
- pRNode->m_pRNTmpData->userData.m_pClipVolume = pVisArea;
- }
- else if (GetClipVolumeManager()->IsClipVolumeRequired(pRNode))
- {
- GetClipVolumeManager()->UpdateEntityClipVolume(pRNode->GetPos(), pRNode);
- }
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-void C3DEngine::RenderRenderNode_ShadowPass(IShadowCaster* pShadowCaster, const SRenderingPassInfo& passInfo, [[maybe_unused]] AZ::LegacyJobExecutor* pJobExecutor)
-{
- assert(passInfo.IsShadowPass());
-
- SRendItemSorter rendItemSorter = SRendItemSorter::CreateShadowPassRendItemSorter(passInfo);
-
- if (!pShadowCaster->IsRenderNode())
- {
- const Vec3 vCamPos = passInfo.GetCamera().GetPosition();
- const AABB objBox = pShadowCaster->GetBBoxVirtual();
-
- SRendParams rParams;
- rParams.fDistance = sqrt_tpl(Distance::Point_AABBSq(vCamPos, objBox)) * passInfo.GetZoomFactor();
- rParams.lodValue = pShadowCaster->ComputeLod(0, passInfo);
- rParams.rendItemSorter = rendItemSorter.GetValue();
-
- pShadowCaster->Render(rParams, passInfo);
- return;
- }
-
- IRenderNode* pRenderNode = static_cast(pShadowCaster);
- if ((pRenderNode->m_dwRndFlags & ERF_HIDDEN) != 0)
- {
- return;
- }
-
- int nStaticObjectLod = -1;
- if (passInfo.GetShadowMapType() == SRenderingPassInfo::SHADOW_MAP_CACHED)
- {
- nStaticObjectLod = GetCVars()->e_ShadowsCacheObjectLod;
- }
- else if (passInfo.GetShadowMapType() == SRenderingPassInfo::SHADOW_MAP_CACHED_MGPU_COPY)
- {
- nStaticObjectLod = pRenderNode->m_cStaticShadowLod;
- }
-
- Get3DEngine()->CheckCreateRNTmpData(&pRenderNode->m_pRNTmpData, pRenderNode, passInfo);
-
- int wantedLod = pRenderNode->m_pRNTmpData->userData.nWantedLod;
-
- if (GetCVars()->e_LodForceUpdate && m_pObjManager)
- {
- const Vec3 vCamPos = passInfo.GetCamera().GetPosition();
- const AABB objBox = pRenderNode->GetBBoxVirtual();
- float fDistance = sqrt_tpl(Distance::Point_AABBSq(vCamPos, objBox)) * passInfo.GetZoomFactor();
- wantedLod = m_pObjManager->GetObjectLOD(pRenderNode, fDistance);
- }
-
- if (pRenderNode->GetShadowLodBias() != IRenderNode::SHADOW_LODBIAS_DISABLE)
- {
- if (passInfo.IsShadowPass() && (pRenderNode->GetDrawFrame(0) < (passInfo.GetFrameID() - 10)))
- {
- wantedLod += GetCVars()->e_ShadowsLodBiasInvis;
- }
- wantedLod += GetCVars()->e_ShadowsLodBiasFixed;
- wantedLod += pRenderNode->GetShadowLodBias();
- }
-
- if (nStaticObjectLod >= 0)
- {
- wantedLod = nStaticObjectLod;
- }
-
- {
- const Vec3 vCamPos = passInfo.GetCamera().GetPosition();
- const AABB objBox = pRenderNode->GetBBoxVirtual();
- SRendParams rParams;
- rParams.fDistance = sqrt_tpl(Distance::Point_AABBSq(vCamPos, objBox)) * passInfo.GetZoomFactor();
- rParams.lodValue = pRenderNode->ComputeLod(wantedLod, passInfo);
- rParams.rendItemSorter = rendItemSorter.GetValue();
- rParams.pRenderNode = pRenderNode;
- pRenderNode->Render(rParams, passInfo);
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-ITimeOfDay* C3DEngine::GetTimeOfDay()
-{
- CTimeOfDay* tod = m_pTimeOfDay;
-
- if (!tod)
- {
- tod = new CTimeOfDay;
- m_pTimeOfDay = tod;
- }
-
- return tod;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-void C3DEngine::TraceFogVolumes(const Vec3& vPos, const AABB& objBBox, SFogVolumeData& fogVolData, const SRenderingPassInfo& passInfo, bool fogVolumeShadingQuality)
-{
- CFogVolumeRenderNode::TraceFogVolumes(vPos, objBBox, fogVolData, passInfo, fogVolumeShadingQuality);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-void C3DEngine::AsyncOctreeUpdate(IRenderNode* pEnt, int nSID, [[maybe_unused]] int nSIDConsideredSafe, uint32 nFrameID, bool bUnRegisterOnly)
-{
- FUNCTION_PROFILER_3DENGINE;
-
-#ifdef _DEBUG // crash test basically
- const char* szClass = pEnt->GetEntityClassName();
- const char* szName = pEnt->GetName();
- if (!szName[0] && !szClass[0])
- {
- Warning("I3DEngine::RegisterEntity: Entity undefined"); // do not register undefined objects
- }
- // if(strstr(szName,"Dude"))
- // int y=0;
-#endif
-
- IF (bUnRegisterOnly, 0)
- {
- UnRegisterEntityImpl(pEnt);
- return;
- }
- ;
-
- AABB aabb;
- pEnt->FillBBox(aabb);
- float fObjRadiusSqr = aabb.GetRadiusSqr();
- EERType eERType = pEnt->GetRenderNodeType();
-
-#ifdef SUPP_HMAP_OCCL
- if (pEnt->m_pRNTmpData)
- {
- pEnt->m_pRNTmpData->userData.m_OcclState.vLastVisPoint.Set(0, 0, 0);
- }
-#endif
-
-
- const unsigned int dwRndFlags = pEnt->GetRndFlags();
-
- if (!(dwRndFlags & ERF_RENDER_ALWAYS) && !(dwRndFlags & ERF_CASTSHADOWMAPS))
- {
- if (GetCVars()->e_ObjFastRegister && pEnt->m_pOcNode && ((COctreeNode*)pEnt->m_pOcNode)->IsRightNode(aabb, fObjRadiusSqr, pEnt->m_fWSMaxViewDist))
- { // same octree node
- Vec3 vEntCenter = GetEntityRegisterPoint(pEnt);
-
- IVisArea* pVisArea = pEnt->GetEntityVisArea();
- if (pVisArea && pVisArea->IsPointInsideVisArea(vEntCenter))
- {
- return; // same visarea
- }
- IVisArea* pVisAreaFromPos = (!m_pVisAreaManager || dwRndFlags & ERF_OUTDOORONLY) ? NULL : GetVisAreaManager()->GetVisAreaFromPos(vEntCenter);
- if (pVisAreaFromPos == pVisArea)
- {
- // NOTE: can only get here when pVisArea==NULL due to 'same visarea' check above. So check for changed clip volume
- if (GetClipVolumeManager()->IsClipVolumeRequired(pEnt))
- {
- GetClipVolumeManager()->UpdateEntityClipVolume(vEntCenter, pEnt);
- }
-
- return; // same visarea or same outdoor
- }
- }
- }
-
- if (pEnt->m_pOcNode)
- {
- UnRegisterEntityImpl(pEnt);
- }
- else if (GetCVars()->e_StreamCgf && (eERType == eERType_RenderComponent || eERType == eERType_DynamicMeshRenderComponent || eERType == eERType_GeomCache))
- { // Temporary solution: Force streaming priority update for objects that was not registered before
- // and was not visible before since usual prediction system was not able to detect them
-
- if ((uint32)pEnt->GetDrawFrame(0) < nFrameID - 16)
- {
- // defer the render node streaming priority update still we have a correct 3D Engine camera
- int nElementID = m_deferredRenderComponentStreamingPriorityUpdates.Find(pEnt);
- if (nElementID == -1) // only add elements once
- {
- m_deferredRenderComponentStreamingPriorityUpdates.push_back(pEnt);
- }
- }
- }
-
- pEnt->m_fWSMaxViewDist = pEnt->GetMaxViewDist();
-
- bool useVisAreas = true;
-
- if (eERType != eERType_Light)
- {
- if (fObjRadiusSqr > sqr(MAX_VALID_OBJECT_VOLUME) || !_finite(fObjRadiusSqr))
- {
- Warning("I3DEngine::RegisterEntity: Object has invalid bbox: name: %s, class name: %s, GetRadius() = %.2f",
- pEnt->GetName(), pEnt->GetEntityClassName(), fObjRadiusSqr);
- return; // skip invalid objects - usually only objects with invalid very big scale will reach this point
- }
-
- if (dwRndFlags & ERF_RENDER_ALWAYS)
- {
- if (m_lstAlwaysVisible.Find(pEnt) < 0)
- {
- m_lstAlwaysVisible.Add(pEnt);
- }
-
- if (dwRndFlags & ERF_HUD)
- {
- return;
- }
- }
-
- if (pEnt->m_dwRndFlags & ERF_OUTDOORONLY)
- {
- useVisAreas = false;
- }
- }
- else
- {
- CLightEntity* pLight = (CLightEntity*)pEnt;
- uint32 lightFlag = pLight->m_light.m_Flags;
- if ((lightFlag & DLF_ATTACH_TO_SUN) || //If the light is attached to the sun, we need to make sure it renders even the entity is not in view port
- (lightFlag & (DLF_IGNORES_VISAREAS | DLF_DEFERRED_LIGHT | DLF_THIS_AREA_ONLY)) == (DLF_IGNORES_VISAREAS | DLF_DEFERRED_LIGHT)
- )
- {
- if (m_lstAlwaysVisible.Find(pEnt) < 0)
- {
- m_lstAlwaysVisible.Add(pEnt);
- }
- }
-
- if (lightFlag & DLF_IGNORES_VISAREAS)
- {
- useVisAreas = false;
- }
- }
-
- //////////////////////////////////////////////////////////////////////////
- // Check for occlusion proxy.
- {
- CStatObj* pStatObj = (CStatObj*)pEnt->GetEntityStatObj();
- if (pStatObj)
- {
- if (pStatObj->m_bHaveOcclusionProxy)
- {
- pEnt->m_dwRndFlags |= ERF_GOOD_OCCLUDER;
- pEnt->m_nInternalFlags |= IRenderNode::HAS_OCCLUSION_PROXY;
- }
- }
- }
- //////////////////////////////////////////////////////////////////////////
- if (!useVisAreas || !(m_pVisAreaManager && m_pVisAreaManager->SetEntityArea(pEnt, aabb, fObjRadiusSqr)))
- {
- if (m_pObjectsTree == nullptr)
- {
- AZ::Aabb terrainAabb = AZ::Aabb::CreateFromPoint(AZ::Vector3::CreateZero());
- AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult(terrainAabb, &AzFramework::Terrain::TerrainDataRequests::GetTerrainAabb);
- m_pObjectsTree = COctreeNode::Create(nSID, AABB(Vec3(0, 0, 0), Vec3(terrainAabb.GetXExtent(), terrainAabb.GetYExtent(), terrainAabb.GetZExtent())), NULL);
- }
-
- m_pObjectsTree->InsertObject(pEnt, aabb, fObjRadiusSqr, aabb.GetCenter());
- }
-
- // update clip volume: use vis area if we have one, otherwise check if we're in the same volume as before. check other volumes as last resort only
- if (pEnt->m_pRNTmpData)
- {
- Vec3 vEntCenter = GetEntityRegisterPoint(pEnt);
- CRNTmpData::SRNUserData& userData = pEnt->m_pRNTmpData->userData;
-
- if (IVisArea* pVisArea = pEnt->GetEntityVisArea())
- {
- userData.m_pClipVolume = pVisArea;
- }
- else if (GetClipVolumeManager()->IsClipVolumeRequired(pEnt))
- {
- GetClipVolumeManager()->UpdateEntityClipVolume(vEntCenter, pEnt);
- }
- }
-
- // register decals, to clean up longer not renderes decals and their render meshes
- if (eERType == eERType_Decal)
- {
- m_decalRenderNodes.push_back((IDecalRenderNode*)pEnt);
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-bool C3DEngine::UnRegisterEntityImpl(IRenderNode* pEnt)
-{
- // make sure we don't try to update the streaming priority if an object
- // was added and removed in the same frame
- int nElementID = m_deferredRenderComponentStreamingPriorityUpdates.Find(pEnt);
- if (nElementID != -1)
- {
- m_deferredRenderComponentStreamingPriorityUpdates.DeleteFastUnsorted(nElementID);
- }
-
- FUNCTION_PROFILER_3DENGINE;
-
-#ifdef _DEBUG // crash test basically
- const char* szClass = pEnt->GetEntityClassName();
- const char* szName = pEnt->GetName();
- if (!szName[0] && !szClass[0])
- {
- Warning("C3DEngine::RegisterEntity: Entity undefined");
- }
-#endif
-
- EERType eRenderNodeType = pEnt->GetRenderNodeType();
-
- bool bFound = false;
-
- if (pEnt->m_pOcNode)
- {
- bFound = ((COctreeNode*)pEnt->m_pOcNode)->DeleteObject(pEnt);
- }
-
- if (pEnt->m_dwRndFlags & ERF_RENDER_ALWAYS || (eRenderNodeType == eERType_Light) || (eRenderNodeType == eERType_FogVolume))
- {
- m_lstAlwaysVisible.Delete(pEnt);
- }
-
- if (eRenderNodeType == eERType_Decal)
- {
- std::vector::iterator it = std::find(m_decalRenderNodes.begin(), m_decalRenderNodes.end(), (IDecalRenderNode*)pEnt);
- if (it != m_decalRenderNodes.end())
- {
- m_decalRenderNodes.erase(it);
- }
- }
-
- if (CClipVolumeManager* pClipVolumeManager = GetClipVolumeManager())
- {
- pClipVolumeManager->UnregisterRenderNode(pEnt);
- }
-
- return bFound;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-Vec3 C3DEngine::GetEntityRegisterPoint(IRenderNode* pEnt)
-{
- AABB aabb;
- pEnt->FillBBox(aabb);
-
- Vec3 vPoint;
-
- if (pEnt->m_dwRndFlags & ERF_REGISTER_BY_POSITION)
- {
- vPoint = pEnt->GetPos();
-
- if (pEnt->GetRenderNodeType() != eERType_Light)
- {
- // check for valid position
- if (aabb.GetDistanceSqr(vPoint) > sqr(128.f))
- {
- Warning("I3DEngine::RegisterEntity: invalid entity position: Name: %s, Class: %s, Pos=(%.1f,%.1f,%.1f), BoxMin=(%.1f,%.1f,%.1f), BoxMax=(%.1f,%.1f,%.1f)",
- pEnt->GetName(), pEnt->GetEntityClassName(),
- pEnt->GetPos().x, pEnt->GetPos().y, pEnt->GetPos().z,
- pEnt->GetBBox().min.x, pEnt->GetBBox().min.y, pEnt->GetBBox().min.z,
- pEnt->GetBBox().max.x, pEnt->GetBBox().max.y, pEnt->GetBBox().max.z
- );
- }
- // clamp by bbox
- vPoint.CheckMin(aabb.max);
- vPoint.CheckMax(aabb.min + Vec3(0, 0, .5f));
- }
- }
- else
- {
- vPoint = aabb.GetCenter();
- }
-
- return vPoint;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-Vec3 C3DEngine::GetSunDirNormalized() const
-{
- return m_vSunDirNormalized;
-}
-
-
diff --git a/Code/CryEngine/Cry3DEngine/3dEngine.cpp b/Code/CryEngine/Cry3DEngine/3dEngine.cpp
deleted file mode 100644
index 1050916423..0000000000
--- a/Code/CryEngine/Cry3DEngine/3dEngine.cpp
+++ /dev/null
@@ -1,5536 +0,0 @@
-/*
-* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
-* its licensors.
-*
-* For complete copyright and license terms please see the LICENSE at the root of this
-* distribution (the "License"). All use of this software is governed by the License,
-* or, if provided, by the license below or the license accompanying this file. Do not
-* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-*
-*/
-// Original file Copyright Crytek GMBH or its affiliates, used under license.
-
-// Description : Implementation of I3DEngine interface methods
-
-
-#include "Cry3DEngine_precompiled.h"
-
-#include "3dEngine.h"
-
-#include
-#include
-#include
-#include "VisAreas.h"
-#include "ObjMan.h"
-#include "Ocean.h"
-#include
-#include "DecalManager.h"
-#include "IndexedMesh.h"
-
-#include "MatMan.h"
-
-#include "CullBuffer.h"
-#include "CGF/CGFLoader.h"
-#include "CGF/ChunkFileWriters.h"
-#include "CGF/ReadOnlyChunkFile.h"
-
-#include "CloudRenderNode.h"
-#include "CloudsManager.h"
-#include "SkyLightManager.h"
-#include "FogVolumeRenderNode.h"
-#include "DecalRenderNode.h"
-#include "TimeOfDay.h"
-#include "LightEntity.h"
-#include "FogVolumeRenderNode.h"
-#include "ObjectsTree.h"
-#include "WaterVolumeRenderNode.h"
-#include "DistanceCloudRenderNode.h"
-#include "VolumeObjectRenderNode.h"
-#include "RenderMeshMerger.h"
-#include "DeferredCollisionEvent.h"
-#include "OpticsManager.h"
-#include "GeomCacheRenderNode.h"
-#include "GeomCacheManager.h"
-#include "ClipVolumeManager.h"
-#include
-#include "PostEffectGroup.h"
-#include "MainThreadRenderRequestBus.h"
-#include "ObjMan.h"
-#include "Environment/OceanEnvironmentBus.h"
-#include
-#include
-
-#if !defined(EXCLUDE_DOCUMENTATION_PURPOSE)
-#include "PrismRenderNode.h"
-#endif // EXCLUDE_DOCUMENTATION_PURPOSE
-
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include
-
-// required for LARGE_INTEGER used by QueryPerformanceCounter
-#ifdef WIN32
-#include
-#endif
-
-threadID Cry3DEngineBase::m_nMainThreadId = 0;
-bool Cry3DEngineBase::m_bRenderTypeEnabled[eERType_TypesNum];
-ISystem* Cry3DEngineBase::m_pSystem = 0;
-IRenderer* Cry3DEngineBase::m_pRenderer = 0;
-ITimer* Cry3DEngineBase::m_pTimer = 0;
-ILog* Cry3DEngineBase::m_pLog = 0;
-
-COcean* Cry3DEngineBase::m_pOcean = nullptr;
-CObjManager* Cry3DEngineBase::m_pObjManager = 0;
-IConsole* Cry3DEngineBase::m_pConsole = 0;
-C3DEngine* Cry3DEngineBase::m_p3DEngine = 0;
-CVars* Cry3DEngineBase::m_pCVars = 0;
-AZ::IO::IArchive* Cry3DEngineBase::m_pCryPak = nullptr;
-IOpticsManager* Cry3DEngineBase::m_pOpticsManager = 0;
-CDecalManager* Cry3DEngineBase::m_pDecalManager = 0;
-CSkyLightManager* Cry3DEngineBase::m_pSkyLightManager = 0;
-CCloudsManager* Cry3DEngineBase::m_pCloudsManager = 0;
-CVisAreaManager* Cry3DEngineBase::m_pVisAreaManager = 0;
-CClipVolumeManager* Cry3DEngineBase::m_pClipVolumeManager = 0;
-CRenderMeshMerger* Cry3DEngineBase::m_pRenderMeshMerger = 0;
-CMatMan* Cry3DEngineBase::m_pMatMan = 0;
-IStreamedObjectListener* Cry3DEngineBase::m_pStreamListener = 0;
-#if defined(USE_GEOM_CACHES)
-CGeomCacheManager* Cry3DEngineBase::m_pGeomCacheManager = 0;
-#endif
-
-bool Cry3DEngineBase::m_bLevelLoadingInProgress = false;
-bool Cry3DEngineBase::m_bIsInRenderScene = false;
-
-int Cry3DEngineBase::m_CpuFlags = 0;
-#if !defined(CONSOLE)
-bool Cry3DEngineBase::m_bEditor = false;
-#endif //!defined(CONSOLE)
-ESystemConfigSpec Cry3DEngineBase::m_LightConfigSpec = CONFIG_VERYHIGH_SPEC;
-int Cry3DEngineBase::m_arrInstancesCounter[eERType_TypesNum];
-
-#define LAST_POTENTIALLY_VISIBLE_TIME 2
-
-namespace
-{
- class CLoadLogListener
- : public ILoaderCGFListener
- {
- public:
- virtual ~CLoadLogListener(){}
- virtual void Warning(const char* format) {Cry3DEngineBase::Warning("%s", format); }
- virtual void Error(const char* format) {Cry3DEngineBase::Error("%s", format); }
- virtual bool IsValidationEnabled() { return Cry3DEngineBase::GetCVars()->e_StatObjValidate != 0; }
- };
-}
-
-namespace OceanGlobals
-{
- float g_oceanLevel = 0.0f;
- float g_oceanStep = 1.0f;
- AZStd::recursive_mutex g_oceanParamsMutex;
-}
-
-//////////////////////////////////////////////////////////////////////
-C3DEngine::C3DEngine(ISystem* pSystem)
-{
- //#if defined(_DEBUG) && defined(WIN32)
- // _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
- //#endif
-
- // Level info
- m_fSunSpecMult = 1.f;
- m_bAreaActivationInUse = false;
-
- Cry3DEngineBase::m_nMainThreadId = CryGetCurrentThreadId();
- Cry3DEngineBase::m_pSystem = pSystem;
- Cry3DEngineBase::m_pRenderer = gEnv->pRenderer;
- Cry3DEngineBase::m_pTimer = gEnv->pTimer;
- Cry3DEngineBase::m_pLog = gEnv->pLog;
- Cry3DEngineBase::m_pConsole = gEnv->pConsole;
- Cry3DEngineBase::m_p3DEngine = this;
- Cry3DEngineBase::m_pCryPak = gEnv->pCryPak;
- Cry3DEngineBase::m_pCVars = 0;
- Cry3DEngineBase::m_pRenderMeshMerger = new CRenderMeshMerger;
- Cry3DEngineBase::m_pMatMan = new CMatMan;
- Cry3DEngineBase::m_pStreamListener = NULL;
- Cry3DEngineBase::m_CpuFlags = pSystem->GetCPUFlags();
-
- memset(Cry3DEngineBase::m_arrInstancesCounter, 0, sizeof(Cry3DEngineBase::m_arrInstancesCounter));
-
-#if !defined(CONSOLE)
- m_bEditor = gEnv->IsEditor();
-#endif
- m_pObjectsTree = nullptr;
- m_pCVars = new CVars();
- Cry3DEngineBase::m_pCVars = m_pCVars;
-
- m_pTimeOfDay = NULL;
-
- m_postEffectGroups = std::make_unique();
- m_postEffectBaseGroup = m_postEffectGroups->GetGroup("Base");
- if (IPostEffectGroup* pPostEffectsDefaultGroup = m_postEffectGroups->GetGroup(m_defaultPostEffectGroup))
- {
- pPostEffectsDefaultGroup->SetEnable(true);
- }
-
- m_szLevelFolder[0] = 0;
-
- m_pSun = 0;
- m_nFlags = 0;
- m_pSkyMat = 0;
- m_pSkyLowSpecMat = 0;
- m_pTerrainWaterMat = 0;
- m_nWaterBottomTexId = 0;
- m_vSunDir = Vec3(5.f, 5.f, DISTANCE_TO_THE_SUN);
- m_vSunDirRealtime = Vec3(5.f, 5.f, DISTANCE_TO_THE_SUN).GetNormalized();
-
- m_nBlackTexID = 0;
-
- // create components
- m_pObjManager = CryAlignedNew();
-
- m_pDecalManager = 0;//new CDecalManager (m_pSystem, this);
- m_pCloudsManager = new CCloudsManager;
- m_pOpticsManager = 0;
- m_pVisAreaManager = 0;
- m_pClipVolumeManager = new CClipVolumeManager();
- m_pSkyLightManager = CryAlignedNew();
-
- // create REs
- m_pRESky = 0;
- m_pREHDRSky = 0;
-
- m_pPhysMaterialEnumerator = 0;
-
- m_fMaxViewDistHighSpec = 8000;
- m_fMaxViewDistLowSpec = 1000;
-
- m_fSkyBoxAngle = 0;
- m_fSkyBoxStretching = 0;
-
-
- m_physicsAreaUpdatesHandler = AZStd::make_unique(m_PhysicsAreaUpdates);
-
- m_bOcean = true;
- m_nOceanRenderFlags = 0;
-
- m_bSunShadows = true;
- m_nSunAdditionalCascades = 0;
- m_CachedShadowsBounds.Reset();
- m_nCachedShadowsUpdateStrategy = ShadowMapFrustum::ShadowCacheData::eFullUpdate;
-
- m_fSunClipPlaneRange = 256.0f;
- m_fSunClipPlaneRangeShift = 0.0f;
-
- m_nRealLightsNum = m_nDeferredLightsNum = 0;
-
- m_pCoverageBuffer = CryAlignedNew();
-
- m_fLightsHDRDynamicPowerFactor = 0.0f;
-
- m_vHDRFilmCurveParams = Vec4(1.0f, 1.0f, 1.0f, 1.0f);
- m_vHDREyeAdaptation = Vec3(0.05f, 0.8f, 0.9f);
- m_fHDRBloomAmount = 0.0f;
- m_vColorBalance = Vec3(1.0f, 1.0f, 1.0f);
- m_fHDRSaturation = 1.0f;
-
- m_vSkyHightlightPos.Set(0, 0, 0);
- m_vSkyHightlightCol.Set(0, 0, 0);
- m_fSkyHighlightSize = 0;
-
- m_volFogGlobalDensity = 0.02f;
- m_volFogGlobalDensityMultiplierLDR = 1.0f;
- m_volFogFinalDensityClamp = 1.0f;
-
- m_idMatLeaves = -1;
-
- m_oceanFogColor = 0.2f * Vec3(29.0f, 102.0f, 141.0f) / 255.0f;
- m_oceanFogColorShallow = Vec3(0, 0, 0); //0.5f * Vec3( 206.0f, 249.0f, 253.0f ) / 255.0f;
- m_oceanFogDensity = 0; //0.2f;
-
- m_oceanCausticsDistanceAtten = 100.0f;
-
- m_oceanCausticDepth = 8.0f;
- m_oceanCausticIntensity = 1.0f;
-
- m_oceanWindDirection = 1;
- m_oceanWindSpeed = 4.0f;
- m_oceanWavesSpeed = 1.0f;
- m_oceanWavesAmount = 1.5f;
- m_oceanWavesSize = 0.75f;
-
- m_fParticlesAmbientMultiplier = m_fParticlesLightMultiplier = 1.f;
- m_fRefreshSceneDataCVarsSumm = -1;
- m_nRenderTypeEnableCVarSum = -1;
-
- if (!m_LTPRootFree.pNext)
- {
- m_LTPRootFree.pNext = &m_LTPRootFree;
- m_LTPRootFree.pPrev = &m_LTPRootFree;
- }
-
- if (!m_LTPRootUsed.pNext)
- {
- m_LTPRootUsed.pNext = &m_LTPRootUsed;
- m_LTPRootUsed.pPrev = &m_LTPRootUsed;
- }
- m_bResetRNTmpDataPool = false;
-
- m_fSunDirUpdateTime = 0;
- m_vSunDirNormalized.zero();
-
- m_volFogRamp = Vec3(0, 100.0f, 0);
- m_volFogShadowRange = Vec3(0.1f, 0, 0);
- m_volFogShadowDarkening = Vec3(0.25f, 1, 1);
- m_volFogShadowEnable = Vec3(0, 0, 0);
- m_volFog2CtrlParams = Vec3(64.0f, 0.0f, 1.0f);
- m_volFog2ScatteringParams = Vec3(1.0f, 0.3f, 0.6f);
- m_volFog2Ramp = Vec3(0.0f, 0.0f, 0.0f);
- m_volFog2Color = Vec3(1.0f, 1.0f, 1.0f);
- m_volFog2GlobalDensity = Vec3(0.1f, 1.0f, 0.4f);
- m_volFog2HeightDensity = Vec3(0.0f, 1.0f, 0.1f);
- m_volFog2HeightDensity2 = Vec3(4000.0f, 0.0001f, 0.95f);
- m_volFog2Color1 = Vec3(1.0f, 1.0f, 1.0f);
- m_volFog2Color2 = Vec3(1.0f, 1.0f, 1.0f);
- m_nightSkyHorizonCol = Vec3(0, 0, 0);
- m_nightSkyZenithCol = Vec3(0, 0, 0);
- m_nightSkyZenithColShift = 0;
- m_nightSkyStarIntensity = 0;
- m_moonDirection = Vec3(0, 0, 0);
- m_nightMoonCol = Vec3(0, 0, 0);
- m_nightMoonSize = 0;
- m_nightMoonInnerCoronaCol = Vec3(0, 0, 0);
- m_nightMoonInnerCoronaScale = 1.0f;
- m_nightMoonOuterCoronaCol = Vec3(0, 0, 0);
- m_nightMoonOuterCoronaScale = 1.0f;
- m_moonRotationLatitude = 0;
- m_moonRotationLongitude = 0;
- m_skyboxMultiplier = 1.0f;
- m_dayNightIndicator = 1.0f;
- m_fogColor2 = Vec3(0, 0, 0);
- m_fogColorRadial = Vec3(0, 0, 0);
- m_volFogHeightDensity = Vec3(0, 1, 0);
- m_volFogHeightDensity2 = Vec3(4000.0f, 0, 0);
- m_volFogGradientCtrl = Vec3(1, 1, 1);
-
- m_vFogColor = Vec3(1.0f, 1.0f, 1.0f);
- m_vAmbGroundCol = Vec3(0.0f, 0.0f, 0.0f);
-
- m_dawnStart = 350.0f / 60.0f;
- m_dawnEnd = 360.0f / 60.0f;
- m_duskStart = 12.0f + 360.0f / 60.0f;
- m_duskEnd = 12.0f + 370.0f / 60.0f;
-
- m_fCloudShadingSunLightMultiplier = 0;
- m_fCloudShadingSkyLightMultiplier = 0;
- m_vCloudShadingCustomSunColor = Vec3(0, 0, 0);
- m_vCloudShadingCustomSkyColor = Vec3(0, 0, 0);
-
- m_vPrevMainFrameCamPos.Set(-1000000.f, -1000000.f, -1000000.f);
- m_fAverageCameraSpeed = 0;
- m_vAverageCameraMoveDir = Vec3(0);
- m_bContentPrecacheRequested = false;
- m_bTerrainTextureStreamingInProgress = false;
- m_bLayersActivated = false;
- m_eShadowMode = ESM_NORMAL;
-
- ClearDebugFPSInfo();
-
- m_fMaxViewDistScale = 1.f;
-
- m_ptexIconLowMemoryUsage = NULL;
- m_ptexIconAverageMemoryUsage = NULL;
- m_ptexIconHighMemoryUsage = NULL;
- m_ptexIconEditorConnectedToConsole = NULL;
- m_pScreenshotCallback = 0;
- m_bInShutDown = false;
- m_bInUnload = false;
- m_bInLoad = false;
-
- m_nCloudShadowTexId = 0;
-
- m_nNightMoonTexId = 0;
-
- m_pDeferredPhysicsEventManager = new CDeferredPhysicsEventManager();
-
-#if defined(USE_GEOM_CACHES)
- m_pGeomCacheManager = new CGeomCacheManager();
-#endif
-
- m_LightVolumesMgr.Init();
-
- m_pBreakableBrushHeap = NULL;
-
- m_nWindSamplePositions = 0;
- m_pWindSamplePositions = NULL;
-
- m_fZoomFactor = 0.0f;
-
- m_fAmbMaxHeight = 0.0f;
- m_fAmbMinHeight = 0.0f;
-
- m_pLightQuality = NULL;
- m_fSaturation = 0.0f;
-
- m_fGsmRange = 0.0f;
- m_fGsmRangeStep = 0.0f;
- m_fShadowsConstBias = 0.0f;
- m_fShadowsSlopeBias = 0.0f;
- m_nCustomShadowFrustumCount = 0;
- m_bHeightMapAoEnabled = false;
-
- m_bendingPoolIdx = 0;
- m_levelLoaded = false;
-}
-
-//////////////////////////////////////////////////////////////////////
-C3DEngine::~C3DEngine()
-{
- m_bInShutDown = true;
- m_bInUnload = true;
- m_bInLoad = false;
-
- CheckMemoryHeap();
-
- ShutDown();
-
- delete m_pTimeOfDay;
- delete m_pDecalManager;
- delete m_pVisAreaManager;
- SAFE_DELETE(m_pClipVolumeManager);
-
- CryAlignedDelete(m_pCoverageBuffer);
- m_pCoverageBuffer = 0;
- CryAlignedDelete(m_pSkyLightManager);
- m_pSkyLightManager = 0;
- SAFE_DELETE(m_pObjectsTree);
- // delete m_pSceneTree;
- delete m_pRenderMeshMerger;
- delete m_pMatMan;
- m_pMatMan = 0;
- delete m_pCloudsManager;
-
- delete m_pCVars;
-
- delete m_pDeferredPhysicsEventManager;
-}
-
-bool C3DEngine::CheckMinSpec(uint32 nMinSpec)
-{
- return Cry3DEngineBase::CheckMinSpec(nMinSpec);
-}
-
-bool C3DEngine::Init()
-{
- m_pOpticsManager = new COpticsManager;
- m_pSystem->SetIOpticsManager(m_pOpticsManager);
-
- for (int i = 0; i < eERType_TypesNum; i++)
- {
- m_bRenderTypeEnabled[i] = true;
- }
-
- UpdateRenderTypeEnableLookup();
-
- // Allocate the temporary pool used for allocations during streaming and loading
- const size_t tempPoolSize = static_cast(GetCVars()->e_3dEngineTempPoolSize) << 10;
- AZ_Assert(tempPoolSize != 0, "Temp pool size should not be 0.");
-
- {
- if (!CTemporaryPool::Initialize(tempPoolSize))
- {
- AZ_Assert(false, "Could not initialize initialize temporary pool for 3D Engine startup.");
- return false;
- }
- }
-
- SFrameLodInfo frameLodInfo;
- frameLodInfo.fLodRatio = GetCVars()->e_LodRatio;
-
- frameLodInfo.fTargetSize = GetCVars()->e_LodFaceAreaTargetSize;
- AZ_Assert(frameLodInfo.fTargetSize > 0.f, "FrameLodInfo target size should be greater than 0.");
- if (frameLodInfo.fTargetSize <= 0.f)
- {
- frameLodInfo.fTargetSize = 1.f;
- }
-
- frameLodInfo.nMinLod = GetCVars()->e_LodMin;
- frameLodInfo.nMaxLod = GetCVars()->e_LodMax;
- if (GetCVars()->e_Lods == 0)
- {
- frameLodInfo.nMinLod = 0;
- frameLodInfo.nMaxLod = 0;
- }
- SetFrameLodInfo(frameLodInfo);
-
- return true;
-}
-
-bool C3DEngine::IsCameraAnd3DEngineInvalid(const SRenderingPassInfo& passInfo, const char* szCaller)
-{
- const CCamera& rCamera = passInfo.GetCamera();
- const float MAX_M23_REPORTED = 3000000.f; // MAT => upped from 100,000 which spammed this message on spear and cityhall. Really should stop editor generating
- // water levels that trigger this message.
-
- if (!_finite(rCamera.GetMatrix().m03) || !_finite(rCamera.GetMatrix().m13) || !_finite(rCamera.GetMatrix().m23) || GetMaxViewDistance() <= 0 ||
- rCamera.GetMatrix().m23 < -MAX_M23_REPORTED || rCamera.GetMatrix().m23 > MAX_M23_REPORTED || rCamera.GetFov() < 0.0001f || rCamera.GetFov() > gf_PI)
- {
- Error("Bad camera passed to 3DEngine from %s: Pos=(%.1f, %.1f, %.1f), Fov=%.1f, MaxViewDist=%.1f. Maybe the water level is too extreme.",
- szCaller,
- rCamera.GetMatrix().m03, rCamera.GetMatrix().m13, rCamera.GetMatrix().m23,
- rCamera.GetFov(), _finite(rCamera.GetMatrix().m03) ? GetMaxViewDistance() : 0);
- return true;
- }
-
- return false;
-}
-
-void C3DEngine::OnFrameStart()
-{
- FUNCTION_PROFILER_3DENGINE;
-
- m_nRenderWorldUSecs = 0;
- m_pDeferredPhysicsEventManager->Update();
-
- m_bendingPoolIdx = (m_bendingPoolIdx + 1) % NUM_BENDING_POOLS;
- m_bendingPool[m_bendingPoolIdx].resize(0);
-
-#if defined(USE_GEOM_CACHES)
- if (!gEnv->IsDedicated())
- {
- if (m_pGeomCacheManager)
- {
- m_pGeomCacheManager->StreamingUpdate();
- }
- }
-#endif
- //update texture load handlers
- for (TTextureLoadHandlers::iterator iter = m_textureLoadHandlers.begin(); iter != m_textureLoadHandlers.end(); iter++)
- {
- (*iter)->Update();
- }
-}
-
-float GetOceanLevelCallback(int ix, int iy)
-{
- using namespace OceanGlobals;
- return OceanToggle::IsActive() ? OceanRequest::GetAccurateOceanHeight(Vec3(ix * g_oceanStep, iy * g_oceanStep, g_oceanLevel)) : gEnv->p3DEngine->GetAccurateOceanHeight(Vec3(ix * g_oceanStep, iy * g_oceanStep, g_oceanLevel));
-}
-
-unsigned char GetOceanSurfTypeCallback([[maybe_unused]] int ix, [[maybe_unused]] int iy)
-{
- return 0;
-}
-
-void C3DEngine::Update()
-{
- FUNCTION_PROFILER_3DENGINE_LEGACYONLY;
- AZ_TRACE_METHOD();
-
- ProcessAsyncStaticObjectLoadRequests();
-
- m_LightConfigSpec = (ESystemConfigSpec)GetCurrentLightSpec();
-
- if (GetObjManager())
- {
- GetObjManager()->ClearStatObjGarbage();
- }
-
- if (m_pDecalManager)
- {
- m_pDecalManager->Update(GetTimer()->GetFrameTime());
- }
-
- if (GetCVars()->e_PrecacheLevel == 3)
- {
- PrecacheLevel(true, 0, 0);
- }
-
- DebugDraw_Draw();
-
- ProcessCVarsChange();
-
- {
- using namespace OceanGlobals;
- AZStd::lock_guard lock(g_oceanParamsMutex);
-
- g_oceanLevel = OceanToggle::IsActive() ? OceanRequest::GetOceanLevel() : GetWaterLevel();
- }
-
- CRenderMeshUtils::ClearHitCache();
-
- CleanUpOldDecals();
-
- CDecalRenderNode::ResetDecalUpdatesCounter();
-
-
- if (m_pBreakableBrushHeap)
- {
- m_pBreakableBrushHeap->Cleanup();
- }
-
- // make sure all jobs from the previous frame have finished
- threadID nThreadID;
- gEnv->pRenderer->EF_Query(EFQ_RenderThreadList, nThreadID);
- gEnv->pRenderer->GetFinalizeRendItemJobExecutor(nThreadID)->WaitForCompletion();
- gEnv->pRenderer->GetFinalizeShadowRendItemJobExecutor(nThreadID)->WaitForCompletion();
-
- UpdateRNTmpDataPool(m_bResetRNTmpDataPool);
- m_bResetRNTmpDataPool = false;
-
- m_PhysicsAreaUpdates.GarbageCollect();
-}
-
-void C3DEngine::Tick()
-{
- AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::System);
-
- // make sure all jobs from the previous frame have finished (also in Tick since Update is not called during loading)
- threadID nThreadID = 0;
- gEnv->pRenderer->EF_Query(EFQ_RenderThreadList, nThreadID);
- gEnv->pRenderer->GetFinalizeRendItemJobExecutor(nThreadID)->WaitForCompletion();
- gEnv->pRenderer->GetFinalizeShadowRendItemJobExecutor(nThreadID)->WaitForCompletion();
-
- AZ::MainThreadRenderRequestBus::ExecuteQueuedEvents();
-
- AZ::MaterialNotificationEventBus::ExecuteQueuedEvents();
-
- // clear stored cameras from last frame
- m_RenderingPassCameras[nThreadID].resize(0);
-}
-
-
-void C3DEngine::ProcessCVarsChange()
-{
- static int nObjectLayersActivation = -1;
-
- if (nObjectLayersActivation != GetCVars()->e_ObjectLayersActivation)
- {
- if (GetCVars()->e_ObjectLayersActivation == 2)
- {
- ActivateObjectsLayer(~0, true, true, true, true, "ALL_OBJECTS");
- }
- if (GetCVars()->e_ObjectLayersActivation == 3)
- {
- ActivateObjectsLayer(~0, false, true, true, true, "ALL_OBJECTS");
- }
-
- nObjectLayersActivation = GetCVars()->e_ObjectLayersActivation;
- }
-
- float fNewCVarsSumm =
- GetCVars()->e_ShadowsCastViewDistRatio +
- GetCVars()->e_Dissolve +
- GetFloatCVar(e_DissolveDistMin) +
- GetFloatCVar(e_DissolveDistMax) +
- GetFloatCVar(e_DissolveDistband) +
- GetCVars()->e_ViewDistRatio +
- GetCVars()->e_ViewDistMin +
- GetCVars()->e_ViewDistRatioDetail +
- GetCVars()->e_DefaultMaterial +
- GetGeomDetailScreenRes() +
- GetCVars()->e_Portals +
- GetCVars()->e_DebugDraw +
- GetFloatCVar(e_ViewDistCompMaxSize) +
- GetCVars()->e_DecalsDefferedStatic +
- GetRenderer()->GetWidth();
-
- if (m_fRefreshSceneDataCVarsSumm != -1 && m_fRefreshSceneDataCVarsSumm != fNewCVarsSumm)
- {
- UpdateStatInstGroups();
-
- AZ::Aabb terrainAabb = AZ::Aabb::CreateFromPoint(AZ::Vector3::CreateZero());
- AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult(terrainAabb, &AzFramework::Terrain::TerrainDataRequests::GetTerrainAabb);
- float terrainSize = AZ::GetMax(terrainAabb.GetXExtent(), terrainAabb.GetYExtent());
-
- // re-register every instance in level
- constexpr float UNREASONABLY_SMALL_TERRAIN_SIZE = 1.0f;
- constexpr float VERY_LARGE_TERRAIN_SIZE = 16.0f * 1024.0f;
- if (terrainSize < UNREASONABLY_SMALL_TERRAIN_SIZE)
- {
- //Only happens when the runtime terrain system was excluded from this build.
- terrainSize = VERY_LARGE_TERRAIN_SIZE;
- }
- GetObjManager()->ReregisterEntitiesInArea(
- Vec3(-terrainSize, -terrainSize, -terrainSize),
- Vec3(terrainSize * 2.f, terrainSize * 2.f, terrainSize * 2.f));
-
- // refresh vegetation properties
- UpdateStatInstGroups();
-
- // force refresh of temporary data associated with visible objects
- MarkRNTmpDataPoolForReset();
- }
-
- m_fRefreshSceneDataCVarsSumm = fNewCVarsSumm;
-
- int nRenderTypeEnableCVarSum =
- (GetCVars()->e_Entities << 2);
-
- if (m_nRenderTypeEnableCVarSum != nRenderTypeEnableCVarSum)
- {
- m_nRenderTypeEnableCVarSum = nRenderTypeEnableCVarSum;
-
- UpdateRenderTypeEnableLookup();
- }
-
- {
- float fNewCVarsSumm2 =
- GetCVars()->e_LodRatio;
-
- static float fCVarsSumm2 = fNewCVarsSumm2;
-
- if (fCVarsSumm2 != fNewCVarsSumm2)
- {
- MarkRNTmpDataPoolForReset();
-
- fCVarsSumm2 = fNewCVarsSumm2;
- }
- }
-
- SFrameLodInfo frameLodInfo;
- frameLodInfo.fLodRatio = GetCVars()->e_LodRatio;
-
- frameLodInfo.fTargetSize = GetCVars()->e_LodFaceAreaTargetSize;
- CRY_ASSERT(frameLodInfo.fTargetSize > 0.f);
- if (frameLodInfo.fTargetSize <= 0.f)
- {
- frameLodInfo.fTargetSize = 1.f;
- }
-
- frameLodInfo.nMinLod = GetCVars()->e_LodMin;
- frameLodInfo.nMaxLod = GetCVars()->e_LodMax;
- if (GetCVars()->e_Lods == 0)
- {
- frameLodInfo.nMinLod = 0;
- frameLodInfo.nMaxLod = 0;
- }
- SetFrameLodInfo(frameLodInfo);
-}
-
-//////////////////////////////////////////////////////////////////////
-void C3DEngine::ShutDown()
-{
- if (GetRenderer() != GetSystem()->GetIRenderer())
- {
- CryFatalError("Renderer was deallocated before I3DEngine::ShutDown() call");
- }
-
- UnlockCGFResources();
-
- UnloadLevel();
-
-#if defined(USE_GEOM_CACHES)
- delete m_pGeomCacheManager;
- m_pGeomCacheManager = 0;
-#endif
-
- if (m_pOpticsManager)
- {
- delete m_pOpticsManager;
- m_pOpticsManager = 0;
- m_pSystem->SetIOpticsManager(m_pOpticsManager);
- }
-
- CryAlignedDelete(m_pObjManager);
- m_pObjManager = 0;
-
-
- // Free the temporary pool's underlying storage
- // and reset the pool
- if (!CTemporaryPool::Shutdown())
- {
- CryFatalError("C3DEngine::Shutdown() could not shutdown temporary pool");
- }
-
- COctreeNode::Shutdown();
-}
-
-#ifndef _RELEASE
-void C3DEngine::ProcessStreamingLatencyTest(const CCamera& camIn, CCamera& camOut, const SRenderingPassInfo& passInfo)
-{
- static float fSQTestOffset = 0;
- static PodArray arrTestTextures;
- static ITexture* pTestTexture = 0;
- static ITexture* pLastNotReadyTexture = 0;
- static float fStartTime = 0;
- static float fDelayStartTime = 0;
- static size_t nMaxTexUsage = 0;
-
- static int nOpenRequestCount = 0;
- SStreamEngineOpenStats stats;
- gEnv->pSystem->GetStreamEngine()->GetStreamingOpenStatistics(stats);
- if (stats.nOpenRequestCount > nOpenRequestCount)
- {
- nOpenRequestCount = stats.nOpenRequestCount;
- }
- else
- {
- nOpenRequestCount = max(0, nOpenRequestCount + stats.nOpenRequestCount) / 2;
- }
-
- ICVar* pTSFlush = GetConsole()->GetCVar("r_TexturesStreamingDebug");
-
- if (GetCVars()->e_SQTestBegin == 1)
- { // Init waiting few seconds until streaming is stabilized and all required textures are loaded
- PrintMessage("======== Starting streaming latency test ========");
- fDelayStartTime = GetCurTimeSec();
- nMaxTexUsage = 0;
- GetCVars()->e_SQTestBegin = 2;
- PrintMessage("Waiting %.1f seconds and zero requests and no camera movement", GetCVars()->e_SQTestDelay);
-
- if (ICVar* pPart = GetConsole()->GetCVar("e_Particles"))
- {
- pPart->Set(0);
- }
- if (ICVar* pAI = GetConsole()->GetCVar("sys_AI"))
- {
- pAI->Set(0);
- }
- }
- else if (GetCVars()->e_SQTestBegin == 2)
- { // Perform waiting
- if (GetCurTimeSec() - fDelayStartTime > GetCVars()->e_SQTestDelay && !nOpenRequestCount && m_fAverageCameraSpeed < .01f)
- {
- pTSFlush->Set(0);
- GetCVars()->e_SQTestBegin = 3;
- }
- else
- {
- pTSFlush->Set(3);
- }
- }
- else if (GetCVars()->e_SQTestBegin == 3)
- { // Build a list of all important loaded textures
- PrintMessage("Collect information about loaded textures");
-
- fSQTestOffset = (float)GetCVars()->e_SQTestDistance;
-
- arrTestTextures.Clear();
- SRendererQueryGetAllTexturesParam param;
-
- GetRenderer()->EF_Query(EFQ_GetAllTextures, param);
- if (param.pTextures)
- {
- for (uint32 i = 0; i < param.numTextures; i++)
- {
- ITexture* pTexture = param.pTextures[i];
- if (pTexture->GetAccessFrameId() > (int)(passInfo.GetMainFrameID() - 4))
- {
- if (pTexture->GetMinLoadedMip() <= GetCVars()->e_SQTestMip)
- {
- if (pTexture->IsStreamable())
- {
- if (pTexture->GetWidth() * pTexture->GetHeight() >= 256 * 256)
- {
- arrTestTextures.Add(pTexture);
-
- if (strstr(pTexture->GetName(), GetCVars()->e_SQTestTextureName->GetString()))
- {
- pTestTexture = pTexture;
- PrintMessage("Test texture name: %s", pTexture->GetName());
- }
- }
- }
- }
- }
- }
- }
-
- GetRenderer()->EF_Query(EFQ_GetAllTexturesRelease, param);
-
- PrintMessage("%d test textures found", arrTestTextures.Count());
-
- PrintMessage("Teleporting camera to offset position");
-
- GetCVars()->e_SQTestBegin = 4;
- }
- else if (GetCVars()->e_SQTestBegin == 4)
- { // Init waiting few seconds until streaming is stabilized and all required textures are loaded
- fDelayStartTime = GetCurTimeSec();
- GetCVars()->e_SQTestBegin = 5;
- PrintMessage("Waiting %.1f seconds and zero requests and no camera movement", GetCVars()->e_SQTestDelay);
- }
- else if (GetCVars()->e_SQTestBegin == 5)
- { // Move camera to offset position and perform waiting
- Matrix34 mat = camIn.GetMatrix();
- Vec3 vPos = camIn.GetPosition() - camIn.GetViewdir() * fSQTestOffset;
- mat.SetTranslation(vPos);
- camOut.SetMatrix(mat);
-
- if (GetCurTimeSec() - fDelayStartTime > GetCVars()->e_SQTestDelay && !nOpenRequestCount && m_fAverageCameraSpeed < .01f)
- {
- PrintMessage("Begin camera movement");
- GetCVars()->e_SQTestBegin = 6;
- pTSFlush->Set(0);
- }
- else
- {
- pTSFlush->Set(3);
- }
- }
- else if (GetCVars()->e_SQTestBegin == 6)
- { // Process camera movement from offset position to test point
- Matrix34 mat = camIn.GetMatrix();
- Vec3 vPos = camIn.GetPosition() - camIn.GetViewdir() * fSQTestOffset;
- mat.SetTranslation(vPos);
- camOut.SetMatrix(mat);
-
- fSQTestOffset -= GetTimer()->GetFrameTime() * (float)GetCVars()->e_SQTestMoveSpeed;
-
- STextureStreamingStats statsTex(true);
- m_pRenderer->EF_Query(EFQ_GetTexStreamingInfo, statsTex);
- nMaxTexUsage = max(nMaxTexUsage, statsTex.nRequiredStreamedTexturesSize);
-
- if (fSQTestOffset <= 0)
- {
- PrintMessage("Finished camera movement");
- fStartTime = GetCurTimeSec();
- PrintMessage("Waiting for %d textures to stream in ...", arrTestTextures.Count());
-
- GetCVars()->e_SQTestBegin = 7;
- pLastNotReadyTexture = 0;
- }
- }
- else if (GetCVars()->e_SQTestBegin == 7)
- { // Wait until test all needed textures are loaded again
- STextureStreamingStats statsTex(true);
- m_pRenderer->EF_Query(EFQ_GetTexStreamingInfo, statsTex);
- nMaxTexUsage = max(nMaxTexUsage, statsTex.nRequiredStreamedTexturesSize);
-
- if (pTestTexture)
- {
- if (pTestTexture->GetMinLoadedMip() <= GetCVars()->e_SQTestMip)
- {
- PrintMessage("BINGO: Selected test texture loaded in %.1f sec", GetCurTimeSec() - fStartTime);
- pTestTexture = NULL;
- if (!arrTestTextures.Count())
- {
- GetCVars()->e_SQTestBegin = 0;
- GetConsole()->GetCVar("e_SQTestBegin")->Set(0);
- }
- }
- }
-
- if (arrTestTextures.Count())
- {
- int nFinishedNum = 0;
- for (int i = 0; i < arrTestTextures.Count(); i++)
- {
- if (arrTestTextures[i]->GetMinLoadedMip() <= GetCVars()->e_SQTestMip)
- {
- nFinishedNum++;
- }
- else
- {
- pLastNotReadyTexture = arrTestTextures[i];
- }
- }
-
- if (nFinishedNum == arrTestTextures.Count())
- {
- PrintMessage("BINGO: %d of %d test texture loaded in %.1f sec", nFinishedNum, arrTestTextures.Count(), GetCurTimeSec() - fStartTime);
- if (pLastNotReadyTexture)
- {
- PrintMessage("LastNotReadyTexture: %s [%d x %d]", pLastNotReadyTexture->GetName(), pLastNotReadyTexture->GetWidth(), pLastNotReadyTexture->GetHeight());
- }
- PrintMessage("MaxTexUsage: %" PRISIZE_T " MB", nMaxTexUsage / 1024 / 1024);
- arrTestTextures.Clear();
-
- GetCVars()->e_SQTestBegin = 0;
- GetConsole()->GetCVar("e_SQTestBegin")->Set(0);
-
- m_arrProcessStreamingLatencyTestResults.Add(GetCurTimeSec() - fStartTime);
- m_arrProcessStreamingLatencyTexNum.Add(nFinishedNum);
-
- if (GetCVars()->e_SQTestCount == 0)
- {
- const char* testResultsFile = "@usercache@/TestResults/Streaming_Latency_Test.xml";
-
- AZ::IO::HandleType resultsFile = gEnv->pCryPak->FOpen(testResultsFile, "wb");
- if (resultsFile != AZ::IO::InvalidHandle)
- {
- float fAverTime = 0;
- for (int i = 0; i < m_arrProcessStreamingLatencyTestResults.Count(); i++)
- {
- fAverTime += m_arrProcessStreamingLatencyTestResults[i];
- }
- fAverTime /= m_arrProcessStreamingLatencyTestResults.Count();
-
- int nAverTexNum = 0;
- for (int i = 0; i < m_arrProcessStreamingLatencyTexNum.Count(); i++)
- {
- nAverTexNum += m_arrProcessStreamingLatencyTexNum[i];
- }
- nAverTexNum /= m_arrProcessStreamingLatencyTexNum.Count();
-
- AZ::IO::Print(resultsFile, "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n",
- fAverTime,
- nAverTexNum);
- gEnv->pCryPak->FClose(resultsFile);
- }
-
- if (GetCVars()->e_SQTestExitOnFinish)
- {
- GetSystem()->Quit();
- }
- }
- }
- else if ((passInfo.GetMainFrameID() & 31) == 0)
- {
- PrintMessage("Waiting: %d of %d test texture loaded in %.1f sec", nFinishedNum, arrTestTextures.Count(), GetCurTimeSec() - fStartTime);
- }
- }
- }
-}
-#endif
-
-//////////////////////////////////////////////////////////////////////
-void C3DEngine::UpdateRenderingCamera([[maybe_unused]] const char* szCallerName, const SRenderingPassInfo& passInfo)
-{
- CCamera newCam = passInfo.GetCamera();
-
- if (passInfo.IsGeneralPass())
- {
- SVOGILegacyRequestBus::Broadcast(&SVOGILegacyRequests::UpdateVoxelData);
- }
-
- if IsCVarConstAccess(constexpr) (bool(GetFloatCVar(e_CameraRotationSpeed)))
- {
- Matrix34 mat = passInfo.GetCamera().GetMatrix();
- Matrix33 matRot;
- matRot.SetRotationZ(-GetCurTimeSec() * GetFloatCVar(e_CameraRotationSpeed));
- newCam.SetMatrix(mat * matRot);
- }
-
-#if !defined(_RELEASE)
-
- {
- //this feature move the camera along with the player to a certain position and sets the angle accordingly
- // (does not work via goto)
- //u can switch it off again via e_CameraGoto 0
- const char* const pCamGoto = GetCVars()->e_CameraGoto->GetString();
- assert(pCamGoto);
- if (strlen(pCamGoto) > 1)
- {
- Ang3 aAngDeg;
- Vec3 vPos;
- int args = azsscanf(pCamGoto, "%f %f %f %f %f %f", &vPos.x, &vPos.y, &vPos.z, &aAngDeg.x, &aAngDeg.y, &aAngDeg.z);
- if (args >= 3)
- {
- Vec3 curPos = newCam.GetPosition();
- if (fabs(vPos.x - curPos.x) > 10.f || fabs(vPos.y - curPos.y) > 10.f || fabs(vPos.z - curPos.z) > 10.f)
- {
- char buf[128];
- sprintf_s(buf, "goto %f %f %f", vPos.x, vPos.y, vPos.z);
- gEnv->pConsole->ExecuteString(buf);
- }
- if (args >= 6)
- {
- Matrix34 mat = passInfo.GetCamera().GetMatrix();
- mat.SetTranslation(vPos);
- mat.SetRotation33(Matrix33::CreateRotationXYZ(DEG2RAD(aAngDeg)));
- newCam.SetMatrix(mat);
- }
- }
- }
- }
-
- // Streaming latency test
- if (GetCVars()->e_SQTestCount && !GetCVars()->e_SQTestBegin)
- {
- GetConsole()->GetCVar("e_SQTestBegin")->Set(1);
- GetConsole()->GetCVar("e_SQTestCount")->Set(GetCVars()->e_SQTestCount - 1);
- }
- if (GetCVars()->e_SQTestBegin)
- {
- ProcessStreamingLatencyTest(passInfo.GetCamera(), newCam, passInfo);
- }
-
-#endif
-
- // set the camera if e_cameraFreeze is not set
- if (GetCVars()->e_CameraFreeze || GetCVars()->e_CoverageBufferDebugFreeze)
- {
- DrawSphere(GetRenderingCamera().GetPosition(), .05f);
-
- // always set camera to request position for the renderer, allows debugging with e_camerafreeze
- GetRenderer()->SetCamera(gEnv->pSystem->GetViewCamera());
- }
- else
- {
- m_RenderingCamera = newCam;
- // always set camera to request position for the renderer, allows debugging with e_camerafreeze
- GetRenderer()->SetCamera(newCam);
- }
-
- // now we have a valid camera, we can start generation of the occlusion buffer
- // only needed for editor here, in game we spawn the job more early
- if (passInfo.IsGeneralPass() && GetCVars()->e_StatObjBufferRenderTasks)
- {
- if (gEnv->IsEditor())
- {
- GetObjManager()->PrepareCullbufferAsync(passInfo.GetCamera());
- }
- else
- {
- assert(IsEquivalent(passInfo.GetCamera().GetViewdir(), GetObjManager()->GetCullThread().GetViewDir())); // early set camera differs from current main camera - will cause occlusion errors
- }
- }
-
- /////////////////////////////////////////////////////////////////////////////
- // update streaming priority of newly seen CComponentRenders (fix for streaming system issue)
- for (int i = 0, nSize = m_deferredRenderComponentStreamingPriorityUpdates.size(); i < nSize; ++i)
- {
- IRenderNode* pRenderNode = m_deferredRenderComponentStreamingPriorityUpdates[i];
- AABB aabb = pRenderNode->GetBBox();
- const Vec3& vCamPos = GetRenderingCamera().GetPosition();
- float fEntDistance = sqrt_tpl(Distance::Point_AABBSq(vCamPos, aabb)) * passInfo.GetZoomFactor();
-
- GetObjManager()->UpdateRenderNodeStreamingPriority(pRenderNode, fEntDistance, 1.0f, false, passInfo);
- if (GetCVars()->e_StreamCgfDebug == 2)
- {
- PrintMessage("C3DEngine::RegisterEntity__GetObjManager()->UpdateRenderNodeStreamingPriority %s", pRenderNode->GetName());
- }
- }
- m_deferredRenderComponentStreamingPriorityUpdates.resize(0);
-}
-
-void C3DEngine::GetSvoStaticTextures(I3DEngine::SSvoStaticTexInfo& svoInfo, PodArray* pLightsTI_S, PodArray* pLightsTI_D)
-{
- SVOGILegacyRequestBus::Broadcast(&SVOGILegacyRequests::GetSvoStaticTextures, svoInfo, pLightsTI_S, pLightsTI_D);
-}
-
-void C3DEngine::GetSvoBricksForUpdate(PodArray& arrNodeInfo, bool getDynamic)
-{
- SVOGILegacyRequestBus::Broadcast(&SVOGILegacyRequests::GetSvoBricksForUpdate, arrNodeInfo, getDynamic);
-}
-
-#if defined(FEATURE_SVO_GI)
-void C3DEngine::LoadTISettings(XmlNodeRef pInputNode)
-{
- const char* szXmlNodeName = "Total_Illumination_v2";
- if (gEnv->pConsole->GetCVar("e_svoTI_Active"))
- {
- gEnv->pConsole->GetCVar("e_svoTI_Active")->Set(GetXMLAttribText(pInputNode, szXmlNodeName, "Active", "0"));
-
- gEnv->pConsole->GetCVar("e_svoTI_InjectionMultiplier")->Set(GetXMLAttribText(pInputNode, szXmlNodeName, "InjectionMultiplier", "0"));
-
- gEnv->pConsole->GetCVar("e_svoTI_NumberOfBounces")->Set(GetXMLAttribText(pInputNode, szXmlNodeName, "NumberOfBounces", "0"));
-
- gEnv->pConsole->GetCVar("e_svoTI_Saturation")->Set(GetXMLAttribText(pInputNode, szXmlNodeName, "Saturation", "0"));
-
- gEnv->pConsole->GetCVar("e_svoTI_ConeMaxLength")->Set(GetXMLAttribText(pInputNode, szXmlNodeName, "ConeMaxLength", "0"));
-
- gEnv->pConsole->GetCVar("e_svoTI_DiffuseConeWidth")->Set(GetXMLAttribText(pInputNode, szXmlNodeName, "DiffuseConeWidth", "0"));
-
- gEnv->pConsole->GetCVar("e_svoTI_SSAOAmount")->Set(GetXMLAttribText(pInputNode, szXmlNodeName, "SSAOAmount", "0"));
- gEnv->pConsole->GetCVar("e_svoTI_UseLightProbes")->Set(GetXMLAttribText(pInputNode, szXmlNodeName, "UseLightProbes", "0"));
- gEnv->pConsole->GetCVar("e_svoTI_AmbientOffsetRed")->Set(GetXMLAttribText(pInputNode, szXmlNodeName, "AmbientOffsetRed", "1"));
- gEnv->pConsole->GetCVar("e_svoTI_AmbientOffsetGreen")->Set(GetXMLAttribText(pInputNode, szXmlNodeName, "AmbientOffsetGreen", "1"));
- gEnv->pConsole->GetCVar("e_svoTI_AmbientOffsetBlue")->Set(GetXMLAttribText(pInputNode, szXmlNodeName, "AmbientOffsetBlue", "1"));
- gEnv->pConsole->GetCVar("e_svoTI_AmbientOffsetBias")->Set(GetXMLAttribText(pInputNode, szXmlNodeName, "AmbientOffsetBias", ".1"));
-
- gEnv->pConsole->GetCVar("e_svoTI_IntegrationMode")->Set(GetXMLAttribText(pInputNode, szXmlNodeName, "IntegrationMode", "0"));
-
- if (gEnv->pConsole->GetCVar("e_svoTI_IntegrationMode")->GetIVal() < 1) // AO
- {
- gEnv->pConsole->GetCVar("e_svoTI_NumberOfBounces")->Set("1");
- }
- }
-}
-#endif
-void C3DEngine::PrepareOcclusion(const CCamera& rCamera)
-{
- if (!gEnv->IsEditor() && GetCVars()->e_StatObjBufferRenderTasks && !gEnv->IsFMVPlaying() && (!IsEquivalent(rCamera.GetPosition(), Vec3(0, 0, 0), VEC_EPSILON) || GetRenderer()->IsPost3DRendererEnabled()))
- {
- GetObjManager()->PrepareCullbufferAsync(rCamera);
- }
-}
-
-void C3DEngine::EndOcclusion()
-{
- GetObjManager()->EndOcclusionCulling();
-}
-
-IStatObj* C3DEngine::LoadStatObjUnsafeManualRef(const char* fileName, const char* geomName, IStatObj::SSubObject** subObject,
- bool useStreaming, unsigned long loadingFlags, const void* data, int dataSize)
-{
- return LoadStatObjInternal(fileName, geomName, subObject, useStreaming, loadingFlags, &CObjManager::LoadStatObjUnsafeManualRef, data, dataSize);
-}
-
-_smart_ptr C3DEngine::LoadStatObjAutoRef(const char* fileName, const char* geomName, IStatObj::SSubObject** subObject,
- bool useStreaming, unsigned long loadingFlags, const void* data, int dataSize)
-{
- return LoadStatObjInternal(fileName, geomName, subObject, useStreaming, loadingFlags, &CObjManager::LoadStatObjAutoRef, data, dataSize);
-}
-
-template
-TReturn C3DEngine::LoadStatObjInternal(const char* fileName, const char* geomName, IStatObj::SSubObject** subObject, bool useStreaming,
- unsigned long loadingFlags, LoadStatObjFunc loadStatObjFunc, const void* data, int dataSize)
-{
- if (!fileName || !fileName[0])
- {
- m_pSystem->Warning(VALIDATOR_MODULE_3DENGINE, VALIDATOR_ERROR, 0, 0, "I3DEngine::LoadStatObj: filename is not specified");
- return nullptr;
- }
-
- if (!m_pObjManager)
- {
- m_pObjManager = CryAlignedNew();
- }
-
- CObjManager* pObjManager = static_cast(m_pObjManager);
- return (pObjManager->*loadStatObjFunc)(fileName, geomName, subObject, useStreaming, loadingFlags, data, dataSize, nullptr);
-}
-
-void C3DEngine::LoadStatObjAsync(I3DEngine::LoadStaticObjectAsyncResult resultCallback, const char* szFileName, const char* szGeomName, bool bUseStreaming, unsigned long nLoadingFlags)
-{
- CRY_ASSERT_MESSAGE(szFileName && szFileName[0], "LoadStatObjAsync: Invalid filename");
- CRY_ASSERT_MESSAGE(m_pObjManager, "Object manager is not ready.");
-
- StaticObjectAsyncLoadRequest request;
- request.m_callback = resultCallback;
- request.m_filename = szFileName;
- request.m_geomName = szGeomName;
- request.m_useStreaming = bUseStreaming;
- request.m_loadingFlags = nLoadingFlags;
-
- {
- AZStd::lock_guard lock(m_statObjQueueLock);
- m_statObjLoadRequests.push(std::move(request));
- }
-}
-
-void C3DEngine::ProcessAsyncStaticObjectLoadRequests()
-{
- // Same scheme as skinned meshes: CharacterManager::ProcessAsyncLoadRequests.
-
- enum
- {
- kMaxLoadsPerFrame = 20
- };
- size_t loadsThisFrame = 0;
-
- while (loadsThisFrame < kMaxLoadsPerFrame)
- {
- StaticObjectAsyncLoadRequest request;
- {
- AZStd::lock_guard lock(m_statObjQueueLock);
- if (m_statObjLoadRequests.empty())
- {
- break;
- }
- request = std::move(m_statObjLoadRequests.front());
- m_statObjLoadRequests.pop();
- }
-
- _smart_ptr object = LoadStatObjAutoRef(request.m_filename.c_str(), request.m_geomName.c_str(), nullptr, request.m_useStreaming, request.m_loadingFlags);
- request.m_callback(object);
-
- ++loadsThisFrame;
- }
-}
-
-IStatObj* C3DEngine::FindStatObjectByFilename(const char* filename)
-{
- if (filename == NULL)
- {
- return NULL;
- }
-
- if (filename[0] == 0)
- {
- return NULL;
- }
-
- return m_pObjManager->FindStaticObjectByFilename(filename);
-}
-
-void C3DEngine::RegisterEntity(IRenderNode* pEnt, int nSID, int nSIDConsideredSafe)
-{
- FUNCTION_PROFILER_3DENGINE;
- if (gEnv->mMainThreadId != CryGetCurrentThreadId())
- {
- CryFatalError("C3DEngine::RegisterEntity should only be called on main thread.");
- }
-
- uint32 nFrameID = GetRenderer()->GetFrameID();
- AsyncOctreeUpdate(pEnt, nSID, nSIDConsideredSafe, nFrameID, false);
-}
-
-void C3DEngine::UnRegisterEntityDirect(IRenderNode* pEnt)
-{
- UnRegisterEntityImpl(pEnt);
-}
-
-void C3DEngine::UnRegisterEntityAsJob(IRenderNode* pEnt)
-{
- AsyncOctreeUpdate(pEnt, (int)0, (int)0, (int)0, true);
-}
-
-bool C3DEngine::CreateDecalInstance(const CryEngineDecalInfo& decal, CDecal* pCallerManagedDecal)
-{
- if (!GetCVars()->e_Decals && !pCallerManagedDecal)
- {
- return false;
- }
-
- return m_pDecalManager->Spawn(decal, pCallerManagedDecal);
-}
-
-void C3DEngine::SelectEntity(IRenderNode* pEntity)
-{
- static IRenderNode* pSelectedNode;
- static float fLastTime;
- if (pEntity && GetCVars()->e_Decals == 3)
- {
- float fCurTime = gEnv->pTimer->GetAsyncCurTime();
- if (fCurTime - fLastTime < 1.0f)
- {
- return;
- }
- fLastTime = fCurTime;
- if (pSelectedNode)
- {
- pSelectedNode->SetRndFlags(ERF_SELECTED, false);
- }
- pEntity->SetRndFlags(ERF_SELECTED, true);
- pSelectedNode = pEntity;
- }
-}
-
-void C3DEngine::CreateDecal(const struct CryEngineDecalInfo& decal)
-{
- IF (!GetCVars()->e_DecalsAllowGameDecals, 0)
- {
- return;
- }
-
- if (GetCVars()->e_Decals == 2)
- {
- IRenderNode* pRN = decal.ownerInfo.pRenderNode;
- PrintMessage("Debug: C3DEngine::CreateDecal: Pos=(%.1f,%.1f,%.1f) Size=%.2f DecalMaterial=%s HitObjectName=%s(%s)",
- decal.vPos.x, decal.vPos.y, decal.vPos.z, decal.fSize, decal.szMaterialName,
- pRN ? pRN->GetName() : "NULL", pRN ? pRN->GetEntityClassName() : "NULL");
- }
-
- assert(!decal.pExplicitRightUpFront); // only game-play decals come here
-
- static uint32 nGroupId = 0;
- nGroupId++;
-
- if ((GetCVars()->e_DecalsDefferedStatic == 1 && decal.pExplicitRightUpFront) ||
- (GetCVars()->e_DecalsDefferedDynamic == 1 && !decal.pExplicitRightUpFront &&
- (!decal.ownerInfo.pRenderNode ||
- decal.ownerInfo.pRenderNode->GetRenderNodeType() == eERType_StaticMeshRenderComponent ||
- decal.fGrowTimeAlpha || decal.fSize > GetFloatCVar(e_DecalsDefferedDynamicMinSize)))
- && !decal.bForceSingleOwner)
- {
- CryEngineDecalInfo decal_adjusted = decal;
- decal_adjusted.nGroupId = nGroupId;
- decal_adjusted.bDeferred = true;
- m_pDecalManager->SpawnHierarchical(decal_adjusted, NULL);
- return;
- }
-
- if (decal.ownerInfo.pRenderNode && decal.fSize > 0.5f && !decal.bForceSingleOwner)
- {
- PodArray lstEntities;
- Vec3 vRadius(decal.fSize, decal.fSize, decal.fSize);
- const AABB cExplosionBox(decal.vPos - vRadius, decal.vPos + vRadius);
-
- if (CVisArea* pArea = (CVisArea*)decal.ownerInfo.pRenderNode->GetEntityVisArea())
- {
- if (pArea->m_pObjectsTree)
- {
- pArea->m_pObjectsTree->MoveObjectsIntoList(&lstEntities, &cExplosionBox, false, true, true, true);
- }
- }
- else
- {
- Get3DEngine()->MoveObjectsIntoListGlobal(&lstEntities, &cExplosionBox, false, true, true, true);
- }
-
- for (int i = 0; i < lstEntities.Count(); i++)
- {
- // decals on statobj's of render node
- CryEngineDecalInfo decalOnRenderNode = decal;
- decalOnRenderNode.ownerInfo.pRenderNode = lstEntities[i].pNode;
- decalOnRenderNode.nGroupId = nGroupId;
-
- // if(decalOnRenderNode.ownerInfo.pRenderNode->GetRenderNodeType() != decal.ownerInfo.pRenderNode->GetRenderNodeType())
- // continue;
-
- if (decalOnRenderNode.ownerInfo.pRenderNode->GetRndFlags() & ERF_HIDDEN)
- {
- continue;
- }
-
- m_pDecalManager->SpawnHierarchical(decalOnRenderNode, NULL);
- }
- }
- else
- {
- CryEngineDecalInfo decalStatic = decal;
- decalStatic.nGroupId = nGroupId;
- m_pDecalManager->SpawnHierarchical(decalStatic, NULL);
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-void C3DEngine::SetSunColor(Vec3 vColor)
-{
- if (m_pObjManager)
- {
- m_pObjManager->SetSunColor(vColor);
- m_pObjManager->SetSunAnimColor(vColor);
- }
-}
-
-Vec3 C3DEngine::GetSunAnimColor()
-{
- if (m_pObjManager)
- {
- return m_pObjManager->GetSunAnimColor();
- }
-
- return Vec3();
-}
-
-void C3DEngine::SetSunAnimColor(const Vec3& sunAnimColor)
-{
- if (m_pObjManager)
- {
- m_pObjManager->SetSunAnimColor(sunAnimColor);
- }
-}
-
-float C3DEngine::GetSunAnimSpeed()
-{
- if (m_pObjManager)
- {
- return m_pObjManager->GetSunAnimSpeed();
- }
-
- return 0.0f;
-}
-
-void C3DEngine::SetSunAnimSpeed(float sunAnimSpeed)
-{
- if (m_pObjManager)
- {
- m_pObjManager->SetSunAnimSpeed(sunAnimSpeed);
- }
-}
-
-AZ::u8 C3DEngine::GetSunAnimPhase()
-{
- if (m_pObjManager)
- {
- return m_pObjManager->GetSunAnimPhase();
- }
-
- return 0;
-}
-
-void C3DEngine::SetSunAnimPhase(AZ::u8 sunAnimPhase)
-{
- if (m_pObjManager)
- {
- m_pObjManager->SetSunAnimPhase(sunAnimPhase);
- }
-}
-
-AZ::u8 C3DEngine::GetSunAnimIndex()
-{
- if (m_pObjManager)
- {
- return m_pObjManager->GetSunAnimIndex();
- }
-
- return 0;
-}
-
-void C3DEngine::SetSunAnimIndex(AZ::u8 sunAnimIndex)
-{
- if (m_pObjManager)
- {
- m_pObjManager->SetSunAnimIndex(sunAnimIndex);
- }
-}
-
-void C3DEngine::SetSSAOAmount(float fMul)
-{
- if (m_pObjManager)
- {
- m_pObjManager->SetSSAOAmount(fMul);
- }
-}
-
-void C3DEngine::SetSSAOContrast(float fMul)
-{
- if (m_pObjManager)
- {
- m_pObjManager->SetSSAOContrast(fMul);
- }
-}
-
-void C3DEngine::RemoveAllStaticObjects([[maybe_unused]] int nSID)
-{
- if (!IsObjectTreeReady())
- {
- return;
- }
-
- PodArray lstObjects;
-
- // Don't remove objects from the octree, since our query will return more objects than just the ones we're looking for.
- const bool removeObjectsFromOctree = false;
-
- // Skip gathering decals, since we're only looking for vegetation.
- const bool skipDecals = true;
- const bool skipERFNoDecalNodeDecals = true;
-
- // Skip dynamic vegetation, since we're only looking to remove static vegetation.
- const bool skipDynamicObjects = true;
-
- GetObjectTree()->MoveObjectsIntoList(&lstObjects, nullptr, removeObjectsFromOctree, skipDecals, skipERFNoDecalNodeDecals, skipDynamicObjects);
-}
-
-void C3DEngine::OnExplosion(Vec3 vPos, float fRadius, [[maybe_unused]] bool bDeformTerrain)
-{
- if (GetCVars()->e_Decals == 2)
- {
- PrintMessage("Debug: C3DEngine::OnExplosion: Pos=(%.1f,%.1f,%.1f) fRadius=%.2f", vPos.x, vPos.y, vPos.z, fRadius);
- }
-
- auto terrain = AzFramework::Terrain::TerrainDataRequestBus::FindFirstHandler();
- if (!terrain)
- {
- return;
- }
-
- AZ::Aabb terrainAabb = terrain->GetTerrainAabb();
- if (!terrainAabb.Contains(LYVec3ToAZVec3(vPos)) || fRadius <= 0)
- {
- return; // out of terrain
- }
-
- const AZ::Vector2 terrainGridResolution = terrain->GetTerrainGridResolution();
- const float unitSizeX = terrainGridResolution.GetX();
- const float unitSizeY = terrainGridResolution.GetY();
-
- // do not create decals near the terrain holes
- {
- for (float x = vPos.x - fRadius; x <= vPos.x + fRadius + 1.0f; x += unitSizeX)
- {
- for (float y = vPos.y - fRadius; y <= vPos.y + fRadius + 1.0f; y += unitSizeY)
- {
- if (terrain->GetIsHoleFromFloats(x, y))
- {
- return;
- }
- }
- }
- }
-
- // reduce ground decals size depending on distance to the ground
-
- // delete decals what can not be correctly updated
- Vec3 vRadius(fRadius, fRadius, fRadius);
- AABB areaBox(vPos - vRadius, vPos + vRadius);
- Get3DEngine()->DeleteDecalsInRange(&areaBox, NULL);
-}
-
-float C3DEngine::GetMaxViewDistance(bool bScaled)
-{
- // lerp between specs
- float fMaxViewDist;
-
- // camera height lerp factor
- if (OceanToggle::IsActive() && !OceanRequest::OceanIsEnabled())
- {
- fMaxViewDist = m_fMaxViewDistHighSpec;
- }
- else
- {
- // spec lerp factor
- float lerpSpec = clamp_tpl(GetCVars()->e_MaxViewDistSpecLerp, 0.0f, 1.0f);
-
- // lerp between specs
- fMaxViewDist = m_fMaxViewDistLowSpec * (1.f - lerpSpec) + m_fMaxViewDistHighSpec * lerpSpec;
-
- const float waterLevel = OceanToggle::IsActive() ? OceanRequest::GetOceanLevel() : GetWaterLevel();
- float lerpHeight = clamp_tpl(max(0.f, GetSystem()->GetViewCamera().GetPosition().z - waterLevel) / GetFloatCVar(e_MaxViewDistFullDistCamHeight), 0.0f, 1.0f);
-
- // lerp between prev result and high spec
- fMaxViewDist = fMaxViewDist * (1.f - lerpHeight) + m_fMaxViewDistHighSpec * lerpHeight;
- }
-
- if (bScaled)
- {
- fMaxViewDist *= m_fMaxViewDistScale;
- }
-
- // for debugging
- const float fMaxViewDistCVar = GetFloatCVar(e_MaxViewDistance);
- fMaxViewDist = (float)fsel(fMaxViewDistCVar, fMaxViewDistCVar, fMaxViewDist);
-
- fMaxViewDist = (float)fsel(fabsf(fMaxViewDist) - 0.100001f, fMaxViewDist, 0.100001f);
-
- // eliminate some floating point inconsistency here, there's no point in nitpicking 7999.9995 view distance vs 8000
- fMaxViewDist = AZ::ClampIfCloseMag(fMaxViewDist, float(round(fMaxViewDist)), 0.01f);
-
- return fMaxViewDist;
-}
-
-void C3DEngine::SetFrameLodInfo(const SFrameLodInfo& frameLodInfo)
-{
- if (frameLodInfo.fLodRatio != m_frameLodInfo.fLodRatio || frameLodInfo.fTargetSize != m_frameLodInfo.fTargetSize)
- {
- ++m_frameLodInfo.nID;
- m_frameLodInfo.fLodRatio = frameLodInfo.fLodRatio;
- m_frameLodInfo.fTargetSize = frameLodInfo.fTargetSize;
- }
- m_frameLodInfo.nMinLod = frameLodInfo.nMinLod;
- m_frameLodInfo.nMaxLod = frameLodInfo.nMaxLod;
-}
-
-void C3DEngine::SetFogColor(const Vec3& vFogColor)
-{
- m_vFogColor = vFogColor;
- GetRenderer()->SetClearColor(m_vFogColor);
-}
-
-Vec3 C3DEngine::GetFogColor()
-{
- return m_vFogColor;
-}
-
-void C3DEngine::GetSkyLightParameters(Vec3& sunDir, Vec3& sunIntensity, float& Km, float& Kr, float& g, Vec3& rgbWaveLengths)
-{
- CSkyLightManager::SSkyDomeCondition skyCond;
- m_pSkyLightManager->GetCurSkyDomeCondition(skyCond);
-
- g = skyCond.m_g;
- Km = skyCond.m_Km;
- Kr = skyCond.m_Kr;
- sunIntensity = skyCond.m_sunIntensity;
- rgbWaveLengths = skyCond.m_rgbWaveLengths;
- sunDir = skyCond.m_sunDirection;
-}
-
-void C3DEngine::SetSkyLightParameters(const Vec3& sunDir, const Vec3& sunIntensity, float Km, float Kr, float g, const Vec3& rgbWaveLengths, bool forceImmediateUpdate)
-{
- CSkyLightManager::SSkyDomeCondition skyCond;
-
- skyCond.m_g = g;
- skyCond.m_Km = Km;
- skyCond.m_Kr = Kr;
- skyCond.m_sunIntensity = sunIntensity;
- skyCond.m_rgbWaveLengths = rgbWaveLengths;
- skyCond.m_sunDirection = sunDir;
-
- m_pSkyLightManager->SetSkyDomeCondition(skyCond);
- if (forceImmediateUpdate && IsHDRSkyMaterial(GetSkyMaterial()))
- {
- m_pSkyLightManager->FullUpdate();
- }
-}
-
-void C3DEngine::SetLightsHDRDynamicPowerFactor(const float value)
-{
- m_fLightsHDRDynamicPowerFactor = value;
-}
-
-float C3DEngine::GetLightsHDRDynamicPowerFactor() const
-{
- return m_fLightsHDRDynamicPowerFactor;
-}
-
-bool C3DEngine::IsTessellationAllowedForShadowMap(const SRenderingPassInfo& passInfo) const
-{
-#ifdef MESH_TESSELLATION_ENGINE
- SRenderingPassInfo::EShadowMapType shadowType = passInfo.GetShadowMapType();
- switch (shadowType)
- {
- case SRenderingPassInfo::SHADOW_MAP_GSM:
- return passInfo.ShadowFrustumLod() < GetCVars()->e_ShadowsTessellateCascades;
- case SRenderingPassInfo::SHADOW_MAP_LOCAL:
- return GetCVars()->e_ShadowsTessellateDLights != 0;
- case SRenderingPassInfo::SHADOW_MAP_NONE:
- default:
- return false;
- }
-#else
-
- return false;
-
-#endif //#ifdef MESH_TESSELLATION_ENGINE
-}
-
-void C3DEngine::SetPhysMaterialEnumerator(IPhysMaterialEnumerator* pPhysMaterialEnumerator)
-{
- m_pPhysMaterialEnumerator = pPhysMaterialEnumerator;
-}
-
-IPhysMaterialEnumerator* C3DEngine::GetPhysMaterialEnumerator()
-{
- return m_pPhysMaterialEnumerator;
-}
-
-float C3DEngine::GetDistanceToSectorWithWater()
-{
- const Vec3 camPosition = GetRenderingCamera().GetPosition();
- const float minDistance = 0.1f;
- const bool oceanActive = OceanToggle::IsActive();
- const bool oceanEnabled = OceanRequest::OceanIsEnabled();
- float distance = minDistance;
-
- if (oceanActive && !oceanEnabled)
- {
- distance = std::numeric_limits::infinity();
- }
- else
- {
- if (oceanActive && oceanEnabled)
- {
- distance = camPosition.z - OceanRequest::GetOceanLevel();
- }
- else
- {
- distance = std::numeric_limits::infinity();
- }
- }
-
- return max(distance, minDistance);
-}
-
-Vec3 C3DEngine::GetSunColor() const
-{
- return m_pObjManager ? m_pObjManager->GetSunColor() : Vec3(0, 0, 0);
-}
-
-float C3DEngine::GetSSAOAmount() const
-{
- return m_pObjManager ? m_pObjManager->GetSSAOAmount() : 1.0f;
-}
-
-float C3DEngine::GetSSAOContrast() const
-{
- return m_pObjManager ? m_pObjManager->GetSSAOContrast() : 1.0f;
-}
-
-void C3DEngine::SetRainParams(const SRainParams& rainParams)
-{
- if (m_pObjManager)
- {
- m_pObjManager->GetRainParams().bIgnoreVisareas = rainParams.bIgnoreVisareas;
- m_pObjManager->GetRainParams().bDisableOcclusion = rainParams.bDisableOcclusion;
- m_pObjManager->GetRainParams().qRainRotation = rainParams.qRainRotation;
- m_pObjManager->GetRainParams().vWorldPos = rainParams.vWorldPos;
- m_pObjManager->GetRainParams().vColor = rainParams.vColor;
- m_pObjManager->GetRainParams().fAmount = rainParams.fAmount;
- m_pObjManager->GetRainParams().fCurrentAmount = rainParams.fCurrentAmount;
- m_pObjManager->GetRainParams().fRadius = rainParams.fRadius;
- m_pObjManager->GetRainParams().fFakeGlossiness = rainParams.fFakeGlossiness;
- m_pObjManager->GetRainParams().fFakeReflectionAmount = rainParams.fFakeReflectionAmount;
- m_pObjManager->GetRainParams().fDiffuseDarkening = rainParams.fDiffuseDarkening;
- m_pObjManager->GetRainParams().fRainDropsAmount = rainParams.fRainDropsAmount;
- m_pObjManager->GetRainParams().fRainDropsSpeed = rainParams.fRainDropsSpeed;
- m_pObjManager->GetRainParams().fRainDropsLighting = rainParams.fRainDropsLighting;
- m_pObjManager->GetRainParams().fMistAmount = rainParams.fMistAmount;
- m_pObjManager->GetRainParams().fMistHeight = rainParams.fMistHeight;
- m_pObjManager->GetRainParams().fPuddlesAmount = rainParams.fPuddlesAmount;
- m_pObjManager->GetRainParams().fPuddlesMaskAmount = rainParams.fPuddlesMaskAmount;
- m_pObjManager->GetRainParams().fPuddlesRippleAmount = rainParams.fPuddlesRippleAmount;
- m_pObjManager->GetRainParams().fSplashesAmount = rainParams.fSplashesAmount;
-
- m_pObjManager->GetRainParams().nUpdateFrameID = GetRenderer()->GetFrameID();
- }
-}
-
-bool C3DEngine::GetRainParams(SRainParams& rainParams)
-{
- bool bRet = false;
- const int nFrmID = GetRenderer()->GetFrameID();
- if (m_pObjManager)
- {
- // Copy shared rain data only
- rainParams.bIgnoreVisareas = m_pObjManager->GetRainParams().bIgnoreVisareas;
- rainParams.bDisableOcclusion = m_pObjManager->GetRainParams().bDisableOcclusion;
- rainParams.qRainRotation = m_pObjManager->GetRainParams().qRainRotation;
- rainParams.vWorldPos = m_pObjManager->GetRainParams().vWorldPos;
- rainParams.vColor = m_pObjManager->GetRainParams().vColor;
- rainParams.fAmount = m_pObjManager->GetRainParams().fAmount;
- rainParams.fCurrentAmount = m_pObjManager->GetRainParams().fCurrentAmount;
- rainParams.fRadius = m_pObjManager->GetRainParams().fRadius;
- rainParams.fFakeGlossiness = m_pObjManager->GetRainParams().fFakeGlossiness;
- rainParams.fFakeReflectionAmount = m_pObjManager->GetRainParams().fFakeReflectionAmount;
- rainParams.fDiffuseDarkening = m_pObjManager->GetRainParams().fDiffuseDarkening;
- rainParams.fRainDropsAmount = m_pObjManager->GetRainParams().fRainDropsAmount;
- rainParams.fRainDropsSpeed = m_pObjManager->GetRainParams().fRainDropsSpeed;
- rainParams.fRainDropsLighting = m_pObjManager->GetRainParams().fRainDropsLighting;
- rainParams.fMistAmount = m_pObjManager->GetRainParams().fMistAmount;
- rainParams.fMistHeight = m_pObjManager->GetRainParams().fMistHeight;
- rainParams.fPuddlesAmount = m_pObjManager->GetRainParams().fPuddlesAmount;
- rainParams.fPuddlesMaskAmount = m_pObjManager->GetRainParams().fPuddlesMaskAmount;
- rainParams.fPuddlesRippleAmount = m_pObjManager->GetRainParams().fPuddlesRippleAmount;
- rainParams.fSplashesAmount = m_pObjManager->GetRainParams().fSplashesAmount;
-
- if (!IsOutdoorVisible() && !rainParams.bIgnoreVisareas)
- {
- rainParams.fAmount = 0.f;
- }
-
- bRet = m_pObjManager->GetRainParams().nUpdateFrameID == nFrmID;
- }
- return bRet;
-}
-
-void C3DEngine::SetSnowSurfaceParams(const Vec3& vCenter, float fRadius, float fSnowAmount, float fFrostAmount, float fSurfaceFreezing)
-{
- if (m_pObjManager)
- {
- m_pObjManager->GetSnowParams().m_vWorldPos = vCenter;
- m_pObjManager->GetSnowParams().m_fRadius = fRadius;
- m_pObjManager->GetSnowParams().m_fSnowAmount = fSnowAmount;
- m_pObjManager->GetSnowParams().m_fFrostAmount = fFrostAmount;
- m_pObjManager->GetSnowParams().m_fSurfaceFreezing = fSurfaceFreezing;
- }
-}
-
-bool C3DEngine::GetSnowSurfaceParams(Vec3& vCenter, float& fRadius, float& fSnowAmount, float& fFrostAmount, float& fSurfaceFreezing)
-{
- bool bRet = false;
- if (m_pObjManager)
- {
- vCenter = m_pObjManager->GetSnowParams().m_vWorldPos;
- fRadius = m_pObjManager->GetSnowParams().m_fRadius;
- fSnowAmount = 0.f;
- fFrostAmount = 0.f;
- fSurfaceFreezing = 0.f;
- if (IsOutdoorVisible())
- {
- fSnowAmount = m_pObjManager->GetSnowParams().m_fSnowAmount;
- fFrostAmount = m_pObjManager->GetSnowParams().m_fFrostAmount;
- fSurfaceFreezing = m_pObjManager->GetSnowParams().m_fSurfaceFreezing;
- }
- bRet = true;
- }
- return bRet;
-}
-
-void C3DEngine::SetSnowFallParams(int nSnowFlakeCount, float fSnowFlakeSize, float fSnowFallBrightness, float fSnowFallGravityScale, float fSnowFallWindScale, float fSnowFallTurbulence, float fSnowFallTurbulenceFreq)
-{
- if (m_pObjManager)
- {
- m_pObjManager->GetSnowParams().m_nSnowFlakeCount = nSnowFlakeCount;
- m_pObjManager->GetSnowParams().m_fSnowFlakeSize = fSnowFlakeSize;
- m_pObjManager->GetSnowParams().m_fSnowFallBrightness = fSnowFallBrightness;
- m_pObjManager->GetSnowParams().m_fSnowFallGravityScale = fSnowFallGravityScale;
- m_pObjManager->GetSnowParams().m_fSnowFallWindScale = fSnowFallWindScale;
- m_pObjManager->GetSnowParams().m_fSnowFallTurbulence = fSnowFallTurbulence;
- m_pObjManager->GetSnowParams().m_fSnowFallTurbulenceFreq = fSnowFallTurbulenceFreq;
- }
-}
-
-bool C3DEngine::GetSnowFallParams(int& nSnowFlakeCount, float& fSnowFlakeSize, float& fSnowFallBrightness, float& fSnowFallGravityScale, float& fSnowFallWindScale, float& fSnowFallTurbulence, float& fSnowFallTurbulenceFreq)
-{
- bool bRet = false;
- if (m_pObjManager)
- {
- nSnowFlakeCount = 0;
- fSnowFlakeSize = 0.f;
- fSnowFallBrightness = 0.f;
- fSnowFallGravityScale = 0.f;
- fSnowFallWindScale = 0.f;
- fSnowFallTurbulence = 0.f;
- fSnowFallTurbulenceFreq = 0.f;
- if (IsOutdoorVisible())
- {
- nSnowFlakeCount = m_pObjManager->GetSnowParams().m_nSnowFlakeCount;
- fSnowFlakeSize = m_pObjManager->GetSnowParams().m_fSnowFlakeSize;
- fSnowFallBrightness = m_pObjManager->GetSnowParams().m_fSnowFallBrightness;
- fSnowFallGravityScale = m_pObjManager->GetSnowParams().m_fSnowFallGravityScale;
- fSnowFallWindScale = m_pObjManager->GetSnowParams().m_fSnowFallWindScale;
- fSnowFallTurbulence = m_pObjManager->GetSnowParams().m_fSnowFallTurbulence;
- fSnowFallTurbulenceFreq = m_pObjManager->GetSnowParams().m_fSnowFallTurbulenceFreq;
- }
- bRet = true;
- }
- return bRet;
-}
-
-void C3DEngine::SetSunDir(const Vec3& newSunDir)
-{
- Vec3 vSunDirNormalized = newSunDir.normalized();
- m_vSunDirRealtime = vSunDirNormalized;
- if (vSunDirNormalized.Dot(m_vSunDirNormalized) < GetFloatCVar(e_SunAngleSnapDot) ||
- GetCurTimeSec() - m_fSunDirUpdateTime > GetFloatCVar(e_SunAngleSnapSec))
- {
- m_vSunDirNormalized = vSunDirNormalized;
- m_vSunDir = m_vSunDirNormalized * DISTANCE_TO_THE_SUN;
-
- m_fSunDirUpdateTime = GetCurTimeSec();
- }
-}
-
-Vec3 C3DEngine::GetSunDir() const
-{
- return m_vSunDir;
-}
-
-Vec3 C3DEngine::GetRealtimeSunDirNormalized() const
-{
- return m_vSunDirRealtime;
-}
-
-void C3DEngine::FreeRenderNodeState(IRenderNode* pEnt)
-{
- // make sure we don't try to update the streaming priority if an object
- // was added and removed in the same frame
- int nElementID = m_deferredRenderComponentStreamingPriorityUpdates.Find(pEnt);
- if (nElementID != -1)
- {
- m_deferredRenderComponentStreamingPriorityUpdates.DeleteFastUnsorted(nElementID);
- }
-
- m_pObjManager->RemoveFromRenderAllObjectDebugInfo(pEnt);
-
-
-#if !defined(_RELEASE)
- if (!gEnv->IsDedicated())
- {
- //As render nodes can be deleted in many places, it's possible that the map of render nodes used by stats gathering (r_stats 6, perfHUD, debug gun) could get aliased.
- //Ensure that this node is removed from the map to prevent a dereference after deletion.
- gEnv->pRenderer->ForceRemoveNodeFromDrawCallsMap(pEnt);
- }
-#endif
-
- m_lstAlwaysVisible.Delete(pEnt);
-
- if (m_pDecalManager && (pEnt->m_nInternalFlags & IRenderNode::DECAL_OWNER))
- {
- m_pDecalManager->OnEntityDeleted(pEnt);
- }
-
- if (pEnt->GetRenderNodeType() == eERType_Light)
- {
- GetRenderer()->OnEntityDeleted(pEnt);
- }
-
- if (pEnt->GetRndFlags() & (ERF_CASTSHADOWMAPS | ERF_HAS_CASTSHADOWMAPS))
- { // make sure pointer to object will not be used somewhere in the renderer
-#if !defined(_RELEASE)
- if (!(pEnt->GetRndFlags() & ERF_HAS_CASTSHADOWMAPS))
- {
- Warning("IRenderNode has ERF_CASTSHADOWMAPS set but not ERF_HAS_CASTSHADOWMAPS, name: '%s', class: '%s'.", pEnt->GetName(), pEnt->GetEntityClassName());
- }
-#endif
- Get3DEngine()->OnCasterDeleted(pEnt);
- }
-
- UnRegisterEntityImpl(pEnt);
-
- if (pEnt->m_pRNTmpData)
- {
- Get3DEngine()->FreeRNTmpData(&pEnt->m_pRNTmpData);
- assert(!pEnt->m_pRNTmpData);
- }
-}
-
-const char* C3DEngine::GetLevelFilePath(const char* szFileName)
-{
- cry_strcpy(m_sGetLevelFilePathTmpBuff, m_szLevelFolder);
- if (*szFileName && (*szFileName == '/' || *szFileName == '\\'))
- {
- cry_strcat(m_sGetLevelFilePathTmpBuff, szFileName + 1);
- }
- else
- {
- cry_strcat(m_sGetLevelFilePathTmpBuff, szFileName);
- }
- return m_sGetLevelFilePathTmpBuff;
-}
-
-void C3DEngine::ActivatePortal(const Vec3& vPos, bool bActivate, const char* szEntityName)
-{
- if (m_pVisAreaManager)
- {
- m_pVisAreaManager->ActivatePortal(vPos, bActivate, szEntityName);
- }
-}
-
-bool C3DEngine::SetStatInstGroup(int nGroupId, const IStatInstGroup& siGroup, int nSID)
-{
- if (m_pObjManager->GetListStaticTypes().Count() == 0)
- {
- AZ_Warning("C3DEngine", false, "Trying to set a Stat instance without an initialized Object manager. This might be caused by using the vegetation system without terrain.");
- return false;
- }
- if ((nSID < 0) || (nSID >= m_pObjManager->GetListStaticTypes().Count()))
- {
- AZ_Assert(false, "Invalid StatInst ID: %d (should be > 0 and < %d)", nSID, m_pObjManager->GetListStaticTypes().Count());
- return false;
- }
-
- m_fRefreshSceneDataCVarsSumm = -100;
-
- m_pObjManager->GetListStaticTypes()[nSID].resize(max(nGroupId + 1, m_pObjManager->GetListStaticTypes()[nSID].Count()));
-
- if (nGroupId < 0 || nGroupId >= m_pObjManager->GetListStaticTypes()[nSID].Count())
- {
- return false;
- }
-
- StatInstGroup& rGroup = m_pObjManager->GetListStaticTypes()[nSID][nGroupId];
-
- // If the object was changed in the editor, ResetActiveNodes will need to be called later
- // Keep track of the previous object so we can check for this later
- _smart_ptr pPreviousObject = rGroup.pStatObj;
- rGroup.pStatObj = siGroup.pStatObj;
-
- if (rGroup.pStatObj)
- {
- cry_strcpy(rGroup.szFileName, siGroup.pStatObj->GetFilePath());
- }
- else
- {
- rGroup.szFileName[0] = 0;
- }
-
- rGroup.bHideability = siGroup.bHideability;
- rGroup.bHideabilitySecondary = siGroup.bHideabilitySecondary;
- rGroup.nPlayerHideable = siGroup.nPlayerHideable;
- rGroup.fBending = siGroup.fBending;
- rGroup.nCastShadowMinSpec = siGroup.nCastShadowMinSpec;
- rGroup.bRecvShadow = siGroup.bRecvShadow;
- rGroup.bDynamicDistanceShadows = siGroup.bDynamicDistanceShadows;
-
- rGroup.bUseAlphaBlending = siGroup.bUseAlphaBlending;
- rGroup.fSpriteDistRatio = siGroup.fSpriteDistRatio;
- rGroup.fLodDistRatio = siGroup.fLodDistRatio;
- rGroup.fShadowDistRatio = siGroup.fShadowDistRatio;
- rGroup.fMaxViewDistRatio = siGroup.fMaxViewDistRatio;
-
- rGroup.fBrightness = siGroup.fBrightness;
-
- _smart_ptr pPreviousGroupMaterial = rGroup.pMaterial;
- rGroup.pMaterial = siGroup.pMaterial;
-
- rGroup.fDensity = siGroup.fDensity;
- rGroup.fElevationMax = siGroup.fElevationMax;
- rGroup.fElevationMin = siGroup.fElevationMin;
- rGroup.fSize = siGroup.fSize;
- rGroup.fSizeVar = siGroup.fSizeVar;
- rGroup.fSlopeMax = siGroup.fSlopeMax;
- rGroup.fSlopeMin = siGroup.fSlopeMin;
- rGroup.fStiffness = siGroup.fStiffness;
- rGroup.fDamping = siGroup.fDamping;
- rGroup.fVariance = siGroup.fVariance;
- rGroup.fAirResistance = siGroup.fAirResistance;
-
- rGroup.bRandomRotation = siGroup.bRandomRotation;
- rGroup.nRotationRangeToTerrainNormal = siGroup.nRotationRangeToTerrainNormal;
- rGroup.nMaterialLayers = siGroup.nMaterialLayers;
-
- rGroup.bAllowIndoor = siGroup.bAllowIndoor;
- rGroup.fAlignToTerrainCoefficient = siGroup.fAlignToTerrainCoefficient;
-
- rGroup.bAutoMerged = siGroup.bAutoMerged;
- rGroup.minConfigSpec = siGroup.minConfigSpec;
-
- rGroup.nID = siGroup.nID;
-
- rGroup.Update(GetCVars(), Get3DEngine()->GetGeomDetailScreenRes());
-
- MarkRNTmpDataPoolForReset();
-
- return true;
-}
-
-bool C3DEngine::GetStatInstGroup(int nGroupId, IStatInstGroup& siGroup, int nSID)
-{
- assert(nSID >= 0 && nSID < m_pObjManager->GetListStaticTypes().Count());
-
- if (nGroupId < 0 || nGroupId >= m_pObjManager->GetListStaticTypes()[nSID].Count())
- {
- return false;
- }
-
- StatInstGroup& rGroup = m_pObjManager->GetListStaticTypes()[nSID][nGroupId];
-
- siGroup.pStatObj = rGroup.pStatObj;
- if (siGroup.pStatObj)
- {
- cry_strcpy(siGroup.szFileName, rGroup.pStatObj->GetFilePath());
- }
-
- siGroup.bHideability = rGroup.bHideability;
- siGroup.bHideabilitySecondary = rGroup.bHideabilitySecondary;
- siGroup.nPlayerHideable = rGroup.nPlayerHideable;
- siGroup.fBending = rGroup.fBending;
- siGroup.nCastShadowMinSpec = rGroup.nCastShadowMinSpec;
- siGroup.bRecvShadow = rGroup.bRecvShadow;
- siGroup.bDynamicDistanceShadows = rGroup.bDynamicDistanceShadows;
-
- siGroup.bUseAlphaBlending = rGroup.bUseAlphaBlending;
- siGroup.fSpriteDistRatio = rGroup.fSpriteDistRatio;
- siGroup.fLodDistRatio = rGroup.fLodDistRatio;
- siGroup.fShadowDistRatio = rGroup.fShadowDistRatio;
- siGroup.fMaxViewDistRatio = rGroup.fMaxViewDistRatio;
-
- siGroup.fBrightness = rGroup.fBrightness;
- siGroup.pMaterial = rGroup.pMaterial;
-
- siGroup.fDensity = rGroup.fDensity;
- siGroup.fElevationMax = rGroup.fElevationMax;
- siGroup.fElevationMin = rGroup.fElevationMin;
- siGroup.fSize = rGroup.fSize;
- siGroup.fSizeVar = rGroup.fSizeVar;
- siGroup.fSlopeMax = rGroup.fSlopeMax;
- siGroup.fSlopeMin = rGroup.fSlopeMin;
- siGroup.bAutoMerged = rGroup.bAutoMerged;
-
- siGroup.fStiffness = rGroup.fStiffness;
- siGroup.fDamping = rGroup.fDamping;
- siGroup.fVariance = rGroup.fVariance;
- siGroup.fAirResistance = rGroup.fAirResistance;
-
- siGroup.nID = rGroup.nID;
-
- return true;
-}
-
-void C3DEngine::UpdateStatInstGroups()
-{
- if (!m_pObjManager)
- {
- return;
- }
-
- for (uint32 nSID = 0; nSID < m_pObjManager->GetListStaticTypes().size(); nSID++)
- {
- PodArray& rGroupTable = m_pObjManager->GetListStaticTypes()[nSID];
- for (uint32 nGroupId = 0; nGroupId < rGroupTable.size(); nGroupId++)
- {
- StatInstGroup& rGroup = rGroupTable[nGroupId];
- rGroup.Update(GetCVars(), Get3DEngine()->GetGeomDetailScreenRes());
- }
- }
-}
-
-void C3DEngine::GetMemoryUsage(class ICrySizer* pSizer) const
-{
- pSizer->AddObject(this, sizeof(*this) + (GetCVars()->e_StreamCgfDebug ? 100 * 1024 * 1024 : 0));
- pSizer->AddObject(m_pCVars);
-
- pSizer->AddObject(m_lstStaticLights);
- pSizer->AddObject(m_arrLightProjFrustums);
-
- pSizer->AddObject(arrFPSforSaveLevelStats);
- pSizer->AddObject(m_lstAlwaysVisible);
-
- if (CTemporaryPool* pPool = CTemporaryPool::Get())
- {
- SIZER_COMPONENT_NAME(pSizer, "Temporary Pool");
- pPool->GetMemoryUsage(pSizer);
- }
-
- {
- SIZER_COMPONENT_NAME(pSizer, "RenderMeshMerger");
- m_pRenderMeshMerger->GetMemoryUsage(pSizer);
- }
-
- {
- SIZER_COMPONENT_NAME(pSizer, "Optics");
- pSizer->AddObject(m_pOpticsManager);
- }
-
- {
- SIZER_COMPONENT_NAME(pSizer, "SkyLightManager");
- pSizer->AddObject(m_pSkyLightManager);
- }
-
- {
- SIZER_COMPONENT_NAME(pSizer, "DecalManager");
- pSizer->AddObject(m_pDecalManager);
- }
-
- {
- SIZER_COMPONENT_NAME(pSizer, "OutdoorObjectsTree");
- pSizer->AddObject(m_pObjectsTree);
- }
-
- {
- SIZER_COMPONENT_NAME(pSizer, "ObjManager");
- pSizer->AddObject(m_pObjManager);
- }
-
- {
- SIZER_COMPONENT_NAME(pSizer, "Ocean");
- pSizer->AddObject(m_pOcean);
- }
-
- {
- SIZER_COMPONENT_NAME(pSizer, "VisAreas");
- pSizer->AddObject(m_pVisAreaManager);
- }
-
- {
- SIZER_COMPONENT_NAME(pSizer, "ClipVolumes");
- pSizer->AddObject(m_pClipVolumeManager);
- }
-
- {
- SIZER_COMPONENT_NAME(pSizer, "CoverageBuffer");
- pSizer->AddObject(m_pCoverageBuffer);
- }
-
- {
- SIZER_COMPONENT_NAME(pSizer, "RNTmpDataPool");
-
- CRNTmpData* pNext = NULL;
-
- for (CRNTmpData* pElem = m_LTPRootFree.pNext; pElem != &m_LTPRootFree; pElem = pNext)
- {
- pSizer->AddObject(pElem, sizeof(*pElem));
- pNext = pElem->pNext;
- }
-
- for (CRNTmpData* pElem = m_LTPRootUsed.pNext; pElem != &m_LTPRootUsed; pElem = pNext)
- {
- pSizer->AddObject(pElem, sizeof(*pElem));
- pNext = pElem->pNext;
- }
- }
-}
-
-void C3DEngine::GetResourceMemoryUsage(ICrySizer* pSizer, const AABB& cstAABB)
-{
- //////////////////////////////////////////////////////////////////////////
- std::vector cFoundRenderNodes;
- unsigned int nFoundObjects(0);
-
- nFoundObjects = GetObjectsInBox(cstAABB);
- cFoundRenderNodes.resize(nFoundObjects, NULL);
- GetObjectsInBox(cstAABB, &cFoundRenderNodes.front());
-
- size_t nCurrentRenderNode(0);
- size_t nTotalNumberOfRenderNodes(0);
-
- nTotalNumberOfRenderNodes = cFoundRenderNodes.size();
- for (nCurrentRenderNode = 0; nCurrentRenderNode < nTotalNumberOfRenderNodes; ++nCurrentRenderNode)
- {
- IRenderNode*& piRenderNode = cFoundRenderNodes[nCurrentRenderNode];
-
- _smart_ptr piMaterial(piRenderNode->GetMaterialOverride());
- if (!piMaterial)
- {
- piMaterial = piRenderNode->GetMaterial();
- }
-
- if (piMaterial)
- {
- piMaterial->GetResourceMemoryUsage(pSizer);
- }
-
- {
- IRenderMesh* piMesh(NULL);
- size_t nCount(0);
-
- piMesh = piRenderNode->GetRenderMesh(nCount);
- for (; piMesh; ++nCount, piMesh = piRenderNode->GetRenderMesh(nCount))
- {
- // Timur, RenderMesh may not be loaded due to streaming!
- piMesh->GetMemoryUsage(pSizer, IRenderMesh::MEM_USAGE_COMBINED);
- }
- }
- }
- //////////////////////////////////////////////////////////////////////////
-}
-
-bool C3DEngine::IsUnderWater(const Vec3& vPos) const
-{
- bool bUnderWater = false;
- // Check underwater
- AZ_UNUSED(vPos)
- CRY_PHYSICS_REPLACEMENT_ASSERT();
- return bUnderWater;
-}
-
-void C3DEngine::SetOceanRenderFlags(uint8 nFlags)
-{
- m_nOceanRenderFlags = nFlags;
-}
-
-uint32 C3DEngine::GetOceanVisiblePixelsCount() const
-{
- return COcean::GetVisiblePixelsCount();
-}
-
-float C3DEngine::GetBottomLevel(const Vec3& referencePos, float maxRelevantDepth, [[maybe_unused]] int objflags)
-{
- FUNCTION_PROFILER_3DENGINE;
-
- float terrainWorldZ = AzFramework::Terrain::TerrainDataRequests::GetDefaultTerrainHeight();
- AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult(terrainWorldZ
- , &AzFramework::Terrain::TerrainDataRequests::GetHeightFromFloats
- , referencePos.x, referencePos.y, AzFramework::Terrain::TerrainDataRequests::Sampler::BILINEAR, nullptr);
-
- const float padding = 0.2f;
- float rayLength;
-
- // NOTE: Terrain is above referencePos, so referencePos is probably inside a voxel or something.
- if (terrainWorldZ <= referencePos.z)
- {
- rayLength = min(maxRelevantDepth, (referencePos.z - terrainWorldZ));
- }
- else
- {
- rayLength = maxRelevantDepth;
- }
-
- rayLength += padding * 2.0f;
-
- // Get bottom level
- CRY_PHYSICS_REPLACEMENT_ASSERT();
-
- // Terrain was above or too far below referencePos, and no solid object was close enough.
- return BOTTOM_LEVEL_UNKNOWN;
-}
-
-float C3DEngine::GetBottomLevel(const Vec3& referencePos, float maxRelevantDepth /* = 10.0f */)
-{
- return GetBottomLevel (referencePos, maxRelevantDepth, ent_terrain | ent_static | ent_sleeping_rigid | ent_rigid);
-}
-
-float C3DEngine::GetBottomLevel(const Vec3& referencePos, int objflags)
-{
- return GetBottomLevel (referencePos, 10.0f, objflags);
-}
-
-#if defined(USE_GEOM_CACHES)
-IGeomCache* C3DEngine::LoadGeomCache(const char* szFileName)
-{
- if (!szFileName || !szFileName[0])
- {
- m_pSystem->Warning(VALIDATOR_MODULE_3DENGINE, VALIDATOR_ERROR, 0, 0, "I3DEngine::LoadGeomCache: filename is not specified");
- return 0;
- }
-
- return m_pGeomCacheManager->LoadGeomCache(szFileName);
-}
-
-IGeomCache* C3DEngine::FindGeomCacheByFilename(const char* szFileName)
-{
- if (!szFileName || szFileName[0] == 0)
- {
- return NULL;
- }
-
- return m_pGeomCacheManager->FindGeomCacheByFilename(szFileName);
-}
-#endif
-
-namespace
-{
- // The return value is the next position of the source buffer.
- int ReadFromBuffer(const char* pSource, int nSourceSize, int nSourcePos, void* pDest, int nDestSize)
- {
- if (pDest == 0 || nDestSize == 0)
- {
- return 0;
- }
-
- if (nSourcePos < 0 || nSourcePos >= nSourceSize)
- {
- return 0;
- }
-
- memcpy(pDest, &pSource[nSourcePos], nDestSize);
-
- return nSourcePos + nDestSize;
- }
-}
-
-IStatObj* C3DEngine::LoadDesignerObject(int nVersion, const char* szBinaryStream, int size)
-{
- if (nVersion < 0 || nVersion > 2)
- {
- return NULL;
- }
-
- int nBufferPos = 0;
- int32 nSubObjectCount = 0;
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nSubObjectCount, sizeof(int32));
-
- IStatObj* pStatObj = gEnv->p3DEngine->CreateStatObj();
- if (!pStatObj)
- {
- return NULL;
- }
-
- std::vector statObjList;
- if (nSubObjectCount == 2)
- {
- pStatObj->AddSubObject(gEnv->p3DEngine->CreateStatObj());
- pStatObj->AddSubObject(gEnv->p3DEngine->CreateStatObj());
- pStatObj->GetIndexedMesh()->FreeStreams();
- statObjList.push_back(pStatObj->GetSubObject(0)->pStatObj);
- statObjList.push_back(pStatObj->GetSubObject(1)->pStatObj);
- }
- else
- {
- statObjList.push_back(pStatObj);
- }
-
- if (nVersion == 2)
- {
- int32 nStaticObjFlags = 0;
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nStaticObjFlags, sizeof(int32));
- pStatObj->SetFlags(nStaticObjFlags);
- }
-
- for (int k = 0, iCount(statObjList.size()); k < iCount; ++k)
- {
- int32 nPositionCount = 0;
- int32 nTexCoordCount = 0;
- int32 nFaceCount = 0;
- int32 nIndexCount = 0;
- int32 nTangentCount = 0;
- int32 nSubsetCount = 0;
-
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nPositionCount, sizeof(int32));
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nTexCoordCount, sizeof(int32));
- if (nPositionCount <= 0 || nTexCoordCount <= 0)
- {
- return NULL;
- }
-
- if (nVersion == 0)
- {
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nFaceCount, sizeof(int32));
- if (nFaceCount <= 0)
- {
- return NULL;
- }
- }
- else if (nVersion >= 1)
- {
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nIndexCount, sizeof(int32));
- if (nIndexCount <= 0)
- {
- return NULL;
- }
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nTangentCount, sizeof(int32));
- }
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nSubsetCount, sizeof(int32));
- IIndexedMesh* pMesh = statObjList[k]->GetIndexedMesh();
- if (!pMesh)
- {
- return NULL;
- }
-
- pMesh->FreeStreams();
- pMesh->SetVertexCount((int)nPositionCount);
- pMesh->SetFaceCount((int)nFaceCount);
- pMesh->SetIndexCount((int)nIndexCount);
- pMesh->SetTexCoordCount((int)nTexCoordCount);
-
- Vec3* const positions = pMesh->GetMesh()->GetStreamPtr(CMesh::POSITIONS);
- Vec3* const normals = pMesh->GetMesh()->GetStreamPtr(CMesh::NORMALS);
- SMeshTexCoord* const texcoords = pMesh->GetMesh()->GetStreamPtr(CMesh::TEXCOORDS);
-
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, positions, sizeof(Vec3) * nPositionCount);
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, normals, sizeof(Vec3) * nPositionCount);
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, texcoords, sizeof(SMeshTexCoord) * nTexCoordCount);
- if (nVersion == 0)
- {
- SMeshFace* const faces = pMesh->GetMesh()->GetStreamPtr(CMesh::FACES);
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, faces, sizeof(SMeshFace) * nFaceCount);
- }
- else if (nVersion >= 1)
- {
- vtx_idx* const indices = pMesh->GetMesh()->GetStreamPtr(CMesh::INDICES);
- if constexpr (sizeof(vtx_idx) == sizeof(uint16))
- {
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, indices, sizeof(uint16) * nIndexCount);
- }
- else
- {
- uint16* indices16 = new uint16[nIndexCount];
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, indices16, sizeof(uint16) * nIndexCount);
- for (int32 i = 0; i < nIndexCount; ++i)
- {
- indices[i] = (vtx_idx)indices16[i];
- }
- delete [] indices16;
- }
- pMesh->SetTangentCount((int)nTangentCount);
- if (nTangentCount > 0)
- {
- SMeshTangents* const tangents = pMesh->GetMesh()->GetStreamPtr(CMesh::TANGENTS);
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, tangents, sizeof(SMeshTangents) * nTangentCount);
- }
- }
-
- pMesh->SetSubSetCount(nSubsetCount);
- for (int i = 0; i < nSubsetCount; ++i)
- {
- SMeshSubset subset;
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &subset.vCenter, sizeof(Vec3));
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &subset.fRadius, sizeof(float));
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &subset.fTexelDensity, sizeof(float));
-
- int32 nFirstIndexId = 0;
- int32 nNumIndices = 0;
- int32 nFirstVertId = 0;
- int32 nNumVerts = 0;
- int32 nMatID = 0;
- int32 nMatFlags = 0;
- int32 nPhysicalizeType = 0;
-
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nFirstIndexId, sizeof(int32));
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nNumIndices, sizeof(int32));
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nFirstVertId, sizeof(int32));
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nNumVerts, sizeof(int32));
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nMatID, sizeof(int32));
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nMatFlags, sizeof(int32));
- nBufferPos = ReadFromBuffer(szBinaryStream, size, nBufferPos, &nPhysicalizeType, sizeof(int32));
-
- pMesh->SetSubsetBounds(i, subset.vCenter, subset.fRadius);
- pMesh->SetSubsetIndexVertexRanges(i, (int)nFirstIndexId, (int)nNumIndices, (int)nFirstVertId, (int)nNumVerts);
- pMesh->SetSubsetMaterialId(i, nMatID == -1 ? 0 : (int)nMatID);
- pMesh->SetSubsetMaterialProperties(i, (int)nMatFlags, (int)nPhysicalizeType, eVF_P3F_C4B_T2F);
- }
-
- if (nVersion == 0)
- {
-#if defined(WIN32) || defined(WIN64)
- pMesh->Optimize();
-#endif
- }
-
- statObjList[k]->Invalidate(true);
- }
-
- return pStatObj;
-}
-
-float C3DEngine::GetWaterLevel(const Vec3* pvPos, IPhysicalEntity* pent, bool bAccurate)
-{
- FUNCTION_PROFILER_3DENGINE;
- if (!OceanGlobals::g_oceanParamsMutex.try_lock())
- {
- return OceanGlobals::g_oceanLevel;
- }
-
- bool bInVisarea = m_pVisAreaManager && m_pVisAreaManager->GetVisAreaFromPos(*pvPos) != 0;
-
-
- AZ_UNUSED(pent);
-
- float max_level = (!bInVisarea) ? (bAccurate ? GetAccurateOceanHeight(*pvPos) : GetWaterLevel()) : WATER_LEVEL_UNKNOWN;
-
-
- OceanGlobals::g_oceanParamsMutex.unlock();
- return max(WATER_LEVEL_UNKNOWN, max_level);
-}
-
-void C3DEngine::SetShadowsGSMCache(bool bCache)
-{
- if (bCache)
- {
- m_nGsmCache = m_pConsole->GetCVar("r_ShadowsCache")->GetIVal();
- }
- else
- {
- m_nGsmCache = 0;
- }
-}
-
-float C3DEngine::GetAccurateOceanHeight(const Vec3& pCurrPos) const
-{
- FUNCTION_PROFILER_3DENGINE;
-
- static int nFrameID = -1;
- const int nEngineFrameID = GetRenderer()->GetFrameID();
- static float fWaterLevel = 0;
- if (nFrameID != nEngineFrameID && m_pOcean)
- {
- fWaterLevel = OceanToggle::IsActive() ? OceanRequest::GetOceanLevel() : m_pOcean->GetWaterLevel();
- nFrameID = nEngineFrameID;
- }
-
- const float waterLevel = fWaterLevel + COcean::GetWave(pCurrPos, GetRenderer()->GetFrameID());
- return waterLevel;
-}
-
-I3DEngine::CausticsParams C3DEngine::GetCausticsParams() const
-{
- I3DEngine::CausticsParams params;
- if (OceanToggle::IsActive())
- {
- params.tiling = OceanRequest::GetCausticsTiling();
- params.distanceAttenuation = OceanRequest::GetCausticsDistanceAttenuation();
- params.depth = OceanRequest::GetCausticsDepth();
- params.intensity = OceanRequest::GetCausticsIntensity();
- }
- else
- {
- params.tiling = m_oceanCausticsTiling;
- params.distanceAttenuation = m_oceanCausticsDistanceAtten;
- params.depth = m_oceanCausticDepth;
- params.intensity = m_oceanCausticIntensity;
- }
- params.height = 0.0f; // @TODO: (@pruiksma) Parameter not currently accessible, need to decide whether to rip out or start using. [LY-62048]
- return params;
-}
-
-void C3DEngine::GetHDRSetupParams(Vec4 pParams[5]) const
-{
- float hdrBloomAmount;
- GetPostEffectParam("Global_User_HDRBloom", hdrBloomAmount);
- pParams[0] = m_vHDRFilmCurveParams;
- pParams[1] = Vec4(hdrBloomAmount * 0.3f, hdrBloomAmount * 0.3f, hdrBloomAmount * 0.3f, m_fGrainAmount);
- pParams[2] = Vec4(m_vColorBalance, m_fHDRSaturation);
- pParams[3] = Vec4(m_vHDREyeAdaptation, 1.0f);
- pParams[4] = Vec4(m_vHDREyeAdaptationLegacy, 1.0f);
-};
-
-
-I3DEngine::OceanAnimationData C3DEngine::GetOceanAnimationParams() const
-{
- I3DEngine::OceanAnimationData data;
- if (OceanToggle::IsActive())
- {
- data.fWavesAmount = OceanRequest::GetWavesAmount();
- data.fWavesSize = OceanRequest::GetWavesSize();
- data.fWavesSpeed = OceanRequest::GetWavesSpeed();
- data.fWindDirection = OceanRequest::GetWindDirection();
- data.fWindSpeed = OceanRequest::GetWindSpeed();
- }
- else
- {
- data.fWavesAmount = m_oceanWavesAmount;
- data.fWavesSize = m_oceanWavesSize;
- data.fWavesSpeed = m_oceanWavesSpeed;
- data.fWindDirection = m_oceanWindDirection;
- data.fWindSpeed = m_oceanWindSpeed;
- }
-
- sincos_tpl(data.fWindDirection, &data.fWindDirectionU, &data.fWindDirectionV);
- return data;
-}
-
-IVisArea* C3DEngine::CreateVisArea(uint64 visGUID)
-{
- return m_pObjManager ? m_pVisAreaManager->CreateVisArea(visGUID) : 0;
-}
-
-void C3DEngine::DeleteVisArea(IVisArea* pVisArea)
-{
- if (!m_pVisAreaManager->IsValidVisAreaPointer((CVisArea*)pVisArea))
- {
- Warning("I3DEngine::DeleteVisArea: Invalid VisArea pointer");
- return;
- }
- if (m_pObjManager)
- {
- CVisArea* pArea = (CVisArea*)pVisArea;
-
- PodArray lstEntitiesInArea;
- if (pArea->m_pObjectsTree)
- {
- pArea->m_pObjectsTree->MoveObjectsIntoList(&lstEntitiesInArea, NULL);
- }
-
- // unregister from indoor
- for (int i = 0; i < lstEntitiesInArea.Count(); i++)
- {
- Get3DEngine()->UnRegisterEntityDirect(lstEntitiesInArea[i].pNode);
- }
-
- if (pArea->m_pObjectsTree)
- {
- assert(pArea->m_pObjectsTree->GetObjectsCount(eMain) == 0);
- }
-
- m_pVisAreaManager->DeleteVisArea((CVisArea*)pVisArea);
-
- for (int i = 0; i < lstEntitiesInArea.Count(); i++)
- {
- Get3DEngine()->RegisterEntity(lstEntitiesInArea[i].pNode);
- }
- }
-}
-
-void C3DEngine::UpdateVisArea(IVisArea* pVisArea, const Vec3* pPoints, int nCount, const char* szName,
- const SVisAreaInfo& info, bool bReregisterObjects)
-{
- if (!m_pObjManager)
- {
- return;
- }
-
- CVisArea* pArea = (CVisArea*)pVisArea;
-
- // PrintMessage("C3DEngine::UpdateVisArea: %s", szName);
-
- Vec3 vTotalBoxMin = pArea->m_boxArea.min;
- Vec3 vTotalBoxMax = pArea->m_boxArea.max;
-
- m_pVisAreaManager->UpdateVisArea((CVisArea*)pVisArea, pPoints, nCount, szName, info);
-
- if (((CVisArea*)pVisArea)->m_pObjectsTree && ((CVisArea*)pVisArea)->m_pObjectsTree->GetObjectsCount(eMain))
- {
- // merge old and new bboxes
- vTotalBoxMin.CheckMin(pArea->m_boxArea.min);
- vTotalBoxMax.CheckMax(pArea->m_boxArea.max);
- }
- else
- {
- vTotalBoxMin = pArea->m_boxArea.min;
- vTotalBoxMax = pArea->m_boxArea.max;
- }
-
- if (bReregisterObjects)
- {
- m_pObjManager->ReregisterEntitiesInArea(vTotalBoxMin - Vec3(8, 8, 8), vTotalBoxMax + Vec3(8, 8, 8));
- }
-}
-
-IClipVolume* C3DEngine::CreateClipVolume()
-{
- return m_pClipVolumeManager->CreateClipVolume();
-}
-
-void C3DEngine::DeleteClipVolume(IClipVolume* pClipVolume)
-{
- m_pClipVolumeManager->DeleteClipVolume(pClipVolume);
-}
-
-void C3DEngine::UpdateClipVolume(IClipVolume* pClipVolume, _smart_ptr pRenderMesh, IBSPTree3D* pBspTree, const Matrix34& worldTM, bool bActive, uint32 flags, const char* szName)
-{
- m_pClipVolumeManager->UpdateClipVolume(pClipVolume, pRenderMesh, pBspTree, worldTM, bActive, flags, szName);
-}
-
-void C3DEngine::ResetParticlesAndDecals()
-{
- if (m_pDecalManager)
- {
- m_pDecalManager->Reset();
- }
-}
-
-IRenderNode* C3DEngine::CreateRenderNode(EERType type)
-{
- switch (type)
- {
- case eERType_Cloud:
- {
- CCloudRenderNode* pCloud = new CCloudRenderNode();
- return pCloud;
- }
- case eERType_FogVolume:
- {
- CFogVolumeRenderNode* pFogVolume = new CFogVolumeRenderNode();
- return pFogVolume;
- }
- case eERType_Decal:
- {
- CDecalRenderNode* pDecal = new CDecalRenderNode();
- return pDecal;
- }
- case eERType_WaterVolume:
- {
- CWaterVolumeRenderNode* pWaterVolume = new CWaterVolumeRenderNode();
- return pWaterVolume;
- }
- case eERType_DistanceCloud:
- {
- CDistanceCloudRenderNode* pRenderNode = new CDistanceCloudRenderNode();
- return pRenderNode;
- }
- case eERType_VolumeObject:
- {
- IVolumeObjectRenderNode* pRenderNode = new CVolumeObjectRenderNode();
- return pRenderNode;
- }
-#if !defined(EXCLUDE_DOCUMENTATION_PURPOSE)
- case eERType_PrismObject:
- {
- IPrismRenderNode* pRenderNode = new CPrismRenderNode();
- return pRenderNode;
- }
-#endif // EXCLUDE_DOCUMENTATION_PURPOSE
-
-#if defined(USE_GEOM_CACHES)
- case eERType_GeomCache:
- {
- IRenderNode* pRenderNode = new CGeomCacheRenderNode();
- return pRenderNode;
- }
-#endif
- }
- assert(!"C3DEngine::CreateRenderNode: Specified node type is not supported.");
- return 0;
-}
-
-void C3DEngine::DeleteRenderNode(IRenderNode* pRenderNode)
-{
- UnRegisterEntityDirect(pRenderNode);
- delete pRenderNode;
-}
-
-
-Vec3 C3DEngine::GetWind(const AABB& box, bool bIndoors) const
-{
- FUNCTION_PROFILER_3DENGINE;
-
-#if defined(CONSOLE_CONST_CVAR_MODE)
- if constexpr (!CVars::e_Wind)
-#else
- if (!m_pCVars->e_Wind)
-#endif
- {
- return Vec3_Zero;
- }
-
- // Start with global wind.
- Vec3 vWind = GetGlobalWind(bIndoors);
-
-#if defined(CONSOLE_CONST_CVAR_MODE)
- if constexpr (CVars::e_WindAreas)
-#else
- if (m_pCVars->e_WindAreas)
-#endif
- {
- const Physics::WindRequests* windRequests = AZ::Interface::Get();
- if (windRequests)
- {
- const AZ::Aabb aabb = LyAABBToAZAabb(box);
- const AZ::Vector3 wind = windRequests->GetWind(aabb);
- vWind += AZVec3ToLYVec3(wind);
- }
- }
-
- return vWind;
-}
-
-Vec3 C3DEngine::GetGlobalWind(bool bIndoors) const
-{
- FUNCTION_PROFILER_3DENGINE;
-
- // We assume indoor wind is zero.
- if (!m_pCVars->e_Wind || bIndoors)
- {
- return Vec3_Zero;
- }
-
- const Physics::WindRequests* windRequests = AZ::Interface::Get();
- if (windRequests)
- {
- const AZ::Vector3 wind = windRequests->GetGlobalWind();
- return AZVec3ToLYVec3(wind);
- }
- return Vec3_Zero;
-}
-
-bool C3DEngine::SampleWind(Vec3* pSamples, int nSamples, const AABB& volume, bool bIndoors) const
-{
- FUNCTION_PROFILER_3DENGINE;
-
- if (!m_pCVars->e_Wind || nSamples == 0)
- {
- return false;
- }
-
- IF (m_nWindSamplePositions < (size_t)nSamples, 0)
- {
- if (m_pWindSamplePositions)
- {
- CryModuleMemalignFree(m_pWindSamplePositions);
- }
- m_nWindSamplePositions = nSamples;
- m_pWindSamplePositions = (Vec3*)CryModuleMemalign(m_nWindSamplePositions * sizeof(Vec3), 128u);
- }
-
- Vec3* pPositions = m_pWindSamplePositions;
- memcpy(pPositions, pSamples, sizeof(Vec3) * nSamples);
-
- // Start with global wind.
- Vec3 vWind = GetGlobalWind(bIndoors);
-
- for (int i = 0; i < nSamples; ++i)
- {
- pSamples[i] = vWind;
- }
-
-#if defined(CONSOLE_CONST_CVAR_MODE)
- if constexpr (CVars::e_WindAreas)
-#else
- if (m_pCVars->e_WindAreas)
-#endif
- {
- const Physics::WindRequests* windRequests = AZ::Interface::Get();
- if (windRequests)
- {
- for (int i = 0; i < nSamples; ++i)
- {
- const AZ::Vector3 position = LYVec3ToAZVec3(pPositions[i]);
- const AZ::Vector3 wind = windRequests->GetWind(position);
- pSamples[i] += AZVec3ToLYVec3(wind);
- }
- }
- }
- AZ_UNUSED(volume);
- return true;
-}
-
-void C3DEngine::SetupBending(CRenderObject*& pObj, const IRenderNode* pNode, const float fRadiusVert, const SRenderingPassInfo& passInfo, bool alreadyDuplicated)
-{
- FUNCTION_PROFILER_3DENGINE;
- if (!GetCVars()->e_VegetationBending)
- {
- return;
- }
-
- if (!pNode->m_pRNTmpData)
- {
- return;
- }
-
- // Get/Update PhysAreaChanged Proxy
- {
- // Lock to avoid a situation where two threads simultaneously find that nProxId is ~0,
- // which would result in two physics proxies for the same render node which eventually leads to a crash
- AUTO_LOCK(m_PhysicsAreaUpdates.m_Mutex);
- const uint32 nProxyId = pNode->m_pRNTmpData->nPhysAreaChangedProxyId;
- if (nProxyId != ~0)
- {
- m_PhysicsAreaUpdates.UpdateProxy(pNode, nProxyId);
- }
- else
- {
- pNode->m_pRNTmpData->nPhysAreaChangedProxyId = m_PhysicsAreaUpdates.CreateProxy(pNode, Area_Air);
- }
- }
-
- CRNTmpData::SRNUserData& userData = pNode->m_pRNTmpData->userData;
- const bool needsUpdate = userData.nBendingLastFrame != (passInfo.GetMainFrameID() & ~(3 << 29));
- const bool isFirstFrame = userData.nBendingLastFrame == 0;
-
- const Vec3& vObjPos = pObj->GetTranslation();
- const float fMaxViewDist = const_cast(pNode)->GetMaxViewDist();
- const float fBendingAttenuation = 1.f - (pObj->m_fDistance / (fMaxViewDist * GetFloatCVar(e_WindBendingDistRatio)));
- uint32 bendingMaskOr = 0u;
- uint32 bendingMaskAnd = ~FOB_BENDED;
-
- if (fBendingAttenuation > 0.f && userData.m_Bending.m_fMainBendingScale > 0.f)
- {
- bendingMaskOr = FOB_BENDED;
- bendingMaskAnd = ~0u;
-
- userData.m_BendingPrev = userData.m_Bending;
-
- if (needsUpdate)
- {
- userData.nBendingLastFrame = passInfo.GetMainFrameID();
-
- static const float fBEND_RESPONSE = 0.25f;
- static const float fMAX_BENDING = 2.f;
- static const float fWAVE_PARALLEL = 0.008f;
- static const float fWAVE_TRANSVERSE = 0.002f;
-
- if (!userData.bWindCurrent)
- {
- userData.vCurrentWind = m_p3DEngine->GetWind(pNode->GetBBox(), !!pNode->GetEntityVisArea());
- userData.bWindCurrent = true;
- }
-
- // Soft clamp bending from wind amplitude.
- Vec2 vBending = Vec2(userData.vCurrentWind) * fBEND_RESPONSE;
- vBending *= fMAX_BENDING / (fMAX_BENDING + vBending.GetLength());
- vBending *= fBendingAttenuation;
-
- SBending* pBending = &userData.m_Bending;
-
- float fWaveFreq = 0.4f / (fRadiusVert + 1.f) + 0.2f;
-
- if (!userData.bBendingSet)
- {
- // First time shown, set full bending.
- pBending->m_vBending = vBending;
- userData.bBendingSet = true;
- }
- else
- {
- // Already visible, fade toward current value.
- float fInterp = min(gEnv->pTimer->GetFrameTime() * fWaveFreq * 0.5f, 1.f);
- pBending->m_vBending += (vBending - pBending->m_vBending) * fInterp;
- }
-
- pBending->m_Waves[0].m_Level = 0.000f;
- pBending->m_Waves[0].m_Freq = fWaveFreq;
- pBending->m_Waves[0].m_Phase = vObjPos.x * 0.125f;
- pBending->m_Waves[0].m_Amp = pBending->m_vBending.x * fWAVE_PARALLEL + pBending->m_vBending.y * fWAVE_TRANSVERSE;
- pBending->m_Waves[0].m_eWFType = eWF_Sin;
-
- pBending->m_Waves[1].m_Level = 0.000f;
- pBending->m_Waves[1].m_Freq = fWaveFreq * 1.125f;
- pBending->m_Waves[1].m_Phase = vObjPos.y * 0.125f;
- pBending->m_Waves[1].m_Amp = pBending->m_vBending.y * fWAVE_PARALLEL - pBending->m_vBending.x * fWAVE_TRANSVERSE;
- pBending->m_Waves[1].m_eWFType = eWF_Sin;
- }
-
- // When starting fresh, we use the same bend info for previous so
- // that we don't get crazy motion changes.
- if (isFirstFrame)
- {
- userData.m_BendingPrev = userData.m_Bending;
- }
- }
-
- if (!alreadyDuplicated)
- {
- pObj = GetRenderer()->EF_DuplicateRO(pObj, passInfo);
- }
- SRenderObjData* pOD = GetRenderer()->EF_GetObjData(pObj, true, passInfo.ThreadID());
- if (!pOD)
- {
- return;
- }
-
- pObj->m_ObjFlags |= bendingMaskOr | FOB_DYNAMIC_OBJECT | FOB_MOTION_BLUR;
- pObj->m_ObjFlags &= bendingMaskAnd;
- pOD->m_pBending = Get3DEngine()->GetBendingEntry(&userData.m_Bending, passInfo);
- pOD->m_BendingPrev = Get3DEngine()->GetBendingEntry(&userData.m_BendingPrev, passInfo);
-}
-
-IVisArea* C3DEngine::GetVisAreaFromPos(const Vec3& vPos)
-{
- if (m_pObjManager && m_pVisAreaManager)
- {
- return m_pVisAreaManager->GetVisAreaFromPos(vPos);
- }
-
- return 0;
-}
-
-bool C3DEngine::IntersectsVisAreas(const AABB& box, void** pNodeCache)
-{
- if (m_pObjManager && m_pVisAreaManager)
- {
- return m_pVisAreaManager->IntersectsVisAreas(box, pNodeCache);
- }
- return false;
-}
-
-bool C3DEngine::ClipToVisAreas(IVisArea* pInside, Sphere& sphere, Vec3 const& vNormal, void* pNodeCache)
-{
- if (pInside)
- {
- return pInside->ClipToVisArea(true, sphere, vNormal);
- }
- else if (m_pVisAreaManager)
- {
- return m_pVisAreaManager->ClipOutsideVisAreas(sphere, vNormal, pNodeCache);
- }
- return false;
-}
-
-bool C3DEngine::IsVisAreasConnected(IVisArea* pArea1, IVisArea* pArea2, int nMaxRecursion, bool bSkipDisabledPortals)
-{
- if (pArea1 == pArea2)
- {
- return (true); // includes the case when both pArea1 & pArea2 are NULL (totally outside)
- }
- // not considered by the other checks
- if (!pArea1 || !pArea2)
- {
- return (false); // avoid a crash - better to put this check only
- }
- // here in one place than in all the places where this function is called
-
- nMaxRecursion *= 2; // include portals since portals are the areas
-
- if (m_pObjManager && m_pVisAreaManager)
- {
- return ((CVisArea*)pArea1)->FindVisArea((CVisArea*)pArea2, nMaxRecursion, bSkipDisabledPortals);
- }
-
- return false;
-}
-
-bool C3DEngine::IsOutdoorVisible()
-{
- if (m_pObjManager && m_pVisAreaManager)
- {
- return m_pVisAreaManager->IsOutdoorAreasVisible();
- }
-
- return false;
-}
-
-void C3DEngine::EnableOceanRendering(bool bOcean)
-{
- m_bOcean = bOcean;
-}
-
-IObjManager* C3DEngine::GetObjManager()
-{
- return Cry3DEngineBase::GetObjManager();
-}
-
-//////////////////////////////////////////////////////////////////////////
-IMaterialHelpers& C3DEngine::GetMaterialHelpers()
-{
- return Cry3DEngineBase::GetMatMan()->s_materialHelpers;
-}
-
-IMaterialManager* C3DEngine::GetMaterialManager()
-{
- return Cry3DEngineBase::GetMatMan();
-}
-
-//////////////////////////////////////////////////////////////////////////
-void C3DEngine::AddTextureLoadHandler(ITextureLoadHandler* pHandler)
-{
- stl::push_back_unique(m_textureLoadHandlers, pHandler);
-}
-
-void C3DEngine::RemoveTextureLoadHandler(ITextureLoadHandler* pHandler)
-{
- stl::find_and_erase(m_textureLoadHandlers, pHandler);
-}
-
-ITextureLoadHandler* C3DEngine::GetTextureLoadHandlerForImage(const char* path)
-{
- const char* ext = PathUtil::GetExt(path);
-
- for (TTextureLoadHandlers::iterator iter = m_textureLoadHandlers.begin(); iter != m_textureLoadHandlers.end(); iter++)
- {
- if ((*iter)->SupportsExtension(ext))
- {
- return *iter;
- }
- }
-
- return nullptr;
-}
-
-void C3DEngine::CheckMemoryHeap()
-{
- assert (CryMemory::IsHeapValid());
-}
-
-//////////////////////////////////////////////////////////////////////////
-int C3DEngine::GetLoadedObjectCount()
-{
- int nObjectsLoaded = m_pObjManager ? m_pObjManager->GetLoadedObjectCount() : 0;
- return nObjectsLoaded;
-}
-
-//////////////////////////////////////////////////////////////////////////
-void C3DEngine::GetLoadedStatObjArray(IStatObj** pObjectsArray, int& nCount)
-{
- if (m_pObjManager)
- {
- m_pObjManager->GetLoadedStatObjArray(pObjectsArray, nCount);
- }
- else
- {
- nCount = 0;
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-void C3DEngine::GetObjectsStreamingStatus(SObjectsStreamingStatus& outStatus)
-{
- if (m_pObjManager)
- {
- m_pObjManager->GetObjectsStreamingStatus(outStatus);
- }
- else
- {
- memset(&outStatus, 0, sizeof(outStatus));
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-void C3DEngine::GetStreamingSubsystemData(int subsystem, SStremaingBandwidthData& outData)
-{
- switch (subsystem)
- {
- case eStreamTaskTypeSound:
- // Audio: bandwidth stats
- break;
- case eStreamTaskTypeGeometry:
- m_pObjManager->GetBandwidthStats(&outData.fBandwidthRequested);
- break;
- case eStreamTaskTypeTexture:
- gEnv->pRenderer->GetBandwidthStats(&outData.fBandwidthRequested);
- break;
- }
-
-#if defined(STREAMENGINE_ENABLE_STATS)
- gEnv->pSystem->GetStreamEngine()->GetBandwidthStats((EStreamTaskType)subsystem, &outData.fBandwidthActual);
-#endif
-}
-
-//////////////////////////////////////////////////////////////////////////
-void C3DEngine::DeleteEntityDecals(IRenderNode* pEntity)
-{
- if (m_pDecalManager && pEntity && (pEntity->m_nInternalFlags & IRenderNode::DECAL_OWNER))
- {
- m_pDecalManager->OnEntityDeleted(pEntity);
- }
-}
-
-void C3DEngine::DeleteDecalsInRange(AABB* pAreaBox, IRenderNode* pEntity)
-{
- if (m_pDecalManager)
- {
- m_pDecalManager->DeleteDecalsInRange(pAreaBox, pEntity);
- }
-}
-
-void C3DEngine::LockCGFResources()
-{
- if (m_pObjManager)
- {
- m_pObjManager->SetLockCGFResources(true);
- }
-}
-
-void C3DEngine::UnlockCGFResources()
-{
- if (m_pObjManager)
- {
- bool bNeedToFreeCGFs = m_pObjManager->IsLockCGFResources();
- m_pObjManager->SetLockCGFResources(false);
- if (bNeedToFreeCGFs)
- {
- m_pObjManager->FreeNotUsedCGFs();
- }
- }
-}
-
-void C3DEngine::FreeUnusedCGFResources()
-{
- if (m_pObjManager)
- {
- m_pObjManager->FreeNotUsedCGFs();
- }
-}
-
-void CLightEntity::ShadowMapInfo::Release([[maybe_unused]] struct IRenderer* pRenderer)
-{
- delete this;
-}
-
-//////////////////////////////////////////////////////////////////////////
-IIndexedMesh* C3DEngine::CreateIndexedMesh()
-{
- return new CIndexedMesh();
-}
-
-void C3DEngine::SerializeState(TSerialize ser)
-{
- ser.Value("m_bOcean", m_bOcean);
- ser.Value("m_moonRotationLatitude", m_moonRotationLatitude);
- ser.Value("m_moonRotationLongitude", m_moonRotationLongitude);
- ser.Value("m_eShadowMode", *(alias_cast(&m_eShadowMode)));
- if (ser.IsReading())
- {
- UpdateMoonDirection();
- }
-
- if (m_pDecalManager)
- {
- m_pDecalManager->Serialize(ser);
- }
-
- m_pTimeOfDay->Serialize(ser);
-}
-
-void C3DEngine::PostSerialize(bool /*bReading*/)
-{
-}
-
-void C3DEngine::InitMaterialDefautMappingAxis(_smart_ptr pMat)
-{
- uint8 arrProj[3] = {'X', 'Y', 'Z'};
- pMat->m_ucDefautMappingAxis = 'Z';
- pMat->m_fDefautMappingScale = 1.f;
- for (int c = 0; c < 3 && c < pMat->GetSubMtlCount(); c++)
- {
- _smart_ptr pSubMat = (_smart_ptr)pMat->GetSubMtl(c);
- pSubMat->m_ucDefautMappingAxis = arrProj[c];
- pSubMat->m_fDefautMappingScale = pMat->m_fDefautMappingScale;
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-CContentCGF* C3DEngine::CreateChunkfileContent(const char* filename)
-{
- return new CContentCGF(filename);
-}
-void C3DEngine::ReleaseChunkfileContent(CContentCGF* pCGF)
-{
- delete pCGF;
-}
-
-bool C3DEngine::LoadChunkFileContent(CContentCGF* pCGF, const char* filename, bool bNoWarningMode, bool bCopyChunkFile)
-{
- CLoadLogListener listener;
-
- if (!pCGF)
- {
- FileWarning(0, filename, "CGF Loading Failed: no content instance passed");
- }
- else
- {
- CLoaderCGF cgf;
-
- CReadOnlyChunkFile* pChunkFile = new CReadOnlyChunkFile(bCopyChunkFile, bNoWarningMode);
-
- if (cgf.LoadCGF(pCGF, filename, *pChunkFile, &listener))
- {
- pCGF->SetChunkFile(pChunkFile);
- return true;
- }
-
- CryWarning(VALIDATOR_MODULE_3DENGINE, VALIDATOR_WARNING, "%s: Failed to load chunk file: '%s'", __FUNCTION__, cgf.GetLastError());
- delete pChunkFile;
- }
-
- return false;
-}
-
-bool C3DEngine::LoadChunkFileContentFromMem(CContentCGF* pCGF, const void* pData, size_t nDataLen, uint32 nLoadingFlags, bool bNoWarningMode, bool bCopyChunkFile)
-{
- if (!pCGF)
- {
- FileWarning(0, "", "CGF Loading Failed: no content instance passed");
- }
- else
- {
- CLoadLogListener listener;
-
- CLoaderCGF cgf;
- CReadOnlyChunkFile* pChunkFile = new CReadOnlyChunkFile(bCopyChunkFile, bNoWarningMode);
-
- if (cgf.LoadCGFFromMem(pCGF, pData, nDataLen, *pChunkFile, &listener, nLoadingFlags))
- {
- pCGF->SetChunkFile(pChunkFile);
- return true;
- }
-
- CryWarning(VALIDATOR_MODULE_3DENGINE, VALIDATOR_WARNING, "%s: Failed to load chunk file: '%s'", __FUNCTION__, cgf.GetLastError());
- delete pChunkFile;
- }
-
- return false;
-}
-
-IChunkFile* C3DEngine::CreateChunkFile(bool bReadOnly)
-{
- if (bReadOnly)
- {
- return new CReadOnlyChunkFile(false);
- }
- else
- {
- return new CChunkFile;
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-ChunkFile::IChunkFileWriter* C3DEngine::CreateChunkFileWriter(EChunkFileFormat eFormat, AZ::IO::IArchive* pPak, const char* filename) const
-{
- ChunkFile::CryPakFileWriter* const p = new ChunkFile::CryPakFileWriter();
-
- if (!p)
- {
- return 0;
- }
-
- if (!p->Create(pPak, filename))
- {
- delete p;
- return 0;
- }
-
- const ChunkFile::MemorylessChunkFileWriter::EChunkFileFormat fmt =
- (eFormat == I3DEngine::eChunkFileFormat_0x745)
- ? ChunkFile::MemorylessChunkFileWriter::eChunkFileFormat_0x745
- : ChunkFile::MemorylessChunkFileWriter::eChunkFileFormat_0x746;
-
- return new ChunkFile::MemorylessChunkFileWriter(fmt, p);
-}
-
-void C3DEngine::ReleaseChunkFileWriter(ChunkFile::IChunkFileWriter* p) const
-{
- if (p)
- {
- delete p->GetWriter();
- delete p;
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-bool C3DEngine::CreateOcean(_smart_ptr pTerrainWaterMat, float waterLevel)
-{
- // make ocean surface
- SAFE_DELETE(m_pOcean);
-
- if (pTerrainWaterMat == nullptr)
- {
- if (!m_pTerrainWaterMat)
- {
- return false;
- }
-
- pTerrainWaterMat = m_pTerrainWaterMat;
- }
-
- if (OceanToggle::IsActive() ? OceanRequest::OceanIsEnabled() : (waterLevel > 0))
- {
- m_pOcean = new COcean(pTerrainWaterMat, waterLevel);
- }
- return m_pOcean != nullptr;
-}
-
-void C3DEngine::DeleteOcean()
-{
- SAFE_DELETE(m_pOcean);
-}
-
-void C3DEngine::ChangeOceanMaterial(_smart_ptr pMat)
-{
- if (m_pOcean)
- {
- m_pOcean->SetMaterial(pMat);
- }
-}
-
-void C3DEngine::ChangeOceanWaterLevel(float fWaterLevel)
-{
- COcean::SetWaterLevelInfo(fWaterLevel);
-
- if (m_pOcean)
- {
- m_pOcean->SetWaterLevel(fWaterLevel);
- }
-}
-
-void C3DEngine::SetStreamableListener(IStreamedObjectListener* pListener)
-{
- m_pStreamListener = pListener;
-}
-
-void C3DEngine::PrecacheLevel(bool bPrecacheAllVisAreas, Vec3* pPrecachePoints, int nPrecachePointsNum)
-{
- LOADING_TIME_PROFILE_SECTION;
-
- if (GetVisAreaManager())
- {
- GetVisAreaManager()->PrecacheLevel(bPrecacheAllVisAreas, pPrecachePoints, nPrecachePointsNum);
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-void C3DEngine::SetGlobalParameter(E3DEngineParameter param, const Vec3& v)
-{
- float fValue = v.x;
- switch (param)
- {
- case E3DPARAM_SUN_COLOR:
- SetSunColor(v);
- break;
-
- case E3DPARAM_SUN_SPECULAR_MULTIPLIER:
- m_fSunSpecMult = v.x;
- break;
-
- case E3DPARAM_AMBIENT_GROUND_COLOR:
- m_vAmbGroundCol = v;
- break;
- case E3DPARAM_AMBIENT_MIN_HEIGHT:
- m_fAmbMaxHeight = v.x;
- break;
- case E3DPARAM_AMBIENT_MAX_HEIGHT:
- m_fAmbMinHeight = v.x;
- break;
-
- case E3DPARAM_SKY_HIGHLIGHT_POS:
- m_vSkyHightlightPos = v;
- break;
- case E3DPARAM_SKY_HIGHLIGHT_COLOR:
- m_vSkyHightlightCol = v;
- break;
- case E3DPARAM_SKY_HIGHLIGHT_SIZE:
- m_fSkyHighlightSize = fValue > 0.0f ? fValue : 0.0f;
- break;
- case E3DPARAM_VOLFOG_RAMP:
- m_volFogRamp = v;
- break;
- case E3DPARAM_VOLFOG_SHADOW_RANGE:
- m_volFogShadowRange = v;
- break;
- case E3DPARAM_VOLFOG_SHADOW_DARKENING:
- m_volFogShadowDarkening = v;
- break;
- case E3DPARAM_VOLFOG_SHADOW_ENABLE:
- m_volFogShadowEnable = v;
- break;
- case E3DPARAM_VOLFOG2_CTRL_PARAMS:
- m_volFog2CtrlParams = v;
- break;
- case E3DPARAM_VOLFOG2_SCATTERING_PARAMS:
- m_volFog2ScatteringParams = v;
- break;
- case E3DPARAM_VOLFOG2_RAMP:
- m_volFog2Ramp = v;
- break;
- case E3DPARAM_VOLFOG2_COLOR:
- m_volFog2Color = v;
- break;
- case E3DPARAM_VOLFOG2_GLOBAL_DENSITY:
- m_volFog2GlobalDensity = v;
- break;
- case E3DPARAM_VOLFOG2_HEIGHT_DENSITY:
- m_volFog2HeightDensity = v;
- break;
- case E3DPARAM_VOLFOG2_HEIGHT_DENSITY2:
- m_volFog2HeightDensity2 = v;
- break;
- case E3DPARAM_VOLFOG2_COLOR1:
- m_volFog2Color1 = v;
- break;
- case E3DPARAM_VOLFOG2_COLOR2:
- m_volFog2Color2 = v;
- break;
- case E3DPARAM_NIGHSKY_HORIZON_COLOR:
- m_nightSkyHorizonCol = v;
- break;
- case E3DPARAM_NIGHSKY_ZENITH_COLOR:
- m_nightSkyZenithCol = v;
- break;
- case E3DPARAM_NIGHSKY_ZENITH_SHIFT:
- m_nightSkyZenithColShift = v.x;
- break;
- case E3DPARAM_NIGHSKY_STAR_INTENSITY:
- m_nightSkyStarIntensity = v.x;
- break;
- case E3DPARAM_NIGHSKY_MOON_COLOR:
- m_nightMoonCol = v;
- break;
- case E3DPARAM_NIGHSKY_MOON_SIZE:
- m_nightMoonSize = v.x;
- break;
- case E3DPARAM_NIGHSKY_MOON_INNERCORONA_COLOR:
- m_nightMoonInnerCoronaCol = v;
- break;
- case E3DPARAM_NIGHSKY_MOON_INNERCORONA_SCALE:
- m_nightMoonInnerCoronaScale = v.x;
- break;
- case E3DPARAM_NIGHSKY_MOON_OUTERCORONA_COLOR:
- m_nightMoonOuterCoronaCol = v;
- break;
- case E3DPARAM_NIGHSKY_MOON_OUTERCORONA_SCALE:
- m_nightMoonOuterCoronaScale = v.x;
- break;
- case E3DPARAM_OCEANFOG_COLOR:
- m_oceanFogColor = v;
- break;
- case E3DPARAM_OCEANFOG_DENSITY:
- m_oceanFogDensity = v.x;
- break;
- case E3DPARAM_SKY_MOONROTATION:
- m_moonRotationLatitude = v.x;
- m_moonRotationLongitude = v.y;
- UpdateMoonDirection();
- break;
- case E3DPARAM_SKYBOX_MULTIPLIER:
- m_skyboxMultiplier = v.x;
- break;
- case E3DPARAM_DAY_NIGHT_INDICATOR:
- m_dayNightIndicator = v.x;
- // Audio: Set daylight parameter
- break;
- case E3DPARAM_FOG_COLOR2:
- m_fogColor2 = v;
- break;
- case E3DPARAM_FOG_RADIAL_COLOR:
- m_fogColorRadial = v;
- break;
- case E3DPARAM_VOLFOG_HEIGHT_DENSITY:
- m_volFogHeightDensity = Vec3(v.x, v.y, 0);
- break;
- case E3DPARAM_VOLFOG_HEIGHT_DENSITY2:
- m_volFogHeightDensity2 = Vec3(v.x, v.y, 0);
- break;
- case E3DPARAM_VOLFOG_GRADIENT_CTRL:
- m_volFogGradientCtrl = v;
- break;
- case E3DPARAM_VOLFOG_GLOBAL_DENSITY:
- m_volFogGlobalDensity = v.x;
- m_volFogFinalDensityClamp = v.z;
- break;
- case E3DPARAM_COLORGRADING_FILTERS_PHOTOFILTER_COLOR:
- m_pPhotoFilterColor = Vec4(v.x, v.y, v.z, 1);
- GetPostEffectBaseGroup()->SetParam("clr_ColorGrading_PhotoFilterColor", m_pPhotoFilterColor);
- break;
- case E3DPARAM_COLORGRADING_FILTERS_PHOTOFILTER_DENSITY:
- m_fPhotoFilterColorDensity = fValue;
- GetPostEffectBaseGroup()->SetParam("ColorGrading_PhotoFilterColorDensity", m_fPhotoFilterColorDensity);
- break;
- case E3DPARAM_COLORGRADING_FILTERS_GRAIN:
- m_fGrainAmount = fValue;
- GetPostEffectBaseGroup()->SetParam("ColorGrading_GrainAmount", m_fGrainAmount);
- break;
- case E3DPARAM_SKY_SKYBOX_ANGLE: // sky box rotation
- m_fSkyBoxAngle = fValue;
- break;
- case E3DPARAM_SKY_SKYBOX_STRETCHING: // sky box stretching
- m_fSkyBoxStretching = fValue;
- break;
- case E3DPARAM_HDR_FILMCURVE_SHOULDER_SCALE:
- m_vHDRFilmCurveParams.x = v.x;
- break;
- case E3DPARAM_HDR_FILMCURVE_LINEAR_SCALE:
- m_vHDRFilmCurveParams.y = v.x;
- break;
- case E3DPARAM_HDR_FILMCURVE_TOE_SCALE:
- m_vHDRFilmCurveParams.z = v.x;
- break;
- case E3DPARAM_HDR_FILMCURVE_WHITEPOINT:
- m_vHDRFilmCurveParams.w = v.x;
- break;
- case E3DPARAM_HDR_EYEADAPTATION_PARAMS:
- m_vHDREyeAdaptation = v;
- break;
- case E3DPARAM_HDR_EYEADAPTATION_PARAMS_LEGACY:
- m_vHDREyeAdaptationLegacy = v;
- break;
- case E3DPARAM_HDR_BLOOM_AMOUNT:
- m_fHDRBloomAmount = v.x;
- break;
- case E3DPARAM_HDR_COLORGRADING_COLOR_SATURATION:
- m_fHDRSaturation = v.x;
- break;
- case E3DPARAM_HDR_COLORGRADING_COLOR_BALANCE:
- m_vColorBalance = v;
- break;
- case E3DPARAM_CLOUDSHADING_MULTIPLIERS:
- m_fCloudShadingSunLightMultiplier = (v.x >= 0) ? v.x : 0;
- m_fCloudShadingSkyLightMultiplier = (v.y >= 0) ? v.y : 0;
- break;
- case E3DPARAM_CLOUDSHADING_SUNCOLOR:
- m_vCloudShadingCustomSunColor = v;
- break;
- case E3DPARAM_CLOUDSHADING_SKYCOLOR:
- m_vCloudShadingCustomSkyColor = v;
- break;
- case E3DPARAM_NIGHSKY_MOON_DIRECTION: // moon direction is fixed per level or updated via FG node (E3DPARAM_SKY_MOONROTATION)
- default:
- assert(0);
- break;
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-void C3DEngine::GetGlobalParameter(E3DEngineParameter param, Vec3& v)
-{
- switch (param)
- {
- case E3DPARAM_SUN_COLOR:
- v = GetSunColor();
- break;
-
- case E3DPARAM_SUN_SPECULAR_MULTIPLIER:
- v = Vec3(m_fSunSpecMult, 0, 0);
- break;
-
- case E3DPARAM_AMBIENT_GROUND_COLOR:
- v = m_vAmbGroundCol;
- break;
- case E3DPARAM_AMBIENT_MIN_HEIGHT:
- v = Vec3(m_fAmbMaxHeight, 0, 0);
- break;
- case E3DPARAM_AMBIENT_MAX_HEIGHT:
- v = Vec3(m_fAmbMinHeight, 0, 0);
- break;
- case E3DPARAM_SKY_HIGHLIGHT_POS:
- v = m_vSkyHightlightPos;
- break;
- case E3DPARAM_SKY_HIGHLIGHT_COLOR:
- v = m_vSkyHightlightCol;
- break;
- case E3DPARAM_SKY_HIGHLIGHT_SIZE:
- v = Vec3(m_fSkyHighlightSize, 0, 0);
- break;
- case E3DPARAM_VOLFOG_RAMP:
- v = m_volFogRamp;
- break;
- case E3DPARAM_VOLFOG_SHADOW_RANGE:
- v = m_volFogShadowRange;
- break;
- case E3DPARAM_VOLFOG_SHADOW_DARKENING:
- v = m_volFogShadowDarkening;
- break;
- case E3DPARAM_VOLFOG_SHADOW_ENABLE:
- v = m_volFogShadowEnable;
- break;
- case E3DPARAM_VOLFOG2_CTRL_PARAMS:
- v = m_volFog2CtrlParams;
- break;
- case E3DPARAM_VOLFOG2_SCATTERING_PARAMS:
- v = m_volFog2ScatteringParams;
- break;
- case E3DPARAM_VOLFOG2_RAMP:
- v = m_volFog2Ramp;
- break;
- case E3DPARAM_VOLFOG2_COLOR:
- v = m_volFog2Color;
- break;
- case E3DPARAM_VOLFOG2_GLOBAL_DENSITY:
- v = m_volFog2GlobalDensity;
- break;
- case E3DPARAM_VOLFOG2_HEIGHT_DENSITY:
- v = m_volFog2HeightDensity;
- break;
- case E3DPARAM_VOLFOG2_HEIGHT_DENSITY2:
- v = m_volFog2HeightDensity2;
- break;
- case E3DPARAM_VOLFOG2_COLOR1:
- v = m_volFog2Color1;
- break;
- case E3DPARAM_VOLFOG2_COLOR2:
- v = m_volFog2Color2;
- break;
- case E3DPARAM_NIGHSKY_HORIZON_COLOR:
- v = m_nightSkyHorizonCol;
- break;
- case E3DPARAM_NIGHSKY_ZENITH_COLOR:
- v = m_nightSkyZenithCol;
- break;
- case E3DPARAM_NIGHSKY_ZENITH_SHIFT:
- v = Vec3(m_nightSkyZenithColShift, 0, 0);
- break;
- case E3DPARAM_NIGHSKY_STAR_INTENSITY:
- v = Vec3(m_nightSkyStarIntensity, 0, 0);
- break;
- case E3DPARAM_NIGHSKY_MOON_DIRECTION:
- v = m_moonDirection;
- break;
- case E3DPARAM_NIGHSKY_MOON_COLOR:
- v = m_nightMoonCol;
- break;
- case E3DPARAM_NIGHSKY_MOON_SIZE:
- v = Vec3(m_nightMoonSize, 0, 0);
- break;
- case E3DPARAM_NIGHSKY_MOON_INNERCORONA_COLOR:
- v = m_nightMoonInnerCoronaCol;
- break;
- case E3DPARAM_NIGHSKY_MOON_INNERCORONA_SCALE:
- v = Vec3(m_nightMoonInnerCoronaScale, 0, 0);
- break;
- case E3DPARAM_NIGHSKY_MOON_OUTERCORONA_COLOR:
- v = m_nightMoonOuterCoronaCol;
- break;
- case E3DPARAM_NIGHSKY_MOON_OUTERCORONA_SCALE:
- v = Vec3(m_nightMoonOuterCoronaScale, 0, 0);
- break;
- case E3DPARAM_SKY_MOONROTATION:
- v = Vec3(m_moonRotationLatitude, m_moonRotationLongitude, 0);
- break;
- case E3DPARAM_OCEANFOG_COLOR:
- v = m_oceanFogColor;
- break;
- case E3DPARAM_OCEANFOG_DENSITY:
- v = Vec3(m_oceanFogDensity, 0, 0);
- break;
- case E3DPARAM_SKYBOX_MULTIPLIER:
- v = Vec3(m_skyboxMultiplier, 0, 0);
- break;
- case E3DPARAM_DAY_NIGHT_INDICATOR:
- v = Vec3(m_dayNightIndicator, 0, 0);
- break;
- case E3DPARAM_FOG_COLOR2:
- v = m_fogColor2;
- break;
- case E3DPARAM_FOG_RADIAL_COLOR:
- v = m_fogColorRadial;
- break;
- case E3DPARAM_VOLFOG_HEIGHT_DENSITY:
- v = m_volFogHeightDensity;
- break;
- case E3DPARAM_VOLFOG_HEIGHT_DENSITY2:
- v = m_volFogHeightDensity2;
- break;
- case E3DPARAM_VOLFOG_GRADIENT_CTRL:
- v = m_volFogGradientCtrl;
- break;
- case E3DPARAM_VOLFOG_GLOBAL_DENSITY:
- v = Vec3(m_volFogGlobalDensity, m_volFogGlobalDensityMultiplierLDR, m_volFogFinalDensityClamp);
- break;
- case E3DPARAM_COLORGRADING_FILTERS_PHOTOFILTER_COLOR:
- v = Vec3(m_pPhotoFilterColor.x, m_pPhotoFilterColor.y, m_pPhotoFilterColor.z);
- break;
- case E3DPARAM_COLORGRADING_FILTERS_PHOTOFILTER_DENSITY:
- v = Vec3(m_fPhotoFilterColorDensity, 0, 0);
- break;
- case E3DPARAM_COLORGRADING_FILTERS_GRAIN:
- v = Vec3(m_fGrainAmount, 0, 0);
- break;
- case E3DPARAM_HDR_FILMCURVE_SHOULDER_SCALE:
- v = Vec3(m_vHDRFilmCurveParams.x, 0, 0);
- break;
- case E3DPARAM_HDR_FILMCURVE_LINEAR_SCALE:
- v = Vec3(m_vHDRFilmCurveParams.y, 0, 0);
- break;
- case E3DPARAM_HDR_FILMCURVE_TOE_SCALE:
- v = Vec3(m_vHDRFilmCurveParams.z, 0, 0);
- break;
- case E3DPARAM_HDR_FILMCURVE_WHITEPOINT:
- v = Vec3(m_vHDRFilmCurveParams.w, 0, 0);
- break;
- case E3DPARAM_HDR_EYEADAPTATION_PARAMS:
- v = m_vHDREyeAdaptation;
- break;
- case E3DPARAM_HDR_EYEADAPTATION_PARAMS_LEGACY:
- v = m_vHDREyeAdaptationLegacy;
- break;
- case E3DPARAM_HDR_BLOOM_AMOUNT:
- v = Vec3(m_fHDRBloomAmount, 0, 0);
- break;
- case E3DPARAM_HDR_COLORGRADING_COLOR_SATURATION:
- v = Vec3(m_fHDRSaturation, 0, 0);
- break;
- case E3DPARAM_HDR_COLORGRADING_COLOR_BALANCE:
- v = m_vColorBalance;
- break;
- case E3DPARAM_CLOUDSHADING_MULTIPLIERS:
- v = Vec3(m_fCloudShadingSunLightMultiplier, m_fCloudShadingSkyLightMultiplier, 0);
- break;
- case E3DPARAM_CLOUDSHADING_SUNCOLOR:
- v = m_vCloudShadingCustomSunColor;
- break;
- case E3DPARAM_CLOUDSHADING_SKYCOLOR:
- v = m_vCloudShadingCustomSkyColor;
- break;
- default:
- assert(0);
- break;
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-void C3DEngine::SetCachedShadowBounds(const AABB& shadowBounds, float fAdditionalCascadesScale)
-{
- const Vec3 boxSize = shadowBounds.GetSize();
- const bool isValid = boxSize.x > 0 && boxSize.y > 0 && boxSize.z > 0;
-
- m_CachedShadowsBounds = isValid ? shadowBounds : AABB(AABB::RESET);
- m_fCachedShadowsCascadeScale = fAdditionalCascadesScale;
-
- m_nCachedShadowsUpdateStrategy = ShadowMapFrustum::ShadowCacheData::eFullUpdate;
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-void C3DEngine::SetRecomputeCachedShadows(uint nUpdateStrategy)
-{
- m_nCachedShadowsUpdateStrategy = nUpdateStrategy;
-}
-
-//////////////////////////////////////////////////////////////////////////
-void C3DEngine::SetShadowsCascadesBias(const float* pCascadeConstBias, const float* pCascadeSlopeBias)
-{
- memcpy(m_pShadowCascadeConstBias, pCascadeConstBias, sizeof(float) * MAX_SHADOW_CASCADES_NUM);
- memcpy(m_pShadowCascadeSlopeBias, pCascadeSlopeBias, sizeof(float) * MAX_SHADOW_CASCADES_NUM);
-}
-
-int C3DEngine::GetShadowsCascadeCount([[maybe_unused]] const CDLight* pLight) const
-{
- int nCascadeCount = m_eShadowMode == ESM_HIGHQUALITY ? MAX_GSM_LODS_NUM : GetCVars()->e_GsmLodsNum;
- return clamp_tpl(nCascadeCount, 0, MAX_GSM_LODS_NUM);
-}
-
-//////////////////////////////////////////////////////////////////////////
-bool C3DEngine::CheckIntersectClouds(const Vec3& p1, const Vec3& p2)
-{
- return m_pCloudsManager->CheckIntersectClouds(p1, p2);
-}
-
-void C3DEngine::OnRenderMeshDeleted(IRenderMesh* pRenderMesh)
-{
- if (m_pDecalManager)
- {
- m_pDecalManager->OnRenderMeshDeleted(pRenderMesh);
- }
-}
-
-bool C3DEngine::RayObjectsIntersection2D([[maybe_unused]] Vec3 vStart, [[maybe_unused]] Vec3 vEnd, [[maybe_unused]] Vec3& vHitPoint, [[maybe_unused]] EERType eERType)
-{
-#ifdef SUPPORT_TERRAIN_AO_PRE_COMPUTATIONS
-
- float fClosestHitDistance = 1000000;
-
- AABB aabb;
- aabb.Reset();
- aabb.Add(vStart);
- aabb.Add(vEnd);
- if (IsObjectTreeReady())
- {
- if (Overlap::AABB_AABB2D(aabb, m_pObjectsTree->GetNodeBox())) //!!!mpeykov: 2D?
- {
- m_pObjectsTree->RayObjectsIntersection2D(vStart, vEnd, vHitPoint, fClosestHitDistance, eERType);
- }
- }
-
- return (fClosestHitDistance < 1000000);
-
-#else
-
- assert(!"C3DEngine::RayObjectsIntersection2D not supported on consoles");
- return 0;
-
-#endif
-}
-
-bool C3DEngine::RenderMeshRayIntersection(IRenderMesh* pRenderMesh, SRayHitInfo& hitInfo, _smart_ptr pCustomMtl)
-{
- return CRenderMeshUtils::RayIntersection(pRenderMesh, hitInfo, pCustomMtl);
-}
-
-static SBending sBendRemoved;
-
-void C3DEngine::FreeRNTmpData(CRNTmpData** ppInfo)
-{
- AUTO_LOCK(m_checkCreateRNTmpData);
-
- CRNTmpData* pTmpRNTData = (*ppInfo);
-
- assert(pTmpRNTData->pNext != &m_LTPRootFree);
- assert(pTmpRNTData->pPrev != &m_LTPRootFree);
- assert(pTmpRNTData != &m_LTPRootUsed);
- if (gEnv->mMainThreadId != CryGetCurrentThreadId())
- {
- CryFatalError("CRNTmpData should only be allocated and free'd on main thread.");
- }
-
- if (pTmpRNTData != &m_LTPRootUsed)
- {
- pTmpRNTData->Unlink();
- }
-
- // Mark for phys area changed proxy for deletion
- if (pTmpRNTData->nPhysAreaChangedProxyId != ~0)
- {
- m_PhysicsAreaUpdates.ResetProxy(pTmpRNTData->nPhysAreaChangedProxyId);
- pTmpRNTData->nPhysAreaChangedProxyId = ~0;
- }
-
- if (pTmpRNTData->nFrameInfoId != ~0)
- {
- m_elementFrameInfo[pTmpRNTData->nFrameInfoId].Reset();
- pTmpRNTData->nFrameInfoId = ~0;
- }
-
- {
-#ifdef SUPP_HWOBJ_OCCL
- if (pTmpRNTData->userData.m_OcclState.pREOcclusionQuery)
- {
- pTmpRNTData->userData.m_OcclState.pREOcclusionQuery->Release(false);
- pTmpRNTData->userData.m_OcclState.pREOcclusionQuery = NULL;
- }
-#endif
- }
-
- if (pTmpRNTData != &m_LTPRootUsed)
- {
- pTmpRNTData->Link(&m_LTPRootFree);
- *(pTmpRNTData->pOwnerRef) = NULL;
- }
-}
-
-void C3DEngine::UpdateRNTmpDataPool(bool bFreeAll)
-{
- // if we are freeing the whole pool, make sure no jobs are still running which could use the RNTmpObjects
- if (bFreeAll)
- {
- threadID nThreadID;
- gEnv->pRenderer->EF_Query(EFQ_MainThreadList, nThreadID);
- gEnv->pRenderer->GetFinalizeRendItemJobExecutor(nThreadID)->WaitForCompletion();
- gEnv->pRenderer->GetFinalizeShadowRendItemJobExecutor(nThreadID)->WaitForCompletion();
- }
- //CryLogAlways("UpdateRNTmpDataPool bFreeAll 0x%x nMainFrameID 0X%x", bFreeAll, nMainFrameID );
- FUNCTION_PROFILER_3DENGINE;
-
- // Ensure continues memory
- m_elementFrameInfo.CoalesceMemory();
-
- const uint32 nSize = m_elementFrameInfo.size();
- if (nSize == 0)
- {
- return;
- }
-
- const uint32 nMainFrameID = GetRenderer()->GetFrameID(false);
- const uint32 nTmpDataMaxFrames = (uint32)GetCVars()->e_RNTmpDataPoolMaxFrames;
-
- if (!bFreeAll && nMainFrameID >= nTmpDataMaxFrames)
- {
- const uint32 nLastValidFrame = nMainFrameID - nTmpDataMaxFrames;
-
- uint32 nNumItemsToDelete = 0;
-
- SFrameInfo* pFrontIter = &m_elementFrameInfo[0];
- SFrameInfo* pBackIter = &m_elementFrameInfo[nSize - 1];
- SFrameInfo* pHead = pFrontIter;
-
- // Handle single element case
- IF (nSize == 1, 0)
- {
- if (pFrontIter->bIsValid && pFrontIter->nLastUsedFrameId >= nLastValidFrame)
- {
- if (pFrontIter->bIsValid)
- {
- FreeRNTmpData(pFrontIter->ppRNTmpData);
- }
-
- ++nNumItemsToDelete;
- }
- }
-
- // Move invalid elements to back of array and free if timed out
- while (pFrontIter < pBackIter)
- {
- while (pFrontIter->bIsValid && pFrontIter->nLastUsedFrameId >= nLastValidFrame && pFrontIter < pBackIter)
- {
- ++pFrontIter;
- } // Find invalid element at front
- while (!(pBackIter->bIsValid && pBackIter->nLastUsedFrameId >= nLastValidFrame) && pFrontIter < pBackIter) // Find valid element at back
- {
- // Element timed out
- if (pBackIter->bIsValid)
- {
- FreeRNTmpData(pBackIter->ppRNTmpData);
- pBackIter->bIsValid = false;
- }
-
- --pBackIter;
- ++nNumItemsToDelete;
- }
-
- if (pFrontIter < pBackIter)
- {
- // Element timed out
- if (pFrontIter->bIsValid)
- {
- FreeRNTmpData(pFrontIter->ppRNTmpData);
- }
-
- // Replace invalid front element with back element
- // Note: No need to swap because we cut the data from the array at the end anyway
- memcpy(pFrontIter, pBackIter, sizeof(SFrameInfo));
- (*pFrontIter->ppRNTmpData)->nFrameInfoId = (uint32)(pFrontIter - pHead);
-
- pBackIter->bIsValid = false; // safety
- pBackIter->ppRNTmpData = 0;
-
- --pBackIter;
- ++pFrontIter;
- ++nNumItemsToDelete;
- }
- }
-
- assert(nSize == m_elementFrameInfo.size());
- m_elementFrameInfo.resize(nSize - nNumItemsToDelete);
- }
- else if (bFreeAll) // Free all
- {
- SFrameInfo* pFrontIter = &m_elementFrameInfo[0];
- SFrameInfo* pBackIter = &m_elementFrameInfo[nSize - 1];
- ++pBackIter; // Point to element after last element in array
-
- // Free all
- while (pFrontIter != pBackIter)
- {
- // Element timed out
- if (pFrontIter->bIsValid)
- {
- FreeRNTmpData(pFrontIter->ppRNTmpData);
- }
-
- ++pFrontIter;
- }
- m_elementFrameInfo.resize(0);
- }
-}
-
-void C3DEngine::FreeRNTmpDataPool()
-{
- // move all into m_LTPRootFree
- UpdateRNTmpDataPool(true);
-
- AUTO_LOCK(m_checkCreateRNTmpData);
- if (gEnv->mMainThreadId != CryGetCurrentThreadId())
- {
- CryFatalError("CRNTmpData should only be allocated and free'd on main thread.");
- }
-
- // delete all elements of m_LTPRootFree
- CRNTmpData* pNext = NULL;
- for (CRNTmpData* pElem = m_LTPRootFree.pNext; pElem != &m_LTPRootFree; pElem = pNext)
- {
- pNext = pElem->pNext;
- pElem->Unlink();
- delete pElem;
- }
-}
-
-void C3DEngine::CopyObjectsByType(EERType objType, const AABB* pBox, PodArray* plstObjects, ObjectTreeQueryFilterCallback filterCallback)
-{
- GetObjectsByTypeGlobal(*plstObjects, objType, pBox, filterCallback);
-
- if (GetVisAreaManager())
- {
- GetVisAreaManager()->GetObjectsByType(*plstObjects, objType, pBox, filterCallback);
- }
-}
-
-void C3DEngine::CopyObjects(const AABB* pBox, PodArray* plstObjects)
-{
- if (IsObjectTreeReady())
- {
- m_pObjectsTree->GetObjects(*plstObjects, pBox);
- }
-
- if (GetVisAreaManager())
- {
- GetVisAreaManager()->GetObjects(*plstObjects, pBox);
- }
-}
-
-uint32 C3DEngine::GetObjectsByType(EERType objType, IRenderNode** pObjects)
-{
- PodArray lstObjects;
- CopyObjectsByType(objType, NULL, &lstObjects);
- if (pObjects && !lstObjects.IsEmpty())
- {
- memcpy(pObjects, &lstObjects[0], lstObjects.GetDataSize());
- }
- return lstObjects.Count();
-}
-
-uint32 C3DEngine::GetObjectsByTypeInBox(EERType objType, const AABB& bbox, IRenderNode** pObjects, ObjectTreeQueryFilterCallback filterCallback)
-{
- PodArray lstObjects;
- CopyObjectsByType(objType, &bbox, &lstObjects, filterCallback);
- if (pObjects && !lstObjects.IsEmpty())
- {
- memcpy(pObjects, &lstObjects[0], lstObjects.GetDataSize());
- }
- return lstObjects.Count();
-}
-
-void C3DEngine::GetObjectsByTypeInBox(EERType objType, const AABB& bbox, PodArray* pLstObjects, ObjectTreeQueryFilterCallback filterCallback)
-{
- CopyObjectsByType(objType, &bbox, pLstObjects, filterCallback);
-}
-
-uint32 C3DEngine::GetObjectsInBox(const AABB& bbox, IRenderNode** pObjects)
-{
- PodArray lstObjects;
- CopyObjects(&bbox, &lstObjects);
- if (pObjects && !lstObjects.IsEmpty())
- {
- memcpy(pObjects, &lstObjects[0], lstObjects.GetDataSize());
- }
- return lstObjects.Count();
-}
-
-uint32 C3DEngine::GetObjectsByFlags(uint dwFlags, IRenderNode** pObjects /* =0 */)
-{
- PodArray lstObjects;
-
- if (Get3DEngine()->IsObjectTreeReady())
- {
- Get3DEngine()->GetObjectTree()->GetObjectsByFlags(dwFlags, lstObjects);
- }
-
- if (GetVisAreaManager())
- {
- GetVisAreaManager()->GetObjectsByFlags(dwFlags, lstObjects);
- }
-
- if (pObjects && !lstObjects.IsEmpty())
- {
- memcpy(pObjects, &lstObjects[0], lstObjects.GetDataSize());
- }
- return lstObjects.Count();
-}
-
-void C3DEngine::OnObjectModified([[maybe_unused]] IRenderNode* pRenderNode, uint dwFlags)
-{
- if ((dwFlags & (ERF_CASTSHADOWMAPS | ERF_HAS_CASTSHADOWMAPS)) != 0)
- {
- SetRecomputeCachedShadows(ShadowMapFrustum::ShadowCacheData::eFullUpdate);
- }
-}
-
-int SImageInfo::GetMemoryUsage()
-{
- int nSize = 0;
- if (detailInfo.pImgMips[0])
- {
- nSize += (int)((float)(detailInfo.nDim * detailInfo.nDim * sizeof(ColorB)) * 1.3f);
- }
- if (baseInfo.pImgMips[0])
- {
- nSize += (int)((float)(baseInfo.nDim * baseInfo.nDim * sizeof(ColorB)) * 1.3f);
- }
- return nSize;
-}
-
-byte** C3DEngine::AllocateMips(byte* pImage, int nDim, byte** pImageMips)
-{
- memset(pImageMips, 0, SImageSubInfo::nMipsNum * sizeof(pImageMips[0]));
-
- pImageMips[0] = new byte[nDim * nDim * sizeof(ColorB)];
- memcpy(pImageMips[0], pImage, nDim * nDim * sizeof(ColorB));
-
- ColorB* pMipMain = (ColorB*)pImageMips[0];
-
- for (int nMip = 1; (nDim >> nMip) && nMip < SImageSubInfo::nMipsNum; nMip++)
- {
- int nDimMip = nDim >> nMip;
-
- int nSubSize = 1 << nMip;
-
- pImageMips[nMip] = new byte[nDimMip * nDimMip * sizeof(ColorB)];
-
- ColorB* pMipThis = (ColorB*)pImageMips[nMip];
-
- for (int x = 0; x < nDimMip; x++)
- {
- for (int y = 0; y < nDimMip; y++)
- {
- ColorF colSumm(0, 0, 0, 0);
- float fCount = 0;
- for (int _x = x * nSubSize - nSubSize / 2; _x < x * nSubSize + nSubSize + nSubSize / 2; _x++)
- {
- for (int _y = y * nSubSize - nSubSize / 2; _y < y * nSubSize + nSubSize + nSubSize / 2; _y++)
- {
- int nMask = nDim - 1;
- int id = (_x & nMask) * nDim + (_y & nMask);
- colSumm.r += 1.f / 255.f * pMipMain[id].r;
- colSumm.g += 1.f / 255.f * pMipMain[id].g;
- colSumm.b += 1.f / 255.f * pMipMain[id].b;
- colSumm.a += 1.f / 255.f * pMipMain[id].a;
- fCount++;
- }
- }
-
- colSumm /= fCount;
-
- colSumm.Clamp(0, 1);
-
- pMipThis[x * nDimMip + y] = colSumm;
- }
- }
- }
-
- return pImageMips;
-}
-
-void C3DEngine::RegisterForStreaming(IStreamable* pObj)
-{
- if (GetObjManager())
- {
- GetObjManager()->RegisterForStreaming(pObj);
- }
-}
-
-void C3DEngine::UnregisterForStreaming(IStreamable* pObj)
-{
- if (GetObjManager())
- {
- GetObjManager()->UnregisterForStreaming(pObj);
- }
-}
-
-SImageSubInfo* C3DEngine::GetImageInfo(const char* pName)
-{
- if (m_imageInfos.find(string(pName)) != m_imageInfos.end())
- {
- return m_imageInfos[string(pName)];
- }
-
- return NULL;
-}
-
-SImageSubInfo* C3DEngine::RegisterImageInfo(byte** pMips, int nDim, const char* pName)
-{
- if (m_imageInfos.find(string(pName)) != m_imageInfos.end())
- {
- return m_imageInfos[string(pName)];
- }
-
- assert(pMips && pMips[0]);
-
- SImageSubInfo* pImgSubInfo = new SImageSubInfo;
-
- pImgSubInfo->nDim = nDim;
-
- int nMipDim = pImgSubInfo->nDim;
-
- for (int m = 0; m < SImageSubInfo::nMipsNum && nMipDim; m++)
- {
- pImgSubInfo->pImgMips[m] = new byte[nMipDim * nMipDim * 4];
-
- memcpy(pImgSubInfo->pImgMips[m], pMips[m], nMipDim * nMipDim * 4);
-
- nMipDim /= 2;
- }
-
- const string strFileName = pName;
-
- pImgSubInfo->nReady = 1;
-
- m_imageInfos[strFileName] = pImgSubInfo;
-
- return pImgSubInfo;
-}
-
-void C3DEngine::SyncProcessStreamingUpdate()
-{
- if (m_pObjManager)
- {
- m_pObjManager->ProcessObjectsStreaming_Finish();
- }
-}
-
-void C3DEngine::SetScreenshotCallback(IScreenshotCallback* pCallback)
-{
- m_pScreenshotCallback = pCallback;
-}
-
-void C3DEngine::ActivateObjectsLayer(uint16 nLayerId, bool bActivate, bool bPhys, bool bObjects, bool bStaticLights, const char* pLayerName, IGeneralMemoryHeap* pHeap, bool bCheckLayerActivation /*=true*/)
-{
- if (bCheckLayerActivation && !IsAreaActivationInUse())
- {
- return;
- }
-
- if (bActivate)
- {
- m_bLayersActivated = true;
- }
-
- if (bActivate && m_nFramesSinceLevelStart <= 1)
- {
- m_vPrevMainFrameCamPos.Set(-1000000.f, -1000000.f, -1000000.f);
- }
-
- FUNCTION_PROFILER_3DENGINE;
-
- PrintMessage("%s object layer %s (Id = %d) (LevelFrameId = %d)", bActivate ? "Activating" : "Deactivating", pLayerName, nLayerId, m_nFramesSinceLevelStart);
- INDENT_LOG_DURING_SCOPE();
-
- if (bObjects)
- {
- if (IsObjectTreeReady())
- {
- m_pObjectsTree->ActivateObjectsLayer(nLayerId, bActivate, bPhys, pHeap);
- }
-
- if (m_pVisAreaManager)
- {
- m_pVisAreaManager->ActivateObjectsLayer(nLayerId, bActivate, bPhys, pHeap);
- }
- }
-
- if (bStaticLights)
- {
- for (size_t i = 0; i < m_lstStaticLights.size(); ++i)
- {
- ILightSource* pLight = m_lstStaticLights[i];
- if (pLight->GetLayerId() == nLayerId)
- {
- pLight->SetRndFlags(ERF_HIDDEN, !bActivate);
- }
- }
- }
-}
-
-
-void C3DEngine::GetLayerMemoryUsage(uint16 nLayerId, ICrySizer* pSizer, int* pNumBrushes, int* pNumDecals) const
-{
- if (pNumBrushes)
- {
- *pNumBrushes = 0;
- }
- if (pNumDecals)
- {
- *pNumDecals = 0;
- }
-
- if (m_pObjectsTree != nullptr)
- {
- m_pObjectsTree->GetLayerMemoryUsage(nLayerId, pSizer, pNumBrushes, pNumDecals);
- }
-}
-
-
-void C3DEngine::SkipLayerLoading(uint16 nLayerId, bool bClearList)
-{
- if (bClearList)
- {
- m_skipedLayers.clear();
- }
- m_skipedLayers.insert(nLayerId);
-}
-
-
-bool C3DEngine::IsLayerSkipped(uint16 nLayerId)
-{
- return m_skipedLayers.find(nLayerId) != m_skipedLayers.end() ? true : false;
-}
-
-void C3DEngine::PrecacheRenderNode(IRenderNode* pObj, float fEntDistanceReal)
-{
- FUNCTION_PROFILER_3DENGINE;
-
- // PrintMessage("==== PrecacheRenderNodePrecacheRenderNode: %s ====", pObj->GetName());
-
- if (m_pObjManager)
- {
- int dwOldRndFlags = pObj->m_dwRndFlags;
- pObj->m_dwRndFlags &= ~ERF_HIDDEN;
-
- SRenderingPassInfo passInfo = SRenderingPassInfo::CreateGeneralPassRenderingInfo(gEnv->pSystem->GetViewCamera());
-
- m_pObjManager->UpdateRenderNodeStreamingPriority(pObj, fEntDistanceReal, 1.0f, fEntDistanceReal < GetFloatCVar(e_StreamCgfFastUpdateMaxDistance), passInfo, true);
- pObj->m_dwRndFlags = dwOldRndFlags;
- }
-}
-
-
-void C3DEngine::CleanUpOldDecals()
-{
- FUNCTION_PROFILER_3DENGINE;
- static uint32 nLastIndex = 0;
- const uint32 nDECALS_PER_FRAME = 50;
-
- if (uint32 nNumDecalRenderNodes = m_decalRenderNodes.size())
- {
- for (uint32 i = 0, end = __min(nDECALS_PER_FRAME, nNumDecalRenderNodes); i < end; ++i, ++nLastIndex)
- {
- // wrap around at the end to restart at the beginning
- if (nLastIndex >= nNumDecalRenderNodes)
- {
- nLastIndex = 0;
- }
-
- m_decalRenderNodes[nLastIndex]->CleanUpOldDecals();
- }
- }
-}
-
-void C3DEngine::UpdateRenderTypeEnableLookup()
-{
- SetRenderNodeTypeEnabled(eERType_RenderComponent, (GetCVars()->e_Entities != 0));
- SetRenderNodeTypeEnabled(eERType_StaticMeshRenderComponent, (GetCVars()->e_Entities != 0));
- SetRenderNodeTypeEnabled(eERType_DynamicMeshRenderComponent, (GetCVars()->e_Entities != 0));
- SetRenderNodeTypeEnabled(eERType_SkinnedMeshRenderComponent, (GetCVars()->e_Entities != 0));
-}
-
-void C3DEngine::SetRenderNodeMaterialAtPosition(EERType eNodeType, const Vec3& vPos, _smart_ptr pMat)
-{
- PodArray lstObjects;
-
- AABB aabbPos(vPos - Vec3(.1f, .1f, .1f), vPos + Vec3(.1f, .1f, .1f));
-
- GetObjectsByTypeGlobal(lstObjects, eNodeType, &aabbPos);
-
- if (GetVisAreaManager())
- {
- GetVisAreaManager()->GetObjectsByType(lstObjects, eNodeType, &aabbPos);
- }
-
- for (int i = 0; i < lstObjects.Count(); i++)
- {
- PrintMessage("Game changed render node material: %s EERType:%d pos: (%d,%d,%d)",
- pMat ? pMat->GetName() : "NULL",
- (int)eNodeType,
- (int)vPos.x, (int)vPos.y, (int)vPos.z);
-
- lstObjects[i]->SetMaterial(pMat);
- }
-}
-
-void C3DEngine::OverrideCameraPrecachePoint(const Vec3& vPos)
-{
- if (m_pObjManager)
- {
- m_pObjManager->GetStreamPreCacheCameras()[0].vPosition = vPos;
- m_pObjManager->SetCameraPrecacheOverridden(true);
- }
-}
-
-int C3DEngine::AddPrecachePoint(const Vec3& vPos, const Vec3& vDir, float fTimeOut, float fImportanceFactor)
-{
- if (m_pObjManager)
- {
- if (m_pObjManager->GetStreamPreCachePointDefs().size() >= CObjManager::MaxPrecachePoints)
- {
- size_t nOldestIdx = 0;
- int nOldestId = INT_MAX;
- for (size_t i = 1, c = m_pObjManager->GetStreamPreCachePointDefs().size(); i < c; ++i)
- {
- if (m_pObjManager->GetStreamPreCachePointDefs()[i].nId < nOldestId)
- {
- nOldestIdx = i;
- nOldestId = m_pObjManager->GetStreamPreCachePointDefs()[i].nId;
- }
- }
-
- assert (nOldestIdx > 0);
-
- CryWarning(VALIDATOR_MODULE_3DENGINE, VALIDATOR_WARNING, "Precache points full - evicting oldest (%f, %f, %f)",
- m_pObjManager->GetStreamPreCacheCameras()[nOldestIdx].vPosition.x,
- m_pObjManager->GetStreamPreCacheCameras()[nOldestIdx].vPosition.y,
- m_pObjManager->GetStreamPreCacheCameras()[nOldestIdx].vPosition.z);
-
- m_pObjManager->GetStreamPreCachePointDefs().DeleteFastUnsorted((int)nOldestIdx);
- m_pObjManager->GetStreamPreCacheCameras().DeleteFastUnsorted((int)nOldestIdx);
- }
-
- SObjManPrecachePoint pp;
- pp.nId = m_pObjManager->IncrementNextPrecachePointId();
- pp.expireTime = gEnv->pTimer->GetAsyncTime() + CTimeValue(fTimeOut);
- SObjManPrecacheCamera pc;
- pc.vPosition = vPos;
- pc.bbox = AABB(vPos, GetCVars()->e_StreamPredictionBoxRadius);
- pc.vDirection = vDir;
- pc.fImportanceFactor = fImportanceFactor;
- m_pObjManager->GetStreamPreCachePointDefs().Add(pp);
- m_pObjManager->GetStreamPreCacheCameras().Add(pc);
-
- return pp.nId;
- }
-
- return -1;
-}
-
-void C3DEngine::ClearPrecachePoint(int id)
-{
- if (m_pObjManager)
- {
- for (size_t i = 1, c = m_pObjManager->GetStreamPreCachePointDefs().size(); i < c; ++i)
- {
- if (m_pObjManager->GetStreamPreCachePointDefs()[i].nId == id)
- {
- m_pObjManager->GetStreamPreCachePointDefs().DeleteFastUnsorted((int)i);
- m_pObjManager->GetStreamPreCacheCameras().DeleteFastUnsorted((int)i);
- break;
- }
- }
- }
-}
-
-void C3DEngine::ClearAllPrecachePoints()
-{
- if (m_pObjManager)
- {
- m_pObjManager->GetStreamPreCachePointDefs().resize(1);
- m_pObjManager->GetStreamPreCacheCameras().resize(1);
- }
-}
-
-void C3DEngine::GetPrecacheRoundIds(int pRoundIds[MAX_STREAM_PREDICTION_ZONES])
-{
- if (m_pObjManager)
- {
- pRoundIds[0] = m_pObjManager->GetUpdateStreamingPrioriryRoundIdFast();
- pRoundIds[1] = m_pObjManager->GetUpdateStreamingPrioriryRoundId();
- }
-}
-
-SBending* C3DEngine::GetBendingEntry(SBending* pSrc, [[maybe_unused]] const SRenderingPassInfo& passInfo)
-{
- assert(pSrc);
- SBending* pStorage = m_bendingPool[m_bendingPoolIdx].push_back_new();
- *pStorage = *pSrc;
- return pStorage;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-CCamera* C3DEngine::GetRenderingPassCamera(const CCamera& rCamera)
-{
- threadID nThreadID = 0;
- gEnv->pRenderer->EF_Query(EFQ_RenderThreadList, nThreadID);
- CCamera* pCamera = m_RenderingPassCameras[nThreadID].push_back_new();
- *pCamera = rCamera;
- return pCamera;
-}
-
-void C3DEngine::GetCollisionClass(SCollisionClass& collclass, int tableIndex)
-{
- if ((unsigned)tableIndex < m_collisionClasses.size())
- {
- collclass = m_collisionClasses[tableIndex];
- }
- else
- {
- collclass = SCollisionClass(0, 0);
- }
-}
-
-class C3DEngine::PhysicsAreaUpdatesHandler
- : private Physics::WindNotificationsBus::Handler
-{
-public:
- explicit PhysicsAreaUpdatesHandler(C3DEngine::PhysicsAreaUpdates& physicsAreaUpdates)
- : m_physicsAreaUpdates(physicsAreaUpdates)
- {
- Physics::WindNotificationsBus::Handler::BusConnect();
- }
-
- ~PhysicsAreaUpdatesHandler()
- {
- Physics::WindNotificationsBus::Handler::BusDisconnect();
- }
-
-private:
- // Physics::WindNotificationsBus::Handler
- void OnGlobalWindChanged() override
- {
- // Using same 'global wind' area size value CryPhysics code had
- const AZ::Vector3 globalWindHalfBound(1e7);
- AZ::Aabb globalWindAabb = AZ::Aabb::CreateFromMinMax(-globalWindHalfBound, globalWindHalfBound);
-
- OnWindChanged(globalWindAabb);
- }
-
- void OnWindChanged(const AZ::Aabb& aabb) override
- {
- SAreaChangeRecord record;
- record.boxAffected = AZAabbToLyAABB(aabb);
- record.uPhysicsMask = Area_Air;
-
- m_physicsAreaUpdates.SetAreaDirty(record);
- }
-
- C3DEngine::PhysicsAreaUpdates& m_physicsAreaUpdates;
-};
-
-void C3DEngine::PhysicsAreaUpdates::SetAreaDirty(const SAreaChangeRecord& rec)
-{
- // Merge with existing bb if close enough and same medium
- AUTO_LOCK(m_Mutex);
- static const float fMERGE_THRESHOLD = 2.f;
- float fNewVolume = rec.boxAffected.GetVolume();
- for (uint i = 0; i < m_DirtyAreas.size(); i++)
- {
- if (m_DirtyAreas[i].uPhysicsMask == rec.uPhysicsMask)
- {
- AABB bbUnion = rec.boxAffected;
- bbUnion.Add(m_DirtyAreas[i].boxAffected);
- if (bbUnion.GetVolume() <= (fNewVolume + m_DirtyAreas[i].boxAffected.GetVolume()) * fMERGE_THRESHOLD)
- {
- m_DirtyAreas[i].boxAffected = bbUnion;
- return;
- }
- }
- }
- m_DirtyAreas.push_back(rec);
-}
-
-void C3DEngine::PhysicsAreaUpdates::Update()
-{
- //
- // (bethelz) This whole class is only used for CParticleEffect right now.
- //
-
- FUNCTION_PROFILER_3DENGINE;
- AUTO_LOCK(m_Mutex);
- if (m_DirtyAreas.empty())
- {
- return;
- }
-
- // Check area against registered proxies
- int nSizeAreasChanged = (int)m_DirtyAreas.size();
- int nSizeProxies = m_Proxies.size();
-
- // Access elements via [i] as the thread safe list does not always safe its element in a continues array
- for (int i = 0; i < nSizeProxies; ++i)
- {
- const SPhysAreaNodeProxy& proxy = m_Proxies[i];
-
- IF (!proxy.bIsValid, 0)
- {
- continue;
- }
-
- for (int j = 0; j < nSizeAreasChanged; ++j)
- {
- const SAreaChangeRecord& rec = m_DirtyAreas[j];
- if ((proxy.uPhysicsMask & rec.uPhysicsMask) && Overlap::AABB_AABB(proxy.bbox, rec.boxAffected))
- {
- if (rec.uPhysicsMask & Area_Air)
- {
- if (proxy.pRenderNode->m_pRNTmpData)
- {
- proxy.pRenderNode->m_pRNTmpData->userData.bWindCurrent = 0;
- }
- }
-
- proxy.pRenderNode->OnPhysAreaChange();
- break;
- }
- }
- }
-
- m_DirtyAreas.resize(0);
-}
-
-void C3DEngine::PhysicsAreaUpdates::Reset()
-{
- stl::free_container(m_DirtyAreas);
-}
-
-uint32 C3DEngine::PhysicsAreaUpdates::CreateProxy(const IRenderNode* pRenderNode, uint16 uPhysicsMask)
-{
- size_t nIndex = ~0;
- SPhysAreaNodeProxy* proxy = m_Proxies.push_back_new(nIndex);
-
- proxy->pRenderNode = (IRenderNode*)pRenderNode;
- proxy->uPhysicsMask = uPhysicsMask;
- proxy->bIsValid = true;
- proxy->bbox = pRenderNode->GetBBox();
- return nIndex;
-}
-
-void C3DEngine::PhysicsAreaUpdates::UpdateProxy(const IRenderNode* pRenderNode, uint32 nProxyId)
-{
- m_Proxies[nProxyId].bbox = pRenderNode->GetBBox();
-}
-
-void C3DEngine::PhysicsAreaUpdates::ResetProxy(uint32 proxyId)
-{
- m_Proxies[proxyId].Reset();
-}
-
-void C3DEngine::PhysicsAreaUpdates::GarbageCollect()
-{
- // Ensure list is continues in memory
- m_Proxies.CoalesceMemory();
-
- const uint32 nSize = m_Proxies.size();
- if (nSize == 0)
- {
- return;
- }
-
- SPhysAreaNodeProxy* pFrontIter = &m_Proxies[0];
- SPhysAreaNodeProxy* pBackIter = &m_Proxies[nSize - 1];
- const SPhysAreaNodeProxy* pHead = pFrontIter;
- uint32 nNumItemsToDelete = 0;
-
- // Move invalid nodes to the back of the array
- do
- {
- while (pFrontIter->bIsValid && pFrontIter < pBackIter)
- {
- ++pFrontIter;
- }
- while (!pBackIter->bIsValid && pFrontIter < pBackIter)
- {
- --pBackIter;
- ++nNumItemsToDelete;
- }
-
- if (pFrontIter < pBackIter)
- {
- // Replace invalid front element with back element
- // Note: No need to swap because we cut the data from the array at the end anyway
- memcpy(pFrontIter, pBackIter, sizeof(SPhysAreaNodeProxy));
- AZ_Assert(pFrontIter->pRenderNode && pFrontIter->pRenderNode->m_pRNTmpData, "The front iterator should have a valid m_pRNTmpData after the data from the valid back iterator has been copied to it.");
- if (pFrontIter->pRenderNode && pFrontIter->pRenderNode->m_pRNTmpData)
- {
- pFrontIter->pRenderNode->m_pRNTmpData->nPhysAreaChangedProxyId = (uint32)(pFrontIter - pHead);
- }
-
- pBackIter->bIsValid = false;
-
- --pBackIter;
- ++pFrontIter;
- ++nNumItemsToDelete;
- }
- } while (pFrontIter < pBackIter);
-
- // Cut off invalid elements
- m_Proxies.resize(nSize - nNumItemsToDelete);
-}
-
-void C3DEngine::UpdateShaderItems()
-{
- if (GetMatMan())
- {
- GetMatMan()->UpdateShaderItems();
- }
-}
-
-void C3DEngine::OnCameraTeleport()
-{
- MarkRNTmpDataPoolForReset();
-}
-
-IObjManager* C3DEngine::GetObjectManager()
-{
- return m_pObjManager;
-}
-
-const IObjManager* C3DEngine::GetObjectManager() const
-{
- return m_pObjManager;
-}
-
-bool C3DEngine::RemoveObjectsInArea(Vec3 vExploPos, float fExploRadius)
-{
- bool bEverythingDeleted = true;
-
- Vec3 vRadius(fExploRadius, fExploRadius, fExploRadius);
-
- PodArray lstEntities;
- const AABB cExplosionBox(vExploPos - vRadius, vExploPos + vRadius);
- MoveObjectsIntoListGlobal(&lstEntities, &cExplosionBox, false, true, true, true);
-
- // remove small objects around
- {
- for (int i = 0; i < lstEntities.Count(); i++)
- {
- IRenderNode* pRenderNode = lstEntities[i].pNode;
- AABB entBox = pRenderNode->GetBBox();
- float fEntRadius = entBox.GetRadius();
- Vec3 vEntCenter = pRenderNode->GetBBox().GetCenter();
- float fDist = vExploPos.GetDistance(vEntCenter);
- if (fDist < fExploRadius + fEntRadius &&
- Overlap::Sphere_AABB(Sphere(vExploPos, fExploRadius), entBox))
- {
- if (fDist >= fExploRadius)
- { //
- Matrix34A objMat;
- CStatObj* pStatObj = (CStatObj*)pRenderNode->GetEntityStatObj(0, 0, &objMat);
- if (!pStatObj)
- {
- continue;
- }
- objMat.Invert();
- //assert(0);
- Vec3 vOSExploPos = objMat.TransformPoint(vExploPos);
-
- Vec3 vScaleTest(0, 0, 1.f);
- vScaleTest = objMat.TransformVector(vScaleTest);
- float fObjScaleInv = vScaleTest.len();
-
- if (!pStatObj->IsSphereOverlap(Sphere(vOSExploPos, fExploRadius * fObjScaleInv)))
- {
- continue;
- }
- }
- }
- }
- }
-
- return bEverythingDeleted;
-}
-
-#ifndef _RELEASE
-
-//////////////////////////////////////////////////////////////////////////
-// onscreen infodebug code for e_debugDraw >= 100
-
-//////////////////////////////////////////////////////////////////////////
-void C3DEngine::AddObjToDebugDrawList(SObjectInfoToAddToDebugDrawList& objInfo)
-{
- m_DebugDrawListMgr.AddObject(objInfo);
-}
-
-
-bool CDebugDrawListMgr::m_dumpLogRequested = false;
-bool CDebugDrawListMgr::m_freezeRequested = false;
-bool CDebugDrawListMgr::m_unfreezeRequested = false;
-uint32 CDebugDrawListMgr::m_filter = I3DEngine::DLOT_ALL;
-
-
-//////////////////////////////////////////////////////////////////////////
-CDebugDrawListMgr::CDebugDrawListMgr()
-{
- m_isFrozen = false;
- ClearFrameData();
- ClearConsoleCommandRequestVars();
- m_assets.reserve(32); // just a reasonable value
- m_drawBoxes.reserve(256); // just a reasonable value
-}
-
-
-//////////////////////////////////////////////////////////////////////////
-void CDebugDrawListMgr::ClearFrameData()
-{
- m_counter = 0;
- m_assetCounter = 0;
- m_assets.clear();
- m_drawBoxes.clear();
- m_indexLeastValueAsset = 0;
- CheckFilterCVar();
-}
-
-
-//////////////////////////////////////////////////////////////////////////
-void CDebugDrawListMgr::ClearConsoleCommandRequestVars()
-{
- m_dumpLogRequested = false;
- m_freezeRequested = false;
- m_unfreezeRequested = false;
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CDebugDrawListMgr::AddObject(I3DEngine::SObjectInfoToAddToDebugDrawList& newObjInfo)
-{
- if (m_isFrozen)
- {
- return;
- }
-
- m_lock.Lock();
-
- m_counter++;
-
- if (!ShouldFilterOutObject(newObjInfo))
- {
- TAssetInfo newAsset(newObjInfo);
- TObjectDrawBoxInfo newDrawBox(newObjInfo);
-
- TAssetInfo* pAssetDuplicated = FindDuplicate(newAsset);
- if (pAssetDuplicated)
- {
- pAssetDuplicated->numInstances++;
- newDrawBox.assetID = pAssetDuplicated->ID;
- m_drawBoxes.push_back(newDrawBox);
- pAssetDuplicated->drawCalls = max(pAssetDuplicated->drawCalls, newAsset.drawCalls);
- }
- else
- {
- newAsset.ID = m_assetCounter;
- newDrawBox.assetID = newAsset.ID;
- bool used = false;
-
- // list not full, so we add
- if (m_assets.size() < uint(Cry3DEngineBase::GetCVars()->e_DebugDrawListSize))
- {
- used = true;
- m_assets.push_back(newAsset);
- }
- else // if is full, only use it if value is greater than the current minimum, and then it substitutes the lowest slot
- {
- const TAssetInfo& leastValueAsset = m_assets[ m_indexLeastValueAsset ];
- if (leastValueAsset < newAsset)
- {
- used = true;
- m_assets[ m_indexLeastValueAsset ] = newAsset;
- }
- }
- if (used)
- {
- m_assetCounter++;
- m_drawBoxes.push_back(newDrawBox);
- FindNewLeastValueAsset();
- }
- }
- }
-
- m_lock.Unlock();
-}
-
-
-//////////////////////////////////////////////////////////////////////////
-CDebugDrawListMgr::TAssetInfo* CDebugDrawListMgr::FindDuplicate(const TAssetInfo& asset)
-{
- std::vector::iterator iter = m_assets.begin();
- std::vector::const_iterator endArray = m_assets.end();
-
- while (iter != endArray)
- {
- TAssetInfo& currAsset = *iter;
- if (currAsset.fileName == asset.fileName)
- {
- return &currAsset;
- }
- ++iter;
- }
- return NULL;
-}
-
-
-
-//////////////////////////////////////////////////////////////////////////
-bool CDebugDrawListMgr::ShouldFilterOutObject(const I3DEngine::SObjectInfoToAddToDebugDrawList& object)
-{
- if (m_filter == I3DEngine::DLOT_ALL)
- {
- return false;
- }
-
- return (m_filter & object.type) == 0;
-}
-
-
-//////////////////////////////////////////////////////////////////////////
-void CDebugDrawListMgr::FindNewLeastValueAsset()
-{
- uint32 size = m_assets.size();
- for (uint32 i = 0; i < size; ++i)
- {
- const TAssetInfo& currAsset = m_assets[ i ];
- const TAssetInfo& leastValueAsset = m_assets[ m_indexLeastValueAsset ];
-
- if (currAsset < leastValueAsset)
- {
- m_indexLeastValueAsset = i;
- }
- }
-}
-
-
-
-//////////////////////////////////////////////////////////////////////////
-void CDebugDrawListMgr::Update()
-{
- m_lock.Lock();
- if (!m_isFrozen)
- {
- std::sort(m_assets.begin(), m_assets.end(), CDebugDrawListMgr::SortComparison);
- }
- gEnv->pRenderer->CollectDrawCallsInfoPerNode(true);
- // it displays values from the previous frame. This mean that if it is disabled, and then enabled again later on, it will display bogus values for 1 frame...but i dont care (yet)
- float X = 10.f;
- float Y = 100.f;
- if (m_isFrozen)
- {
- PrintText(X, Y, Col_Red, "FROZEN DEBUGINFO");
- }
- Y += 20.f;
- PrintText(X, Y, Col_White, "total assets: %d Ordered by: Showing:", m_counter);
- PrintText(X + 240, Y, Col_Yellow, GetStrCurrMode());
- TMyStandardString filterStr;
- GetStrCurrFilter(filterStr);
- PrintText(X + 420, Y, Col_Yellow, filterStr.c_str());
- Y += 20.f;
- float XName = 270;
-
- const char* pHeaderStr = "";
- switch (Cry3DEngineBase::GetCVars()->e_DebugDraw)
- {
- case LM_TRI_COUNT:
- pHeaderStr = " tris " " meshMem " "rep " " type ";
- break;
- case LM_VERT_COUNT:
- pHeaderStr = " verts " " meshMem " "rep " " type ";
- break;
- case LM_DRAWCALLS:
- pHeaderStr = "draw Calls " " tris " "rep " " type ";
- break;
- case LM_TEXTMEM:
- pHeaderStr = " texMem " " meshMem " "rep " " type ";
- break;
- case LM_MESHMEM:
- pHeaderStr = " meshMem " " texMem " "rep " " type ";
- break;
- }
-
-
- PrintText(X, Y, Col_White, pHeaderStr);
- const int standardNameSize = 48;
- PrintText(XName, Y, Col_White, "Entity (class)");
- PrintText(XName + (standardNameSize + 2) * 7, Y, Col_White, "File name");
-
- Y += 20.f;
- for (uint32 i = 0; i < m_assets.size(); ++i)
- {
- ColorF colorLine = Col_Cyan;
- if (Cry3DEngineBase::GetCVars()->e_DebugDrawListBBoxIndex - 1 == i)
- {
- colorLine = Col_Blue;
- }
- const TAssetInfo& currAsset = m_assets[ i ];
- TMyStandardString texMemoryStr;
- TMyStandardString meshMemoryStr;
- MemToString(currAsset.texMemory, texMemoryStr);
- MemToString(currAsset.meshMemory, meshMemoryStr);
-
- switch (Cry3DEngineBase::GetCVars()->e_DebugDraw)
- {
- case LM_TRI_COUNT:
- PrintText(X, Y + 20.f * i, colorLine, "%7d " "%s " "%3d " "%s",
- currAsset.numTris, meshMemoryStr.c_str(), currAsset.numInstances, GetAssetTypeName(currAsset.type));
- break;
- case LM_VERT_COUNT:
- PrintText(X, Y + 20.f * i, colorLine, "%7d " "%s " "%3d " "%s",
- currAsset.numVerts, meshMemoryStr.c_str(), currAsset.numInstances, GetAssetTypeName(currAsset.type));
- break;
- case LM_DRAWCALLS:
- {
- PrintText(X, Y + 20.f * i, colorLine, " %5d " "%7d " "%3d " "%s",
- currAsset.drawCalls, currAsset.numTris, currAsset.numInstances, GetAssetTypeName(currAsset.type));
- }
- break;
- case LM_TEXTMEM:
- PrintText(X, Y + 20.f * i, colorLine, "%s " "%s " "%3d " "%s",
- texMemoryStr.c_str(), meshMemoryStr.c_str(), currAsset.numInstances, GetAssetTypeName(currAsset.type));
- break;
- case LM_MESHMEM:
- PrintText(X, Y + 20.f * i, colorLine, "%s " "%s " "%3d " "%s",
- meshMemoryStr.c_str(), texMemoryStr.c_str(), currAsset.numInstances, GetAssetTypeName(currAsset.type));
- break;
- }
-
- int filenameSep = 7 * (max(standardNameSize, int(currAsset.name.length())) + 2);
- float XFileName = XName + filenameSep;
-
- PrintText(XName, Y + 20.f * i, colorLine, currAsset.name.c_str());
- PrintText(XFileName, Y + 20.f * i, colorLine, currAsset.fileName.c_str());
- }
-
- if (Cry3DEngineBase::GetCVars()->e_DebugDrawListBBoxIndex > 0 && uint(Cry3DEngineBase::GetCVars()->e_DebugDrawListBBoxIndex - 1) < m_assets.size())
- {
- const TAssetInfo& assetInfo = m_assets[ Cry3DEngineBase::GetCVars()->e_DebugDrawListBBoxIndex - 1 ];
- uint32 numBoxesDrawn = 0;
- for (uint32 i = 0; i < m_drawBoxes.size(); ++i)
- {
- const TObjectDrawBoxInfo& drawBox = m_drawBoxes[ i ];
- if (drawBox.assetID == assetInfo.ID)
- {
- gEnv->pRenderer->GetIRenderAuxGeom()->DrawAABB(drawBox.bbox, drawBox.mat, true, ColorB(0, 0, 255, 100), eBBD_Faceted);
- numBoxesDrawn++;
- if (numBoxesDrawn >= assetInfo.numInstances)
- {
- break;
- }
- }
- }
- }
-
- if (m_freezeRequested)
- {
- m_isFrozen = true;
- }
- if (m_unfreezeRequested)
- {
- m_isFrozen = false;
- }
- if (m_dumpLogRequested)
- {
- DumpLog();
- }
-
- ClearConsoleCommandRequestVars();
-
- if (!m_isFrozen)
- {
- ClearFrameData();
- m_assets.reserve(Cry3DEngineBase::GetCVars()->e_DebugDrawListSize);
- }
- m_lock.Unlock();
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CDebugDrawListMgr::PrintText(float x, float y, const ColorF& fColor, const char* label_text, ...)
-{
- va_list args;
- va_start(args, label_text);
- SDrawTextInfo ti;
- ti.xscale = ti.yscale = 1.2f;
- ti.flags = eDrawText_2D | eDrawText_FixedSize | eDrawText_Monospace;
- {
- ti.color[0] = fColor[0];
- ti.color[1] = fColor[1];
- ti.color[2] = fColor[2];
- ti.color[3] = fColor[3];
- }
- gEnv->pRenderer->DrawTextQueued(Vec3(x, y, 0.5f), ti, label_text, args);
- va_end(args);
-}
-
-
-//////////////////////////////////////////////////////////////////////////
-void CDebugDrawListMgr::MemToString(uint32 memVal, TMyStandardString& outStr)
-{
- if (memVal < 1024 * 1024)
- {
- outStr.Format("%5.1f kb", memVal / (1024.f));
- }
- else
- {
- outStr.Format("%5.1f MB", memVal / (1024.f * 1024.f));
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-bool CDebugDrawListMgr::TAssetInfo::operator<(const TAssetInfo& other) const
-{
- switch (Cry3DEngineBase::GetCVars()->e_DebugDraw)
- {
- case LM_TRI_COUNT:
- return (numTris < other.numTris);
-
- case LM_VERT_COUNT:
- return (numVerts < other.numVerts);
-
- case LM_DRAWCALLS:
- return (drawCalls < other.drawCalls);
-
- case LM_TEXTMEM:
- return (texMemory < other.texMemory);
-
- case LM_MESHMEM:
- return (meshMemory < other.meshMemory);
-
- default:
- assert(false);
- return false;
- }
-}
-
-
-//////////////////////////////////////////////////////////////////////////
-CDebugDrawListMgr::TAssetInfo::TAssetInfo(const I3DEngine::SObjectInfoToAddToDebugDrawList& objInfo)
-{
- type = objInfo.type;
- if (!objInfo.pClassName)
- {
- // custom functions to avoid any heap allocation
- MyString_Assign(name, objInfo.pName);
- MyStandardString_Concatenate(name, "(");
- MyStandardString_Concatenate(name, objInfo.pClassName);
- MyStandardString_Concatenate(name, ")");
- }
-
- MyFileNameString_Assign(fileName, objInfo.pFileName);
-
- numTris = objInfo.numTris;
- numVerts = objInfo.numVerts;
- texMemory = objInfo.texMemory;
- meshMemory = objInfo.meshMemory;
- drawCalls = gEnv->pRenderer->GetDrawCallsPerNode(objInfo.pRenderNode);
- numInstances = 1;
- ID = UNDEFINED_ASSET_ID;
-}
-
-
-//////////////////////////////////////////////////////////////////////////
-CDebugDrawListMgr::TObjectDrawBoxInfo::TObjectDrawBoxInfo(const I3DEngine::SObjectInfoToAddToDebugDrawList& objInfo)
-{
- mat.SetIdentity();
- bbox.Reset();
- if (objInfo.pMat)
- {
- mat = *objInfo.pMat;
- }
- if (objInfo.pBox)
- {
- bbox = *objInfo.pBox;
- }
- assetID = UNDEFINED_ASSET_ID;
-}
-
-
-
-//////////////////////////////////////////////////////////////////////////
-void CDebugDrawListMgr::MyStandardString_Concatenate(TMyStandardString& outStr, const char* pStr)
-{
- if (pStr && outStr.length() < outStr.capacity())
- {
- outStr._ConcatenateInPlace(pStr, min(strlen(pStr), outStr.capacity() - outStr.length()));
- }
-}
-
-
-//////////////////////////////////////////////////////////////////////////
-void CDebugDrawListMgr::MyFileNameString_Assign(TFilenameString& outStr, const char* pStr)
-{
- char tempBuf[ outStr.MAX_SIZE + 1 ];
-
- uint32 outInd = 0;
- if (pStr)
- {
- while (*pStr != 0 && outInd < outStr.MAX_SIZE)
- {
- tempBuf[outInd] = *pStr;
- outInd++;
- if (*pStr == '%' && outInd < outStr.MAX_SIZE)
- {
- tempBuf[outInd] = '%';
- outInd++;
- }
- pStr++;
- }
- }
- tempBuf[ outInd ] = 0;
- outStr = tempBuf;
-}
-
-
-//////////////////////////////////////////////////////////////////////////
-void CDebugDrawListMgr::ConsoleCommand(IConsoleCmdArgs* args)
-{
- if (args->GetArgCount() > 1 && args->GetArg(1))
- {
- switch (toupper(args->GetArg(1)[0]))
- {
- case 'F':
- m_freezeRequested = true;
- break;
- case 'C':
- m_unfreezeRequested = true;
- break;
- case 'D':
- m_dumpLogRequested = true;
- break;
- }
- }
-}
-
-
-//////////////////////////////////////////////////////////////////////////
-void CDebugDrawListMgr::CheckFilterCVar()
-{
- ICVar* pCVar = gEnv->pConsole->GetCVar("e_debugdrawlistfilter");
-
- if (!pCVar)
- {
- return;
- }
-
- const char* pVal = pCVar->GetString();
-
- if (pVal && azstricmp(pVal, "all") == 0)
- {
- m_filter = I3DEngine::DLOT_ALL;
- return;
- }
-
- m_filter = 0;
- while (pVal && pVal[0])
- {
- switch (toupper(pVal[0]))
- {
- case 'C':
- m_filter |= I3DEngine::DLOT_CHARACTER;
- break;
- case 'S':
- m_filter |= I3DEngine::DLOT_STATOBJ;
- break;
- }
- ++pVal;
- }
-}
-
-
-//////////////////////////////////////////////////////////////////////////
-void CDebugDrawListMgr::DumpLog()
-{
- TMyStandardString filterStr;
- GetStrCurrFilter(filterStr);
- CryLog("--------------------------------------------------------------------------------");
- CryLog(" DebugDrawList infodebug");
- CryLog("--------------------------------------------------------------------------------");
- CryLog(" total objects: %d Ordered by: %s Showing: %s", m_counter, GetStrCurrMode(), filterStr.c_str());
- CryLog(PRINTF_EMPTY_FORMAT);
- CryLog(" tris verts draw Calls texMem meshMem type");
- CryLog(" ------- -------- ---------- -------- -------- ----------");
- for (uint32 i = 0; i < m_assets.size(); ++i)
- {
- const TAssetInfo& currAsset = m_assets[ i ];
- TMyStandardString texMemoryStr;
- TMyStandardString meshMemoryStr;
- MemToString(currAsset.texMemory, texMemoryStr);
- MemToString(currAsset.meshMemory, meshMemoryStr);
- CryLog("%8d %8d %5d %s %s %s %s %s", currAsset.numTris, currAsset.numVerts, currAsset.drawCalls,
- texMemoryStr.c_str(), meshMemoryStr.c_str(), GetAssetTypeName(currAsset.type), currAsset.name.c_str(), currAsset.fileName.c_str());
- }
- CryLog("--------------------------------------------------------------------------------");
-}
-
-
-
-//////////////////////////////////////////////////////////////////////////
-const char* CDebugDrawListMgr::GetStrCurrMode()
-{
- const char* pModesNames[] =
- {
- "Tri count",
- "Vert count",
- "Draw calls",
- "Texture memory",
- "Mesh memory"
- };
-
- uint32 index = Cry3DEngineBase::GetCVars()->e_DebugDraw - LM_BASENUMBER;
- uint32 numElems = sizeof(pModesNames) / sizeof *(pModesNames);
- if (index < numElems)
- {
- return pModesNames[index];
- }
- else
- {
- return "";
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-void CDebugDrawListMgr::GetStrCurrFilter(TMyStandardString& strOut)
-{
- const char* pFilterNames[] =
- {
- "",
- "Characters",
- "StatObjs"
- };
-
- uint32 numElems = sizeof(pFilterNames) / sizeof *(pFilterNames);
- for (uint32 i = 1, bitVal = 1; i < numElems; ++i)
- {
- if ((bitVal & m_filter) != 0)
- {
- if (strOut.size() > 0)
- {
- strOut += "+";
- }
- strOut += pFilterNames[i];
- }
- bitVal *= 2;
- }
-
- if (strOut.size() == 0)
- {
- strOut = "ALL";
- }
-}
-
-
-//////////////////////////////////////////////////////////////////////////
-const char* CDebugDrawListMgr::GetAssetTypeName(I3DEngine::EDebugDrawListAssetTypes type)
-{
- const char* pNames[] =
- {
- "",
- "Brush ",
- "Vegetation",
- "Character ",
- "StatObj "
- };
-
- uint32 numElems = sizeof(pNames) / sizeof *(pNames);
- for (uint32 i = 1, bitVal = 1; i < numElems; ++i)
- {
- if (bitVal == type)
- {
- return pNames[i];
- }
- bitVal *= 2;
- }
-
- return "";
-}
-
-
-
-#endif //RELEASE
-
-void C3DEngine::GetStatObjAndMatTables(DynArray* pStatObjTable, DynArray<_smart_ptr >* pMatTable, DynArray* pStatInstGroupTable, uint32 nObjTypeMask)
-{
- SHotUpdateInfo exportInfo;
- exportInfo.nObjTypeMask = nObjTypeMask;
-
- std::vector statObjTable;
- std::vector<_smart_ptr > matTable;
- std::vector statInstGroupTable;
-
- if (Get3DEngine() && Get3DEngine()->IsObjectTreeReady())
- {
- Get3DEngine()->GetObjectTree()->GenerateStatObjAndMatTables((pStatObjTable != NULL) ? &statObjTable : NULL,
- (pMatTable != NULL) ? &matTable : NULL,
- (pStatInstGroupTable != NULL) ? &statInstGroupTable : NULL,
- &exportInfo);
- }
-
- if (GetVisAreaManager())
- {
- GetVisAreaManager()->GenerateStatObjAndMatTables((pStatObjTable != NULL) ? &statObjTable : NULL,
- (pMatTable != NULL) ? &matTable : NULL,
- (pStatInstGroupTable != NULL) ? &statInstGroupTable : NULL,
- &exportInfo);
- }
-
- if (pStatObjTable)
- {
- pStatObjTable->resize(statObjTable.size());
- for (size_t i = 0; i < statObjTable.size(); ++i)
- {
- (*pStatObjTable)[i] = statObjTable[i];
- }
-
- statObjTable.clear();
- }
-
- if (pMatTable)
- {
- pMatTable->resize(matTable.size());
- for (size_t i = 0; i < matTable.size(); ++i)
- {
- (*pMatTable)[i] = matTable[i];
- }
-
- matTable.clear();
- }
-
- if (pStatInstGroupTable)
- {
- pStatInstGroupTable->resize(statInstGroupTable.size());
- for (size_t i = 0; i < statInstGroupTable.size(); ++i)
- {
- (*pStatInstGroupTable)[i] = statInstGroupTable[i];
- }
-
- statInstGroupTable.clear();
- }
-}
-
diff --git a/Code/CryEngine/Cry3DEngine/3dEngine.h b/Code/CryEngine/Cry3DEngine/3dEngine.h
deleted file mode 100644
index a8e46c32ae..0000000000
--- a/Code/CryEngine/Cry3DEngine/3dEngine.h
+++ /dev/null
@@ -1,1514 +0,0 @@
-/*
-* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
-* its licensors.
-*
-* For complete copyright and license terms please see the LICENSE at the root of this
-* distribution (the "License"). All use of this software is governed by the License,
-* or, if provided, by the license below or the license accompanying this file. Do not
-* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-*
-*/
-// Original file Copyright Crytek GMBH or its affiliates, used under license.
-
-#ifndef CRYINCLUDE_CRY3DENGINE_3DENGINE_H
-#define CRYINCLUDE_CRY3DENGINE_3DENGINE_H
-#pragma once
-
-#include
-#include
-#include
-#include
-#include
-#include
-
-#ifdef DrawText
-#undef DrawText
-#endif //DrawText
-
-struct IOctreeNode;
-struct IDeferredPhysicsEventManager;
-class COctreeNode;
-class CCullBuffer;
-
-struct StatInstGroup;
-
-
-namespace LegacyProceduralVegetation
-{
- class VegetationPoolManager;
-}
-
-class CMemoryBlock
- : public IMemoryBlock
-{
-public:
- virtual void* GetData() { return m_pData; }
- virtual int GetSize() { return m_nSize; }
- virtual ~CMemoryBlock() { delete[] m_pData; }
-
- CMemoryBlock() { m_pData = 0; m_nSize = 0; }
- CMemoryBlock(const void* pData, int nSize)
- {
- m_pData = 0;
- m_nSize = 0;
- SetData(pData, nSize);
- }
- void SetData(const void* pData, int nSize)
- {
- delete[] m_pData;
- m_pData = new uint8[nSize];
- memcpy(m_pData, pData, nSize);
- m_nSize = nSize;
- }
- void Free()
- {
- delete[] m_pData;
- m_pData = NULL;
- m_nSize = 0;
- }
- void Allocate(int nSize)
- {
- delete[] m_pData;
- m_pData = new uint8[nSize];
- memset(m_pData, 0, nSize);
- m_nSize = nSize;
- }
-
- static CMemoryBlock* CompressToMemBlock(void* pData, int nSize, ISystem* pSystem)
- {
- CMemoryBlock* pMemBlock = NULL;
- uint8* pTmp = new uint8[nSize + 4];
- size_t nComprSize = nSize;
- *(uint32*)pTmp = nSize;
- if (pSystem->CompressDataBlock(pData, nSize, pTmp + 4, nComprSize))
- {
- pMemBlock = new CMemoryBlock(pTmp, nComprSize + 4);
- }
-
- delete[] pTmp;
- return pMemBlock;
- }
-
- static CMemoryBlock* DecompressFromMemBlock(CMemoryBlock* pMemBlock, ISystem* pSystem)
- {
- size_t nUncompSize = *(uint32*)pMemBlock->GetData();
- SwapEndian(nUncompSize);
- CMemoryBlock* pResult = new CMemoryBlock;
- pResult->Allocate(nUncompSize);
- if (!pSystem->DecompressDataBlock((byte*)pMemBlock->GetData() + 4, pMemBlock->GetSize() - 4, pResult->GetData(), nUncompSize))
- {
- assert(!"CMemoryBlock::DecompressFromMemBlock failed");
- delete pResult;
- pResult = NULL;
- }
-
- return pResult;
- }
-
- uint8* m_pData;
- int m_nSize;
-};
-
-// Values to combine for phys area type selection
-enum EAreaPhysics
-{
- Area_Water = BIT(0),
- Area_Air = BIT(1),
- // Other physics media can be masked in as well
-
- Area_Gravity = BIT(14),
- Area_Other = BIT(15),
-};
-
-struct SAreaChangeRecord
-{
- AABB boxAffected; // Area of change
- uint16 uPhysicsMask; // Types of mediums for this area
-};
-
-struct SPhysAreaNodeProxy
-{
- void Reset()
- {
- pRenderNode = (IRenderNode*)(intptr_t)-1;
- bIsValid = false;
- bbox.Reset();
- }
-
- IRenderNode* pRenderNode; // RenderNode
- uint16 uPhysicsMask; // Bit mask of physics interested in
- bool bIsValid; // Does the proxy carry valid data
- AABB bbox; // Bounding box of render node
-};
-
-struct SFrameInfo
-{
- void Reset()
- {
- ppRNTmpData = (CRNTmpData**)(intptr_t)-1;
- bIsValid = false;
- nCreatedFrameId = nLastUsedFrameId = ~0;
- }
-
- uint32 nLastUsedFrameId;
- uint32 nCreatedFrameId;
- bool bIsValid;
- CRNTmpData** ppRNTmpData;
-};
-
-struct SNodeInfo;
-class CStitchedImage;
-struct DLightAmount
-{
- CDLight* pLight;
- float fAmount;
-};
-
-template
-struct CPoolAllocator
-{
- CPoolAllocator() { m_nCounter = 0; }
-
- ~CPoolAllocator()
- {
- Reset();
- }
-
- void Reset()
- {
- for (int i = 0; i < m_Pools.Count(); i++)
- {
- delete[](byte*)m_Pools[i];
- m_Pools[i] = NULL;
- }
- m_nCounter = 0;
- }
-
- void ReleaseElement(T* pElem)
- {
- if (pElem)
- {
- m_FreeElements.Add(pElem);
- }
- }
-
- T* GetNewElement()
- {
- if (m_FreeElements.Count())
- {
- T* pPtr = m_FreeElements.Last();
- m_FreeElements.DeleteLast();
- return pPtr;
- }
-
- int nPoolId = m_nCounter / nMaxElemsInChunk;
- int nElemId = m_nCounter - nPoolId * nMaxElemsInChunk;
- m_Pools.PreAllocate(nPoolId + 1, nPoolId + 1);
- if (!m_Pools[nPoolId])
- {
- m_Pools[nPoolId] = (T*)new byte[nMaxElemsInChunk * sizeof(T)];
- }
- m_nCounter++;
- return &m_Pools[nPoolId][nElemId];
- }
-
- int GetCount() { return m_nCounter - m_FreeElements.Count(); }
- int GetCapacity() { return m_Pools.Count() * nMaxElemsInChunk; }
- int GetCapacityBytes() { return GetCapacity() * sizeof(T); }
-
-private:
-
- int m_nCounter;
- PodArray m_Pools;
- PodArray m_FreeElements;
-};
-
-struct SImageSubInfo
-{
- SImageSubInfo() { memset(this, 0, sizeof(*this)); fTiling = fTilingIn = 1.f; }
-
- static const int nMipsNum = 4;
-
- union
- {
- byte* pImgMips[nMipsNum];
- int pImgMipsSizeKeeper[8];
- };
-
- float fAmount;
- int nReady;
- int nDummy[4];
-
- _smart_ptr pMat;
- int nDim;
- float fTilingIn;
- float fTiling;
- float fSpecularAmount;
- int nSortOrder;
- int nAlignFix;
-
- AUTO_STRUCT_INFO
-};
-
-struct SImageInfo
- : public Cry3DEngineBase
-{
- SImageInfo()
- {
- szDetMatName[0] = szBaseTexName[0] = '\0';
- nPhysSurfaceType = 0;
- nLayerId = 0;
- fUseRemeshing = 0;
- fBr = 1.f;
- layerFilterColor = Col_White;
- nDetailSurfTypeId = 0;
- ZeroStruct(arrTextureId);
- }
-
- void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { /*nothing*/ }
-
- SImageSubInfo baseInfo;
- SImageSubInfo detailInfo;
-
- char szDetMatName[128 - 20];
-
- int arrTextureId[4];
- int nPhysSurfaceType;
-
- char szBaseTexName[128];
-
- float fUseRemeshing;
- ColorF layerFilterColor;
- int nLayerId;
- float fBr;
- int nDetailSurfTypeId;
-
- int GetMemoryUsage();
-
- AUTO_STRUCT_INFO
-};
-
-struct SSceneFrustum
-{
- uint32* pRgbImage;
- uint32 nRgbWidth, nRgbHeight;
-
- float* pDepthImage;
- uint32 nDepthWidth, nDepthHeight;
-
- CCamera camera;
-
- IRenderMesh* pRM;
- _smart_ptr pMaterial;
-
- float fDistance;
- int nId;
-
- static int Compare(const void* v1, const void* v2)
- {
- SSceneFrustum* p[2] = { (SSceneFrustum*)v1, (SSceneFrustum*)v2 };
-
- if (p[0]->fDistance > p[1]->fDistance)
- {
- return 1;
- }
- if (p[0]->fDistance < p[1]->fDistance)
- {
- return -1;
- }
-
- if (p[0]->nId > p[1]->nId)
- {
- return 1;
- }
- if (p[0]->nId < p[1]->nId)
- {
- return -1;
- }
-
- return 0;
- }
-};
-
-struct SPerObjectShadow
-{
- IShadowCaster* pCaster;
- float fConstBias;
- float fSlopeBias;
- float fJitter;
- Vec3 vBBoxScale;
- uint nTexSize;
-};
-//////////////////////////////////////////////////////////////////////
-#define LV_MAX_COUNT 256
-#define LV_LIGHTS_MAX_COUNT 64
-
-#define LV_WORLD_BUCKET_SIZE 512
-#define LV_LIGHTS_WORLD_BUCKET_SIZE 512
-
-#define LV_WORLD_SIZEX 128
-#define LV_WORLD_SIZEY 128
-#define LV_WORLD_SIZEZ 64
-
-#define LV_CELL_SIZEX 4
-#define LV_CELL_SIZEY 4
-#define LV_CELL_SIZEZ 8
-
-#define LV_CELL_RSIZEX (1.0f / (float)LV_CELL_SIZEX)
-#define LV_CELL_RSIZEY (1.0f / (float)LV_CELL_SIZEY)
-#define LV_CELL_RSIZEZ (1.0f / (float)LV_CELL_SIZEZ)
-
-#define LV_LIGHT_CELL_SIZE 32
-#define LV_LIGHT_CELL_R_SIZE (1.0f / (float)LV_LIGHT_CELL_SIZE)
-
-#define LV_DLF_LIGHTVOLUMES_MASK (DLF_DISABLED | DLF_FAKE | DLF_AMBIENT | DLF_DEFERRED_CUBEMAPS)
-
-class CLightVolumesMgr
- : public Cry3DEngineBase
-{
-public:
- CLightVolumesMgr()
- {
- Init();
- }
-
- void Init();
- void Reset();
- uint16 RegisterVolume(const Vec3& vPos, f32 fRadius, uint8 nClipVolumeRef, const SRenderingPassInfo& passInfo);
- void RegisterLight(const CDLight& pDL, uint32 nLightID, const SRenderingPassInfo& passInfo);
- void Update(const SRenderingPassInfo& passInfo);
- void Clear(const SRenderingPassInfo& passInfo);
- void GetLightVolumes(threadID nThreadID, SLightVolume*& pLightVols, uint32& nNumVols);
-#ifndef _RELEASE
- void DrawDebug(const SRenderingPassInfo& passInfo);
-#endif
-
-private:
- struct SLightVolInfo
- {
- SLightVolInfo()
- : vVolume(ZERO, 0.0f)
- , nNextVolume(0)
- , nClipVolumeID(0)
- {
- };
- SLightVolInfo(const Vec3& pPos, float fRad, uint8 clipVolumeID)
- : vVolume(pPos, fRad)
- , nNextVolume(0)
- , nClipVolumeID(clipVolumeID)
- {
- };
-
- Vec4 vVolume; // xyz: position, w: radius
- uint16 nNextVolume; // index of next light volume for this hash bucket (0 if none)
- uint8 nClipVolumeID; // clip volume stencil ref
- };
-
- struct SLightCell
- {
- SLightCell()
- : nLightCount(0)
- {
- };
-
- uint16 nLightID[LV_LIGHTS_MAX_COUNT];
- uint8 nLightCount;
- };
-
- inline int32 GetIntHash(const int32 k, [[maybe_unused]] const int32 nBucketSize = LV_WORLD_BUCKET_SIZE) const
- {
- static const uint32 nHashBits = 9;
- static const uint32 nGoldenRatio32bits = 2654435761u; // (2^32) / (golden ratio)
- return (k * nGoldenRatio32bits) >> (32 - nHashBits); // ref: knuths integer multiplicative hash function
- }
-
- inline uint16 GetWorldHashBucketKey(const int32 x, const int32 y, const int32 z, const int32 nBucketSize = LV_WORLD_BUCKET_SIZE) const
- {
- const uint32 nPrimeNum = 101;//0xd8163841;
- return aznumeric_caster((((GetIntHash(x) + nPrimeNum) * nPrimeNum + GetIntHash(y)) * nPrimeNum + GetIntHash(z)) & (nBucketSize - 1));
- }
-
- void AddLight(const SRenderLight& pLight, const SLightVolInfo* __restrict pVolInfo, SLightVolume& pVolume);
-
- typedef DynArray LightVolumeVector;
-
-private:
- LightVolumeVector m_pLightVolumes[RT_COMMAND_BUF_COUNT]; // Final light volume list. move light list creation to renderer to avoid double-buffering this
- DynArray m_pLightVolsInfo[RT_COMMAND_BUF_COUNT]; // World cells data
- SLightCell m_pWorldLightCells[LV_LIGHTS_WORLD_BUCKET_SIZE]; // 2D World cell buckets for light sources ids
- uint16 m_nWorldCells[LV_WORLD_BUCKET_SIZE]; // World cell buckets for light volumes
- bool m_bUpdateLightVolumes : 1;
-};
-
-// onscreen infodebug for e_debugDraw >= 100
-#ifndef _RELEASE
-class CDebugDrawListMgr
-{
- typedef CryFixedStringT<64> TMyStandardString;
- typedef CryFixedStringT<128> TFilenameString;
-
-public:
-
- CDebugDrawListMgr();
- void Update();
- void AddObject(I3DEngine::SObjectInfoToAddToDebugDrawList& objInfo);
- void DumpLog();
- bool IsEnabled() const { return Cry3DEngineBase::GetCVars()->e_DebugDraw >= LM_BASENUMBER; }
- static void ConsoleCommand(IConsoleCmdArgs* args);
-
-private:
-
- enum
- {
- UNDEFINED_ASSET_ID = 0xffffffff
- };
-
- struct TAssetInfo
- {
- TMyStandardString name;
- TFilenameString fileName;
- uint32 numTris;
- uint32 numVerts;
- uint32 texMemory;
- uint32 meshMemory;
- uint32 drawCalls;
- uint32 numInstances;
- I3DEngine::EDebugDrawListAssetTypes type;
- uint32 ID; // to identify which drawBoxes belong to this asset
-
- TAssetInfo(const I3DEngine::SObjectInfoToAddToDebugDrawList& objInfo);
- bool operator<(const TAssetInfo& other) const;
- };
-
- struct TObjectDrawBoxInfo
- {
- Matrix34 mat;
- AABB bbox;
- uint32 assetID;
-
- TObjectDrawBoxInfo(const I3DEngine::SObjectInfoToAddToDebugDrawList& objInfo);
- };
-
- void FindNewLeastValueAsset();
- void ClearFrameData();
- void ClearConsoleCommandRequestVars();
- static bool SortComparison(const TAssetInfo& A, const TAssetInfo& B) { return B < A; }
- const char* GetStrCurrMode();
- void GetStrCurrFilter(TMyStandardString& strOut);
- bool ShouldFilterOutObject(const I3DEngine::SObjectInfoToAddToDebugDrawList& newObject);
- void MemToString(uint32 memVal, TMyStandardString& outStr);
- static void PrintText(float x, float y, const ColorF& fColor, const char* label_text, ...);
- const char* GetAssetTypeName(I3DEngine::EDebugDrawListAssetTypes type);
- TAssetInfo* FindDuplicate(const TAssetInfo& object);
- void CheckFilterCVar();
-
- // to avoid any heap allocation
- static void MyStandardString_Concatenate(TMyStandardString& outStr, const char* str);
- static void MyFileNameString_Assign(TFilenameString& outStr, const char* pStr);
-
- template
- static void MyString_Assign(T& outStr, const char* pStr)
- {
- if (pStr)
- {
- outStr._Assign(pStr, min(strlen(pStr), outStr.capacity()));
- }
- else
- {
- outStr = "";
- }
- }
-
-
-
- enum EListModes
- {
- LM_BASENUMBER = 100,
- LM_TRI_COUNT = LM_BASENUMBER,
- LM_VERT_COUNT,
- LM_DRAWCALLS,
- LM_TEXTMEM,
- LM_MESHMEM
- };
-
-
- bool m_isFrozen;
- uint32 m_counter;
- uint32 m_assetCounter;
- uint32 m_indexLeastValueAsset;
- std::vector m_assets;
- std::vector m_drawBoxes;
- CryCriticalSection m_lock;
-
- static bool m_dumpLogRequested;
- static bool m_freezeRequested;
- static bool m_unfreezeRequested;
- static uint32 m_filter;
-};
-#endif //_RELEASE
-
-//////////////////////////////////////////////////////////////////////
-class C3DEngine
- : public I3DEngine
- , public Cry3DEngineBase
-{
-public:
-
- // I3DEngine interface implementation
- virtual bool Init();
- virtual void OnFrameStart();
- virtual void Update();
- virtual void RenderWorld(int nRenderFlags, const SRenderingPassInfo& passInfo, const char* szDebugName);
- virtual void PreWorldStreamUpdate(const CCamera& cam);
- virtual void WorldStreamUpdate();
- virtual void ShutDown();
- virtual void Release() { CryAlignedDelete(this); };
- virtual void SetLevelPath(const char* szFolderName);
- virtual bool LoadLevel(const char* szFolderName, const char* szMissionName);
- virtual void UnloadLevel();
- virtual void PostLoadLevel();
- virtual bool InitLevelForEditor(const char* szFolderName, const char* szMissionName);
- virtual bool LevelLoadingInProgress();
- virtual void DisplayInfo(float& fTextPosX, float& fTextPosY, float& fTextStepY, bool bEnhanced);
- virtual void DisplayMemoryStatistics();
- virtual void SetupDistanceFog();
- virtual IStatObj* LoadStatObjUnsafeManualRef(const char* fileName, const char* geomName = nullptr, /*[Out]*/ IStatObj::SSubObject** subObject = nullptr,
- bool useStreaming = true, unsigned long loadingFlags = 0, const void* data = nullptr, int dataSize = 0) override;
- virtual _smart_ptr LoadStatObjAutoRef(const char* fileName, const char* geomName = nullptr, /*[Out]*/ IStatObj::SSubObject** subObject = nullptr,
- bool useStreaming = true, unsigned long loadingFlags = 0, const void* data = nullptr, int dataSize = 0) override;
- virtual const IObjManager* GetObjectManager() const;
- virtual IObjManager* GetObjectManager();
-
- virtual IStatObj* FindStatObjectByFilename(const char* filename);
- virtual void RegisterEntity(IRenderNode* pEnt, int nSID = -1, int nSIDConsideredSafe = -1);
- virtual bool IsSunShadows(){ return m_bSunShadows; };
- virtual void SelectEntity(IRenderNode* pEnt);
- virtual void LoadEmptyLevel() override;
-
- virtual void LoadStatObjAsync(LoadStaticObjectAsyncResult resultCallback, const char* szFileName, const char* szGeomName = nullptr, bool bUseStreaming = true, unsigned long nLoadingFlags = 0);
- virtual void ProcessAsyncStaticObjectLoadRequests() override;
-
-#ifndef _RELEASE
- virtual void AddObjToDebugDrawList(SObjectInfoToAddToDebugDrawList& objInfo);
- virtual bool IsDebugDrawListEnabled() const { return m_DebugDrawListMgr.IsEnabled(); }
-#endif
-
- virtual void UnRegisterEntityDirect(IRenderNode* pEnt);
- virtual void UnRegisterEntityAsJob(IRenderNode* pEnt);
-
- virtual bool IsUnderWater(const Vec3& vPos) const;
- virtual void SetOceanRenderFlags(uint8 nFlags);
- virtual uint8 GetOceanRenderFlags() const { return m_nOceanRenderFlags; }
- virtual uint32 GetOceanVisiblePixelsCount() const;
- virtual float GetBottomLevel(const Vec3& referencePos, float maxRelevantDepth, int objtypes);
- virtual float GetBottomLevel(const Vec3& referencePos, float maxRelevantDepth /* = 10.0f*/);
- virtual float GetBottomLevel(const Vec3& referencePos, int objflags);
-
-#if defined(USE_GEOM_CACHES)
- virtual IGeomCache* LoadGeomCache(const char* szFileName);
- virtual IGeomCache* FindGeomCacheByFilename(const char* szFileName);
-#endif
-
- virtual IStatObj* LoadDesignerObject(int nVersion, const char* szBinaryStream, int size);
-
- void AsyncOctreeUpdate(IRenderNode* pEnt, int nSID, int nSIDConsideredSafe, uint32 nFrameID, bool bUnRegisterOnly);
- bool UnRegisterEntityImpl(IRenderNode* pEnt);
-
- // Fast option - use if just ocean height required
- virtual float GetWaterLevel();
- // This will return ocean height or water volume height, optional for accurate water height query
- virtual float GetWaterLevel(const Vec3* pvPos, IPhysicalEntity* pent = NULL, bool bAccurate = false);
- // Only use for Accurate query - this will return exact ocean height
- virtual float GetAccurateOceanHeight(const Vec3& pCurrPos) const;
-
- virtual CausticsParams GetCausticsParams() const;
- virtual OceanAnimationData GetOceanAnimationParams() const override;
- virtual void GetHDRSetupParams(Vec4 pParams[5]) const;
- virtual void CreateDecal(const CryEngineDecalInfo& Decal);
-
- virtual void SetSunDir(const Vec3& newSunOffset);
- virtual Vec3 GetSunDir() const;
- virtual Vec3 GetSunDirNormalized() const;
- virtual Vec3 GetRealtimeSunDirNormalized() const;
- virtual void SetSunColor(Vec3 vColor);
- Vec3 GetSunAnimColor() override;
- void SetSunAnimColor(const Vec3& sunAnimColor) override;
- float GetSunAnimSpeed() override;
- void SetSunAnimSpeed(float sunAnimSpeed) override;
- AZ::u8 GetSunAnimPhase() override;
- void SetSunAnimPhase(AZ::u8 sunAnimPhase) override;
- AZ::u8 GetSunAnimIndex() override;
- void SetSunAnimIndex(AZ::u8 sunAnimIndex) override;
- virtual void SetSSAOAmount(float fMul);
- virtual void SetSSAOContrast(float fMul);
- virtual void SetRainParams(const SRainParams& rainParams);
- virtual bool GetRainParams(SRainParams& rainParams);
- virtual void SetSnowSurfaceParams(const Vec3& vCenter, float fRadius, float fSnowAmount, float fFrostAmount, float fSurfaceFreezing);
- virtual bool GetSnowSurfaceParams(Vec3& vCenter, float& fRadius, float& fSnowAmount, float& fFrostAmount, float& fSurfaceFreezing);
- virtual void SetSnowFallParams(int nSnowFlakeCount, float fSnowFlakeSize, float fSnowFallBrightness, float fSnowFallGravityScale, float fSnowFallWindScale, float fSnowFallTurbulence, float fSnowFallTurbulenceFreq);
- virtual bool GetSnowFallParams(int& nSnowFlakeCount, float& fSnowFlakeSize, float& fSnowFallBrightness, float& fSnowFallGravityScale, float& fSnowFallWindScale, float& fSnowFallTurbulence, float& fSnowFallTurbulenceFreq);
- virtual void OnExplosion(Vec3 vPos, float fRadius, bool bDeformTerrain = true);
- //! For editor
- virtual void RemoveAllStaticObjects(int nSID);
-
- virtual void SetPhysMaterialEnumerator(IPhysMaterialEnumerator* pPhysMaterialEnumerator);
- virtual IPhysMaterialEnumerator* GetPhysMaterialEnumerator();
- virtual void LoadMissionDataFromXMLNode(const char* szMissionName);
-
- void AddDynamicLightSource(const class CDLight& LSource, ILightSource* pEnt, int nEntityLightId, float fFadeout, const SRenderingPassInfo& passInfo);
-
- inline void AddLightToRenderer(const CDLight& pLight, float fMult, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter)
- {
- const uint32 nLightID = GetRenderer()->EF_GetDeferredLightsNum();
- GetRenderer()->EF_AddDeferredLight(pLight, fMult, passInfo, rendItemSorter);
- Get3DEngine()->m_LightVolumesMgr.RegisterLight(pLight, nLightID, passInfo);
- m_nDeferredLightsNum++;
- }
-
- virtual void SetMaxViewDistanceScale(float fScale) { m_fMaxViewDistScale = fScale; }
- virtual float GetMaxViewDistance(bool bScaled = true);
- virtual const SFrameLodInfo& GetFrameLodInfo() const { return m_frameLodInfo; }
- virtual void SetFrameLodInfo(const SFrameLodInfo& frameLodInfo);
- virtual void SetFogColor(const Vec3& vFogColor);
- virtual Vec3 GetFogColor();
- virtual float GetDistanceToSectorWithWater();
-
- virtual void GetSkyLightParameters(Vec3& sunDir, Vec3& sunIntensity, float& Km, float& Kr, float& g, Vec3& rgbWaveLengths);
- virtual void SetSkyLightParameters(const Vec3& sunDir, const Vec3& sunIntensity, float Km, float Kr, float g, const Vec3& rgbWaveLengths, bool forceImmediateUpdate = false);
-
- void SetLightsHDRDynamicPowerFactor(const float value);
- virtual float GetLightsHDRDynamicPowerFactor() const;
-
- // Return true if tessellation is allowed (by cvars) into currently set shadow map LOD
- bool IsTessellationAllowedForShadowMap(const SRenderingPassInfo& passInfo) const;
- // Return true if tessellation is allowed for given render object
- virtual bool IsTessellationAllowed(const CRenderObject* pObj, const SRenderingPassInfo& passInfo, bool bIgnoreShadowPass = false) const;
-
- virtual void SetRenderNodeMaterialAtPosition(EERType eNodeType, const Vec3& vPos, _smart_ptr pMat);
- virtual void OverrideCameraPrecachePoint(const Vec3& vPos);
- virtual int AddPrecachePoint(const Vec3& vPos, const Vec3& vDir, float fTimeOut = 3.f, float fImportanceFactor = 1.0f);
- virtual void ClearPrecachePoint(int id);
- virtual void ClearAllPrecachePoints();
- virtual void GetPrecacheRoundIds(int pRoundIds[MAX_STREAM_PREDICTION_ZONES]);
-
- virtual void TraceFogVolumes(const Vec3& vPos, const AABB& objBBox, SFogVolumeData& fogVolData, const SRenderingPassInfo& passInfo, bool fogVolumeShadingQuality);
-
- virtual Vec3 GetSunColor() const;
- virtual float GetSSAOAmount() const;
- virtual float GetSSAOContrast() const;
-
- virtual void FreeRenderNodeState(IRenderNode* pEnt);
- virtual const char* GetLevelFilePath(const char* szFileName);
-
- bool LoadCompiledOctreeForEditor() override;
- virtual bool SetStatInstGroup(int nGroupId, const IStatInstGroup& siGroup, int nSID);
- virtual bool GetStatInstGroup(int nGroupId, IStatInstGroup& siGroup, int nSID);
- virtual void ActivatePortal(const Vec3& vPos, bool bActivate, const char* szEntityName);
- virtual void GetMemoryUsage(ICrySizer* pSizer) const;
- virtual void GetResourceMemoryUsage(ICrySizer* pSizer, const AABB& cstAABB);
- virtual IVisArea* CreateVisArea(uint64 visGUID);
- virtual void DeleteVisArea(IVisArea* pVisArea);
- virtual void UpdateVisArea(IVisArea* pArea, const Vec3* pPoints, int nCount, const char* szName,
- const SVisAreaInfo& info, bool bReregisterObjects);
- virtual IClipVolume* CreateClipVolume();
- virtual void DeleteClipVolume(IClipVolume* pClipVolume);
- virtual void UpdateClipVolume(IClipVolume* pClipVolume, _smart_ptr pRenderMesh, IBSPTree3D* pBspTree, const Matrix34& worldTM, bool bActive, uint32 flags, const char* szName);
- virtual void ResetParticlesAndDecals();
- virtual IRenderNode* CreateRenderNode(EERType type);
- virtual void DeleteRenderNode(IRenderNode* pRenderNode);
- virtual Vec3 GetWind(const AABB& box, bool bIndoors) const;
- virtual Vec3 GetGlobalWind(bool bIndoors) const;
- virtual bool SampleWind(Vec3* pSamples, int nSamples, const AABB& volume, bool bIndoors) const;
- void SetupBending(CRenderObject*& pObj, const IRenderNode* pNode, const float fRadiusVert, const SRenderingPassInfo& passInfo, bool alreadyDuplicated = false);
- virtual IVisArea* GetVisAreaFromPos(const Vec3& vPos);
- virtual bool IntersectsVisAreas(const AABB& box, void** pNodeCache = 0);
- virtual bool ClipToVisAreas(IVisArea* pInside, Sphere& sphere, Vec3 const& vNormal, void* pNodeCache = 0);
- virtual bool IsVisAreasConnected(IVisArea* pArea1, IVisArea* pArea2, int nMaxReqursion, bool bSkipDisabledPortals);
- void EnableOceanRendering(bool bOcean); // todo: remove
-
- virtual void AddTextureLoadHandler(ITextureLoadHandler* pHandler);
- virtual void RemoveTextureLoadHandler(ITextureLoadHandler* pHandler);
- virtual ITextureLoadHandler* GetTextureLoadHandlerForImage(const char* ext);
- virtual struct ILightSource* CreateLightSource();
- virtual void DeleteLightSource(ILightSource* pLightSource);
- virtual bool RestoreTerrainFromDisk(int nSID);
- virtual void CheckMemoryHeap();
-
- virtual int GetLoadedObjectCount();
- virtual void GetLoadedStatObjArray(IStatObj** pObjectsArray, int& nCount);
- virtual void GetObjectsStreamingStatus(SObjectsStreamingStatus& outStatus);
- virtual void GetStreamingSubsystemData(int subsystem, SStremaingBandwidthData& outData);
- virtual void DeleteEntityDecals(IRenderNode* pEntity);
- virtual void DeleteDecalsInRange(AABB* pAreaBox, IRenderNode* pEntity);
- virtual void LockCGFResources();
- virtual void UnlockCGFResources();
- virtual void FreeUnusedCGFResources();
-
- virtual void SerializeState(TSerialize ser);
- virtual void PostSerialize(bool bReading);
-
- virtual void SetStreamableListener(IStreamedObjectListener* pListener);
-
- //////////////////////////////////////////////////////////////////////////
- // Materials access.
- virtual IMaterialHelpers& GetMaterialHelpers();
- virtual IMaterialManager* GetMaterialManager();
- //////////////////////////////////////////////////////////////////////////
-
- //////////////////////////////////////////////////////////////////////////
- // ObjManager access.
- virtual IObjManager* GetObjManager() override;
- //////////////////////////////////////////////////////////////////////////
-
- //////////////////////////////////////////////////////////////////////////
- // CGF Loader.
- //////////////////////////////////////////////////////////////////////////
- virtual CContentCGF* CreateChunkfileContent(const char* filename);
- virtual void ReleaseChunkfileContent(CContentCGF*);
- virtual bool LoadChunkFileContent(CContentCGF* pCGF, const char* filename, bool bNoWarningMode = false, bool bCopyChunkFile = true);
- virtual bool LoadChunkFileContentFromMem(CContentCGF* pCGF, const void* pData, size_t nDataLen, uint32 nLoadingFlags, bool bNoWarningMode = false, bool bCopyChunkFile = true);
- //////////////////////////////////////////////////////////////////////////
- virtual IChunkFile* CreateChunkFile(bool bReadOnly = false);
-
- //////////////////////////////////////////////////////////////////////////
- // Chunk file writer.
- //////////////////////////////////////////////////////////////////////////
- virtual ChunkFile::IChunkFileWriter* CreateChunkFileWriter(EChunkFileFormat eFormat, AZ::IO::IArchive* pPak, const char* filename) const;
- virtual void ReleaseChunkFileWriter(ChunkFile::IChunkFileWriter* p) const;
-
- //////////////////////////////////////////////////////////////////////////
- // Post processing effects interfaces
-
- class IPostEffectGroupManager* GetPostEffectGroups() const override { return m_postEffectGroups.get(); }
- class IPostEffectGroup* GetPostEffectBaseGroup() const override { return m_postEffectBaseGroup; }
-
- // Most code should use either GetPostEffectGroups() or GetPostEffectBaseGroup() instead of these
- virtual void SetPostEffectParam(const char* pParam, float fValue, bool bForceValue = false) const;
- virtual void SetPostEffectParamVec4(const char* pParam, const Vec4& pValue, bool bForceValue = false) const;
- virtual void SetPostEffectParamString(const char* pParam, const char* pszArg) const;
-
- virtual void GetPostEffectParam(const char* pParam, float& fValue) const;
- virtual void GetPostEffectParamVec4(const char* pParam, Vec4& pValue) const;
- virtual void GetPostEffectParamString(const char* pParam, const char*& pszArg) const;
-
- virtual int32 GetPostEffectID(const char* pPostEffectName);
-
- virtual void ResetPostEffects(bool bOnSpecChange = false);
- virtual void DisablePostEffects();
-
- virtual void SetShadowsGSMCache(bool bCache);
- virtual void SetCachedShadowBounds(const AABB& shadowBounds, float fAdditionalCascadesScale);
- virtual void SetRecomputeCachedShadows(uint nUpdateStrategy = 0);
- void SetShadowsCascadesBias(const float* pCascadeConstBias, const float* pCascadeSlopeBias);
- const float* GetShadowsCascadesConstBias() const { return m_pShadowCascadeConstBias; }
- const float* GetShadowsCascadesSlopeBias() const { return m_pShadowCascadeSlopeBias; }
- int GetShadowsCascadeCount(const CDLight* pLight) const;
-
- virtual uint32 GetObjectsByType(EERType objType, IRenderNode** pObjects);
- uint32 GetObjectsByTypeInBox(EERType objType, const AABB& bbox, IRenderNode** pObjects, ObjectTreeQueryFilterCallback filterCallback = nullptr) override;
- virtual uint32 GetObjectsInBox(const AABB& bbox, IRenderNode** pObjects = 0);
- void GetObjectsByTypeInBox(EERType objType, const AABB& bbox, PodArray* pLstObjects, ObjectTreeQueryFilterCallback filterCallback = nullptr) override;
- virtual uint32 GetObjectsByFlags(uint dwFlags, IRenderNode** pObjects = 0);
- virtual void OnObjectModified(IRenderNode* pRenderNode, uint dwFlags);
-
- virtual void ActivateObjectsLayer(uint16 nLayerId, bool bActivate, bool bPhys, bool bObjects, bool bStaticLights, const char* pLayerName, IGeneralMemoryHeap* pHeap = NULL, bool bCheckLayerActivation = true);
- virtual void GetLayerMemoryUsage(uint16 nLayerId, ICrySizer* pSizer, int* pNumBrushes, int* pNumDecals) const;
- virtual void SkipLayerLoading(uint16 nLayerId, bool bClearList);
- bool IsLayerSkipped(uint16 nLayerId);
-
- //////////////////////////////////////////////////////////////////////////
-
- const char* GetLevelFolder() override { return m_szLevelFolder; }
-
- bool SaveCGF(std::vector& pObjs);
-
- virtual bool IsAreaActivationInUse() { return m_bAreaActivationInUse && GetCVars()->e_ObjectLayersActivation; }
-
- int GetCurrentLightSpec()
- {
- return CONFIG_VERYHIGH_SPEC; // very high spec.
- }
-
- bool CheckMinSpec(uint32 nMinSpec) override;
-
- void UpdateRenderingCamera(const char* szCallerName, const SRenderingPassInfo& passInfo);
- virtual void PrepareOcclusion(const CCamera& rCamera);
- virtual void EndOcclusion();
-#ifndef _RELEASE
- void ProcessStreamingLatencyTest(const CCamera& camIn, CCamera& camOut, const SRenderingPassInfo& passInfo);
-#endif
-
- void ScreenShotHighRes(CStitchedImage* pStitchedImage, const int nRenderFlags, const SRenderingPassInfo& passInfo, uint32 SliceCount, f32 fTransitionSize);
-
- // cylindrical mapping made by multiple slices rendered and distorted
- // Returns:
- // true=mode is active, stop normal rendering, false=mode is not active
- bool ScreenShotPanorama(CStitchedImage* pStitchedImage, const int nRenderFlags, const SRenderingPassInfo& passInfo, uint32 SliceCount, f32 fTransitionSize);
- // Render simple top-down screenshot for map overviews
- bool ScreenShotMap(CStitchedImage* pStitchedImage, const int nRenderFlags, const SRenderingPassInfo& passInfo, uint32 SliceCount, f32 fTransitionSize);
-
- void ScreenshotDispatcher(const int nRenderFlags, const SRenderingPassInfo& passInfo);
-
- virtual void FillDebugFPSInfo(SDebugFPSInfo& info);
-
- void ClearDebugFPSInfo(bool bUnload = false)
- {
- m_fAverageFPS = 0.0f;
- m_fMinFPS = m_fMinFPSDecay = 999.f;
- m_fMaxFPS = m_fMaxFPSDecay = 0.0f;
- ClearPrecacheInfo();
- if (bUnload)
- {
- stl::free_container(arrFPSforSaveLevelStats);
- }
- else
- {
- arrFPSforSaveLevelStats.clear();
- }
- }
-
- void ClearPrecacheInfo()
- {
- m_nFramesSinceLevelStart = 0;
- m_nStreamingFramesSinceLevelStart = 0;
- m_bPreCacheEndEventSent = false;
- m_fTimeStateStarted = 0.0f;
- }
-
- virtual const CCamera& GetRenderingCamera() const { return m_RenderingCamera; }
- virtual float GetZoomFactor() const { return m_fZoomFactor; }
- virtual void Tick();
-
- virtual void UpdateShaderItems();
- void GetCollisionClass(SCollisionClass& collclass, int tableIndex);
-
- C3DEngine(ISystem* pSystem);
- ~C3DEngine();
-
- const float GetGSMRange() override { return m_fGsmRange; }
- const float GetGSMRangeStep() override { return m_fGsmRangeStep; }
-
- void UpdatePreRender(const SRenderingPassInfo& passInfo);
- void UpdatePostRender(const SRenderingPassInfo& passInfo);
-
- virtual void RenderScene(const int nRenderFlags, const SRenderingPassInfo& passInfo);
- virtual void RenderSceneReflection(int nRenderFlags, const SRenderingPassInfo& passInfo);
- virtual void DebugDraw_UpdateDebugNode();
-
- void DebugDraw_Draw();
- bool IsOutdoorVisible();
- void RenderSkyBox(_smart_ptr pMat, const SRenderingPassInfo& passInfo);
-
- int GetStreamingFramesSinceLevelStart() { return m_nStreamingFramesSinceLevelStart; }
- int GetRenderFramesSinceLevelStart() { return m_nFramesSinceLevelStart; }
-
- bool CreateDecalInstance(const CryEngineDecalInfo&DecalInfo, class CDecal* pCallerManagedDecal);
- Vec3 GetTerrainSurfaceNormal(Vec3 vPos);
- void LoadEnvironmentSettingsFromXML(XmlNodeRef pInputNode, int nSID);
-#if defined(FEATURE_SVO_GI)
- void LoadTISettings(XmlNodeRef pInputNode);
-#endif
- void LoadDefaultAssets();
-
- // access to components
- static CVars* GetCVars() { return m_pCVars; }
- ILINE CVisAreaManager* GetVisAreaManager() { return m_pVisAreaManager; }
- ILINE CClipVolumeManager* GetClipVolumeManager() { return m_pClipVolumeManager; }
- ILINE PodArray* GetLightEntities() { return &m_lstStaticLights; }
-
- ILINE IGeneralMemoryHeap* GetBreakableBrushHeap() { return m_pBreakableBrushHeap; }
-
- virtual void OnCameraTeleport();
-
- bool m_bAreaActivationInUse;
-
- // Level info
- float m_fSkyBoxAngle, m_fSkyBoxStretching;
-
- float m_fMaxViewDistScale;
- float m_fMaxViewDistHighSpec;
- float m_fMaxViewDistLowSpec;
-
- float m_volFogGlobalDensity;
- float m_volFogGlobalDensityMultiplierLDR;
- float m_volFogFinalDensityClamp;
-
- float m_fCloudShadingSunLightMultiplier;
- float m_fCloudShadingSkyLightMultiplier;
- Vec3 m_vCloudShadingCustomSunColor;
- Vec3 m_vCloudShadingCustomSkyColor;
-
- Vec3 m_vFogColor;
- Vec3 m_vDefFogColor;
- Vec3 m_vSunDir;
- Vec3 m_vSunDirNormalized;
- float m_fSunDirUpdateTime;
- Vec3 m_vSunDirRealtime;
-
- Vec3 m_volFogRamp;
- Vec3 m_volFogShadowRange;
- Vec3 m_volFogShadowDarkening;
- Vec3 m_volFogShadowEnable;
-
- Vec3 m_volFog2CtrlParams;
- Vec3 m_volFog2ScatteringParams;
- Vec3 m_volFog2Ramp;
- Vec3 m_volFog2Color;
- Vec3 m_volFog2GlobalDensity;
- Vec3 m_volFog2HeightDensity;
- Vec3 m_volFog2HeightDensity2;
- Vec3 m_volFog2Color1;
- Vec3 m_volFog2Color2;
-
- Vec3 m_nightSkyHorizonCol;
- Vec3 m_nightSkyZenithCol;
- float m_nightSkyZenithColShift;
- float m_nightSkyStarIntensity;
- Vec3 m_nightMoonCol;
- float m_nightMoonSize;
- Vec3 m_nightMoonInnerCoronaCol;
- float m_nightMoonInnerCoronaScale;
- Vec3 m_nightMoonOuterCoronaCol;
- float m_nightMoonOuterCoronaScale;
-
- float m_moonRotationLatitude;
- float m_moonRotationLongitude;
- Vec3 m_moonDirection;
- int m_nWaterBottomTexId;
- int m_nNightMoonTexId;
- float m_fSunClipPlaneRange;
- float m_fSunClipPlaneRangeShift;
- bool m_bSunShadows;
-
- int m_nCloudShadowTexId;
-
- float m_fGsmRange;
- float m_fGsmRangeStep;
- float m_fShadowsConstBias;
- float m_fShadowsSlopeBias;
-
- int m_nSunAdditionalCascades;
- int m_nGsmCache;
- Vec3 m_oceanFogColor;
- Vec3 m_oceanFogColorShallow;
- float m_oceanFogDensity;
- float m_skyboxMultiplier;
- float m_dayNightIndicator;
- bool m_bHeightMapAoEnabled;
-
- Vec3 m_fogColor2;
- Vec3 m_fogColorRadial;
- Vec3 m_volFogHeightDensity;
- Vec3 m_volFogHeightDensity2;
- Vec3 m_volFogGradientCtrl;
-
-private:
- float m_oceanWindDirection;
- float m_oceanWindSpeed;
- float m_oceanWavesSpeed;
- float m_oceanWavesAmount;
- float m_oceanWavesSize;
-
-public:
- float m_dawnStart;
- float m_dawnEnd;
- float m_duskStart;
- float m_duskEnd;
-
- float m_fParticlesAmbientMultiplier;
- float m_fParticlesLightMultiplier;
- // film characteristic curve tweakables
- Vec4 m_vHDRFilmCurveParams;
- Vec3 m_vHDREyeAdaptation;
- Vec3 m_vHDREyeAdaptationLegacy;
- float m_fHDRBloomAmount;
-
- // hdr color grading
- Vec3 m_vColorBalance;
- float m_fHDRSaturation;
-
- // default post effect group path
- const char* m_defaultPostEffectGroup = "Libs/PostEffectGroups/Default.xml";
-
-#ifndef _RELEASE
- CDebugDrawListMgr m_DebugDrawListMgr;
-#endif
-
-#define MAX_SHADOW_CASCADES_NUM 20
-
- float m_pShadowCascadeConstBias[MAX_SHADOW_CASCADES_NUM];
- float m_pShadowCascadeSlopeBias[MAX_SHADOW_CASCADES_NUM];
-
- AABB m_CachedShadowsBounds;
- uint m_nCachedShadowsUpdateStrategy;
- float m_fCachedShadowsCascadeScale;
-
- // special case for combat mode adjustments
- float m_fSaturation;
- Vec4 m_pPhotoFilterColor;
- float m_fPhotoFilterColorDensity;
- float m_fGrainAmount;
- float m_fSunSpecMult;
-
- // Level shaders
- _smart_ptr m_pTerrainWaterMat;
- _smart_ptr m_pSkyMat;
- _smart_ptr m_pSkyLowSpecMat;
- _smart_ptr m_pSunMat;
-
- // Fog Materials
- _smart_ptr< IMaterial > m_pMatFogVolEllipsoid;
- _smart_ptr< IMaterial > m_pMatFogVolBox;
-
- void CleanLevelShaders()
- {
- m_pTerrainWaterMat = 0;
- m_pSkyMat = 0;
- m_pSkyLowSpecMat = 0;
- m_pSunMat = 0;
-
- m_pMatFogVolEllipsoid = 0;
- m_pMatFogVolBox = 0;
- }
-
- // Render elements
- CRESky* m_pRESky;
- CREHDRSky* m_pREHDRSky;
-
- int m_nDeferredLightsNum;
-
- mutable Vec3* m_pWindSamplePositions;
- mutable size_t m_nWindSamplePositions;
-
- // functions SRenderingPass
- virtual CCamera* GetRenderingPassCamera(const CCamera& rCamera);
-
- virtual void GetSvoStaticTextures(I3DEngine::SSvoStaticTexInfo& svoInfo, PodArray* pLightsTI_S, PodArray* pLightsTI_D);
- virtual void GetSvoBricksForUpdate(PodArray& arrNodeInfo, bool getDynamic);
-
- bool IsShadersSyncLoad() { return m_bContentPrecacheRequested && GetCVars()->e_AutoPrecacheTexturesAndShaders; }
- bool IsStatObjSyncLoad() { return m_bContentPrecacheRequested && GetCVars()->e_AutoPrecacheCgf; }
- float GetAverageCameraSpeed() { return m_fAverageCameraSpeed; }
- Vec3 GetAverageCameraMoveDir() { return m_vAverageCameraMoveDir; }
-
- typedef std::map ShadowFrustumListsCacheUsers;
- ShadowFrustumListsCacheUsers m_FrustumsCacheUsers[2];
-
- struct ILightSource* GetSunEntity();
-
- void OnCasterDeleted(IShadowCaster* pCaster) override;
-
- CCullBuffer* GetCoverageBuffer() { return m_pCoverageBuffer; }
-
- void InitShadowFrustums(const SRenderingPassInfo& passInfo);
-
- ///////////////////////////////////////////////////////////////////////////////
-
- virtual void GetLightVolumes(threadID nThreadID, SLightVolume*& pLightVols, uint32& nNumVols);
- virtual uint16 RegisterVolumeForLighting(const Vec3& vPos, f32 fRadius, uint8 nClipVolumeRef, const SRenderingPassInfo& passInfo);
-
- CLightVolumesMgr m_LightVolumesMgr;
-
- ///////////////////////////////////////////////////////////////////////////////
-
- void RemoveEntityLightSources(IRenderNode* pEntity);
-
- int GetRealLightsNum() { return m_nRealLightsNum; }
- void SetupClearColor();
- void CheckAddLight(CDLight* pLight, const SRenderingPassInfo& passInfo);
-
- void DrawTextRightAligned(const float x, const float y, const char* format, ...) PRINTF_PARAMS(4, 5);
- void DrawTextRightAligned(const float x, const float y, const float scale, const ColorF& color, const char* format, ...) PRINTF_PARAMS(6, 7);
- void DrawTextLeftAligned(const float x, const float y, const float scale, const ColorF& color, const char* format, ...) PRINTF_PARAMS(6, 7);
- void DrawTextAligned(int flags, const float x, const float y, const float scale, const ColorF& color, const char* format, ...) PRINTF_PARAMS(7, 8);
-
- void DrawBBoxHelper(const Vec3& vMin, const Vec3& vMax, ColorB col = Col_White) override { DrawBBox(vMin, vMax, col); }
- void DrawBBoxHelper(const AABB& box, ColorB col = Col_White) override { DrawBBox(box, col); }
-
- float GetLightAmount(CDLight* pLight, const AABB& objBox);
-
- IStatObj* CreateStatObj();
- virtual IStatObj* CreateStatObjOptionalIndexedMesh(bool createIndexedMesh);
-
- // Creates a new indexed mesh.
- IIndexedMesh* CreateIndexedMesh();
-
- void InitMaterialDefautMappingAxis(_smart_ptr pMat) override;
- _smart_ptr MakeSystemMaterialFromShaderHelper(const char* sShaderName, SInputShaderResources* Res = NULL) override
- {
- return MakeSystemMaterialFromShader(sShaderName, Res);
- }
-
- bool CheckMinSpecHelper(uint32 nMinSpec) override { return CheckMinSpec(nMinSpec); }
-
- virtual IVisAreaManager* GetIVisAreaManager() { return (IVisAreaManager*)m_pVisAreaManager; }
- bool CreateOcean(_smart_ptr pTerrainWaterMat, float waterLevel) override;
- void DeleteOcean() override;
- void ChangeOceanMaterial(_smart_ptr pMat) override;
- void ChangeOceanWaterLevel(float fWaterLevel) override;
-
- bool LoadVisAreas(std::vector** ppStatObjTable, std::vector<_smart_ptr