Fixed merge conflict.

Signed-off-by: Chris Galvan <chgalvan@amazon.com>
This commit is contained in:
Chris Galvan
2021-08-25 16:13:22 -05:00
148 changed files with 1583 additions and 16213 deletions
@@ -51,8 +51,8 @@ class TestAutomationBase:
cls.asset_processor.teardown()
cls._kill_ly_processes()
def _run_test(self, request, workspace, editor, testcase_module, extra_cmdline_args=[], use_null_renderer=True):
def _run_test(self, request, workspace, editor, testcase_module, extra_cmdline_args=[], batch_mode=True,
autotest_mode=True, use_null_renderer=True):
test_starttime = time.time()
self.logger = logging.getLogger(__name__)
errors = []
@@ -90,9 +90,13 @@ class TestAutomationBase:
editor_starttime = time.time()
self.logger.debug("Running automated test")
testcase_module_filepath = self._get_testcase_module_filepath(testcase_module)
pycmd = ["--runpythontest", testcase_module_filepath, "-BatchMode", "-autotest_mode", f"-pythontestcase={request.node.originalname}"]
pycmd = ["--runpythontest", testcase_module_filepath, f"-pythontestcase={request.node.originalname}"]
if use_null_renderer:
pycmd += ["-rhi=null"]
if batch_mode:
pycmd += ["-BatchMode"]
if autotest_mode:
pycmd += ["-autotest_mode"]
pycmd += extra_cmdline_args
editor.args.extend(pycmd) # args are added to the WinLauncher start command
editor.start(backupFiles = False, launch_ap = False)
@@ -11,22 +11,8 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_
NAME AutomatedTesting::EditorTests_Main
TEST_SUITE main
TEST_SERIAL
PATH ${CMAKE_CURRENT_LIST_DIR}
PYTEST_MARKS "SUITE_main and not REQUIRES_gpu"
RUNTIME_DEPENDENCIES
Legacy::Editor
AZ::AssetProcessor
AutomatedTesting.Assets
COMPONENT
Editor
)
ly_add_pytest(
NAME AutomatedTesting::EditorTests_Periodic
TEST_SUITE periodic
TEST_SERIAL
PATH ${CMAKE_CURRENT_LIST_DIR}
PYTEST_MARKS "SUITE_periodic and not REQUIRES_gpu"
PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Main.py
PYTEST_MARKS "not REQUIRES_gpu"
RUNTIME_DEPENDENCIES
Legacy::Editor
AZ::AssetProcessor
@@ -40,8 +26,21 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_
TEST_SUITE main
TEST_SERIAL
TEST_REQUIRES gpu
PATH ${CMAKE_CURRENT_LIST_DIR}
PYTEST_MARKS "SUITE_main and REQUIRES_gpu"
PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Main.py
PYTEST_MARKS "REQUIRES_gpu"
RUNTIME_DEPENDENCIES
Legacy::Editor
AZ::AssetProcessor
AutomatedTesting.Assets
COMPONENT
Editor
)
ly_add_pytest(
NAME AutomatedTesting::EditorTests_Periodic
TEST_SUITE periodic
TEST_SERIAL
PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Periodic.py
RUNTIME_DEPENDENCIES
Legacy::Editor
AZ::AssetProcessor
@@ -54,8 +53,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_
NAME AutomatedTesting::EditorTests_Sandbox
TEST_SUITE sandbox
TEST_SERIAL
PATH ${CMAKE_CURRENT_LIST_DIR}
PYTEST_MARKS "SUITE_sandbox"
PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Sandbox.py
RUNTIME_DEPENDENCIES
Legacy::Editor
AZ::AssetProcessor
@@ -63,4 +61,47 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_
COMPONENT
Editor
)
ly_add_pytest(
NAME AutomatedTesting::EditorTests_Main_Optimized
TEST_SUITE main
TEST_SERIAL
PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Main_Optimized.py
PYTEST_MARKS "not REQUIRES_gpu"
RUNTIME_DEPENDENCIES
Legacy::Editor
AZ::AssetProcessor
AutomatedTesting.Assets
COMPONENT
Editor
)
ly_add_pytest(
NAME AutomatedTesting::EditorTests_Main_GPU_Optimized
TEST_SUITE main
TEST_SERIAL
TEST_REQUIRES gpu
PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Main_Optimized.py
PYTEST_MARKS "REQUIRES_gpu"
RUNTIME_DEPENDENCIES
Legacy::Editor
AZ::AssetProcessor
AutomatedTesting.Assets
COMPONENT
Editor
)
ly_add_pytest(
NAME AutomatedTesting::EditorTests_Sandbox_Optimized
TEST_SUITE sandbox
TEST_SERIAL
PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Sandbox_Optimized.py
RUNTIME_DEPENDENCIES
Legacy::Editor
AZ::AssetProcessor
AutomatedTesting.Assets
COMPONENT
Editor
)
endif()
@@ -5,30 +5,24 @@ For complete copyright and license terms please see the LICENSE at the root of t
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
"""
C13660194 : Asset Browser - Filtering
"""
import os
import sys
from PySide2 import QtWidgets, QtTest, QtCore
from PySide2.QtCore import Qt
import azlmbr.legacy.general as general
import azlmbr.paths
sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests'))
import editor_python_test_tools.hydra_editor_utils as hydra
import editor_python_test_tools.pyside_utils as pyside_utils
from editor_python_test_tools.editor_test_helper import EditorTestHelper
class Tests:
asset_filtered = (
"Asset was filtered to in the Asset Browser",
"Failed to filter to the expected asset"
)
asset_type_filtered = (
"Expected asset type was filtered to in the Asset Browser",
"Failed to filter to the expected asset type"
)
class AssetBrowserSearchFilteringTest(EditorTestHelper):
def __init__(self):
EditorTestHelper.__init__(self, log_prefix="AssetBrowser_SearchFiltering", args=["level"])
def AssetBrowser_SearchFiltering():
import editor_python_test_tools.pyside_utils as pyside_utils
@pyside_utils.wrap_async
async def run_test(self):
async def run_test():
"""
Summary:
Asset Browser - Filtering
@@ -60,7 +54,13 @@ class AssetBrowserSearchFilteringTest(EditorTestHelper):
:return: None
"""
self.incorrect_file_found = False
from PySide2 import QtWidgets, QtTest, QtCore
from PySide2.QtCore import Qt
import azlmbr.legacy.general as general
from editor_python_test_tools.utils import Report
from editor_python_test_tools.utils import TestHelper as helper
def verify_files_appeared(model, allowed_asset_extentions, parent_index=QtCore.QModelIndex()):
indexes = [parent_index]
@@ -74,25 +74,24 @@ class AssetBrowserSearchFilteringTest(EditorTestHelper):
and (cur_data.lower().split(".")[-1] not in allowed_asset_extentions)
and not cur_data[-1] == ")"
):
print(f"Incorrect file found: {cur_data}")
self.incorrect_file_found = True
indexes = list()
break
Report.info(f"Incorrect file found: {cur_data}")
return False
indexes.append(cur_index)
return True
# 1) Open an existing simple level
helper.init_idle()
helper.open_level("Physics", "Base")
# 1) Open level
self.test_success = self.create_level(
self.args["level"],
heightmap_resolution=1024,
heightmap_meters_per_pixel=1,
terrain_texture_resolution=4096,
use_terrain=False,
)
# 2) Open Asset Browser
general.close_pane("Asset Browser")
general.open_pane("Asset Browser")
# 2) Open Asset Browser (if not opened already)
editor_window = pyside_utils.get_editor_main_window()
asset_browser_open = general.is_pane_visible("Asset Browser")
if not asset_browser_open:
Report.info("Opening Asset Browser")
action = pyside_utils.get_action_for_menu_path(editor_window, "Tools", "Asset Browser")
action.trigger()
else:
Report.info("Asset Browser is already open")
editor_window = pyside_utils.get_editor_main_window()
app = QtWidgets.QApplication.instance()
@@ -103,10 +102,9 @@ class AssetBrowserSearchFilteringTest(EditorTestHelper):
asset_browser_tree = asset_browser.findChild(QtWidgets.QTreeView, "m_assetBrowserTreeViewWidget")
model_index = pyside_utils.find_child_by_pattern(asset_browser_tree, "cedar.fbx")
pyside_utils.item_view_index_mouse_click(asset_browser_tree, model_index)
is_filtered = pyside_utils.wait_for_condition(
is_filtered = await pyside_utils.wait_for_condition(
lambda: asset_browser_tree.indexBelow(asset_browser_tree.currentIndex()) == QtCore.QModelIndex(), 5.0)
if is_filtered:
print("cedar.fbx asset is filtered in Asset Browser")
Report.result(Tests.asset_filtered, is_filtered)
# 4) Click the "X" in the search bar.
clear_search = asset_browser.findChild(QtWidgets.QToolButton, "ClearToolButton")
@@ -122,40 +120,47 @@ class AssetBrowserSearchFilteringTest(EditorTestHelper):
tree.model().setData(animation_model_index, 2, Qt.CheckStateRole)
general.idle_wait(1.0)
# check asset types after clicking on Animation filter
verify_files_appeared(asset_browser_tree.model(), ["i_caf", "fbx", "xml", "animgraph", "motionset"])
print(f"Animation file type(s) is present in the file tree: {not self.incorrect_file_found}")
asset_type_filter = verify_files_appeared(asset_browser_tree.model(), ["i_caf", "fbx", "xml", "animgraph", "motionset"])
Report.result(Tests.asset_type_filtered, asset_type_filter)
# 6) Add additional filter(FileTag) from the filter menu
self.incorrect_file_found = False
line_edit.setText("FileTag")
filetag_model_index = await pyside_utils.wait_for_child_by_pattern(tree, "FileTag")
tree.model().setData(filetag_model_index, 2, Qt.CheckStateRole)
general.idle_wait(1.0)
# check asset types after clicking on FileTag filter
verify_files_appeared(
more_types_filtered = verify_files_appeared(
asset_browser_tree.model(), ["i_caf", "fbx", "xml", "animgraph", "motionset", "filetag"]
)
print(f"FileTag file type(s) and Animation file type(s) is present in the file tree: {not self.incorrect_file_found}")
Report.result(Tests.asset_type_filtered, more_types_filtered)
# 7) Remove one of the filtered asset types from the list of applied filters
self.incorrect_file_found = False
filter_layout = asset_browser.findChild(QtWidgets.QFrame, "filteredLayout")
animation_close_button = filter_layout.children()[1]
first_close_button = animation_close_button.findChild(QtWidgets.QPushButton, "closeTag")
first_close_button.click()
general.idle_wait(1.0)
# check asset types after removing Animation filter
verify_files_appeared(asset_browser_tree.model(), ["filetag"])
print(f"FileTag file type(s) is present in the file tree after removing Animation filter: {not self.incorrect_file_found}")
remove_filtered = verify_files_appeared(asset_browser_tree.model(), ["filetag"])
Report.result(Tests.asset_type_filtered, remove_filtered)
# 8) Remove all of the filter asset types from the list of filters
filetag_close_button = filter_layout.children()[1]
second_close_button = filetag_close_button.findChild(QtWidgets.QPushButton, "closeTag")
second_close_button.click()
# 9) Close the asset browser
asset_browser.close()
# Click off of the Asset Browser filter window to close it
QtTest.QTest.mouseClick(tree, Qt.LeftButton, Qt.NoModifier)
# 9) Restore Asset Browser tool state and
if not asset_browser_open:
Report.info("Closing Asset Browser")
general.close_pane("Asset Browser")
run_test()
test = AssetBrowserSearchFilteringTest()
test.run()
if __name__ == "__main__":
from editor_python_test_tools.utils import Report
Report.start_test(AssetBrowser_SearchFiltering)
@@ -5,124 +5,119 @@ For complete copyright and license terms please see the LICENSE at the root of t
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
"""
C13660195: Asset Browser - File Tree Navigation
"""
import os
import sys
from PySide2 import QtWidgets, QtTest, QtCore
import azlmbr.legacy.general as general
import azlmbr.paths
sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests'))
from editor_python_test_tools.editor_test_helper import EditorTestHelper
import editor_python_test_tools.pyside_utils as pyside_utils
class Tests:
collapse_expand = (
"Asset Browser hierarchy successfully collapsed/expanded",
"Failed to collapse/expand Asset Browser hierarchy"
)
asset_visible = (
"Expected asset is visible in the Asset Browser hierarchy",
"Failed to find expected asset in the Asset Browser hierarchy"
)
scrollbar_visible = (
"Scrollbar is visible",
"Scrollbar was not found"
)
class AssetBrowserTreeNavigationTest(EditorTestHelper):
def __init__(self):
EditorTestHelper.__init__(self, log_prefix="AssetBrowser_TreeNavigation", args=["level"])
def AssetBrowser_TreeNavigation():
"""
Summary:
Verify if we are able to expand a file hierarchy in the Asset Browser and ScrollBar appears
appropriately.
def run_test(self):
"""
Summary:
Verify if we are able to expand a file hierarchy in the Asset Browser and ScrollBar appears
appropriately.
Expected Behavior:
The folder list is expanded to display the children of the selected folder.
A scroll bar appears to allow scrolling up and down through the asset browser.
Assets are present in the Asset Browser.
Expected Behavior:
The folder list is expanded to display the children of the selected folder.
A scroll bar appears to allow scrolling up and down through the asset browser.
Assets are present in the Asset Browser.
Test Steps:
1) Open a simple level
2) Open Asset Browser
3) Collapse all files initially
4) Get all Model Indexes
5) Expand each of the folder and verify if it is opened
6) Verify if the ScrollBar appears after expanding the tree
Test Steps:
1) Open a new level
2) Open Asset Browser
3) Collapse all files initially
4) Get all Model Indexes
5) Expand each of the folder and verify if it is opened
6) Verify if the ScrollBar appears after expanding the tree
Note:
- This test file must be called from the Open 3D Engine Editor command terminal
- Any passed and failed tests are written to the Editor.log file.
Parsing the file or running a log_monitor are required to observe the test results.
Note:
- This test file must be called from the Open 3D Engine Editor command terminal
- Any passed and failed tests are written to the Editor.log file.
Parsing the file or running a log_monitor are required to observe the test results.
:return: None
"""
:return: None
"""
from PySide2 import QtWidgets, QtTest, QtCore
def collapse_expand_and_verify(model_index, hierarchy_level):
tree.collapse(model_index)
collapse_success = not tree.isExpanded(model_index)
self.log(f"Level {hierarchy_level} collapsed: {collapse_success}")
tree.expand(model_index)
expand_success = tree.isExpanded(model_index)
self.log(f"Level {hierarchy_level} expanded: {expand_success}")
return collapse_success and expand_success
import azlmbr.legacy.general as general
# This is the hierarchy we are expanding (4 steps inside)
self.file_path = ("AutomatedTesting", "Assets", "ImageGradients", "image_grad_test_gsi.png")
import editor_python_test_tools.pyside_utils as pyside_utils
from editor_python_test_tools.utils import Report
from editor_python_test_tools.utils import TestHelper as helper
# 1) Open a new level
self.test_success = self.create_level(
self.args["level"],
heightmap_resolution=1024,
heightmap_meters_per_pixel=1,
terrain_texture_resolution=4096,
use_terrain=False,
)
def collapse_expand_and_verify(model_index, hierarchy_level):
tree.collapse(model_index)
collapse_success = not tree.isExpanded(model_index)
Report.info(f"Level {hierarchy_level} collapsed: {collapse_success}")
tree.expand(model_index)
expand_success = tree.isExpanded(model_index)
Report.info(f"Level {hierarchy_level} expanded: {expand_success}")
return collapse_success and expand_success
# 2) Open Asset Browser (if not opened already)
editor_window = pyside_utils.get_editor_main_window()
asset_browser_open = general.is_pane_visible("Asset Browser")
if not asset_browser_open:
self.log("Opening Asset Browser")
action = pyside_utils.get_action_for_menu_path(editor_window, "Tools", "Asset Browser")
action.trigger()
else:
self.log("Asset Browser is already open")
# This is the hierarchy we are expanding (4 steps inside)
file_path = ("AutomatedTesting", "Assets", "ImageGradients", "image_grad_test_gsi.png")
# 3) Collapse all files initially
main_window = editor_window.findChild(QtWidgets.QMainWindow)
asset_browser = pyside_utils.find_child_by_hierarchy(main_window, ..., "Asset Browser")
tree = pyside_utils.find_child_by_hierarchy(asset_browser, ..., "m_assetBrowserTreeViewWidget")
scroll_area = tree.findChild(QtWidgets.QWidget, "qt_scrollarea_vcontainer")
scroll_bar = scroll_area.findChild(QtWidgets.QScrollBar)
tree.collapseAll()
# 1) Open an existing simple level
helper.init_idle()
helper.open_level("Physics", "Base")
# 4) Get all Model Indexes
model_index_1 = pyside_utils.find_child_by_hierarchy(tree, self.file_path[0])
model_index_2 = pyside_utils.find_child_by_hierarchy(model_index_1, self.file_path[1])
model_index_3 = pyside_utils.find_child_by_hierarchy(model_index_2, self.file_path[2])
model_index_4 = pyside_utils.find_child_by_hierarchy(model_index_3, self.file_path[3])
# 2) Open Asset Browser (if not opened already)
editor_window = pyside_utils.get_editor_main_window()
asset_browser_open = general.is_pane_visible("Asset Browser")
if not asset_browser_open:
Report.info("Opening Asset Browser")
action = pyside_utils.get_action_for_menu_path(editor_window, "Tools", "Asset Browser")
action.trigger()
else:
Report.info("Asset Browser is already open")
# 5) Verify each level of the hierarchy to the file can be collapsed/expanded
self.test_success = collapse_expand_and_verify(model_index_1, 1) and self.test_success
self.test_success = collapse_expand_and_verify(model_index_2, 2) and self.test_success
self.test_success = collapse_expand_and_verify(model_index_3, 3) and self.test_success
self.log(f"Collapse/Expand tests: {self.test_success}")
# 3) Collapse all files initially
main_window = editor_window.findChild(QtWidgets.QMainWindow)
asset_browser = pyside_utils.find_child_by_hierarchy(main_window, ..., "Asset Browser")
tree = pyside_utils.find_child_by_hierarchy(asset_browser, ..., "m_assetBrowserTreeViewWidget")
scroll_area = tree.findChild(QtWidgets.QWidget, "qt_scrollarea_vcontainer")
scroll_bar = scroll_area.findChild(QtWidgets.QScrollBar)
tree.collapseAll()
# Select the asset
tree.scrollTo(model_index_4)
pyside_utils.item_view_index_mouse_click(tree, model_index_4)
# 4) Get all Model Indexes
model_index_1 = pyside_utils.find_child_by_hierarchy(tree, file_path[0])
model_index_2 = pyside_utils.find_child_by_hierarchy(model_index_1, file_path[1])
model_index_3 = pyside_utils.find_child_by_hierarchy(model_index_2, file_path[2])
model_index_4 = pyside_utils.find_child_by_hierarchy(model_index_3, file_path[3])
# Verify if the currently selected item model index is same as the Asset Model index
# to prove that it is visible
asset_visible = tree.currentIndex() == model_index_4
self.test_success = asset_visible and self.test_success
self.log(f"Asset visibility test: {asset_visible}")
# 5) Verify each level of the hierarchy to the file can be collapsed/expanded
Report.result(Tests.collapse_expand, collapse_expand_and_verify(model_index_1, 1) and
collapse_expand_and_verify(model_index_2, 2) and collapse_expand_and_verify(model_index_3, 3))
# 6) Verify if the ScrollBar appears after expanding the tree
scrollbar_visible = scroll_bar.isVisible()
self.test_success = scrollbar_visible and self.test_success
self.log(f"Scrollbar visibility test: {scrollbar_visible}")
# Select the asset
tree.scrollTo(model_index_4)
pyside_utils.item_view_index_mouse_click(tree, model_index_4)
# 7) Restore Asset Browser tool state
if not asset_browser_open:
self.log("Closing Asset Browser")
general.close_pane("Asset Browser")
# Verify if the currently selected item model index is same as the Asset Model index
# to prove that it is visible
Report.result(Tests.asset_visible, tree.currentIndex() == model_index_4)
# 6) Verify if the ScrollBar appears after expanding the tree
Report.result(Tests.scrollbar_visible, scroll_bar.isVisible())
# 7) Restore Asset Browser tool state
if not asset_browser_open:
Report.info("Closing Asset Browser")
general.close_pane("Asset Browser")
test = AssetBrowserTreeNavigationTest()
test.run()
if __name__ == "__main__":
from editor_python_test_tools.utils import Report
Report.start_test(AssetBrowser_TreeNavigation)
@@ -5,33 +5,13 @@ For complete copyright and license terms please see the LICENSE at the root of t
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
"""
C13751579: Asset Picker UI/UX
"""
import os
import sys
from PySide2 import QtWidgets, QtTest, QtCore
from PySide2.QtCore import Qt
def AssetPicker_UI_UX():
import azlmbr.asset as asset
import azlmbr.bus as bus
import azlmbr.legacy.general as general
import azlmbr.paths
import azlmbr.math as math
sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests'))
import editor_python_test_tools.hydra_editor_utils as hydra
import editor_python_test_tools.pyside_utils as pyside_utils
from editor_python_test_tools.editor_test_helper import EditorTestHelper
class AssetPickerUIUXTest(EditorTestHelper):
def __init__(self):
EditorTestHelper.__init__(self, log_prefix="AssetPicker_UI_UX", args=["level"])
import editor_python_test_tools.pyside_utils as pyside_utils
@pyside_utils.wrap_async
async def run_test(self):
async def run_test():
"""
Summary:
Verify the functionality of Asset Picker and UI/UX properties
@@ -45,7 +25,7 @@ class AssetPickerUIUXTest(EditorTestHelper):
The asset picker is closed and the selected asset is assigned to the mesh component.
Test Steps:
1) Open a new level
1) Open a simple level
2) Create entity and add Mesh component
3) Access Entity Inspector
4) Click Asset Picker (Mesh Asset)
@@ -68,10 +48,20 @@ class AssetPickerUIUXTest(EditorTestHelper):
:return: None
"""
self.file_path = ["AutomatedTesting", "Assets", "Objects", "Foliage"]
self.incorrect_file_found = False
self.mesh_asset = "cedar.azmodel"
self.prefix = ""
import os
from PySide2 import QtWidgets, QtTest, QtCore
from PySide2.QtCore import Qt
import azlmbr.asset as asset
import azlmbr.bus as bus
import azlmbr.legacy.general as general
import azlmbr.math as math
import editor_python_test_tools.hydra_editor_utils as hydra
from editor_python_test_tools.utils import Report
from editor_python_test_tools.utils import TestHelper as helper
file_path = ["AutomatedTesting", "Assets", "Objects", "Foliage"]
def is_asset_assigned(component, interaction_option):
path = os.path.join("assets", "objects", "foliage", "cedar.azmodel")
@@ -80,7 +70,7 @@ class AssetPickerUIUXTest(EditorTestHelper):
result = hydra.get_component_property_value(component, "Controller|Configuration|Mesh Asset")
expected_asset_str = expected_asset_id.invoke("ToString")
result_str = result.invoke("ToString")
print(f"Asset assigned for {interaction_option} option: {expected_asset_str == result_str}")
Report.info(f"Asset assigned for {interaction_option} option: {expected_asset_str == result_str}")
return expected_asset_str == result_str
def move_and_resize_widget(widget):
@@ -89,9 +79,11 @@ class AssetPickerUIUXTest(EditorTestHelper):
x, y = initial_position.x() + 5, initial_position.y() + 5
widget.move(x, y)
curr_position = widget.pos()
move_success = curr_position.x() == x and curr_position.y() == y
self.test_success = move_success and self.test_success
self.log(f"Widget Move Test: {move_success}")
asset_picker_moved = (
"Asset Picker widget moved successfully",
"Failed to move Asset Picker widget"
)
Report.result(asset_picker_moved, curr_position.x() == x and curr_position.y() == y)
# Resize the widget and verify size
width, height = (
@@ -99,9 +91,36 @@ class AssetPickerUIUXTest(EditorTestHelper):
widget.geometry().height() + 10,
)
widget.resize(width, height)
resize_success = widget.geometry().width() == width and widget.geometry().height() == height
self.test_success = resize_success and self.test_success
self.log(f"Widget Resize Test: {resize_success}")
asset_picker_resized = (
"Resized Asset Picker widget successfully",
"Failed to resize Asset Picker widget"
)
Report.result(asset_picker_resized, widget.geometry().width() == width and widget.geometry().height() ==
height)
def verify_expand(model_index, tree):
initially_collapsed = (
"Folder initially collapsed",
"Folder unexpectedly expanded"
)
expanded = (
"Folder expanded successfully",
"Failed to expand folder"
)
# Check initial collapse
Report.result(initially_collapsed, not tree.isExpanded(model_index))
# Expand at the specified index
tree.expand(model_index)
# Verify expansion
Report.result(expanded, tree.isExpanded(model_index))
def verify_collapse(model_index, tree):
collapsed = (
"Folder hierarchy collapsed successfully",
"Failed to collapse folder hierarchy"
)
tree.collapse(model_index)
Report.result(collapsed, not tree.isExpanded(model_index))
def verify_files_appeared(model, allowed_asset_extensions, parent_index=QtCore.QModelIndex()):
indices = [parent_index]
@@ -115,22 +134,20 @@ class AssetPickerUIUXTest(EditorTestHelper):
and (cur_data.lower().split(".")[-1] not in allowed_asset_extensions)
and not cur_data[-1] == ")"
):
print(f"Incorrect file found: {cur_data}")
self.incorrect_file_found = True
indices = list()
break
Report.info(f"Incorrect file found: {cur_data}")
return False
indices.append(cur_index)
self.test_success = not self.incorrect_file_found and self.test_success
return True
def print_message_prefix(message):
print(f"{self.prefix}: {message}")
async def asset_picker(prefix, allowed_asset_extensions, asset, interaction_option):
async def asset_picker(allowed_asset_extensions, asset, interaction_option):
active_modal_widget = await pyside_utils.wait_for_modal_widget()
if active_modal_widget and self.prefix == "":
self.prefix = prefix
if active_modal_widget:
dialog = active_modal_widget.findChildren(QtWidgets.QDialog, "AssetPickerDialogClass")[0]
print_message_prefix(f"Asset Picker title for Mesh: {dialog.windowTitle()}")
asset_picker_title = (
"Asset Picker window is titled as expected",
"Asset Picker window has an unexpected title"
)
Report.result(asset_picker_title, dialog.windowTitle() == "Pick ModelAsset")
tree = dialog.findChildren(QtWidgets.QTreeView, "m_assetBrowserTreeViewWidget")[0]
scroll_area = tree.findChild(QtWidgets.QWidget, "qt_scrollarea_vcontainer")
scroll_bar = scroll_area.findChild(QtWidgets.QScrollBar)
@@ -138,39 +155,42 @@ class AssetPickerUIUXTest(EditorTestHelper):
# a) Collapse all the files initially and verify if scroll bar is not visible
tree.collapseAll()
await pyside_utils.wait_for_condition(lambda: not scroll_bar.isVisible(), 0.5)
print_message_prefix(
f"Scroll Bar is not visible before expanding the tree: {not scroll_bar.isVisible()}"
scroll_bar_hidden = (
"Scroll Bar is not visible before tree expansion",
"Scroll Bar is visible before tree expansion"
)
Report.result(scroll_bar_hidden, not scroll_bar.isVisible())
# Get Model Index of the file paths
model_index_1 = pyside_utils.find_child_by_pattern(tree, self.file_path[0])
print(model_index_1.model())
model_index_2 = pyside_utils.find_child_by_pattern(model_index_1, self.file_path[1])
model_index_1 = pyside_utils.find_child_by_pattern(tree, file_path[0])
model_index_2 = pyside_utils.find_child_by_pattern(model_index_1, file_path[1])
# b) Expand/Verify Top folder of file path
print_message_prefix(f"Top level folder initially collapsed: {not tree.isExpanded(model_index_1)}")
tree.expand(model_index_1)
print_message_prefix(f"Top level folder expanded: {tree.isExpanded(model_index_1)}")
verify_expand(model_index_1, tree)
# c) Expand/Verify Nested folder of file path
print_message_prefix(f"Nested folder initially collapsed: {not tree.isExpanded(model_index_2)}")
tree.expand(model_index_2)
print_message_prefix(f"Nested folder expanded: {tree.isExpanded(model_index_2)}")
verify_expand(model_index_2, tree)
# d) Verify if the ScrollBar appears after expanding folders
tree.expandAll()
await pyside_utils.wait_for_condition(lambda: scroll_bar.isVisible(), 0.5)
print_message_prefix(f"Scroll Bar appeared after expanding tree: {scroll_bar.isVisible()}")
scroll_bar_visible = (
"Scroll Bar is visible after tree expansion",
"Scroll Bar is not visible after tree expansion"
)
Report.result(scroll_bar_visible, scroll_bar.isVisible())
# e) Collapse Nested and Top Level folders and verify if collapsed
tree.collapse(model_index_2)
print_message_prefix(f"Nested folder collapsed: {not tree.isExpanded(model_index_2)}")
tree.collapse(model_index_1)
print_message_prefix(f"Top level folder collapsed: {not tree.isExpanded(model_index_1)}")
verify_collapse(model_index_2, tree)
verify_collapse(model_index_1, tree)
# f) Verify if the correct files are appearing in the Asset Picker
verify_files_appeared(tree.model(), allowed_asset_extensions)
print_message_prefix(f"Expected Assets populated in the file picker: {not self.incorrect_file_found}")
asset_picker_correct_files_appear = (
"Expected assets populated in the file picker",
"Found unexpected assets in the file picker"
)
Report.result(asset_picker_correct_files_appear, verify_files_appeared(tree.model(),
allowed_asset_extensions))
# While we are here we can also check if we can resize and move the widget
move_and_resize_widget(active_modal_widget)
@@ -193,16 +213,10 @@ class AssetPickerUIUXTest(EditorTestHelper):
await pyside_utils.click_button_async(ok_button)
elif interaction_option == "enter":
QtTest.QTest.keyClick(tree, Qt.Key_Enter, Qt.NoModifier)
self.prefix = ""
# 1) Open a new level
self.test_success = self.create_level(
self.args["level"],
heightmap_resolution=1024,
heightmap_meters_per_pixel=1,
terrain_texture_resolution=4096,
use_terrain=False,
)
# 1) Open an existing simple level
helper.init_idle()
helper.open_level("Physics", "Base")
# 2) Create entity and add Mesh component
entity_position = math.Vector3(125.0, 136.0, 32.0)
@@ -222,7 +236,7 @@ class AssetPickerUIUXTest(EditorTestHelper):
# Assign Mesh Asset via OK button
pyside_utils.click_button_async(attached_button)
await asset_picker("Mesh Asset", ["azmodel", "fbx"], "cedar (ModelAsset)", "ok")
await asset_picker(["azmodel", "fbx"], "cedar (ModelAsset)", "ok")
# 5) Verify if Mesh Asset is assigned
try:
@@ -231,7 +245,11 @@ class AssetPickerUIUXTest(EditorTestHelper):
except pyside_utils.EventLoopTimeoutException as err:
print(err)
mesh_success = False
self.test_success = mesh_success and self.test_success
mesh_asset_assigned_ok = (
"Successfully assigned Mesh asset via OK button",
"Failed to assign Mesh asset via OK button"
)
Report.result(mesh_asset_assigned_ok, mesh_success)
# Clear Mesh Asset
hydra.get_set_test(entity, 0, "Controller|Configuration|Mesh Asset", None)
@@ -242,7 +260,7 @@ class AssetPickerUIUXTest(EditorTestHelper):
# Assign Mesh Asset via Enter
pyside_utils.click_button_async(attached_button)
await asset_picker("Mesh Asset", ["azmodel", "fbx"], "cedar (ModelAsset)", "enter")
await asset_picker(["azmodel", "fbx"], "cedar (ModelAsset)", "enter")
# 5) Verify if Mesh Asset is assigned
try:
@@ -251,8 +269,16 @@ class AssetPickerUIUXTest(EditorTestHelper):
except pyside_utils.EventLoopTimeoutException as err:
print(err)
mesh_success = False
self.test_success = mesh_success and self.test_success
mesh_asset_assigned_enter = (
"Successfully assigned Mesh asset via Enter button",
"Failed to assign Mesh asset via Enter button"
)
Report.result(mesh_asset_assigned_enter, mesh_success)
run_test()
test = AssetPickerUIUXTest()
test.run()
if __name__ == "__main__":
from editor_python_test_tools.utils import Report
Report.start_test(AssetPicker_UI_UX)
@@ -5,36 +5,44 @@ For complete copyright and license terms please see the LICENSE at the root of t
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
"""
C6351273: Create a new level
C6384955: Basic Workflow: Entity Manipulation in the Outliner
C16929880: Add Delete Components
C15167490: Save a level
C15167491: Export a level
"""
import os
import sys
from PySide2 import QtWidgets
import azlmbr.bus as bus
import azlmbr.editor as editor
import azlmbr.entity as entity
import azlmbr.math as math
import azlmbr.paths
sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests'))
from editor_python_test_tools.editor_test_helper import EditorTestHelper
import editor_python_test_tools.pyside_utils as pyside_utils
import editor_python_test_tools.hydra_editor_utils as hydra
class Tests:
level_created = (
"New level created successfully",
"Failed to create new level"
)
new_entity_created = (
"New entity created successfully",
"Failed to create a new entity"
)
child_entity_created = (
"New child entity created successfully",
"Failed to create new child entity"
)
component_added = (
"Component added to entity successfully",
"Failed to add component to entity"
)
component_updated = (
"Component property updated successfully",
"Failed to update component property"
)
component_removed = (
"Component removed from entity successfully",
"Failed to remove component from entity"
)
level_saved_and_exported = (
"Level saved and exported successfully",
"Failed to save/export level"
)
class TestBasicEditorWorkflows(EditorTestHelper):
def __init__(self):
EditorTestHelper.__init__(self, log_prefix="BasicEditorWorkflows_LevelEntityComponent", args=["level"])
def BasicEditorWorkflows_LevelEntityComponentCRUD():
import editor_python_test_tools.pyside_utils as pyside_utils
@pyside_utils.wrap_async
async def run_test(self):
async def run_test():
"""
Summary:
Open O3DE editor and check if basic Editor workflows are completable.
@@ -55,6 +63,18 @@ class TestBasicEditorWorkflows(EditorTestHelper):
:return: None
"""
import os
from PySide2 import QtWidgets
import azlmbr.bus as bus
import azlmbr.editor as editor
import azlmbr.entity as entity
import azlmbr.math as math
import azlmbr.paths
import editor_python_test_tools.hydra_editor_utils as hydra
from editor_python_test_tools.utils import Report
def find_entity_by_name(entity_name):
search_filter = entity.SearchFilter()
search_filter.names = [entity_name]
@@ -64,6 +84,7 @@ class TestBasicEditorWorkflows(EditorTestHelper):
return None
# 1) Create a new level
level = "tmp_level"
editor_window = pyside_utils.get_editor_main_window()
new_level_action = pyside_utils.get_action_for_menu_path(editor_window, "File", "New Level")
pyside_utils.trigger_action_async(new_level_action)
@@ -71,21 +92,17 @@ class TestBasicEditorWorkflows(EditorTestHelper):
new_level_dlg = active_modal_widget.findChild(QtWidgets.QWidget, "CNewLevelDialog")
if new_level_dlg:
if new_level_dlg.windowTitle() == "New Level":
self.log("New Level dialog opened")
Report.info("New Level dialog opened")
grp_box = new_level_dlg.findChild(QtWidgets.QGroupBox, "STATIC_GROUP1")
level_name = grp_box.findChild(QtWidgets.QLineEdit, "LEVEL")
level_name.setText(self.args["level"])
level_name.setText(level)
button_box = new_level_dlg.findChild(QtWidgets.QDialogButtonBox, "buttonBox")
button_box.button(QtWidgets.QDialogButtonBox.Ok).click()
# Verify new level was created successfully
level_create_success = await pyside_utils.wait_for_condition(lambda: editor.EditorToolsApplicationRequestBus(
bus.Broadcast, "GetCurrentLevelName") == self.args["level"], 5.0)
self.test_success = level_create_success
self.log(f"Create and load new level: {level_create_success}")
# Execute EditorTestHelper setup since level was created outside of EditorTestHelper's methods
self.test_success = self.test_success and self.after_level_load()
bus.Broadcast, "GetCurrentLevelName") == level, 5.0)
Report.critical_result(Tests.level_created, level_create_success)
# 2) Delete existing entities, and create and manipulate new entities via Entity Inspector
search_filter = azlmbr.entity.SearchFilter()
@@ -99,8 +116,7 @@ class TestBasicEditorWorkflows(EditorTestHelper):
# Find the new entity
parent_entity_id = find_entity_by_name("Entity1")
parent_entity_success = await pyside_utils.wait_for_condition(lambda: parent_entity_id is not None, 5.0)
self.test_success = self.test_success and parent_entity_success
self.log(f"New entity creation: {parent_entity_success}")
Report.critical_result(Tests.new_entity_created, parent_entity_success)
# TODO: Replace Hydra call to creates child entity and add components with context menu triggering - LYN-3951
# Create a new child entity
@@ -111,29 +127,27 @@ class TestBasicEditorWorkflows(EditorTestHelper):
# Verify entity hierarchy
child_entity.get_parent_info()
self.test_success = self.test_success and child_entity.parent_id == parent_entity_id
self.log(f"Create entity hierarchy: {child_entity.parent_id == parent_entity_id}")
Report.result(Tests.child_entity_created, child_entity.parent_id == parent_entity_id)
# 3) Add/configure a component on an entity
# Add component and verify success
child_entity.add_component("Box Shape")
component_add_success = self.wait_for_condition(lambda: hydra.has_components(child_entity.id, ["Box Shape"]), 5.0)
self.test_success = self.test_success and component_add_success
self.log(f"Add component: {component_add_success}")
component_add_success = await pyside_utils.wait_for_condition(lambda: hydra.has_components(child_entity.id,
["Box Shape"]), 5.0)
Report.result(Tests.component_added, component_add_success)
# Update the component
dimensions_to_set = math.Vector3(16.0, 16.0, 16.0)
child_entity.get_set_test(0, "Box Shape|Box Configuration|Dimensions", dimensions_to_set)
box_shape_dimensions = hydra.get_component_property_value(child_entity.components[0], "Box Shape|Box Configuration|Dimensions")
self.test_success = self.test_success and box_shape_dimensions == dimensions_to_set
self.log(f"Component update: {box_shape_dimensions == dimensions_to_set}")
box_shape_dimensions = hydra.get_component_property_value(child_entity.components[0],
"Box Shape|Box Configuration|Dimensions")
Report.result(Tests.component_updated, box_shape_dimensions == dimensions_to_set)
# Remove the component
child_entity.remove_component("Box Shape")
component_rem_success = self.wait_for_condition(lambda: not hydra.has_components(child_entity.id, ["Box Shape"]),
5.0)
self.test_success = self.test_success and component_rem_success
self.log(f"Remove component: {component_rem_success}")
component_rem_success = await pyside_utils.wait_for_condition(lambda: not hydra.has_components(child_entity.id,
["Box Shape"]), 5.0)
Report.result(Tests.component_removed, component_rem_success)
# 4) Save the level
save_level_action = pyside_utils.get_action_for_menu_path(editor_window, "File", "Save")
@@ -143,12 +157,15 @@ class TestBasicEditorWorkflows(EditorTestHelper):
export_action = pyside_utils.get_action_for_menu_path(editor_window, "Game", "Export to Engine")
pyside_utils.trigger_action_async(export_action)
level_pak_file = os.path.join(
"AutomatedTesting", "Levels", self.args["level"], "level.pak"
"AutomatedTesting", "Levels", level, "level.pak"
)
export_success = self.wait_for_condition(lambda: os.path.exists(level_pak_file), 5.0)
self.test_success = self.test_success and export_success
self.log(f"Save and Export: {export_success}")
export_success = await pyside_utils.wait_for_condition(lambda: os.path.exists(level_pak_file), 5.0)
Report.result(Tests.level_saved_and_exported, export_success)
run_test()
test = TestBasicEditorWorkflows()
test.run()
if __name__ == "__main__":
from editor_python_test_tools.utils import Report
Report.start_test(BasicEditorWorkflows_LevelEntityComponentCRUD)
@@ -5,37 +5,39 @@ For complete copyright and license terms please see the LICENSE at the root of t
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
"""
C16929880: Add Delete Components
"""
import os
import sys
from PySide2 import QtWidgets, QtTest, QtCore
from PySide2.QtCore import Qt
import azlmbr.legacy.general as general
import azlmbr.bus as bus
import azlmbr.editor as editor
import azlmbr.entity as entity
import azlmbr.math as math
import azlmbr.paths
sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests'))
import editor_python_test_tools.hydra_editor_utils as hydra
import editor_python_test_tools.pyside_utils as pyside_utils
from editor_python_test_tools.editor_test_helper import EditorTestHelper
class Tests:
entity_created = (
"Entity created successfully",
"Failed to create entity"
)
box_component_added = (
"Box Shape component added to entity",
"Failed to add Box Shape component to entity"
)
mesh_component_added = (
"Mesh component added to entity",
"Failed to add Mesh component to entity"
)
mesh_component_deleted = (
"Mesh component removed from entity",
"Failed to remove Mesh component from entity"
)
mesh_component_delete_undo = (
"Mesh component removal was successfully undone",
"Failed to undo Mesh component removal"
)
class AddDeleteComponentsTest(EditorTestHelper):
def __init__(self):
EditorTestHelper.__init__(self, log_prefix="ComponentCRUD_Add_Delete_Components", args=["level"])
def ComponentCRUD_Add_Delete_Components():
import editor_python_test_tools.pyside_utils as pyside_utils
@pyside_utils.wrap_async
async def run_test(self):
async def run_test():
"""
Summary:
Add/Delete Components to an entity.
Add/Delete Components to/from an entity.
Expected Behavior:
1) Components can be added to an entity.
@@ -61,36 +63,43 @@ class AddDeleteComponentsTest(EditorTestHelper):
:return: None
"""
from PySide2 import QtWidgets, QtTest, QtCore
from PySide2.QtCore import Qt
import azlmbr.legacy.general as general
import azlmbr.bus as bus
import azlmbr.editor as editor
import azlmbr.entity as entity
import azlmbr.math as math
import editor_python_test_tools.hydra_editor_utils as hydra
from editor_python_test_tools.utils import Report
from editor_python_test_tools.utils import TestHelper as helper
async def add_component(component_name):
pyside_utils.click_button_async(add_comp_btn)
popup = await pyside_utils.wait_for_popup_widget()
tree = popup.findChild(QtWidgets.QTreeView, "Tree")
component_index = pyside_utils.find_child_by_pattern(tree, component_name)
if component_index.isValid():
print(f"{component_name} found")
Report.info(f"{component_name} found")
tree.expand(component_index)
tree.setCurrentIndex(component_index)
QtTest.QTest.keyClick(tree, Qt.Key_Enter, Qt.NoModifier)
# 1) Open level
self.test_success = self.create_level(
self.args["level"],
heightmap_resolution=1024,
heightmap_meters_per_pixel=1,
terrain_texture_resolution=4096,
use_terrain=False,
)
# 1) Open an existing simple level
helper.init_idle()
helper.open_level("Physics", "Base")
# 2) Create entity
entity_position = math.Vector3(125.0, 136.0, 32.0)
entity_id = editor.ToolsApplicationRequestBus(
bus.Broadcast, "CreateNewEntityAtPosition", entity_position, entity.EntityId()
)
if entity_id.IsValid():
print("Entity Created")
Report.critical_result(Tests.entity_created, entity_id.IsValid())
# 3) Select the newly created entity
general.select_object("Entity2")
general.select_object("Entity1")
# Give the Entity Inspector time to fully create its contents
general.idle_wait(0.5)
@@ -100,11 +109,11 @@ class AddDeleteComponentsTest(EditorTestHelper):
entity_inspector = editor_window.findChild(QtWidgets.QDockWidget, "Entity Inspector")
add_comp_btn = entity_inspector.findChild(QtWidgets.QPushButton, "m_addComponentButton")
await add_component("Box Shape")
print(f"Box Shape Component added: {hydra.has_components(entity_id, ['Box Shape'])}")
Report.result(Tests.box_component_added, hydra.has_components(entity_id, ['Box Shape']))
# 5) Add/verify Mesh component
await add_component("Mesh")
print(f"Mesh Component added: {hydra.has_components(entity_id, ['Mesh'])}")
Report.result(Tests.mesh_component_added, hydra.has_components(entity_id, ['Mesh']))
# 6) Delete Mesh Component
general.idle_wait(0.5)
@@ -116,15 +125,17 @@ class AddDeleteComponentsTest(EditorTestHelper):
QtTest.QTest.mouseClick(mesh_frame, Qt.LeftButton, Qt.NoModifier)
QtTest.QTest.keyClick(mesh_frame, Qt.Key_Delete, Qt.NoModifier)
success = await pyside_utils.wait_for_condition(lambda: not hydra.has_components(entity_id, ['Mesh']), 5.0)
if success:
print(f"Mesh Component deleted: {not hydra.has_components(entity_id, ['Mesh'])}")
Report.result(Tests.mesh_component_deleted, success)
# 7) Undo deletion of component
QtTest.QTest.keyPress(entity_inspector, Qt.Key_Z, Qt.ControlModifier)
success = await pyside_utils.wait_for_condition(lambda: hydra.has_components(entity_id, ['Mesh']), 5.0)
if success:
print(f"Mesh Component deletion undone: {hydra.has_components(entity_id, ['Mesh'])}")
Report.result(Tests.mesh_component_delete_undo, success)
run_test()
test = AddDeleteComponentsTest()
test.run()
if __name__ == "__main__":
from editor_python_test_tools.utils import Report
Report.start_test(ComponentCRUD_Add_Delete_Components)
@@ -7,27 +7,32 @@ SPDX-License-Identifier: Apache-2.0 OR MIT
C6376081: Basic Function: Docked/Undocked Tools
"""
import os
import sys
from PySide2 import QtWidgets, QtTest, QtCore
import azlmbr.legacy.general as general
import azlmbr.bus as bus
import azlmbr.editor as editor
import azlmbr.entity as entity
import azlmbr.paths
sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests'))
from editor_python_test_tools.editor_test_helper import EditorTestHelper
import editor_python_test_tools.pyside_utils as pyside_utils
class Tests:
all_tools_docked = (
"The tools are all docked together in a tabbed widget",
"Failed to dock all tools together"
)
docked_outliner_works = (
"Entity Outliner works when docked, can select an Entity",
"Failed to select an Entity in the Outliner while docked"
)
docked_inspector_works = (
"Entity Inspector works when docked, Entity name changed",
"Failed to change Entity name in the Inspector while docked"
)
docked_console_works = (
"Console works when docked, sent a Console Command",
"Failed to send Console Command in the Console while docked"
)
class TestDockingBasicDockedTools(EditorTestHelper):
def __init__(self):
EditorTestHelper.__init__(self, log_prefix="Docking_BasicDockedTools", args=["level"])
def Docking_BasicDockedTools():
import editor_python_test_tools.pyside_utils as pyside_utils
@pyside_utils.wrap_async
async def run_test(self):
async def run_test():
"""
Summary:
Test that tools still work as expected when docked together.
@@ -50,14 +55,19 @@ class TestDockingBasicDockedTools(EditorTestHelper):
:return: None
"""
# Create a level since we are going to be dealing with an Entity.
self.create_level(
self.args["level"],
heightmap_resolution=1024,
heightmap_meters_per_pixel=1,
terrain_texture_resolution=4096,
use_terrain=False,
)
from PySide2 import QtWidgets, QtTest, QtCore
import azlmbr.legacy.general as general
import azlmbr.bus as bus
import azlmbr.editor as editor
import azlmbr.entity as entity
from editor_python_test_tools.utils import Report
from editor_python_test_tools.utils import TestHelper as helper
# Open an existing simple level
helper.init_idle()
helper.open_level("Physics", "Base")
# Make sure the Entity Outliner, Entity Inspector and Console tools are open
general.open_pane("Entity Outliner (PREVIEW)")
@@ -101,12 +111,14 @@ class TestDockingBasicDockedTools(EditorTestHelper):
entity_inspector_parent = entity_inspector.parentWidget()
entity_outliner_parent = entity_outliner.parentWidget()
console_parent = console.parentWidget()
print(f"Entity Inspector parent = {entity_inspector_parent}, Entity Outliner parent = {entity_outliner_parent}, Console parent = {console_parent}")
return isinstance(entity_inspector_parent, QtWidgets.QStackedWidget) and (entity_inspector_parent == entity_outliner_parent) and (entity_outliner_parent == console_parent)
Report.info(f"Entity Inspector parent = {entity_inspector_parent}, Entity Outliner parent = "
f"{entity_outliner_parent}, Console parent = {console_parent}")
return isinstance(entity_inspector_parent, QtWidgets.QStackedWidget) and \
(entity_inspector_parent == entity_outliner_parent) and \
(entity_outliner_parent == console_parent)
success = await pyside_utils.wait_for(check_all_panes_tabbed, timeout=3.0)
if success:
print("The tools are all docked together in a tabbed widget")
Report.result(Tests.all_tools_docked, success)
# 2.1,2) Select an Entity in the Entity Outliner.
entity_inspector = editor_window.findChild(QtWidgets.QDockWidget, "Entity Inspector")
@@ -116,8 +128,7 @@ class TestDockingBasicDockedTools(EditorTestHelper):
test_entity_index = pyside_utils.find_child_by_pattern(object_tree, entity_original_name)
object_tree.clearSelection()
object_tree.setCurrentIndex(test_entity_index)
if object_tree.currentIndex():
print("Entity Outliner works when docked, can select an Entity")
Report.result(Tests.docked_outliner_works, object_tree.currentIndex() == test_entity_index)
# 2.3,4) Change the name of the selected Entity via the Entity Inspector.
entity_inspector_name_field = entity_inspector.findChild(QtWidgets.QLineEdit, "m_entityNameEditor")
@@ -125,14 +136,23 @@ class TestDockingBasicDockedTools(EditorTestHelper):
entity_inspector_name_field.setText(expected_new_name)
QtTest.QTest.keyClick(entity_inspector_name_field, QtCore.Qt.Key_Enter)
entity_new_name = editor.EditorEntityInfoRequestBus(bus.Event, "GetName", entity_id)
if entity_new_name == expected_new_name:
print(f"Entity Inspector works when docked, Entity name changed to {entity_new_name}")
Report.result(Tests.docked_inspector_works, entity_new_name == expected_new_name)
# 2.5,6) Send a console command.
console_line_edit = console.findChild(QtWidgets.QLineEdit, "lineEdit")
console_line_edit.setText("Hello, world!")
console_line_edit.setText("t_Scale 2")
QtTest.QTest.keyClick(console_line_edit, QtCore.Qt.Key_Enter)
general.get_cvar("t_Scale")
Report.result(Tests.docked_console_works, general.get_cvar("t_Scale") == "2")
# Reset the altered cvar
console_line_edit.setText("t_Scale 1")
QtTest.QTest.keyClick(console_line_edit, QtCore.Qt.Key_Enter)
run_test()
test = TestDockingBasicDockedTools()
test.run()
if __name__ == "__main__":
from editor_python_test_tools.utils import Report
Report.start_test(Docking_BasicDockedTools)
@@ -5,32 +5,36 @@ For complete copyright and license terms please see the LICENSE at the root of t
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
"""
C1506881: Adding/Removing Event Groups
"""
import os
import sys
from PySide2 import QtWidgets
class Tests:
asset_editor_opened = (
"Successfully opened the Asset Editor",
"Failed to open the Asset Editor"
)
event_groups_added = (
"Successfully added event groups via +",
"Failed to add event groups"
)
single_event_group_deleted = (
"Successfully deleted an event group",
"Failed to delete event group"
)
all_event_groups_deleted = (
"Successfully deleted all event groups",
"Failed to delete all event groups"
)
asset_editor_closed = (
"Successfully closed the Asset Editor",
"Failed to close the Asset Editor"
)
import azlmbr.legacy.general as general
import azlmbr.bus as bus
import azlmbr.editor as editor
import azlmbr.entity as entity
import azlmbr.math as math
import azlmbr.paths
sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests'))
import editor_python_test_tools.hydra_editor_utils as hydra
import editor_python_test_tools.pyside_utils as pyside_utils
from editor_python_test_tools.editor_test_helper import EditorTestHelper
def InputBindings_Add_Remove_Input_Events():
class AddRemoveInputEventsTest(EditorTestHelper):
def __init__(self):
EditorTestHelper.__init__(self, log_prefix="InputBindings_Add_Remove_Input_Events", args=["level"])
import editor_python_test_tools.pyside_utils as pyside_utils
@pyside_utils.wrap_async
async def run_test(self):
async def run_test():
"""
Summary:
Verify if we are able add/remove input events in inputbindings file.
@@ -42,7 +46,7 @@ class AddRemoveInputEventsTest(EditorTestHelper):
Test Steps:
1) Open a new level
1) Open an existing level
2) Open Asset Editor
3) Access Asset Editor
4) Create a new .inputbindings file and add event groups
@@ -61,6 +65,13 @@ class AddRemoveInputEventsTest(EditorTestHelper):
:return: None
"""
from PySide2 import QtWidgets
import azlmbr.legacy.general as general
from editor_python_test_tools.utils import Report
from editor_python_test_tools.utils import TestHelper as helper
def open_asset_editor():
general.open_pane("Asset Editor")
return general.is_pane_visible("Asset Editor")
@@ -69,17 +80,12 @@ class AddRemoveInputEventsTest(EditorTestHelper):
general.close_pane("Asset Editor")
return not general.is_pane_visible("Asset Editor")
# 1) Open a new level
self.test_success = self.create_level(
self.args["level"],
heightmap_resolution=1024,
heightmap_meters_per_pixel=1,
terrain_texture_resolution=4096,
use_terrain=False,
)
# 1) Open an existing simple level
helper.init_idle()
helper.open_level("Physics", "Base")
# 2) Open Asset Editor
print(f"Asset Editor opened: {open_asset_editor()}")
Report.result(Tests.asset_editor_opened, open_asset_editor())
# 3) Access Asset Editor
editor_window = pyside_utils.get_editor_main_window()
@@ -103,8 +109,7 @@ class AddRemoveInputEventsTest(EditorTestHelper):
# 5) Verify if there are 3 elements in the Input Event Groups label
no_of_elements_label = input_event_groups.findChild(QtWidgets.QLabel, "DefaultLabel")
success = await pyside_utils.wait_for_condition(lambda: "3 elements" in no_of_elements_label.text(), 2.0)
if success:
print("New Event Groups added when + is clicked")
Report.result(Tests.event_groups_added, success)
# 6) Delete one event group
event = asset_editor_widget.findChildren(QtWidgets.QFrame, "<Unspecified Event>")[0]
@@ -121,11 +126,11 @@ class AddRemoveInputEventsTest(EditorTestHelper):
input_event_group = input_event_groups[1]
no_of_elements_label = input_event_group.findChild(QtWidgets.QLabel, "DefaultLabel")
return no_of_elements_label.text()
return ""
return "";
success = await pyside_utils.wait_for_condition(lambda: "2 elements" in get_elements_label_text(asset_editor_widget), 2.0)
if success:
print("Event Group deleted when the Delete button is clicked on an Event Group")
success = await pyside_utils.wait_for_condition(lambda: "2 elements" in
get_elements_label_text(asset_editor_widget), 2.0)
Report.result(Tests.single_event_group_deleted, success)
# 8) Click on Delete button to delete all the Event Groups
# First QToolButton child of active input_event_groups is +, Second QToolButton is Delete
@@ -141,13 +146,17 @@ class AddRemoveInputEventsTest(EditorTestHelper):
yes_button.click()
# 9) Verify if all the elements are deleted
success = await pyside_utils.wait_for_condition(lambda: "0 elements" in get_elements_label_text(asset_editor_widget), 2.0)
if success:
print("All event groups deleted on clicking the Delete button")
success = await pyside_utils.wait_for_condition(lambda: "0 elements" in
get_elements_label_text(asset_editor_widget), 2.0)
Report.result(Tests.all_event_groups_deleted, success)
# 10) Close Asset Editor
print(f"Asset Editor closed: {close_asset_editor()}")
Report.result(Tests.asset_editor_closed, close_asset_editor())
run_test()
test = AddRemoveInputEventsTest()
test.run()
if __name__ == "__main__":
from editor_python_test_tools.utils import Report
Report.start_test(InputBindings_Add_Remove_Input_Events)
@@ -5,93 +5,78 @@ For complete copyright and license terms please see the LICENSE at the root of t
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
"""
C24064529: Base Edit Menu Options
"""
import os
import sys
def Menus_EditMenuOptions_Work():
"""
Summary:
Interact with Edit Menu options and verify if all the options are working.
import azlmbr.paths
Expected Behavior:
The Edit menu functions normally.
sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests'))
from editor_python_test_tools.editor_test_helper import EditorTestHelper
import editor_python_test_tools.pyside_utils as pyside_utils
Test Steps:
1) Open an existing level
2) Interact with Edit Menu options
Note:
- This test file must be called from the O3DE Editor command terminal
- Any passed and failed tests are written to the Editor.log file.
Parsing the file or running a log_monitor are required to observe the test results.
class TestEditMenuOptions(EditorTestHelper):
def __init__(self):
EditorTestHelper.__init__(self, log_prefix="Menus_EditMenuOptions", args=["level"])
:return: None
"""
def run_test(self):
"""
Summary:
Interact with Edit Menu options and verify if all the options are working.
import editor_python_test_tools.pyside_utils as pyside_utils
from editor_python_test_tools.utils import Report
from editor_python_test_tools.utils import TestHelper as helper
Expected Behavior:
The Edit menu functions normally.
edit_menu_options = [
("Undo",),
("Redo",),
("Duplicate",),
("Delete",),
("Select All",),
("Invert Selection",),
("Toggle Pivot Location",),
("Reset Entity Transform",),
("Reset Manipulator",),
("Reset Transform (Local)",),
("Reset Transform (World)",),
("Hide Selection",),
("Show All",),
("Modify", "Snap", "Snap angle"),
("Modify", "Transform Mode", "Move"),
("Modify", "Transform Mode", "Rotate"),
("Modify", "Transform Mode", "Scale"),
("Editor Settings", "Global Preferences"),
("Editor Settings", "Editor Settings Manager"),
("Editor Settings", "Keyboard Customization", "Customize Keyboard"),
("Editor Settings", "Keyboard Customization", "Export Keyboard Settings"),
("Editor Settings", "Keyboard Customization", "Import Keyboard Settings"),
]
Test Steps:
1) Create a temp level
2) Interact with Edit Menu options
# 1) Open an existing simple level
helper.init_idle()
helper.open_level("Physics", "Base")
Note:
- This test file must be called from the O3DE Editor command terminal
- Any passed and failed tests are written to the Editor.log file.
Parsing the file or running a log_monitor are required to observe the test results.
:return: None
"""
edit_menu_options = [
("Undo",),
("Redo",),
("Duplicate",),
("Delete",),
("Select All",),
("Invert Selection",),
("Toggle Pivot Location",),
("Reset Entity Transform",),
("Reset Manipulator",),
("Reset Transform (Local)",),
("Reset Transform (World)",),
("Hide Selection",),
("Show All",),
("Modify", "Snap", "Snap angle"),
("Modify", "Transform Mode", "Move"),
("Modify", "Transform Mode", "Rotate"),
("Modify", "Transform Mode", "Scale"),
("Editor Settings", "Global Preferences"),
("Editor Settings", "Editor Settings Manager"),
("Editor Settings", "Keyboard Customization", "Customize Keyboard"),
("Editor Settings", "Keyboard Customization", "Export Keyboard Settings"),
("Editor Settings", "Keyboard Customization", "Import Keyboard Settings"),
]
# 1) Create and open the temp level
self.test_success = self.create_level(
self.args["level"],
heightmap_resolution=1024,
heightmap_meters_per_pixel=1,
terrain_texture_resolution=4096,
use_terrain=False,
)
def on_action_triggered(action_name):
print(f"{action_name} Action triggered")
# 2) Interact with Edit Menu options
# 2) Interact with Edit Menu options
editor_window = pyside_utils.get_editor_main_window()
for option in edit_menu_options:
try:
editor_window = pyside_utils.get_editor_main_window()
for option in edit_menu_options:
action = pyside_utils.get_action_for_menu_path(editor_window, "Edit", *option)
trig_func = lambda: on_action_triggered(action.iconText())
action.triggered.connect(trig_func)
action.trigger()
action.triggered.disconnect(trig_func)
action = pyside_utils.get_action_for_menu_path(editor_window, "Edit", *option)
action.trigger()
action_triggered = True
except Exception as e:
self.test_success = False
action_triggered = False
print(e)
menu_action_triggered = (
f"{action.iconText()} action triggered successfully",
f"Failed to trigger {action.iconText()} action"
)
Report.result(menu_action_triggered, action_triggered)
test = TestEditMenuOptions()
test.run()
if __name__ == "__main__":
from editor_python_test_tools.utils import Report
Report.start_test(Menus_EditMenuOptions_Work)
@@ -5,80 +5,69 @@ For complete copyright and license terms please see the LICENSE at the root of t
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import os
import sys
import azlmbr.paths
def Menus_FileMenuOptions_Work():
"""
Summary:
Interact with File Menu options and verify if all the options are working.
sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests'))
from editor_python_test_tools.editor_test_helper import EditorTestHelper
import editor_python_test_tools.pyside_utils as pyside_utils
Expected Behavior:
The File menu functions normally.
Test Steps:
1) Open level
2) Interact with File Menu options
class TestFileMenuOptions(EditorTestHelper):
def __init__(self):
EditorTestHelper.__init__(self, log_prefix="file_menu_options: ", args=["level"])
Note:
- This test file must be called from the O3DE Editor command terminal
- Any passed and failed tests are written to the Editor.log file.
Parsing the file or running a log_monitor are required to observe the test results.
def run_test(self):
"""
Summary:
Interact with File Menu options and verify if all the options are working.
:return: None
"""
Expected Behavior:
The File menu functions normally.
import editor_python_test_tools.pyside_utils as pyside_utils
from editor_python_test_tools.utils import Report
from editor_python_test_tools.utils import TestHelper as helper
Test Steps:
1) Open level
2) Interact with File Menu options
file_menu_options = [
("New Level",),
("Open Level",),
("Import",),
("Save",),
("Save As",),
("Save Level Statistics",),
("Edit Project Settings",),
("Edit Platform Settings",),
("New Project",),
("Open Project",),
("Show Log File",),
("Resave All Slices",),
("Exit",),
]
Note:
- This test file must be called from the O3DE Editor command terminal
- Any passed and failed tests are written to the Editor.log file.
Parsing the file or running a log_monitor are required to observe the test results.
# 1) Open an existing simple level
helper.init_idle()
helper.open_level("Physics", "Base")
:return: None
"""
file_menu_options = [
("New Level",),
("Open Level",),
("Import",),
("Save",),
("Save As",),
("Save Level Statistics",),
("Edit Project Settings",),
("Edit Platform Settings",),
("New Project",),
("Open Project",),
("Show Log File",),
("Resave All Slices",),
("Exit",),
]
# 1) Open level
self.test_success = self.create_level(
self.args["level"],
heightmap_resolution=1024,
heightmap_meters_per_pixel=1,
terrain_texture_resolution=4096,
use_terrain=False,
)
def on_action_triggered(action_name):
print(f"{action_name} Action triggered")
# 2) Interact with File Menu options
# 2) Interact with File Menu options
editor_window = pyside_utils.get_editor_main_window()
for option in file_menu_options:
try:
editor_window = pyside_utils.get_editor_main_window()
for option in file_menu_options:
action = pyside_utils.get_action_for_menu_path(editor_window, "File", *option)
trig_func = lambda: on_action_triggered(action.iconText())
action.triggered.connect(trig_func)
action.trigger()
action.triggered.disconnect(trig_func)
action = pyside_utils.get_action_for_menu_path(editor_window, "File", *option)
action.trigger()
action_triggered = True
except Exception as e:
self.test_success = False
action_triggered = False
print(e)
menu_action_triggered = (
f"{action.iconText()} action triggered successfully",
f"Failed to trigger {action.iconText()} action"
)
Report.result(menu_action_triggered, action_triggered)
test = TestFileMenuOptions()
test.run()
if __name__ == "__main__":
from editor_python_test_tools.utils import Report
Report.start_test(Menus_FileMenuOptions_Work)
@@ -5,81 +5,66 @@ For complete copyright and license terms please see the LICENSE at the root of t
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
"""
C24064534: The View menu options function normally
"""
import os
import sys
def Menus_ViewMenuOptions_Work():
"""
Summary:
Interact with View Menu options and verify if all the options are working.
import azlmbr.paths
Expected Behavior:
The View menu functions normally.
sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests'))
from editor_python_test_tools.editor_test_helper import EditorTestHelper
import editor_python_test_tools.pyside_utils as pyside_utils
Test Steps:
1) Open an existing level
2) Interact with View Menu options
Note:
- This test file must be called from the O3DE Editor command terminal
- Any passed and failed tests are written to the Editor.log file.
Parsing the file or running a log_monitor are required to observe the test results.
class TestViewMenuOptions(EditorTestHelper):
def __init__(self):
EditorTestHelper.__init__(self, log_prefix="Menus_EditMenuOptions", args=["level"])
:return: None
"""
def run_test(self):
"""
Summary:
Interact with View Menu options and verify if all the options are working.
import editor_python_test_tools.pyside_utils as pyside_utils
from editor_python_test_tools.utils import Report
from editor_python_test_tools.utils import TestHelper as helper
Expected Behavior:
The View menu functions normally.
view_menu_options = [
("Center on Selection",),
("Show Quick Access Bar",),
("Viewport", "Configure Layout"),
("Viewport", "Go to Position"),
("Viewport", "Center on Selection"),
("Viewport", "Go to Location"),
("Viewport", "Remember Location"),
("Viewport", "Switch Camera"),
("Viewport", "Show/Hide Helpers"),
("Refresh Style",),
]
Test Steps:
1) Create a temp level
2) Interact with View Menu options
# 1) Open an existing simple level
helper.init_idle()
helper.open_level("Physics", "Base")
Note:
- This test file must be called from the O3DE Editor command terminal
- Any passed and failed tests are written to the Editor.log file.
Parsing the file or running a log_monitor are required to observe the test results.
:return: None
"""
view_menu_options = [
("Center on Selection",),
("Show Quick Access Bar",),
("Viewport", "Configure Layout"),
("Viewport", "Go to Position"),
("Viewport", "Center on Selection"),
("Viewport", "Go to Location"),
("Viewport", "Remember Location"),
("Viewport", "Switch Camera"),
("Viewport", "Show/Hide Helpers"),
("Refresh Style",),
]
# 1) Create and open the temp level
self.test_success = self.create_level(
self.args["level"],
heightmap_resolution=1024,
heightmap_meters_per_pixel=1,
terrain_texture_resolution=4096,
use_terrain=False,
)
def on_action_triggered(action_name):
print(f"{action_name} Action triggered")
# 2) Interact with View Menu options
# 2) Interact with View Menu options
editor_window = pyside_utils.get_editor_main_window()
for option in view_menu_options:
try:
editor_window = pyside_utils.get_editor_main_window()
for option in view_menu_options:
action = pyside_utils.get_action_for_menu_path(editor_window, "View", *option)
trig_func = lambda: on_action_triggered(action.iconText())
action.triggered.connect(trig_func)
action.trigger()
action.triggered.disconnect(trig_func)
action = pyside_utils.get_action_for_menu_path(editor_window, "View", *option)
action.trigger()
action_triggered = True
except Exception as e:
self.test_success = False
action_triggered = False
print(e)
menu_action_triggered = (
f"{action.iconText()} action triggered successfully",
f"Failed to trigger {action.iconText()} action"
)
Report.result(menu_action_triggered, action_triggered)
test = TestViewMenuOptions()
test.run()
if __name__ == "__main__":
from editor_python_test_tools.utils import Report
Report.start_test(Menus_ViewMenuOptions_Work)
@@ -0,0 +1,43 @@
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import os
import pytest
import sys
import ly_test_tools.environment.file_system as file_system
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared')
from base import TestAutomationBase
@pytest.fixture
def remove_test_level(request, workspace, project):
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", "tmp_level")], True, True)
def teardown():
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", "tmp_level")], True, True)
request.addfinalizer(teardown)
@pytest.mark.SUITE_main
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
@pytest.mark.parametrize("project", ["AutomatedTesting"])
class TestAutomation(TestAutomationBase):
def test_BasicEditorWorkflows_LevelEntityComponentCRUD(self, request, workspace, editor, launcher_platform,
remove_test_level):
from .EditorScripts import BasicEditorWorkflows_LevelEntityComponentCRUD as test_module
self._run_test(request, workspace, editor, test_module, batch_mode=False, autotest_mode=False)
@pytest.mark.REQUIRES_gpu
def test_BasicEditorWorkflows_GPU_LevelEntityComponentCRUD(self, request, workspace, editor, launcher_platform,
remove_test_level):
from .EditorScripts import BasicEditorWorkflows_LevelEntityComponentCRUD as test_module
self._run_test(request, workspace, editor, test_module, batch_mode=False, autotest_mode=False,
use_null_renderer=False)
@@ -0,0 +1,75 @@
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import os
import pytest
import ly_test_tools.environment.file_system as file_system
from ly_test_tools.o3de.editor_test import EditorSingleTest, EditorSharedTest, EditorParallelTest, EditorTestSuite
@pytest.mark.xfail(reason="Optimized tests are experimental, we will enable xfail and monitor them temporarily.")
@pytest.mark.SUITE_main
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
@pytest.mark.parametrize("project", ["AutomatedTesting"])
class TestAutomationNoAutoTestMode(EditorTestSuite):
# Disable -autotest_mode and -BatchMode. Tests cannot run in -BatchMode due to UI interactions, and these tests
# interact with modal dialogs
global_extra_cmdline_args = []
class test_BasicEditorWorkflows_LevelEntityComponentCRUD(EditorSingleTest):
# Custom teardown to remove slice asset created during test
def teardown(self, request, workspace, editor, editor_test_results, launcher_platform):
file_system.delete([os.path.join(workspace.paths.engine_root(), "AutomatedTesting", "Levels", "tmp_level")],
True, True)
from .EditorScripts import BasicEditorWorkflows_LevelEntityComponentCRUD as test_module
@pytest.mark.REQUIRES_gpu
class test_BasicEditorWorkflows_GPU_LevelEntityComponentCRUD(EditorSingleTest):
# Disable null renderer
use_null_renderer = False
# Custom teardown to remove slice asset created during test
def teardown(self, request, workspace, editor, editor_test_results, launcher_platform):
file_system.delete([os.path.join(workspace.paths.engine_root(), "AutomatedTesting", "Levels", "tmp_level")],
True, True)
from .EditorScripts import BasicEditorWorkflows_LevelEntityComponentCRUD as test_module
class test_InputBindings_Add_Remove_Input_Events(EditorSharedTest):
from .EditorScripts import InputBindings_Add_Remove_Input_Events as test_module
@pytest.mark.skip(reason="Crashes Editor: ATOM-15493")
class test_AssetPicker_UI_UX(EditorSharedTest):
from .EditorScripts import AssetPicker_UI_UX as test_module
@pytest.mark.xfail(reason="Optimized tests are experimental, we will enable xfail and monitor them temporarily.")
@pytest.mark.SUITE_main
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
@pytest.mark.parametrize("project", ["AutomatedTesting"])
class TestAutomationAutoTestMode(EditorTestSuite):
# Enable only -autotest_mode for these tests. Tests cannot run in -BatchMode due to UI interactions
global_extra_cmdline_args = ["-autotest_mode"]
class test_AssetBrowser_TreeNavigation(EditorSharedTest):
from .EditorScripts import AssetBrowser_TreeNavigation as test_module
@pytest.mark.skip(reason="Crashes Editor: ATOM-15493")
class test_AssetBrowser_SearchFiltering(EditorSharedTest):
from .EditorScripts import AssetBrowser_SearchFiltering as test_module
class test_ComponentCRUD_Add_Delete_Components(EditorSharedTest):
from .EditorScripts import ComponentCRUD_Add_Delete_Components as test_module
class test_Menus_ViewMenuOptions_Work(EditorSharedTest):
from .EditorScripts import Menus_ViewMenuOptions as test_module
@pytest.mark.skip(reason="Times out due to dialogs failing to dismiss: LYN-4208")
class test_Menus_FileMenuOptions_Work(EditorSharedTest):
from .EditorScripts import Menus_FileMenuOptions as test_module
@@ -0,0 +1,62 @@
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import os
import pytest
import sys
import ly_test_tools.environment.file_system as file_system
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared')
from base import TestAutomationBase
@pytest.fixture
def remove_test_level(request, workspace, project):
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", "tmp_level")], True, True)
def teardown():
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", "tmp_level")], True, True)
request.addfinalizer(teardown)
@pytest.mark.SUITE_periodic
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
@pytest.mark.parametrize("project", ["AutomatedTesting"])
class TestAutomation(TestAutomationBase):
def test_AssetBrowser_TreeNavigation(self, request, workspace, editor, launcher_platform):
from .EditorScripts import AssetBrowser_TreeNavigation as test_module
self._run_test(request, workspace, editor, test_module, batch_mode=False)
@pytest.mark.skip(reason="Crashes Editor: ATOM-15493")
def test_AssetBrowser_SearchFiltering(self, request, workspace, editor, launcher_platform):
from .EditorScripts import AssetBrowser_SearchFiltering as test_module
self._run_test(request, workspace, editor, test_module, batch_mode=False)
@pytest.mark.skip(reason="Crashes Editor: ATOM-15493")
def test_AssetPicker_UI_UX(self, request, workspace, editor, launcher_platform):
from .EditorScripts import AssetPicker_UI_UX as test_module
self._run_test(request, workspace, editor, test_module, autotest_mode=False, batch_mode=False)
def test_ComponentCRUD_Add_Delete_Components(self, request, workspace, editor, launcher_platform):
from .EditorScripts import ComponentCRUD_Add_Delete_Components as test_module
self._run_test(request, workspace, editor, test_module, batch_mode=False)
def test_InputBindings_Add_Remove_Input_Events(self, request, workspace, editor, launcher_platform):
from .EditorScripts import InputBindings_Add_Remove_Input_Events as test_module
self._run_test(request, workspace, editor, test_module, batch_mode=False, autotest_mode=False)
def test_Menus_ViewMenuOptions_Work(self, request, workspace, editor, launcher_platform):
from .EditorScripts import Menus_ViewMenuOptions as test_module
self._run_test(request, workspace, editor, test_module, batch_mode=False)
@pytest.mark.skip(reason="Times out due to dialogs failing to dismiss: LYN-4208")
def test_Menus_FileMenuOptions_Work(self, request, workspace, editor, launcher_platform):
from .EditorScripts import Menus_FileMenuOptions as test_module
self._run_test(request, workspace, editor, test_module, batch_mode=False)
@@ -0,0 +1,27 @@
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import os
import pytest
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared')
from base import TestAutomationBase
@pytest.mark.SUITE_sandbox
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
@pytest.mark.parametrize("project", ["AutomatedTesting"])
class TestAutomation(TestAutomationBase):
def test_Menus_EditMenuOptions_Work(self, request, workspace, editor, launcher_platform):
from .EditorScripts import Menus_EditMenuOptions as test_module
self._run_test(request, workspace, editor, test_module, batch_mode=False)
def test_Docking_BasicDockedTools(self, request, workspace, editor, launcher_platform):
from .EditorScripts import Docking_BasicDockedTools as test_module
self._run_test(request, workspace, editor, test_module, batch_mode=False)
@@ -0,0 +1,27 @@
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import os
import pytest
from ly_test_tools.o3de.editor_test import EditorSingleTest, EditorSharedTest, EditorParallelTest, EditorTestSuite
@pytest.mark.xfail(reason="Optimized tests are experimental, we will enable xfail and monitor them temporarily.")
@pytest.mark.SUITE_sandbox
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
@pytest.mark.parametrize("project", ["AutomatedTesting"])
class TestAutomationAutoTestMode(EditorTestSuite):
# Enable only -autotest_mode for these tests. Tests cannot run in -BatchMode due to UI interactions
global_extra_cmdline_args = ["-autotest_mode"]
class test_Docking_BasicDockedTools(EditorSharedTest):
from .EditorScripts import Docking_BasicDockedTools as test_module
class test_Menus_EditMenuOptions_Work(EditorSharedTest):
from .EditorScripts import Menus_EditMenuOptions as test_module
@@ -1,89 +0,0 @@
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
"""
C13660195: Asset Browser - File Tree Navigation
"""
import os
import pytest
# Bail on the test if ly_test_tools doesn't exist.
pytest.importorskip('ly_test_tools')
import ly_test_tools.environment.file_system as file_system
import editor_python_test_tools.hydra_test_utils as hydra
test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts")
log_monitor_timeout = 180
@pytest.mark.parametrize('project', ['AutomatedTesting'])
@pytest.mark.parametrize('level', ['tmp_level'])
@pytest.mark.usefixtures("automatic_process_killer")
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
class TestAssetBrowser(object):
@pytest.fixture(autouse=True)
def setup_teardown(self, request, workspace, project, level):
def teardown():
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
request.addfinalizer(teardown)
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
@pytest.mark.test_case_id("C13660195")
@pytest.mark.SUITE_periodic
def test_AssetBrowser_TreeNavigation(self, request, editor, level, launcher_platform):
expected_lines = [
"Collapse/Expand tests: True",
"Asset visibility test: True",
"Scrollbar visibility test: True",
"AssetBrowser_TreeNavigation: result=SUCCESS"
]
hydra.launch_and_validate_results(
request,
test_directory,
editor,
"AssetBrowser_TreeNavigation.py",
expected_lines,
run_python="--runpython",
cfg_args=[level],
timeout=log_monitor_timeout
)
@pytest.mark.test_case_id("C13660194")
@pytest.mark.SUITE_periodic
def test_AssetBrowser_SearchFiltering(self, request, editor, level, launcher_platform):
expected_lines = [
"cedar.fbx asset is filtered in Asset Browser",
"Animation file type(s) is present in the file tree: True",
"FileTag file type(s) and Animation file type(s) is present in the file tree: True",
"FileTag file type(s) is present in the file tree after removing Animation filter: True",
]
unexpected_lines = [
"Asset Browser opened: False",
"Animation file type(s) is present in the file tree: False",
"FileTag file type(s) and Animation file type(s) is present in the file tree: False",
"FileTag file type(s) is present in the file tree after removing Animation filter: False",
]
hydra.launch_and_validate_results(
request,
test_directory,
editor,
"AssetBrowser_SearchFiltering.py",
expected_lines,
unexpected_lines=unexpected_lines,
cfg_args=[level],
auto_test_mode=False,
run_python="--runpython",
timeout=log_monitor_timeout,
)
@@ -1,74 +0,0 @@
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
"""
C13751579: Asset Picker UI/UX
"""
import os
import pytest
# Bail on the test if ly_test_tools doesn't exist.
pytest.importorskip('ly_test_tools')
import ly_test_tools.environment.file_system as file_system
import editor_python_test_tools.hydra_test_utils as hydra
test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts")
log_monitor_timeout = 90
@pytest.mark.parametrize('project', ['AutomatedTesting'])
@pytest.mark.parametrize('level', ['tmp_level'])
@pytest.mark.usefixtures("automatic_process_killer")
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
class TestAssetPicker(object):
@pytest.fixture(autouse=True)
def setup_teardown(self, request, workspace, project, level):
def teardown():
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
request.addfinalizer(teardown)
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
@pytest.mark.test_case_id("C13751579", "C1508814")
@pytest.mark.SUITE_periodic
@pytest.mark.xfail # ATOM-15493
def test_AssetPicker_UI_UX(self, request, editor, level, launcher_platform):
expected_lines = [
"TestEntity Entity successfully created",
"Mesh component was added to entity",
"Entity has a Mesh component",
"Mesh Asset: Asset Picker title for Mesh: Pick ModelAsset",
"Mesh Asset: Scroll Bar is not visible before expanding the tree: True",
"Mesh Asset: Top level folder initially collapsed: True",
"Mesh Asset: Top level folder expanded: True",
"Mesh Asset: Nested folder initially collapsed: True",
"Mesh Asset: Nested folder expanded: True",
"Mesh Asset: Scroll Bar appeared after expanding tree: True",
"Mesh Asset: Nested folder collapsed: True",
"Mesh Asset: Top level folder collapsed: True",
"Mesh Asset: Expected Assets populated in the file picker: True",
"Widget Move Test: True",
"Widget Resize Test: True",
"Asset assigned for ok option: True",
"Asset assigned for enter option: True",
"AssetPicker_UI_UX: result=SUCCESS"
]
hydra.launch_and_validate_results(
request,
test_directory,
editor,
"AssetPicker_UI_UX.py",
expected_lines,
cfg_args=[level],
run_python="--runpython",
auto_test_mode=False,
timeout=log_monitor_timeout,
)
@@ -1,96 +0,0 @@
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import os
import pytest
# Bail on the test if ly_test_tools doesn't exist.
pytest.importorskip('ly_test_tools')
import ly_test_tools.environment.file_system as file_system
import ly_test_tools._internal.pytest_plugin as internal_plugin
import editor_python_test_tools.hydra_test_utils as hydra
test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts")
log_monitor_timeout = 180
@pytest.mark.parametrize('project', ['AutomatedTesting'])
@pytest.mark.parametrize('level', ['tmp_level'])
@pytest.mark.usefixtures("automatic_process_killer")
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
class TestBasicEditorWorkflows(object):
@pytest.fixture(autouse=True)
def setup_teardown(self, request, workspace, project, level):
def teardown():
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
request.addfinalizer(teardown)
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
@pytest.mark.test_case_id("C6351273", "C6384955", "C16929880", "C15167490", "C15167491")
@pytest.mark.SUITE_main
def test_BasicEditorWorkflows_LevelEntityComponentCRUD(self, request, editor, level, launcher_platform):
# Skip test if running against Debug build
if "debug" in internal_plugin.build_directory:
pytest.skip("Does not execute against debug builds.")
expected_lines = [
"Create and load new level: True",
"New entity creation: True",
"Create entity hierarchy: True",
"Add component: True",
"Component update: True",
"Remove component: True",
"Save and Export: True",
"BasicEditorWorkflows_LevelEntityComponent: result=SUCCESS",
]
hydra.launch_and_validate_results(
request,
test_directory,
editor,
"BasicEditorWorkflows_LevelEntityComponentCRUD.py",
expected_lines,
cfg_args=[level],
timeout=log_monitor_timeout,
auto_test_mode=False
)
@pytest.mark.test_case_id("C6351273", "C6384955", "C16929880", "C15167490", "C15167491")
@pytest.mark.SUITE_main
@pytest.mark.REQUIRES_gpu
def test_BasicEditorWorkflows_GPU_LevelEntityComponentCRUD(self, request, editor, level, launcher_platform):
# Skip test if running against Debug build
if "debug" in internal_plugin.build_directory:
pytest.skip("Does not execute against debug builds.")
expected_lines = [
"Create and load new level: True",
"New entity creation: True",
"Create entity hierarchy: True",
"Add component: True",
"Component update: True",
"Remove component: True",
"Save and Export: True",
"BasicEditorWorkflows_LevelEntityComponent: result=SUCCESS",
]
hydra.launch_and_validate_results(
request,
test_directory,
editor,
"BasicEditorWorkflows_LevelEntityComponentCRUD.py",
expected_lines,
cfg_args=[level],
timeout=log_monitor_timeout,
auto_test_mode=False,
null_renderer=False
)
@@ -1,62 +0,0 @@
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
"""
C16929880: Add Delete Components
"""
import os
import pytest
# Bail on the test if ly_test_tools doesn't exist.
pytest.importorskip('ly_test_tools')
import ly_test_tools.environment.file_system as file_system
import editor_python_test_tools.hydra_test_utils as hydra
test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts")
log_monitor_timeout = 180
@pytest.mark.parametrize('project', ['AutomatedTesting'])
@pytest.mark.parametrize('level', ['tmp_level'])
@pytest.mark.usefixtures("automatic_process_killer")
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
class TestComponentCRUD(object):
@pytest.fixture(autouse=True)
def setup_teardown(self, request, workspace, project, level):
def teardown():
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
request.addfinalizer(teardown)
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
@pytest.mark.test_case_id("C16929880", "C16877220")
@pytest.mark.SUITE_periodic
@pytest.mark.BAT
def test_ComponentCRUD_Add_Delete_Components(self, request, editor, level, launcher_platform):
expected_lines = [
"Entity Created",
"Box Shape found",
"Box Shape Component added: True",
"Mesh found",
"Mesh Component added: True",
"Mesh Component deleted: True",
"Mesh Component deletion undone: True",
]
hydra.launch_and_validate_results(
request,
test_directory,
editor,
"ComponentCRUD_Add_Delete_Components.py",
expected_lines,
cfg_args=[level],
auto_test_mode=False,
timeout=log_monitor_timeout
)
@@ -1,55 +0,0 @@
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
C6376081: Basic Function: Docked/Undocked Tools
"""
import os
import pytest
# Bail on the test if ly_test_tools doesn't exist.
pytest.importorskip('ly_test_tools')
import ly_test_tools.environment.file_system as file_system
import editor_python_test_tools.hydra_test_utils as hydra
test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts")
log_monitor_timeout = 180
@pytest.mark.parametrize('project', ['AutomatedTesting'])
@pytest.mark.parametrize('level', ['tmp_level'])
@pytest.mark.usefixtures("automatic_process_killer")
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
class TestDocking(object):
@pytest.fixture(autouse=True)
def setup_teardown(self, request, workspace, project, level):
def teardown():
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
request.addfinalizer(teardown)
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
@pytest.mark.test_case_id("C6376081")
@pytest.mark.SUITE_sandbox
def test_Docking_BasicDockedTools(self, request, editor, level, launcher_platform):
expected_lines = [
"The tools are all docked together in a tabbed widget",
"Entity Outliner works when docked, can select an Entity",
"Entity Inspector works when docked, Entity name changed to DifferentName",
"Hello, world!" # This line verifies the Console is working while docked
]
hydra.launch_and_validate_results(
request,
test_directory,
editor,
"Docking_BasicDockedTools.py",
expected_lines,
cfg_args=[level],
timeout=log_monitor_timeout,
)
@@ -1,66 +0,0 @@
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
"""
C1506881: Adding/Removing Event Groups
"""
import os
import pytest
# Bail on the test if ly_test_tools doesn't exist.
pytest.importorskip('ly_test_tools')
import ly_test_tools.environment.file_system as file_system
import editor_python_test_tools.hydra_test_utils as hydra
test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts")
log_monitor_timeout = 180
@pytest.mark.parametrize('project', ['AutomatedTesting'])
@pytest.mark.parametrize('level', ['tmp_level'])
@pytest.mark.usefixtures("automatic_process_killer")
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
class TestInputBindings(object):
@pytest.fixture(autouse=True)
def setup_teardown(self, request, workspace, project, level):
def teardown():
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
request.addfinalizer(teardown)
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
@pytest.mark.test_case_id("C1506881")
@pytest.mark.SUITE_periodic
def test_InputBindings_Add_Remove_Input_Events(self, request, editor, level, launcher_platform):
expected_lines = [
"Asset Editor opened: True",
"New Event Groups added when + is clicked",
"Event Group deleted when the Delete button is clicked on an Event Group",
"All event groups deleted on clicking the Delete button",
"Asset Editor closed: True",
]
unexpected_lines = [
"Asset Editor opened: False",
"Asset Editor closed: False",
]
hydra.launch_and_validate_results(
request,
test_directory,
editor,
"InputBindings_Add_Remove_Input_Events.py",
expected_lines,
unexpected_lines=unexpected_lines,
cfg_args=[level],
run_python="--runpython",
auto_test_mode=False,
timeout=log_monitor_timeout,
)
@@ -1,132 +0,0 @@
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import os
import pytest
# Bail on the test if ly_test_tools doesn't exist.
pytest.importorskip('ly_test_tools')
import ly_test_tools.environment.file_system as file_system
import ly_test_tools.environment.process_utils as process_utils
import editor_python_test_tools.hydra_test_utils as hydra
test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts")
log_monitor_timeout = 180
@pytest.mark.parametrize('project', ['AutomatedTesting'])
@pytest.mark.parametrize('level', ['tmp_level'])
@pytest.mark.usefixtures("automatic_process_killer")
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
class TestMenus(object):
@pytest.fixture(autouse=True)
def setup_teardown(self, request, workspace, project, level):
def teardown():
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
process_utils.kill_processes_named("o3de", ignore_extensions=True) # Kill ProjectManager windows
request.addfinalizer(teardown)
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
@pytest.mark.test_case_id("C16780783", "C2174438")
@pytest.mark.SUITE_sandbox
def test_Menus_EditMenuOptions_Work(self, request, editor, level, launcher_platform):
expected_lines = [
"Undo Action triggered",
"Redo Action triggered",
"Duplicate Action triggered",
"Delete Action triggered",
"Select All Action triggered",
"Invert Selection Action triggered",
"Toggle Pivot Location Action triggered",
"Reset Entity Transform",
"Reset Manipulator",
"Reset Transform (Local) Action triggered",
"Reset Transform (World) Action triggered",
"Hide Selection Action triggered",
"Show All Action triggered",
"Snap angle Action triggered",
"Move Action triggered",
"Rotate Action triggered",
"Scale Action triggered",
"Global Preferences Action triggered",
"Editor Settings Manager Action triggered",
"Customize Keyboard Action triggered",
"Export Keyboard Settings Action triggered",
"Import Keyboard Settings Action triggered",
"Menus_EditMenuOptions: result=SUCCESS"
]
hydra.launch_and_validate_results(
request,
test_directory,
editor,
"Menus_EditMenuOptions.py",
expected_lines,
cfg_args=[level],
run_python="--runpython",
timeout=log_monitor_timeout
)
@pytest.mark.test_case_id("C16780807")
@pytest.mark.SUITE_periodic
def test_Menus_ViewMenuOptions_Work(self, request, editor, level, launcher_platform):
expected_lines = [
"Center on Selection Action triggered",
"Show Quick Access Bar Action triggered",
"Configure Layout Action triggered",
"Go to Position Action triggered",
"Center on Selection Action triggered",
"Go to Location Action triggered",
"Remember Location Action triggered",
"Switch Camera Action triggered",
"Show/Hide Helpers Action triggered",
"Refresh Style Action triggered",
]
hydra.launch_and_validate_results(
request,
test_directory,
editor,
"Menus_ViewMenuOptions.py",
expected_lines,
cfg_args=[level],
run_python="--runpython",
timeout=log_monitor_timeout
)
@pytest.mark.test_case_id("C16780778")
@pytest.mark.SUITE_sandbox
@pytest.mark.xfail # LYN-4208
def test_Menus_FileMenuOptions_Work(self, request, editor, level, launcher_platform):
expected_lines = [
"New Level Action triggered",
"Open Level Action triggered",
"Import Action triggered",
"Save Action triggered",
"Save As Action triggered",
"Save Level Statistics Action triggered",
"Edit Project Settings Action triggered",
"Edit Platform Settings Action triggered",
"New Project Action triggered",
"Open Project Action triggered",
"Show Log File Action triggered",
"Resave All Slices Action triggered",
"Exit Action triggered",
]
hydra.launch_and_validate_results(
request,
test_directory,
editor,
"Menus_FileMenuOptions.py",
expected_lines,
cfg_args=[level],
run_python="--runpython",
timeout=log_monitor_timeout
)
+1
View File
@@ -14,6 +14,7 @@
#include <QPoint>
#include <QRect>
#include "Cry_Vector2.h"
#include <AzCore/Casting/numeric_cast.h>
//////////////////////////////////////////////////////////////////////////
class CWndGridHelper
-1
View File
@@ -78,7 +78,6 @@ AZ_POP_DISABLE_WARNING
// CryCommon
#include <CryCommon/ITimer.h>
#include <CryCommon/IPhysics.h>
#include <CryCommon/ILevelSystem.h>
// Editor
+10 -71
View File
@@ -54,6 +54,8 @@
// CryCommon
#include <CryCommon/HMDBus.h>
#include <CryCommon/IRenderAuxGeom.h>
#include <CryCommon/physinterface.h>
// AzFramework
#include <AzFramework/Render/IntersectorInterface.h>
@@ -739,9 +741,13 @@ void EditorViewportWidget::OnBeginPrepareRender()
RenderAll();
// Draw 2D helpers.
#ifdef LYSHINE_ATOM_TODO
TransformationMatrices backupSceneMatrices;
#endif
m_debugDisplay->DepthTestOff();
//m_renderer->Set2DMode(m_rcClient.right(), m_rcClient.bottom(), backupSceneMatrices);
#ifdef LYSHINE_ATOM_TODO
m_renderer->Set2DMode(m_rcClient.right(), m_rcClient.bottom(), backupSceneMatrices);
#endif
auto prevState = m_debugDisplay->GetState();
m_debugDisplay->SetState(e_Mode3D | e_AlphaBlended | e_FillModeSolid | e_CullModeBack | e_DepthWriteOn | e_DepthTestOn);
@@ -1283,7 +1289,7 @@ void EditorViewportWidget::SetViewportId(int id)
m_renderViewport->GetControllerList()->Add(AZStd::make_shared<SandboxEditor::ViewportManipulatorController>());
m_renderViewport->GetControllerList()->Add(CreateModularViewportCameraController(AzFramework::ViewportId(id)));
m_renderViewport->SetViewportSettings(&g_EditorViewportSettings);
UpdateScene();
@@ -1643,7 +1649,7 @@ void EditorViewportWidget::SetViewTM(const Matrix34& camMatrix, bool bMoveOnly)
{
// Should be impossible anyways
AZ_Assert(false, "Internal logic error - view entity Id and view source type out of sync. Please report this as a bug");
return ShouldUpdateObject::No;
return ShouldUpdateObject::No;
}
// Check that the current view is the same view as the view entity view
@@ -2008,73 +2014,6 @@ Vec3 EditorViewportWidget::ViewToWorldNormal(const QPoint& vp, bool onlyTerrain,
return Vec3(0, 0, 1);
}
//////////////////////////////////////////////////////////////////////////
bool EditorViewportWidget::AdjustObjectPosition(const ray_hit& hit, Vec3& outNormal, Vec3& outPos) const
{
Matrix34A objMat, objMatInv;
Matrix33 objRot, objRotInv;
if (hit.pCollider->GetiForeignData() != PHYS_FOREIGN_ID_STATIC)
{
return false;
}
IRenderNode* pNode = (IRenderNode*) hit.pCollider->GetForeignData(PHYS_FOREIGN_ID_STATIC);
if (!pNode || !pNode->GetEntityStatObj())
{
return false;
}
IStatObj* pEntObject = pNode->GetEntityStatObj(hit.partid, 0, &objMat, false);
if (!pEntObject || !pEntObject->GetRenderMesh())
{
return false;
}
objRot = Matrix33(objMat);
objRot.NoScale(); // No scale.
objRotInv = objRot;
objRotInv.Invert();
float fWorldScale = objMat.GetColumn(0).GetLength(); // GetScale
float fWorldScaleInv = 1.0f / fWorldScale;
// transform decal into object space
objMatInv = objMat;
objMatInv.Invert();
// put into normal object space hit direction of projection
Vec3 invhitn = -(hit.n);
Vec3 vOS_HitDir = objRotInv.TransformVector(invhitn).GetNormalized();
// put into position object space hit position
Vec3 vOS_HitPos = objMatInv.TransformPoint(hit.pt);
vOS_HitPos -= vOS_HitDir * RENDER_MESH_TEST_DISTANCE * fWorldScaleInv;
IRenderMesh* pRM = pEntObject->GetRenderMesh();
AABB aabbRNode;
pRM->GetBBox(aabbRNode.min, aabbRNode.max);
Vec3 vOut(0, 0, 0);
if (!Intersect::Ray_AABB(Ray(vOS_HitPos, vOS_HitDir), aabbRNode, vOut))
{
return false;
}
if (!pRM || !pRM->GetVerticesCount())
{
return false;
}
if (RayRenderMeshIntersection(pRM, vOS_HitPos, vOS_HitDir, outPos, outNormal))
{
outNormal = objRot.TransformVector(outNormal).GetNormalized();
outPos = objMat.TransformPoint(outPos);
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
bool EditorViewportWidget::RayRenderMeshIntersection(IRenderMesh* pRenderMesh, const Vec3& vInPos, const Vec3& vInDir, Vec3& vOutPos, Vec3& vOutNormal) const
{
@@ -2507,7 +2446,7 @@ void EditorViewportWidget::SetViewFromEntityPerspective(const AZ::EntityId& enti
void EditorViewportWidget::SetViewAndMovementLockFromEntityPerspective(const AZ::EntityId& entityId, [[maybe_unused]] bool lockCameraMovement)
{
// This is an editor event, so is only serviced during edit mode, not play game mode
//
//
if (m_playInEditorState != PlayInEditorState::Editor)
{
AZ_Warning("EditorViewportWidget", false,
-1
View File
@@ -220,7 +220,6 @@ private:
// Draw a selected region if it has been selected
void RenderSelectedRegion();
bool AdjustObjectPosition(const ray_hit& hit, Vec3& outNormal, Vec3& outPos) const;
bool RayRenderMeshIntersection(IRenderMesh* pRenderMesh, const Vec3& vInPos, const Vec3& vInDir, Vec3& vOutPos, Vec3& vOutNormal) const;
bool AddCameraMenuItems(QMenu* menu);
-3
View File
@@ -15,9 +15,6 @@
#pragma once
struct IStatObj;
struct IMaterial;
#include "Include/IIconManager.h" // for IIconManager
#include "IEditor.h" // for IDocListener
-4
View File
@@ -6,8 +6,6 @@
*
*/
#pragma once
#ifndef CRYINCLUDE_EDITOR_INCLUDE_IEDITORMATERIAL_H
#define CRYINCLUDE_EDITOR_INCLUDE_IEDITORMATERIAL_H
#include "BaseLibraryItem.h"
@@ -20,5 +18,3 @@ struct IEditorMaterial
virtual _smart_ptr<IMaterial> GetMatInfo(bool bUseExistingEngineMaterial = false) = 0;
virtual void DisableHighlightForFrame() = 0;
};
#endif
-1
View File
@@ -63,7 +63,6 @@ struct SANDBOX_API DisplayContext
CDisplaySettings* settings;
IDisplayViewport* view;
IRenderer* renderer;
IRenderAuxGeom* pRenderAuxGeom;
IIconManager* pIconManager;
CCamera* camera;
+23 -2
View File
@@ -26,7 +26,6 @@
DisplayContext::DisplayContext()
{
view = 0;
renderer = 0;
flags = 0;
settings = 0;
pIconManager = 0;
@@ -1083,7 +1082,10 @@ void DisplayContext::DrawTerrainLine(Vec3 worldPos1, Vec3 worldPos2)
//////////////////////////////////////////////////////////////////////////
void DisplayContext::DrawTextLabel(const Vec3& pos, float size, const char* text, const bool bCenter, [[maybe_unused]] int srcOffsetX, [[maybe_unused]] int scrOffsetY)
{
ColorF col(m_color4b.r * (1.0f / 255.0f), m_color4b.g * (1.0f / 255.0f), m_color4b.b * (1.0f / 255.0f), m_color4b.a * (1.0f / 255.0f));
AZ_ErrorOnce(nullptr, false, "DisplayContext::DrawTextLabel needs to be removed/ported to use Atom");
#if 0
ColorF col(m_color4b.r * (1.0f / 255.0f), m_color4b.g * (1.0f / 255.0f), m_color4b.b * (1.0f / 255.0f), m_color4b.a * (1.0f / 255.0f));
float fCol[4] = { col.r, col.g, col.b, col.a };
if (flags & DISPLAY_2D)
@@ -1096,13 +1098,28 @@ void DisplayContext::DrawTextLabel(const Vec3& pos, float size, const char* text
{
renderer->DrawLabelEx(pos, size, fCol, true, true, text);
}
#else
AZ_UNUSED(pos);
AZ_UNUSED(size);
AZ_UNUSED(text);
AZ_UNUSED(bCenter);
#endif
}
//////////////////////////////////////////////////////////////////////////
void DisplayContext::Draw2dTextLabel(float x, float y, float size, const char* text, bool bCenter)
{
AZ_ErrorOnce(nullptr, false, "DisplayContext::Draw2dTextLabel needs to be removed/ported to use Atom");
#if 0
float col[4] = { m_color4b.r * (1.0f / 255.0f), m_color4b.g * (1.0f / 255.0f), m_color4b.b * (1.0f / 255.0f), m_color4b.a * (1.0f / 255.0f) };
renderer->Draw2dLabel(x, y, size, col, bCenter, "%s", text);
#else
AZ_UNUSED(x);
AZ_UNUSED(y);
AZ_UNUSED(size);
AZ_UNUSED(text);
AZ_UNUSED(bCenter);
#endif
}
//////////////////////////////////////////////////////////////////////////
@@ -1269,6 +1286,9 @@ void DisplayContext::Flush2D()
int rcw, rch;
view->GetDimensions(&rcw, &rch);
AZ_ErrorOnce(nullptr, false, "DisplayContext::Flush2D needs to be removed/ported to use Atom");
#if 0
TransformationMatrices backupSceneMatrices;
renderer->Set2DMode(rcw, rch, backupSceneMatrices, 0.0f, 1.0f);
@@ -1310,6 +1330,7 @@ void DisplayContext::Flush2D()
}
renderer->Unset2DMode(backupSceneMatrices);
#endif
m_textureLabels.clear();
}
+6 -1
View File
@@ -177,11 +177,15 @@ void CTrackGizmo::DrawAxis(DisplayContext& dc, const Vec3& org)
float col[4] = { 1, 1, 1, 1 };
float hcol[4] = { 1, 0, 0, 1 };
Vec3 colX(1, 0, 0), colY(0, 1, 0), colZ(0, 0, 1);
AZ_ErrorOnce(nullptr, false, "CTrackGizmo::DrawAxis needs to be removed/ported to use Atom");
#if 0
dc.renderer->DrawLabelEx(org + x, 1.2f, col, true, true, "X");
dc.renderer->DrawLabelEx(org + y, 1.2f, col, true, true, "Y");
dc.renderer->DrawLabelEx(org + z, 1.2f, col, true, true, "Z");
Vec3 colX(1, 0, 0), colY(0, 1, 0), colZ(0, 0, 1);
if (s_highlightAxis)
{
float col2[4] = { 1, 0, 0, 1 };
@@ -201,6 +205,7 @@ void CTrackGizmo::DrawAxis(DisplayContext& dc, const Vec3& org)
dc.renderer->DrawLabelEx(org + z, 1.2f, col2, true, true, "Z");
}
}
#endif
x = x * 0.8f;
y = y * 0.8f;
+1
View File
@@ -13,6 +13,7 @@
#include "Include/IEditorClassFactory.h"
#include "Util/GuidUtil.h"
#include <map>
//! Derive from this class to decrease the amount of work for creating a new class description
//! Provides standard reference counter implementation for IUnknown
@@ -40,6 +40,7 @@
#include <LmbrCentral/Rendering/MaterialOwnerBus.h>
#include <IDisplayViewport.h>
#include <CryCommon/Cry_GeoIntersect.h>
#include <MathConversion.h>
#include <TrackView/TrackViewAnimNode.h>
#include <ViewManager.h>
+1 -1
View File
@@ -987,7 +987,7 @@ QString CSettingsManager::GenerateContentHash(XmlNodeRef& node, QString sourceNa
return sourceName;
}
uint32 hash = CCrc32::ComputeLowercase(node->getXML(0));
uint32 hash = AZ::Crc32(node->getXML(0));
hashStr = QString::number(hash);
return hashStr;
@@ -13,6 +13,7 @@
// CryCommon
#include <CryCommon/Maestro/Types/AnimParamType.h>
#include <CryCommon/IFont.h>
// Editor
#include "Settings.h"
+1 -1
View File
@@ -24,7 +24,7 @@ QColor ColorLinearToGamma(ColorF col)
g = (float)(g <= 0.0031308 ? (12.92 * g) : (1.055 * pow((double)g, 1.0 / 2.4) - 0.055));
b = (float)(b <= 0.0031308 ? (12.92 * b) : (1.055 * pow((double)b, 1.0 / 2.4) - 0.055));
return QColor(FtoI(r * 255.0f), FtoI(g * 255.0f), FtoI(b * 255.0f), FtoI(a * 255.0f));
return QColor(int(r * 255.0f), int(g * 255.0f), int(b * 255.0f), int(a * 255.0f));
}
//////////////////////////////////////////////////////////////////////////
+1 -1
View File
@@ -205,7 +205,7 @@ QColor ColorLinearToGamma(ColorF col)
g = (float)(g <= 0.0031308 ? (12.92 * g) : (1.055 * pow((double)g, 1.0 / 2.4) - 0.055));
b = (float)(b <= 0.0031308 ? (12.92 * b) : (1.055 * pow((double)b, 1.0 / 2.4) - 0.055));
return QColor(FtoI(r * 255.0f), FtoI(g * 255.0f), FtoI(b * 255.0f), FtoI(a * 255.0f));
return QColor(int(r * 255.0f), int(g * 255.0f), int(b * 255.0f), int(a * 255.0f));
}
//////////////////////////////////////////////////////////////////////////
+1
View File
@@ -14,6 +14,7 @@
#pragma once
#include <Editor/Util/EditorUtils.h>
#include <CryCommon/Cry_GeoIntersect.h>
//! Half PI
#define PI_HALF (3.1415926535897932384626433832795f / 2.0f)
+1
View File
@@ -9,6 +9,7 @@
#include "StringHelpers.h"
#include "Util.h"
#include <cwctype>
int StringHelpers::CompareIgnoreCase(const AZStd::string& str0, const AZStd::string& str1)
{
+1 -8
View File
@@ -655,7 +655,7 @@ namespace AZ
static void Validate() {}
};
template <class Function, bool IsBindExpression = AZStd::is_bind_expression_v<Function>>
template <class Function>
struct ArgumentValidatorHelper
{
constexpr static void Validate()
@@ -674,13 +674,6 @@ namespace AZ
}
};
// bind has already copied/bound its arguments, we can't validate them further in any reasonable way
template <class Function>
struct ArgumentValidatorHelper<Function, true>
{
constexpr static void Validate() {}
};
template <class Function>
struct QueueFunctionArgumentValidator<Function, false>
{
@@ -9,6 +9,7 @@
#include <AzCore/std/createdestroy.h>
#include <AzCore/std/iterator.h>
#include <AzCore/std/limits.h>
namespace AZStd
-564
View File
@@ -1,564 +0,0 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#ifndef CRYINCLUDE_CRYCOMMON_CRYNAME_H
#define CRYINCLUDE_CRYCOMMON_CRYNAME_H
#pragma once
#include <ISystem.h>
#include <StlUtils.h>
#include <CrySizer.h>
#include <CryCrc32.h>
#include <AzCore/std/containers/unordered_map.h>
class CNameTable;
struct INameTable
{
virtual ~INameTable(){}
// Name entry header, immediately after this header in memory starts actual string data.
struct SNameEntry
{
enum
{
TAG = 0xdeadbeef
};
int nTag; // tag to ensure that this is actually a name entry
// Reference count of this string.
int nRefCount;
// Current length of string.
int nLength;
// Size of memory allocated at the end of this class.
int nAllocSize;
// Here in memory starts character buffer of size nAllocSize.
//char data[nAllocSize]
const char* GetStr() { return (char*)(this + 1); }
void AddRef() { nRefCount++; /*InterlockedIncrement(&_header()->nRefCount);*/};
int Release() { return --nRefCount; };
int GetMemoryUsage() { return static_cast<int>(sizeof(SNameEntry) + strlen(GetStr())); }
int GetLength(){return nLength; }
};
// Finds an existing name table entry, or creates a new one if not found.
virtual INameTable::SNameEntry* GetEntry(const char* str) = 0;
// Only finds an existing name table entry, return 0 if not found.
virtual INameTable::SNameEntry* FindEntry(const char* str) = 0;
// Release existing name table entry.
virtual void Release(SNameEntry* pEntry) = 0;
virtual int GetMemoryUsage() = 0;
virtual int GetNumberOfEntries() = 0;
// Output all names from the table to log.
virtual void LogNames() = 0;
virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0;
};
//////////////////////////////////////////////////////////////////////////
class CNameTable
: public INameTable
{
private:
typedef AZStd::unordered_map<const char*, SNameEntry*, stl::hash_string_caseless<const char*>, stl::equality_string_caseless<const char*> > NameMap;
NameMap m_nameMap;
public:
CNameTable()
{
// Ensure that SNameEntry is an aligned size
static_assert(sizeof(INameTable::SNameEntry) % sizeof(void*) == 0, "SNameEntry must be an aligned size");
}
~CNameTable()
{
for (NameMap::iterator it = m_nameMap.begin(); it != m_nameMap.end(); ++it)
{
CryModuleFree(it->second);
}
}
// Only finds an existing name table entry, return 0 if not found.
virtual INameTable::SNameEntry* FindEntry(const char* str)
{
SNameEntry* pEntry = stl::find_in_map(m_nameMap, str, 0);
return pEntry;
}
// Finds an existing name table entry, or creates a new one if not found.
virtual INameTable::SNameEntry* GetEntry(const char* str)
{
SNameEntry* pEntry = FindEntry(str);
if (!pEntry)
{
// Create a new entry.
size_t nLen = strlen(str);
size_t allocLen = sizeof(SNameEntry) + (nLen + 1) * sizeof(char);
pEntry = (SNameEntry*)CryModuleMalloc(allocLen);
assert(pEntry != NULL);
pEntry->nTag = SNameEntry::TAG;
pEntry->nRefCount = 0;
pEntry->nLength = static_cast<int>(nLen);
pEntry->nAllocSize = static_cast<int>(allocLen);
// Copy string to the end of name entry.
char* pEntryStr = const_cast<char*>(pEntry->GetStr());
memcpy(pEntryStr, str, nLen + 1);
// put in map.
//m_nameMap.insert( NameMap::value_type(pEntry->GetStr(),pEntry) );
m_nameMap[pEntry->GetStr()] = pEntry;
}
return pEntry;
}
// Release existing name table entry.
virtual void Release(SNameEntry* pEntry)
{
assert(pEntry);
m_nameMap.erase(pEntry->GetStr());
CryModuleFree(pEntry);
}
virtual int GetMemoryUsage()
{
int nSize = 0;
NameMap::iterator it;
int n = 0;
for (it = m_nameMap.begin(); it != m_nameMap.end(); it++)
{
nSize += static_cast<int>(strlen(it->first));
nSize += it->second->GetMemoryUsage();
n++;
}
nSize += n * 8;
return nSize;
}
virtual void GetMemoryUsage(ICrySizer* pSizer) const
{
pSizer->AddObject(this, sizeof(*this));
pSizer->AddContainer(m_nameMap);
}
virtual int GetNumberOfEntries()
{
return static_cast<int>(m_nameMap.size());
}
// Log all names inside CryName table.
virtual void LogNames()
{
NameMap::iterator it;
for (it = m_nameMap.begin(); it != m_nameMap.end(); ++it)
{
SNameEntry* pNameEntry = it->second;
CryLog("[%4d] %s", pNameEntry->nLength, pNameEntry->GetStr());
}
}
};
///////////////////////////////////////////////////////////////////////////////
// Class CCryName.
//////////////////////////////////////////////////////////////////////////
class CCryName
{
public:
CCryName();
CCryName(const CCryName& n);
explicit CCryName(const char* s);
CCryName(const char* s, bool bOnlyFind);
~CCryName();
CCryName& operator=(const CCryName& n);
CCryName& operator=(const char* s);
bool operator==(const CCryName& n) const;
bool operator!=(const CCryName& n) const;
bool operator==(const char* s) const;
bool operator!=(const char* s) const;
bool operator<(const CCryName& n) const;
bool operator>(const CCryName& n) const;
bool empty() const { return !m_str || !m_str[0]; }
void reset() { _release(m_str); m_str = 0; }
void addref() { _addref(m_str); }
const char* c_str() const
{
return (m_str) ? m_str : "";
}
int length() const { return _length(); };
static bool find(const char* str) { return GetNameTable()->FindEntry(str) != 0; }
void GetMemoryUsage(ICrySizer* pSizer) const
{
//pSizer->AddObject(m_str);
pSizer->AddObject(GetNameTable()); // cause for slowness?
}
static int GetMemoryUsage()
{
#ifdef USE_STATIC_NAME_TABLE
CNameTable* pTable = GetNameTable();
#else
INameTable* pTable = GetNameTable();
#endif
return pTable->GetMemoryUsage();
}
static int GetNumberOfEntries()
{
#ifdef USE_STATIC_NAME_TABLE
CNameTable* pTable = GetNameTable();
#else
INameTable* pTable = GetNameTable();
#endif
return pTable->GetNumberOfEntries();
}
// Compare functor for sorting CCryNames lexically.
struct CmpLex
{
bool operator () (const CCryName& n1, const CCryName& n2) const
{
return strcmp(n1.c_str(), n2.c_str()) < 0;
}
};
private:
typedef INameTable::SNameEntry SNameEntry;
#ifdef USE_STATIC_NAME_TABLE
static CNameTable* GetNameTable()
{
// Note: can not use a 'static CNameTable sTable' here, because that
// implies a static destruction order depenency - the name table is
// accessed from static destructor calls.
static CNameTable* table = NULL;
if (table == NULL)
{
table = new CNameTable();
}
return table;
}
#else
//static INameTable* GetNameTable() { return GetISystem()->GetINameTable(); }
static INameTable* GetNameTable()
{
assert(gEnv && gEnv->pNameTable);
return gEnv->pNameTable;
}
#endif
SNameEntry* _entry(const char* pBuffer) const
{
CRY_ASSERT(pBuffer);
CRY_ASSERT((((SNameEntry*)pBuffer) - 1)->nTag == SNameEntry::TAG);
return ((SNameEntry*)pBuffer) - 1;
}
void _release(const char* pBuffer)
{
if (pBuffer && _entry(pBuffer)->Release() <= 0 && gEnv)
{
GetNameTable()->Release(_entry(pBuffer));
}
}
int _length() const { return (m_str) ? _entry(m_str)->nLength : 0; };
void _addref(const char* pBuffer)
{
if (pBuffer)
{
_entry(pBuffer)->AddRef();
}
}
const char* m_str;
};
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// CryName
//////////////////////////////////////////////////////////////////////////
inline CCryName::CCryName()
{
m_str = 0;
}
//////////////////////////////////////////////////////////////////////////
inline CCryName::CCryName(const CCryName& n)
{
_addref(n.m_str);
m_str = n.m_str;
}
//////////////////////////////////////////////////////////////////////////
inline CCryName::CCryName(const char* s)
{
m_str = 0;
*this = s;
}
//////////////////////////////////////////////////////////////////////////
inline CCryName::CCryName(const char* s, [[maybe_unused]] bool bOnlyFind)
{
assert(s);
m_str = 0;
if (*s) // if not empty
{
SNameEntry* pNameEntry = GetNameTable()->FindEntry(s);
if (pNameEntry)
{
m_str = pNameEntry->GetStr();
_addref(m_str);
}
}
}
inline CCryName::~CCryName()
{
_release(m_str);
}
//////////////////////////////////////////////////////////////////////////
inline CCryName& CCryName::operator=(const CCryName& n)
{
if (m_str != n.m_str)
{
_release(m_str);
m_str = n.m_str;
_addref(m_str);
}
return *this;
}
//////////////////////////////////////////////////////////////////////////
inline CCryName& CCryName::operator=(const char* s)
{
assert(s);
const char* pBuf = 0;
if (s && *s) // if not empty
{
pBuf = GetNameTable()->GetEntry(s)->GetStr();
}
if (m_str != pBuf)
{
_release(m_str);
m_str = pBuf;
_addref(m_str);
}
return *this;
}
//////////////////////////////////////////////////////////////////////////
inline bool CCryName::operator==(const CCryName& n) const
{
return m_str == n.m_str;
}
inline bool CCryName::operator!=(const CCryName& n) const
{
return !(*this == n);
}
inline bool CCryName::operator==(const char* str) const
{
return m_str && _stricmp(m_str, str) == 0;
}
inline bool CCryName::operator!=(const char* str) const
{
if (!m_str)
{
return true;
}
return _stricmp(m_str, str) != 0;
}
inline bool CCryName::operator<(const CCryName& n) const
{
return m_str < n.m_str;
}
inline bool CCryName::operator>(const CCryName& n) const
{
return m_str > n.m_str;
}
inline bool operator==(const AZStd::string& s, const CCryName& n)
{
return s == n.c_str();
}
inline bool operator!=(const AZStd::string& s, const CCryName& n)
{
return s != n.c_str();
}
inline bool operator==(const char* s, const CCryName& n)
{
return n == s;
}
inline bool operator!=(const char* s, const CCryName& n)
{
return n != s;
}
///////////////////////////////////////////////////////////////////////////////
// Class CCryNameCRC.
//////////////////////////////////////////////////////////////////////////
class CCryNameCRC
{
public:
CCryNameCRC();
CCryNameCRC(const CCryNameCRC& n);
CCryNameCRC(const char* s);
CCryNameCRC(const char* s, bool bOnlyFind);
explicit CCryNameCRC(uint32 n) { m_nID = n; } // We use "explicit" to prevent comparison of strings with ints due to implicit conversion.
~CCryNameCRC();
CCryNameCRC& operator=(const CCryNameCRC& n);
CCryNameCRC& operator=(const char* s);
bool operator==(const CCryNameCRC& n) const;
bool operator!=(const CCryNameCRC& n) const;
bool operator==(const char* s) const;
bool operator!=(const char* s) const;
bool operator<(const CCryNameCRC& n) const;
bool operator>(const CCryNameCRC& n) const;
bool empty() const { return m_nID == 0; }
void reset() { m_nID = 0; }
uint32 get() const { return m_nID; }
void add(int nAdd) { m_nID += nAdd; }
AUTO_STRUCT_INFO
void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { /*nothing*/}
private:
uint32 m_nID;
};
//////////////////////////////////////////////////////////////////////////
// CCryNameCRC
//////////////////////////////////////////////////////////////////////////
inline CCryNameCRC::CCryNameCRC()
{
m_nID = 0;
}
//////////////////////////////////////////////////////////////////////////
inline CCryNameCRC::CCryNameCRC(const CCryNameCRC& n)
{
m_nID = n.m_nID;
}
//////////////////////////////////////////////////////////////////////////
inline CCryNameCRC::CCryNameCRC(const char* s)
{
m_nID = 0;
*this = s;
}
inline CCryNameCRC::~CCryNameCRC()
{
m_nID = 0;
}
//////////////////////////////////////////////////////////////////////////
inline CCryNameCRC& CCryNameCRC::operator=(const CCryNameCRC& n)
{
m_nID = n.m_nID;
return *this;
}
//////////////////////////////////////////////////////////////////////////
inline CCryNameCRC& CCryNameCRC::operator=(const char* s)
{
assert(s);
if (*s) // if not empty
{
m_nID = CCrc32::ComputeLowercase(s);
}
return *this;
}
//////////////////////////////////////////////////////////////////////////
inline bool CCryNameCRC::operator==(const CCryNameCRC& n) const
{
return m_nID == n.m_nID;
}
inline bool CCryNameCRC::operator!=(const CCryNameCRC& n) const
{
return !(*this == n);
}
inline bool CCryNameCRC::operator==(const char* str) const
{
assert(str);
if (*str) // if not empty
{
uint32 nID = CCrc32::ComputeLowercase(str);
return m_nID == nID;
}
return m_nID == 0;
}
inline bool CCryNameCRC::operator!=(const char* str) const
{
if (!m_nID)
{
return true;
}
if (*str) // if not empty
{
uint32 nID = CCrc32::ComputeLowercase(str);
return m_nID != nID;
}
return false;
}
inline bool CCryNameCRC::operator<(const CCryNameCRC& n) const
{
return m_nID < n.m_nID;
}
inline bool CCryNameCRC::operator>(const CCryNameCRC& n) const
{
return m_nID > n.m_nID;
}
inline bool operator==(const AZStd::string& s, const CCryNameCRC& n)
{
return n == s.c_str();
}
inline bool operator!=(const AZStd::string& s, const CCryNameCRC& n)
{
return n != s.c_str();
}
inline bool operator==(const char* s, const CCryNameCRC& n)
{
return n == s;
}
inline bool operator!=(const char* s, const CCryNameCRC& n)
{
return n != s;
}
#endif // CRYINCLUDE_CRYCOMMON_CRYNAME_H
-4
View File
@@ -21,10 +21,6 @@
class ICrySizer;
class CCryName;
AZStd::string ToString(CCryName const& val);
bool FromString(CCryName& val, const char* s);
//---------------------------------------------------------------------------
// Specify options for converting data to/from strings
struct FToString
-188
View File
@@ -18,7 +18,6 @@
#include <Cry_Math.h>
#include <Cry_Geo.h>
#include <MemoryAccess.h>
#include <Cry_XOptimise.h>
//DOC-IGNORE-END
//////////////////////////////////////////////////////////////////////
@@ -557,9 +556,6 @@ public:
ILINE Vec3 GetPosition() const { return m_Matrix.GetTranslation(); }
ILINE void SetPosition(const Vec3& p) { m_Matrix.SetTranslation(p); UpdateFrustum(); }
ILINE void SetPositionNoUpdate(const Vec3& p) { m_Matrix.SetTranslation(p); }
ILINE bool Project(const Vec3& p, Vec3& result, Vec2i topLeft = Vec2i(0, 0), Vec2i widthHeight = Vec2i(0, 0)) const;
ILINE bool Unproject(const Vec3& viewportPos, Vec3& result, Vec2i topLeft = Vec2i(0, 0), Vec2i widthHeight = Vec2i(0, 0)) const;
ILINE void CalcScreenBounds(int* vOut, const AABB* pAABB, int nWidth, int nHeight) const;
ILINE Vec3 GetUp() const { return m_Matrix.GetColumn2(); }
//------------------------------------------------------------
@@ -894,190 +890,6 @@ ILINE Vec3 CCamera::CreateViewdir(const Ang3& ypr)
return Vec3(-sz * cx, cz * cx, sx); //calculate the view-direction
}
// Description
// <PRE>
//p=world space position
//result=spreen space pos
//retval=is visible on screen
// </PRE>
ILINE bool CCamera::Project(const Vec3& p, Vec3& result, Vec2i topLeft, Vec2i widthHeight) const
{
Matrix44A mProj, mView;
Vec4 in, transformed, projected;
mathMatrixPerspectiveFov(&mProj, GetFov(), GetProjRatio(), GetNearPlane(), GetFarPlane());
mathMatrixLookAt(&mView, GetPosition(), GetPosition() + GetViewdir(), GetUp());
int pViewport[4] = {0, 0, GetViewSurfaceX(), GetViewSurfaceZ()};
if (!topLeft.IsZero() || !widthHeight.IsZero())
{
pViewport[0] = topLeft.x;
pViewport[1] = topLeft.y;
pViewport[2] = widthHeight.x;
pViewport[3] = widthHeight.y;
}
in.x = p.x;
in.y = p.y;
in.z = p.z;
in.w = 1.0f;
mathVec4Transform((f32*)&transformed, (f32*)&mView, (f32*)&in);
bool visible = transformed.z < 0.0f;
mathVec4Transform((f32*)&projected, (f32*)&mProj, (f32*)&transformed);
if (projected.w == 0.0f)
{
result = Vec3(0.f, 0.f, 0.f);
return false;
}
projected.x /= projected.w;
projected.y /= projected.w;
projected.z /= projected.w;
visible = visible && (fabs_tpl(projected.x) <= 1.0f) && (fabs_tpl(projected.y) <= 1.0f);
//output coords
result.x = pViewport[0] + (1 + projected.x) * pViewport[2] / 2;
result.y = pViewport[1] + (1 - projected.y) * pViewport[3] / 2; //flip coords for y axis
result.z = projected.z;
return visible;
}
ILINE bool CCamera::Unproject(const Vec3& viewportPos, Vec3& result, Vec2i topLeft, Vec2i widthHeight) const
{
Matrix44A mProj, mView;
mathMatrixPerspectiveFov(&mProj, GetFov(), GetProjRatio(), GetNearPlane(), GetFarPlane());
mathMatrixLookAt(&mView, GetPosition(), GetPosition() + GetViewdir(), Vec3(0, 0, 1));
int viewport[4] = {0, 0, GetViewSurfaceX(), GetViewSurfaceZ()};
if (!topLeft.IsZero() || !widthHeight.IsZero())
{
viewport[0] = topLeft.x;
viewport[1] = topLeft.y;
viewport[2] = widthHeight.x;
viewport[3] = widthHeight.y;
}
Vec4 vIn;
vIn.x = (viewportPos.x - viewport[0]) * 2 / viewport[2] - 1.0f;
vIn.y = (viewportPos.y - viewport[1]) * 2 / viewport[3] - 1.0f;
vIn.z = viewportPos.z;
vIn.w = 1.0;
Matrix44A m;
const float* proj = mProj.GetData();
const float* view = mView.GetData();
float* mdata = m.GetData();
for (int i = 0; i < 4; i++)
{
float ai0 = proj[i], ai1 = proj[4 + i], ai2 = proj[8 + i], ai3 = proj[12 + i];
mdata[i] = ai0 * view[0] + ai1 * view[1] + ai2 * view[2] + ai3 * view[3];
mdata[4 + i] = ai0 * view[4] + ai1 * view[5] + ai2 * view[6] + ai3 * view[7];
mdata[8 + i] = ai0 * view[8] + ai1 * view[9] + ai2 * view[10] + ai3 * view[11];
mdata[12 + i] = ai0 * view[12] + ai1 * view[13] + ai2 * view[14] + ai3 * view[15];
}
m.Invert();
if (!m.IsValid())
{
return false;
}
Vec4 vOut = vIn * m;
if (vOut.w == 0.0)
{
return false;
}
result = Vec3(vOut.x / vOut.w, vOut.y / vOut.w, vOut.z / vOut.w);
return true;
}
ILINE void CCamera::CalcScreenBounds(int* vOut, const AABB* pAABB, int nWidth, int nHeight) const
{
Matrix44A mProj, mView, mVP;
mathMatrixPerspectiveFov(&mProj, GetFov(), GetProjRatio(), GetNearPlane(), GetFarPlane());
mathMatrixLookAt(&mView, GetPosition(), GetPosition() + GetViewdir(), GetMatrix().GetColumn2());
mVP = mView * mProj;
Vec3 verts[8];
Vec2i topLeft = Vec2i(0, 0);
Vec2i widthHeight = Vec2i(nWidth, nHeight);
float pViewport[4] = {0.0f, 0.0f, (float)widthHeight.x, (float)widthHeight.y};
float x0 = 9999.9f, x1 = -9999.9f, y0 = 9999.9f, y1 = -9999.9f;
float fIntersect = 1.0f;
Vec3 vDir = GetViewdir();
Vec3 vPos = GetPosition();
float d = vPos.Dot(vDir);
verts[0] = Vec3(pAABB->min.x, pAABB->min.y, pAABB->min.z);
verts[1] = Vec3(pAABB->max.x, pAABB->min.y, pAABB->min.z);
verts[2] = Vec3(pAABB->min.x, pAABB->max.y, pAABB->min.z);
verts[3] = Vec3(pAABB->max.x, pAABB->max.y, pAABB->min.z);
verts[4] = Vec3(pAABB->min.x, pAABB->min.y, pAABB->max.z);
verts[5] = Vec3(pAABB->max.x, pAABB->min.y, pAABB->max.z);
verts[6] = Vec3(pAABB->min.x, pAABB->max.y, pAABB->max.z);
verts[7] = Vec3(pAABB->max.x, pAABB->max.y, pAABB->max.z);
for (int i = 0; i < 8; i++)
{
float fDist = verts[i].Dot(vDir) - d;
fDist = (float)fsel(fDist, 0.0f, -fDist);
//Project(verts[i],vertsOut[i], topLeft, widthHeight);
Vec3 result = Vec3(0.0f, 0.0f, 0.0f);
Vec4 transformed, projected, vIn;
vIn = Vec4(verts[i].x, verts[i].y, verts[i].z, 1.0f);
mathVec4Transform((f32*)&projected, (f32*)&mVP, (f32*)&vIn);
fIntersect = (float)fsel(-projected.w, 0.0f, 1.0f);
if (!fzero(fIntersect) && !fzero(projected.w))
{
projected.x /= projected.w;
projected.y /= projected.w;
projected.z /= projected.w;
//output coords
result.x = pViewport[0] + (1.0f + projected.x) * pViewport[2] / 2.0f;
result.y = pViewport[1] + (1.0f - projected.y) * pViewport[3] / 2.0f; //flip coords for y axis
result.z = projected.z;
}
else
{
vOut[0] = topLeft.x;
vOut[1] = topLeft.y;
vOut[2] = widthHeight.x;
vOut[3] = widthHeight.y;
return;
}
x0 = min(x0, result.x);
x1 = max(x1, result.x);
y0 = min(y0, result.y);
y1 = max(y1, result.y);
}
vOut[0] = (int)max(0.0f, min(pViewport[2], x0));
vOut[1] = (int)max(0.0f, min(pViewport[3], y0));
vOut[2] = (int)max(0.0f, min(pViewport[2], x1));
vOut[3] = (int)max(0.0f, min(pViewport[3], y1));
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
-14
View File
@@ -1067,20 +1067,6 @@ public:
}
};
//////////////////////////////////////////////////////////////////////////
#include "Cry_GeoDistance.h"
#include "Cry_GeoOverlap.h"
#include "Cry_GeoIntersect.h"
/////////////////////////////////////////////////////////////////////////
//this is some special engine stuff, should be moved to a better location
/////////////////////////////////////////////////////////////////////////
File diff suppressed because it is too large Load Diff
+5 -746
View File
@@ -8,19 +8,14 @@
// Description : Common intersection-tests
#ifndef CRYINCLUDE_CRYCOMMON_CRY_GEOINTERSECT_H
#define CRYINCLUDE_CRYCOMMON_CRY_GEOINTERSECT_H
#pragma once
#include <Cry_Geo.h>
namespace Intersect {
inline bool Ray_Plane(const Ray& ray, const Plane_tpl<f32>& plane, Vec3& output, bool bSingleSidePlane = true)
{
float cosine = plane.n | ray.direction;
float cosine = plane.n | ray.direction;
//REJECTION 1: if "line-direction" is perpendicular to "plane-normal", an intersection is not possible! That means ray is parallel
// to the plane
@@ -33,9 +28,9 @@ namespace Intersect {
return false;
}
float numer = plane.DistFromPlane(ray.origin);
float fLength = -numer / cosine;
output = ray.origin + (ray.direction * fLength);
float numer = plane.DistFromPlane(ray.origin);
float fLength = -numer / cosine;
output = ray.origin + (ray.direction * fLength);
//skip, if cutting-point is "behind" ray.origin
if (fLength < 0.0f)
{
@@ -45,232 +40,6 @@ namespace Intersect {
return true; //intersection occurred
}
inline bool Line_Plane(const Line& line, const Plane_tpl<f32>& plane, Vec3& output, bool bSingleSidePlane = true)
{
float cosine = plane.n | line.direction;
//REJECTION 1: if "line-direction" is perpendicular to "plane-normal", an intersection is not possible! That means ray is parallel
// to the plane
//REJECTION 2: if bSingleSidePlane == true we deal with single-sided planes. That means
// if "line-direction" is pointing in the same direction as "the plane-normal",
// an intersection is not possible!
if ((cosine == 0.0f) || // normal is orthogonal to vector, cant intersect
(bSingleSidePlane && (cosine > 0.0f))) // we are trying to find an intersection in the same direction as the plane normal
{
return false;
}
//an intersection is possible: calculate the exact point!
float perpdist = plane | line.pointonline;
float pd_c = -perpdist / cosine;
output = line.pointonline + (line.direction * pd_c);
return true; //intersection occurred
}
// Algorithm description:
// http://softsurfer.com/Archive/algorithm_0104/algorithm_0104B.htm#Line-Plane%20Intersection
template <typename T>
inline bool Segment_Plane(const Lineseg_tpl<T>& segment, const Plane_tpl<T>& plane, Vec3_tpl<T>& vOutput, bool bSingleSidePlane = true)
{
Vec3_tpl<T> vSegment = segment.end - segment.start;
T planeNormalDotSegment = plane.n | vSegment;
//REJECTION 1: if "line-direction" is perpendicular to "plane-normal", an intersection is not possible! That means ray is parallel
// to the plane
//REJECTION 2: if bSingleSidePlane == true we deal with single-sided planes. That means
// if "line-direction" is pointing in the same direction as "the plane-normal",
// an intersection is not possible!
if ((planeNormalDotSegment == T(0)) || // normal is orthogonal to vector, cant intersect
(bSingleSidePlane && (planeNormalDotSegment > T(0)))) // we are trying to find an intersection in the same direction as the plane normal
{
return false;
}
// n Dot (segment.start - closest_point_in_plane) = 1 * DistFromPlane(segment.start) * cos(0) = DistFromPlane(segment.start)
T distanceToStart = plane.DistFromPlane(segment.start);
T scale = -distanceToStart / planeNormalDotSegment;
vOutput = segment.start + (vSegment * scale);
// skip, if segment start and ends in one side of the plane
if ((scale < T(0)) || (scale > T(1)))
{
return false;
}
return true; //intersection occurred
}
/// Intersection between two line segments in 2D (ignoring z coordinate). The two parametric
/// values are set to between 0 and 1 if intersection occurs. If intersection does not occur
/// their values will indicate the parametric values for intersection of the lines extended
/// beyond the segment lengths. Parallel lines will result in a negative result, but the parametric
/// values will both be equal to 0.5
template<typename F>
inline bool Lineseg_Lineseg2D(const Lineseg_tpl<F>& lineA, const Lineseg_tpl<F>& lineB, F& outA, F& outB)
{
const F Epsilon = (F)0.0000001;
Vec3_tpl<F> delta = lineB.start - lineA.start;
Vec3_tpl<F> dirA = lineA.end - lineA.start;
Vec3_tpl<F> dirB = lineB.end - lineB.start;
F det = dirA.x * dirB.y - dirA.y * dirB.x;
F detA = delta.x * dirB.y - delta.y * dirB.x;
F detB = delta.x * dirA.y - delta.y * dirA.x;
F absDet = fabs_tpl(det);
if (absDet >= Epsilon)
{
F invDet = (F)1.0 / det;
F a = detA * invDet;
F b = detB * invDet;
outA = a;
outB = b;
if ((a > (F)1.0) || (a < (F)0.0) || (b > (F)1.0) || (b < (F)0.0))
{
return false;
}
}
else
{
outA = outB = (F)0.5;
return false;
}
return true;
}
/// Calculates the intersection between a line segment and a polygon, in 2D (i.e.
/// ignoring z coordinate). The VecContainer should be a container of Vec3 such
/// that we can traverse it using iterators. intersectionPoint is set to the intersection
/// point or the end of the segment, if no intersection.
template<typename VecIterator>
inline bool Lineseg_Polygon2D(const Lineseg& lineseg, VecIterator polygonBegin, VecIterator polygonEnd, Vec3& intersectionPoint, Vec3* pNormal = NULL, bool bForceNormalOutwards = false)
{
intersectionPoint = lineseg.end;
bool gotIntersection = false;
float tmin = 1.0f;
VecIterator iend = polygonEnd;
VecIterator li, linext;
Lineseg intersectSegment;
for (li = polygonBegin; li != iend; ++li)
{
linext = li;
++linext;
if (linext == iend)
{
linext = polygonBegin;
}
Lineseg segmentPoly(*li, *linext);
float s, t;
if (Intersect::Lineseg_Lineseg2D(lineseg, segmentPoly, s, t))
{
if (s < 0.00001f || s > 0.99999f || t < 0.00001f || t > 0.99999f)
{
continue;
}
if (s < tmin)
{
tmin = s;
gotIntersection = true;
intersectSegment = segmentPoly;
}
}
}
intersectionPoint = lineseg.start + tmin * (lineseg.end - lineseg.start);
if (pNormal && gotIntersection)
{
Vec3 vPolyseg = intersectSegment.end - intersectSegment.start;
Vec3 vIntSeg = (lineseg.end - lineseg.start);
pNormal->x = vPolyseg.y;
pNormal->y = -vPolyseg.x;
pNormal->z = 0;
pNormal->NormalizeSafe();
// returns the normal towards the start point of the intersecting segment (if it's not forced to be outwards)
if (!bForceNormalOutwards && vIntSeg.Dot(*pNormal) > 0)
{
pNormal->x = -pNormal->x;
pNormal->y = -pNormal->y;
}
}
return gotIntersection;
}
template<typename VecContainer>
inline bool Lineseg_Polygon2D(const Lineseg& lineseg, const VecContainer& polygon, Vec3& intersectionPoint, Vec3* pNormal = NULL, bool bForceNormalOutwards = false)
{
return Lineseg_Polygon2D(lineseg, polygon.begin(), polygon.end(), intersectionPoint, pNormal, bForceNormalOutwards);
}
/*
* calculates intersection between a line and a triangle.
* IMPORTANT: this is a single-sided intersection test. That means its not enough
* that the triangle and line overlap, its also important that the triangle
* is "visible" when you are looking along the line-direction.
*
* If you need a double-sided test, you'll have to call this function twice with
* reversed order of triangle vertices.
*
* return values
* if there is an intertection the functions return "true" and stores the
* 3d-intersection point in "output". if the function returns "false" the value in
* "output" is undefined
*
*/
inline bool Line_Triangle(const Line& line, const Vec3& v0, const Vec3& v1, const Vec3& v2, Vec3& output)
{
const float Epsilon = 0.0000001f;
Vec3 edgeA = v1 - v0;
Vec3 edgeB = v2 - v0;
Vec3 dir = line.direction;
Vec3 p = dir.Cross(edgeA);
Vec3 t = line.pointonline - v0;
Vec3 q = t.Cross(edgeB);
float dot = edgeB.Dot(p);
float u = t.Dot(p);
float v = dir.Dot(q);
float DotGreaterThanEpsilon = dot - Epsilon;
float VGreaterEqualThanZero = v;
float UGreaterEqualThanZero = u;
float UVLessThanDot = dot - (u + v);
float ULessThanDot = dot - u;
float UVGreaterEqualThanZero = (float)fsel(VGreaterEqualThanZero, UGreaterEqualThanZero, VGreaterEqualThanZero);
float UUVLessThanDot = (float)fsel(UVLessThanDot, ULessThanDot, UVLessThanDot);
float BothGood = (float)fsel(UVGreaterEqualThanZero, UUVLessThanDot, UVGreaterEqualThanZero);
float AllGood = (float)fsel(DotGreaterThanEpsilon, BothGood, DotGreaterThanEpsilon);
if (AllGood < 0.0f)
{
return false;
}
float dt = edgeA.Dot(q) / dot;
Vec3 result = (dir * dt) + line.pointonline;
output = result;
return true;
}
/*
* calculates intersection between a ray and a triangle.
* IMPORTANT: this is a single-sided intersection test. That means its not sufficient
@@ -329,80 +98,6 @@ namespace Intersect {
return AfterStart >= 0.0f;
}
/*
* Description:
* Calculates intersection between a line-segment and a triangle.
* Remarks:
* IMPORTANT: this is a single-sided intersection test. That means its not sufficient
* that the triangle and line-segment overlap, its also important that the triangle
* is "visible" when you are looking along the linesegment from "start" to "end".
* Notes:
* If you need a double-sided test, you'll have to call this function twice with
* reversed order of triangle vertices.
*
* Return value:
* If there is an intertection the the functions return "true" and stores the
* 3d-intersection point in "output". if the function returns "false" the value in
* "output" is undefined. If pT is non-zero then if there is an intersection the "t-value"
* (from 0-1) is also returned (unmodified if there is no intersection).
*/
inline bool Lineseg_Triangle(const Lineseg& lineseg, const Vec3& v0, const Vec3& v1, const Vec3& v2, Vec3& output,
float* outT = 0)
{
const float Epsilon = 0.0000001f;
Vec3 edgeA = v1 - v0;
Vec3 edgeB = v2 - v0;
Vec3 dir = lineseg.end - lineseg.start;
Vec3 p = dir.Cross(edgeA);
Vec3 t = lineseg.start - v0;
Vec3 q = t.Cross(edgeB);
float dot = edgeB.Dot(p);
float u = t.Dot(p);
float v = dir.Dot(q);
float DotGreaterThanEpsilon = dot - Epsilon;
float VGreaterEqualThanZero = v;
float UGreaterEqualThanZero = u;
float UVLessThanDot = dot - (u + v);
float ULessThanDot = dot - u;
float UVGreaterEqualThanZero = (float)fsel(VGreaterEqualThanZero, UGreaterEqualThanZero, VGreaterEqualThanZero);
float UUVLessThanDot = (float)fsel(UVLessThanDot, ULessThanDot, UVLessThanDot);
float BothGood = (float)fsel(UVGreaterEqualThanZero, UUVLessThanDot, UVGreaterEqualThanZero);
float AllGood = (float)fsel(DotGreaterThanEpsilon, BothGood, DotGreaterThanEpsilon);
if (AllGood < 0.0f)
{
return false;
}
float dt = edgeA.Dot(q) / dot;
Vec3 result = (dir * dt) + lineseg.start;
output = result;
float AfterStart = (result - lineseg.start).Dot(dir);
float BeforeEnd = -(result - lineseg.end).Dot(dir);
float Within = (float)fsel(AfterStart, BeforeEnd, AfterStart);
if (outT)
{
*outT = dt;
}
return Within >= 0.0f;
}
//----------------------------------------------------------------------------------
// Ray_AABB
//
@@ -466,359 +161,6 @@ namespace Intersect {
return 0x00;//no intersection
}
//----------------------------------------------------------------------------------
// Ray_OBB
//
// just ONE intersection point is calculated, and thats the entry point -
// Lineseg and OBB are assumed to be in the same space
//
//--- 0x00 = no intersection (output undefined) ----
//--- 0x01 = intersection (intersection point in output) --------------
//--- 0x02 = start of Lineseg is inside the OBB (ls.start is output)
//----------------------------------------------------------------------------------
inline uint8 Ray_OBB(const Ray& ray, const Vec3& pos, const OBB& obb, Vec3& output1)
{
AABB aabb(obb.c - obb.h, obb.c + obb.h);
Ray aray((ray.origin - pos) * obb.m33, ray.direction * obb.m33);
uint8 cflags;
float cosine;
Vec3 cut;
//--------------------------------------------------------------------------------------
//---- check if "aray.origin" is inside of AABB ---------------------------
//--------------------------------------------------------------------------------------
cflags = (aray.origin.x > aabb.min.x) << 0;
cflags |= (aray.origin.x < aabb.max.x) << 1;
cflags |= (aray.origin.y > aabb.min.y) << 2;
cflags |= (aray.origin.y < aabb.max.y) << 3;
cflags |= (aray.origin.z > aabb.min.z) << 4;
cflags |= (aray.origin.z < aabb.max.z) << 5;
if (cflags == 0x3f)
{
output1 = aray.origin;
return 0x02;
}
//--------------------------------------------------------------------------------------
//---- check intersection with planes ------------------------------
//--------------------------------------------------------------------------------------
for (int i = 0; i < 3; i++)
{
if ((aray.direction[i] > 0) && (aray.origin[i] < aabb.min[i]))
{
cosine = (-aray.origin[i] + aabb.min[i]) / aray.direction[i];
cut[i] = aabb.min[i];
cut[incm3(i)] = aray.origin[incm3(i)] + (aray.direction[incm3(i)] * cosine);
cut[decm3(i)] = aray.origin[decm3(i)] + (aray.direction[decm3(i)] * cosine);
if ((cut[incm3(i)] > aabb.min[incm3(i)]) && (cut[incm3(i)] < aabb.max[incm3(i)]) && (cut[decm3(i)] > aabb.min[decm3(i)]) && (cut[decm3(i)] < aabb.max[decm3(i)]))
{
output1 = obb.m33 * cut + pos;
return 0x01;
}
}
if ((aray.direction[i] < 0) && (aray.origin[i] > aabb.max[i]))
{
cosine = (+aray.origin[i] - aabb.max[i]) / aray.direction[i];
cut[i] = aabb.max[i];
cut[incm3(i)] = aray.origin[incm3(i)] - (aray.direction[incm3(i)] * cosine);
cut[decm3(i)] = aray.origin[decm3(i)] - (aray.direction[decm3(i)] * cosine);
if ((cut[incm3(i)] > aabb.min[incm3(i)]) && (cut[incm3(i)] < aabb.max[incm3(i)]) && (cut[decm3(i)] > aabb.min[decm3(i)]) && (cut[decm3(i)] < aabb.max[decm3(i)]))
{
output1 = obb.m33 * cut + pos;
return 0x01;
}
}
}
return 0x00;//no intersection
}
//----------------------------------------------------------------------------------
// Lineseg_AABB
//
// just ONE intersection point is calculated, and thats the entry point -
// Lineseg and AABB are assumed to be in the same space
//
//--- 0x00 = no intersection (output undefined) --------------------------
//--- 0x01 = intersection (intersection point in output) --------------
//--- 0x02 = start of Lineseg is inside the AABB (ls.start is output)
//----------------------------------------------------------------------------------
inline uint8 Lineseg_AABB(const Lineseg& ls, const AABB& aabb, Vec3& output1)
{
uint8 cflags;
float cosine;
Vec3 cut;
Vec3 lnormal = (ls.start - ls.end).GetNormalized();
//--------------------------------------------------------------------------------------
//---- check if "ls.start" is inside of AABB ---------------------------
//--------------------------------------------------------------------------------------
cflags = (ls.start.x > aabb.min.x) << 0;
cflags |= (ls.start.x < aabb.max.x) << 1;
cflags |= (ls.start.y > aabb.min.y) << 2;
cflags |= (ls.start.y < aabb.max.y) << 3;
cflags |= (ls.start.z > aabb.min.z) << 4;
cflags |= (ls.start.z < aabb.max.z) << 5;
if (cflags == 0x3f)
{
//ls.start is inside of aabb
output1 = ls.start;
return 0x02;
}
//--------------------------------------------------------------------------------------
//---- check intersection with x-planes ------------------------------
//--------------------------------------------------------------------------------------
if (lnormal.x)
{
if ((ls.start.x < aabb.min.x) && (ls.end.x > aabb.min.x))
{
cosine = (-ls.start.x + (+aabb.min.x)) / lnormal.x;
cut(aabb.min.x, ls.start.y + (lnormal.y * cosine), ls.start.z + (lnormal.z * cosine));
//check if cut-point is inside YZ-plane border
if ((cut.y > aabb.min.y) && (cut.y < aabb.max.y) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z))
{
output1 = cut;
return 0x01;
}
}
if ((ls.start.x > aabb.max.x) && (ls.end.x < aabb.max.x))
{
cosine = (+ls.start.x + (-aabb.max.x)) / lnormal.x;
cut(aabb.max.x, ls.start.y - (lnormal.y * cosine), ls.start.z - (lnormal.z * cosine));
//check if cut-point is inside YZ-plane border
if ((cut.y > aabb.min.y) && (cut.y < aabb.max.y) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z))
{
output1 = cut;
return 0x01;
}
}
}
//--------------------------------------------------------------------------------------
//---- check intersection with z-planes ------------------------------
//--------------------------------------------------------------------------------------
if (lnormal.z)
{
if ((ls.start.z < aabb.min.z) && (ls.end.z > aabb.min.z))
{
cosine = (-ls.start.z + (+aabb.min.z)) / lnormal.z;
cut(ls.start.x + (lnormal.x * cosine), ls.start.y + (lnormal.y * cosine), aabb.min.z);
//check if cut-point is inside XY-plane border
if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.y > aabb.min.y) && (cut.y < aabb.max.y))
{
output1 = cut;
return 0x01;
}
}
if ((ls.start.z > aabb.max.z) && (ls.end.z < aabb.max.z))
{
cosine = (+ls.start.z + (-aabb.max.z)) / lnormal.z;
cut(ls.start.x - (lnormal.x * cosine), ls.start.y - (lnormal.y * cosine), aabb.max.z);
//check if cut-point is inside XY-plane border
if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.y > aabb.min.y) && (cut.y < aabb.max.y))
{
output1 = cut;
return 0x01;
}
}
}
//--------------------------------------------------------------------------------------
//---- check intersection with y-planes ------------------------------
//--------------------------------------------------------------------------------------
if (lnormal.y)
{
if ((ls.start.y < aabb.min.y) && (ls.end.y > aabb.min.y))
{
cosine = (-ls.start.y + (+aabb.min.y)) / lnormal.y;
cut(ls.start.x + (lnormal.x * cosine), aabb.min.y, ls.start.z + (lnormal.z * cosine));
//check if cut-point is inside XZ-plane border
if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z))
{
output1 = cut;
return 0x01;
}
}
if ((ls.start.y > aabb.max.y) && (ls.end.y < aabb.max.y))
{
cosine = (+ls.start.y + (-aabb.max.y)) / lnormal.y;
cut(ls.start.x - (lnormal.x * cosine), aabb.max.y, ls.start.z - (lnormal.z * cosine));
//check if cut-point is inside XZ-plane border
if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z))
{
output1 = cut;
return 0x01;
}
}
}
//no intersection
return 0x00;
}
//----------------------------------------------------------------------------------
// Lineseg_OBB
//
// just ONE intersection point is calculated, and thats the entry point -
// Lineseg and OBB are assumed to be in the same space
//
//--- 0x00 = no intersection (output undefined) --------------------------
//--- 0x01 = intersection (intersection point in output) --------------
//--- 0x02 = start of Lineseg is inside the OBB (ls.start is output)
//----------------------------------------------------------------------------------
inline uint8 Lineseg_OBB(const Lineseg& lseg, const Vec3& pos, const OBB& obb, Vec3& output1)
{
AABB aabb(obb.c - obb.h, obb.c + obb.h);
Lineseg ls((lseg.start - pos) * obb.m33, (lseg.end - pos) * obb.m33);
uint8 cflags;
float cosine;
Vec3 cut;
Vec3 lnormal = (ls.start - ls.end).GetNormalized();
//--------------------------------------------------------------------------------------
//---- check if "ls.start" is inside of AABB ---------------------------
//--------------------------------------------------------------------------------------
cflags = (ls.start.x > aabb.min.x) << 0;
cflags |= (ls.start.x < aabb.max.x) << 1;
cflags |= (ls.start.y > aabb.min.y) << 2;
cflags |= (ls.start.y < aabb.max.y) << 3;
cflags |= (ls.start.z > aabb.min.z) << 4;
cflags |= (ls.start.z < aabb.max.z) << 5;
if (cflags == 0x3f)
{
//ls.start is inside of aabb
output1 = obb.m33 * ls.start + pos;
return 0x02;
}
//--------------------------------------------------------------------------------------
//---- check intersection with x-planes ------------------------------
//--------------------------------------------------------------------------------------
if (lnormal.x)
{
if ((ls.start.x < aabb.min.x) && (ls.end.x > aabb.min.x))
{
cosine = (-ls.start.x + (+aabb.min.x)) / lnormal.x;
cut(aabb.min.x, ls.start.y + (lnormal.y * cosine), ls.start.z + (lnormal.z * cosine));
//check if cut-point is inside YZ-plane border
if ((cut.y > aabb.min.y) && (cut.y < aabb.max.y) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z))
{
output1 = obb.m33 * cut + pos;
return 0x01;
}
}
if ((ls.start.x > aabb.max.x) && (ls.end.x < aabb.max.x))
{
cosine = (+ls.start.x + (-aabb.max.x)) / lnormal.x;
cut(aabb.max.x, ls.start.y - (lnormal.y * cosine), ls.start.z - (lnormal.z * cosine));
//check if cut-point is inside YZ-plane border
if ((cut.y > aabb.min.y) && (cut.y < aabb.max.y) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z))
{
output1 = obb.m33 * cut + pos;
return 0x01;
}
}
}
//--------------------------------------------------------------------------------------
//---- check intersection with z-planes ------------------------------
//--------------------------------------------------------------------------------------
if (lnormal.z)
{
if ((ls.start.z < aabb.min.z) && (ls.end.z > aabb.min.z))
{
cosine = (-ls.start.z + (+aabb.min.z)) / lnormal.z;
cut(ls.start.x + (lnormal.x * cosine), ls.start.y + (lnormal.y * cosine), aabb.min.z);
//check if cut-point is inside XY-plane border
if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.y > aabb.min.y) && (cut.y < aabb.max.y))
{
output1 = obb.m33 * cut + pos;
return 0x01;
}
}
if ((ls.start.z > aabb.max.z) && (ls.end.z < aabb.max.z))
{
cosine = (+ls.start.z + (-aabb.max.z)) / lnormal.z;
cut(ls.start.x - (lnormal.x * cosine), ls.start.y - (lnormal.y * cosine), aabb.max.z);
//check if cut-point is inside XY-plane border
if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.y > aabb.min.y) && (cut.y < aabb.max.y))
{
output1 = obb.m33 * cut + pos;
return 0x01;
}
}
}
//--------------------------------------------------------------------------------------
//---- check intersection with y-planes ------------------------------
//--------------------------------------------------------------------------------------
if (lnormal.y)
{
if ((ls.start.y < aabb.min.y) && (ls.end.y > aabb.min.y))
{
cosine = (-ls.start.y + (+aabb.min.y)) / lnormal.y;
cut(ls.start.x + (lnormal.x * cosine), aabb.min.y, ls.start.z + (lnormal.z * cosine));
//check if cut-point is inside XZ-plane border
if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z))
{
output1 = obb.m33 * cut + pos;
return 0x01;
}
}
if ((ls.start.y > aabb.max.y) && (ls.end.y < aabb.max.y))
{
cosine = (+ls.start.y + (-aabb.max.y)) / lnormal.y;
cut(ls.start.x - (lnormal.x * cosine), aabb.max.y, ls.start.z - (lnormal.z * cosine));
//check if cut-point is inside XZ-plane border
if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z))
{
output1 = obb.m33 * cut + pos;
return 0x01;
}
}
}
//no intersection
return 0x00;
}
//----------------------------------------------------------------------------------
//--- 0x00 = no intersection --------------------------
//--- 0x01 = not possible --
//--- 0x02 = not possible --
//--- 0x03 = two intersection, lineseg has ENTRY and EXIT point --
//----------------------------------------------------------------------------------
inline unsigned char Line_Sphere(const Line& line, const ::Sphere& s, Vec3& i0, Vec3& i1)
{
Vec3 end = line.pointonline + line.direction;
float a = line.direction | line.direction;
float b = (line.direction | (line.pointonline - s.center)) * 2.0f;
float c = ((line.pointonline - s.center) | (line.pointonline - s.center)) - (s.radius * s.radius);
float desc = (b * b) - (4 * a * c);
unsigned char intersection = 0;
if (desc >= 0.0f)
{
float lamba0 = (-b - sqrt_tpl(desc)) / (2.0f * a);
//_stprintf(d3dApp.token,"lamba0: %20.12f",lamba0);
//d3dApp.m_pFont->DrawText( 2, d3dApp.PrintY, D3DCOLOR_ARGB(255,255,255,0), d3dApp.token ); d3dApp.PrintY+=20;
i0 = line.pointonline + ((end - line.pointonline) * lamba0);
intersection = 1;
float lamba1 = (-b + sqrt_tpl(desc)) / (2.0f * a);
//_stprintf(d3dApp.token,"lamba1: %20.12f",lamba1);
//d3dApp.m_pFont->DrawText( 2, d3dApp.PrintY, D3DCOLOR_ARGB(255,255,255,0), d3dApp.token ); d3dApp.PrintY+=20;
i1 = line.pointonline + ((end - line.pointonline) * lamba1);
intersection |= 2;
}
return intersection;
}
//----------------------------------------------------------------------------------
//--- 0x00 = no intersection --------------------------
//--- 0x01 = not possible --
@@ -873,87 +215,4 @@ namespace Intersect {
}
return false;
}
//----------------------------------------------------------------------------------
//--- 0x00 = no intersection --------------------------
//--- 0x01 = one intersection, lineseg has just an ENTRY point but no EXIT point (ls.end is inside the sphere) --
//--- 0x02 = one intersection, lineseg has just an EXIT point but no ENTRY point (ls.start is inside the sphere) --
//--- 0x03 = two intersection, lineseg has ENTRY and EXIT point --
//----------------------------------------------------------------------------------
inline unsigned char Lineseg_Sphere(const Lineseg& ls, const ::Sphere& s, Vec3& i0, Vec3& i1)
{
Vec3 dir = (ls.end - ls.start);
float a = dir | dir;
if (a == 0.0f)
{
return 0;
}
float b = (dir | (ls.start - s.center)) * 2.0f;
float c = ((ls.start - s.center) | (ls.start - s.center)) - (s.radius * s.radius);
float desc = (b * b) - (4 * a * c);
unsigned char intersection = 0;
if (desc >= 0.0f)
{
float lamba0 = (-b - sqrt_tpl(desc)) / (2.0f * a);
if (lamba0 > 0.0f)
{
i0 = ls.start + ((ls.end - ls.start) * lamba0);
//skip, if 1st cutting-point is "in front" of ls.end
if (((i0 - ls.end) | dir) > 0)
{
return 0;
}
intersection = 0x01;
}
float lamba1 = (-b + sqrt_tpl(desc)) / (2.0f * a);
if (lamba1 > 0.0f)
{
i1 = ls.start + ((ls.end - ls.start) * lamba1);
//skip, if 2nd cutting-point is "in front" of ls.end (=ls.end is inside sphere)
if (((i1 - ls.end) | dir) > 0)
{
return intersection;
}
intersection |= 0x02;
}
}
return intersection;
}
inline bool Lineseg_SphereFirst(const Lineseg& lineseg, const ::Sphere& s, Vec3& intPoint)
{
Vec3 p2;
uint8 res = Lineseg_Sphere(lineseg, s, intPoint, p2);
if (res == 2)
{
intPoint = p2;
}
if (res > 1)
{
return true;
}
return false;
}
}; //CIntersect
#endif // CRYINCLUDE_CRYCOMMON_CRY_GEOINTERSECT_H
} //Intersect
-58
View File
@@ -657,64 +657,6 @@ namespace Overlap {
return AfterStart >= 0.0f;
}
/*!
*
* overlap-test between line-segment and a triangle.
* IMPORTANT: this is a single-sided test. That means its not sufficient
* that the triangle and line-segment overlap, its also important that the triangle
* is "visible" when you are looking along the linesegment from "start" to "end".
*
* If you need a double-sided test, you'll have to call this function twice with
* reversed order of triangle vertices.
*
* return values
* return "true" if linesegment and triangle overlap.
*/
inline bool Lineseg_Triangle(const Lineseg& lineseg, const Vec3& v0, const Vec3& v1, const Vec3& v2)
{
const float Epsilon = 0.0000001f;
Vec3 edgeA = v1 - v0;
Vec3 edgeB = v2 - v0;
Vec3 dir = lineseg.end - lineseg.start;
Vec3 p = dir.Cross(edgeA);
Vec3 t = lineseg.start - v0;
Vec3 q = t.Cross(edgeB);
float dot = edgeB.Dot(p);
float u = t.Dot(p);
float v = dir.Dot(q);
float DotGreaterThanEpsilon = dot - Epsilon;
float VGreaterEqualThanZero = v;
float UGreaterEqualThanZero = u;
float UVLessThanDot = dot - (u + v);
float ULessThanDot = dot - u;
float UVGreaterEqualThanZero = (float)fsel(VGreaterEqualThanZero, UGreaterEqualThanZero, VGreaterEqualThanZero);
float UUVLessThanDot = (float)fsel(UVLessThanDot, ULessThanDot, UVLessThanDot);
float BothGood = (float)fsel(UVGreaterEqualThanZero, UUVLessThanDot, UVGreaterEqualThanZero);
float AllGood = (float)fsel(DotGreaterThanEpsilon, BothGood, DotGreaterThanEpsilon);
if (AllGood < 0.0f)
{
return false;
}
float dt = edgeA.Dot(q) / dot;
Vec3 result = (dir * dt) + lineseg.start;
float AfterStart = (result - lineseg.start).Dot(dir);
float BeforeEnd = -(result - lineseg.end).Dot(dir);
float Within = (float)fsel(AfterStart, BeforeEnd, AfterStart);
return Within >= 0.0f;
}
/*----------------------------------------------------------------------------------
* Sphere_AABB
* Sphere and AABB are assumed to be in the same space
-2
View File
@@ -592,14 +592,12 @@ enum type_identity
#include "Cry_Vector2.h"
#include "Cry_Vector3.h"
#include "Cry_Vector4.h"
#include "Cry_MatrixDiag.h"
#include "Cry_Matrix33.h"
#include "Cry_Matrix34.h"
#include "Cry_Matrix44.h"
#include "Cry_Quat.h"
#include "Cry_HWVector3.h"
#include "Cry_HWMatrix.h"
#include "Cry_XOptimise.h"
//////////////////////////////////////////////////////////////////////////
-72
View File
@@ -177,44 +177,6 @@ struct Matrix33_tpl
m22 = F(vz.z);
}
//CONSTRUCTOR for identical float-types. It converts a Diag33 into a Matrix33.
//Matrix33(diag33);
ILINE Matrix33_tpl<F>(const Diag33_tpl<F>&d)
{
assert(d.IsValid());
m00 = d.x;
m01 = 0;
m02 = 0;
m10 = 0;
m11 = d.y;
m12 = 0;
m20 = 0;
m21 = 0;
m22 = d.z;
}
//CONSTRUCTOR for different float-types. It converts a Diag33 into a Matrix33 and also converts between double/float.
//Matrix33(diag33);
template<class F1>
ILINE Matrix33_tpl<F>(const Diag33_tpl<F1>&d)
{
assert(d.IsValid());
m00 = F(d.x);
m01 = 0;
m02 = 0;
m10 = 0;
m11 = F(d.y);
m12 = 0;
m20 = 0;
m21 = 0;
m22 = F(d.z);
}
//CONSTRUCTOR for identical float-types
//Matrix33 m=m33;
ILINE Matrix33_tpl<F>(const Matrix33_tpl<F>&m)
@@ -1252,40 +1214,6 @@ typedef Matrix33_tpl<real> Matrix33r; //variable float precision. depending on t
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
template<class F1, class F2>
ILINE Matrix33_tpl<F1> operator*(const Matrix33_tpl<F1>& l, const Diag33_tpl<F2>& r)
{
assert(l.IsValid());
assert(r.IsValid());
Matrix33_tpl<F1> res;
res.m00 = l.m00 * r.x;
res.m01 = l.m01 * r.y;
res.m02 = l.m02 * r.z;
res.m10 = l.m10 * r.x;
res.m11 = l.m11 * r.y;
res.m12 = l.m12 * r.z;
res.m20 = l.m20 * r.x;
res.m21 = l.m21 * r.y;
res.m22 = l.m22 * r.z;
return res;
}
template<class F1, class F2>
ILINE Matrix33_tpl<F1>& operator *= (Matrix33_tpl<F1>& l, const Diag33_tpl<F2>& r)
{
assert(l.IsValid());
assert(r.IsValid());
l.m00 *= r.x;
l.m01 *= r.y;
l.m02 *= r.z;
l.m10 *= r.x;
l.m11 *= r.y;
l.m12 *= r.z;
l.m20 *= r.x;
l.m21 *= r.y;
l.m22 *= r.z;
return l;
}
//Matrix33 operations with another Matrix33
template<class F1, class F2>
ILINE Matrix33_tpl<F1> operator * (const Matrix33_tpl<F1>& l, const Matrix33_tpl<F2>& r)
-37
View File
@@ -1281,43 +1281,6 @@ ILINE Vec3_tpl<F> operator * (const Matrix34_tpl<F>& m, const Vec3_tpl<F>& p)
return tp;
}
template<class F1, class F2>
ILINE Matrix34_tpl<F1> operator*(const Matrix34_tpl<F1>& l, const Diag33_tpl<F2>& r)
{
assert(l.IsValid());
assert(r.IsValid());
Matrix34_tpl<F1> m;
m.m00 = l.m00 * r.x;
m.m01 = l.m01 * r.y;
m.m02 = l.m02 * r.z;
m.m03 = l.m03;
m.m10 = l.m10 * r.x;
m.m11 = l.m11 * r.y;
m.m12 = l.m12 * r.z;
m.m13 = l.m13;
m.m20 = l.m20 * r.x;
m.m21 = l.m21 * r.y;
m.m22 = l.m22 * r.z;
m.m23 = l.m23;
return m;
}
template<class F1, class F2>
ILINE Matrix34_tpl<F1>& operator *= (Matrix34_tpl<F1>& l, const Diag33_tpl<F2>& r)
{
assert(l.IsValid());
assert(r.IsValid());
l.m00 *= r.x;
l.m01 *= r.y;
l.m02 *= r.z;
l.m10 *= r.x;
l.m11 *= r.y;
l.m12 *= r.z;
l.m20 *= r.x;
l.m21 *= r.y;
l.m22 *= r.z;
return l;
}
template<class F1, class F2>
ILINE Matrix34_tpl<F1> operator + (const Matrix34_tpl<F1>& l, const Matrix34_tpl<F2>& r)
{
-57
View File
@@ -680,63 +680,6 @@ typedef Matrix44_tpl<real> Matrix44r; //variable float precision. depending on
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
/*!
* Implements the multiplication operator: Matrix44=Matrix44*Matrix33diag
*
* Matrix44 and Matrix33diag are specified in collumn order.
* AxB = operation B followed by operation A.
* This operation takes 12 mults.
*
* Example:
* Matrix33diag diag(1,2,3);
* Matrix44 m44=CreateRotationZ33(3.14192f);
* Matrix44 result=m44*diag;
*/
template<class F1, class F2>
ILINE Matrix44_tpl<F1> operator * (const Matrix44_tpl<F1>& l, const Diag33_tpl<F2>& r)
{
assert(l.IsValid());
assert(r.IsValid());
Matrix44_tpl<F1> m;
m.m00 = l.m00 * r.x;
m.m01 = l.m01 * r.y;
m.m02 = l.m02 * r.z;
m.m03 = l.m03;
m.m10 = l.m10 * r.x;
m.m11 = l.m11 * r.y;
m.m12 = l.m12 * r.z;
m.m13 = l.m13;
m.m20 = l.m20 * r.x;
m.m21 = l.m21 * r.y;
m.m22 = l.m22 * r.z;
m.m23 = l.m23;
m.m30 = l.m30 * r.x;
m.m31 = l.m31 * r.y;
m.m32 = l.m32 * r.z;
m.m33 = l.m33;
return m;
}
template<class F1, class F2>
ILINE Matrix44_tpl<F1>& operator *= (Matrix44_tpl<F1>& l, const Diag33_tpl<F2>& r)
{
assert(l.IsValid());
assert(r.IsValid());
l.m00 *= r.x;
l.m01 *= r.y;
l.m02 *= r.z;
l.m10 *= r.x;
l.m11 *= r.y;
l.m12 *= r.z;
l.m20 *= r.x;
l.m21 *= r.y;
l.m22 *= r.z;
l.m30 *= r.x;
l.m31 *= r.y;
l.m32 *= r.z;
return l;
}
/*!
* Implements the multiplication operator: Matrix44=Matrix44*Matrix33
*
-192
View File
@@ -1,192 +0,0 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
// Description : Common matrix class
#ifndef CRYINCLUDE_CRYCOMMON_CRY_MATRIXDIAG_H
#define CRYINCLUDE_CRYCOMMON_CRY_MATRIXDIAG_H
#pragma once
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct Diag33_tpl
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
template<typename F>
struct Diag33_tpl
{
F x, y, z;
#ifdef _DEBUG
ILINE Diag33_tpl()
{
if constexpr (sizeof(F) == 4)
{
uint32* p = alias_cast<uint32*>(&x);
p[0] = F32NAN;
p[1] = F32NAN;
p[2] = F32NAN;
}
if constexpr (sizeof(F) == 8)
{
uint64* p = alias_cast<uint64*>(&x);
p[0] = F64NAN;
p[1] = F64NAN;
p[2] = F64NAN;
}
}
#else
ILINE Diag33_tpl() {};
#endif
Diag33_tpl(F dx, F dy, F dz) { x = dx; y = dy; z = dz; }
Diag33_tpl(const Vec3_tpl<F>& v) { x = v.x; y = v.y; z = v.z; }
template<class F1>
const Diag33_tpl& operator=(const Vec3_tpl<F1>& v) { x = v.x; y = v.y; z = v.z; return *this; }
Diag33_tpl& operator=(const Diag33_tpl<F>& diag) { x = diag.x; y = diag.y; z = diag.z; return *this; }
template<class F1>
Diag33_tpl& operator=(const Diag33_tpl<F1>& diag) { x = diag.x; y = diag.y; z = diag.z; return *this; }
const void SetIdentity() { x = y = z = 1; }
Diag33_tpl(type_identity) { x = y = z = 1; }
const Diag33_tpl& zero() { x = y = z = 0; return *this; }
Diag33_tpl& fabs() { x = fabs_tpl(x); y = fabs_tpl(y); z = fabs_tpl(z); return *this; }
Diag33_tpl& invert() // in-place inversion
{
F det = determinant();
if (det == 0)
{
return *this;
}
det = (F)1.0 / det;
F oldata[3];
oldata[0] = x;
oldata[1] = y;
oldata[2] = z;
x = oldata[1] * oldata[2] * det;
y = oldata[0] * oldata[2] * det;
z = oldata[0] * oldata[1] * det;
return *this;
}
/*!
* Linear-Interpolation between Diag33(lerp)
*
* Example:
* Diag33 r=Diag33::CreateLerp( p, q, 0.345f );
*/
ILINE void SetLerp(const Diag33_tpl<F>& p, const Diag33_tpl<F>& q, F t)
{
x = p.x * (1.0f - t) + q.x * t;
y = p.y * (1.0f - t) + q.y * t;
z = p.z * (1.0f - t) + q.z * t;
}
ILINE static Diag33_tpl<F> CreateLerp(const Diag33_tpl<F>& p, const Diag33_tpl<F>& q, F t)
{
Diag33_tpl<F> d;
d.x = p.x * (1.0f - t) + q.x * t;
d.y = p.y * (1.0f - t) + q.y * t;
d.z = p.z * (1.0f - t) + q.z * t;
return d;
}
F determinant() const { return x * y * z; }
ILINE bool IsValid() const
{
if (!NumberValid(x))
{
return false;
}
if (!NumberValid(y))
{
return false;
}
if (!NumberValid(z))
{
return false;
}
return true;
}
};
///////////////////////////////////////////////////////////////////////////////
// Typedefs //
///////////////////////////////////////////////////////////////////////////////
typedef Diag33_tpl<f32> Diag33; //always 32 bit
typedef Diag33_tpl<f64> Diag33d;//always 64 bit
typedef Diag33_tpl<real> Diag33r;//variable float precision. depending on the target system it can be between 32, 64 or 80 bit
template<class F1, class F2>
Diag33_tpl<F1> operator*(const Diag33_tpl<F1>& l, const Diag33_tpl<F2>& r)
{
return Diag33_tpl<F1>(l.x * r.x, l.y * r.y, l.z * r.z);
}
template<class F1, class F2>
Matrix33_tpl<F2> operator*(const Diag33_tpl<F1>& l, const Matrix33_tpl<F2>& r)
{
Matrix33_tpl<F2> res;
res.m00 = r.m00 * l.x;
res.m01 = r.m01 * l.x;
res.m02 = r.m02 * l.x;
res.m10 = r.m10 * l.y;
res.m11 = r.m11 * l.y;
res.m12 = r.m12 * l.y;
res.m20 = r.m20 * l.z;
res.m21 = r.m21 * l.z;
res.m22 = r.m22 * l.z;
return res;
}
template<class F1, class F2>
Matrix34_tpl<F2> operator*(const Diag33_tpl<F1>& l, const Matrix34_tpl<F2>& r)
{
Matrix34_tpl<F2> m;
m.m00 = l.x * r.m00;
m.m01 = l.x * r.m01;
m.m02 = l.x * r.m02;
m.m03 = l.x * r.m03;
m.m10 = l.y * r.m10;
m.m11 = l.y * r.m11;
m.m12 = l.y * r.m12;
m.m13 = l.y * r.m13;
m.m20 = l.z * r.m20;
m.m21 = l.z * r.m21;
m.m22 = l.z * r.m22;
m.m23 = l.z * r.m23;
return m;
}
template<class F1, class F2>
Vec3_tpl<F2> operator *(const Diag33_tpl<F1>& mtx, const Vec3_tpl<F2>& vec)
{
return Vec3_tpl<F2>(mtx.x * vec.x, mtx.y * vec.y, mtx.z * vec.z);
}
template<class F1, class F2>
Vec3_tpl<F1> operator *(const Vec3_tpl<F1>& vec, const Diag33_tpl<F2>& mtx)
{
return Vec3_tpl<F1>(mtx.x * vec.x, mtx.y * vec.y, mtx.z * vec.z);
}
#endif // CRYINCLUDE_CRYCOMMON_CRY_MATRIXDIAG_H
-566
View File
@@ -1,566 +0,0 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
// Description : Misc mathematical functions
#ifndef CRYINCLUDE_CRYCOMMON_CRY_XOPTIMISE_H
#define CRYINCLUDE_CRYCOMMON_CRY_XOPTIMISE_H
#pragma once
#include <platform.h>
inline float AngleMod(float a)
{
a = (float)((360.0 / 65536) * ((int)(a * (65536 / 360.0)) & 65535));
return a;
}
inline float AngleModRad(float a)
{
a = (float)((gf_PI2 / 65536) * ((int)(a * (65536 / gf_PI2)) & 65535));
return a;
}
inline unsigned short Degr2Word(float f)
{
return (unsigned short)(AngleMod(f) / 360.0f * 65536.0f);
}
inline float Word2Degr(unsigned short s)
{
return (float)s / 65536.0f * 360.0f;
}
#if defined(_CPU_X86)
ILINE float __fastcall Ffabs(float f)
{
*((unsigned*) &f) &= ~0x80000000;
return (f);
}
#else
inline float Ffabs(float x) { return fabsf(x); }
#endif
#define mathMatrixRotationZ(pOut, angle) (*(Matrix44*)pOut) = GetTransposed44(Matrix44(Matrix34::CreateRotationZ(angle)))
#define mathMatrixRotationY(pOut, angle) (*(Matrix44*)pOut) = GetTransposed44(Matrix44(Matrix34::CreateRotationY(angle)))
#define mathMatrixRotationX(pOut, angle) (*(Matrix44*)pOut) = GetTransposed44(Matrix44(Matrix34::CreateRotationX(angle)))
#define mathMatrixTranslation(pOut, x, y, z) (*(Matrix44*)pOut) = GetTransposed44(Matrix44(Matrix34::CreateTranslationMat(Vec3(x, y, z))))
#define mathMatrixScaling(pOut, sx, sy, sz) (*(Matrix44*)pOut) = GetTransposed44(Matrix44(Matrix34::CreateScale(Vec3(sx, sy, sz))))
template <class T>
inline void ExchangeVals(T& X, T& Y)
{
const T Tmp = X;
X = Y;
Y = Tmp;
}
inline void mathMatrixPerspectiveFov(Matrix44A* pMatr, f32 fovY, f32 Aspect, f32 zn, f32 zf)
{
f32 yScale = 1.0f / tan_tpl(fovY / 2.0f);
f32 xScale = yScale / Aspect;
f32 m22 = f32(f64(zf) / (f64(zn) - f64(zf)));
f32 m32 = f32(f64(zn) * f64(zf) / (f64(zn) - f64(zf)));
(*pMatr)(0, 0) = xScale;
(*pMatr)(0, 1) = 0;
(*pMatr)(0, 2) = 0;
(*pMatr)(0, 3) = 0;
(*pMatr)(1, 0) = 0;
(*pMatr)(1, 1) = yScale;
(*pMatr)(1, 2) = 0;
(*pMatr)(1, 3) = 0;
(*pMatr)(2, 0) = 0;
(*pMatr)(2, 1) = 0;
(*pMatr)(2, 2) = m22;
(*pMatr)(2, 3) = -1.0f;
(*pMatr)(3, 0) = 0;
(*pMatr)(3, 1) = 0;
(*pMatr)(3, 2) = m32;
(*pMatr)(3, 3) = 0;
}
inline void mathMatrixOrtho(Matrix44A* pMatr, f32 w, f32 h, f32 zn, f32 zf)
{
f32 m22 = f32(1.0 / (f64(zn) - f64(zf)));
f32 m32 = f32(f64(zn) / (f64(zn) - f64(zf)));
(*pMatr)(0, 0) = 2.0f / w;
(*pMatr)(0, 1) = 0;
(*pMatr)(0, 2) = 0;
(*pMatr)(0, 3) = 0;
(*pMatr)(1, 0) = 0;
(*pMatr)(1, 1) = 2.0f / h;
(*pMatr)(1, 2) = 0;
(*pMatr)(1, 3) = 0;
(*pMatr)(2, 0) = 0;
(*pMatr)(2, 1) = 0;
(*pMatr)(2, 2) = m22;
(*pMatr)(2, 3) = 0;
(*pMatr)(3, 0) = 0;
(*pMatr)(3, 1) = 0;
(*pMatr)(3, 2) = m32;
(*pMatr)(3, 3) = 1;
}
inline void mathMatrixOrthoOffCenter(Matrix44A* pMatr, f32 l, f32 r, f32 b, f32 t, f32 zn, f32 zf)
{
f32 m22 = f32(1.0 / (f64(zn) - f64(zf)));
f32 m32 = f32(f64(zn) / (f64(zn) - f64(zf)));
(*pMatr)(0, 0) = 2.0f / (r - l);
(*pMatr)(0, 1) = 0;
(*pMatr)(0, 2) = 0;
(*pMatr)(0, 3) = 0;
(*pMatr)(1, 0) = 0;
(*pMatr)(1, 1) = 2.0f / (t - b);
(*pMatr)(1, 2) = 0;
(*pMatr)(1, 3) = 0;
(*pMatr)(2, 0) = 0;
(*pMatr)(2, 1) = 0;
(*pMatr)(2, 2) = m22;
(*pMatr)(2, 3) = 0;
(*pMatr)(3, 0) = (l + r) / (l - r);
(*pMatr)(3, 1) = (t + b) / (b - t);
(*pMatr)(3, 2) = m32;
(*pMatr)(3, 3) = 1.0f;
}
inline void mathMatrixOrthoOffCenterLH(Matrix44A* pMatr, f32 l, f32 r, f32 b, f32 t, f32 zn, f32 zf)
{
f32 m22 = f32(1.0 / (f64(zf) - f64(zn)));
f32 m32 = f32(f64(zn) / (f64(zn) - f64(zf)));
(*pMatr)(0, 0) = 2.0f / (r - l);
(*pMatr)(0, 1) = 0;
(*pMatr)(0, 2) = 0;
(*pMatr)(0, 3) = 0;
(*pMatr)(1, 0) = 0;
(*pMatr)(1, 1) = 2.0f / (t - b);
(*pMatr)(1, 2) = 0;
(*pMatr)(1, 3) = 0;
(*pMatr)(2, 0) = 0;
(*pMatr)(2, 1) = 0;
(*pMatr)(2, 2) = m22;
(*pMatr)(2, 3) = 0;
(*pMatr)(3, 0) = (l + r) / (l - r);
(*pMatr)(3, 1) = (t + b) / (b - t);
(*pMatr)(3, 2) = m32;
(*pMatr)(3, 3) = 1.0f;
}
inline void mathMatrixPerspectiveOffCenter(Matrix44A* pMatr, f32 l, f32 r, f32 b, f32 t, f32 zn, f32 zf)
{
f32 m22 = f32(f64(zf) / (f64(zn) - f64(zf)));
f32 m32 = f32(f64(zn) * f64(zf) / (f64(zn) - f64(zf)));
(*pMatr)(0, 0) = 2 * zn / (r - l);
(*pMatr)(0, 1) = 0;
(*pMatr)(0, 2) = 0;
(*pMatr)(0, 3) = 0;
(*pMatr)(1, 0) = 0;
(*pMatr)(1, 1) = 2 * zn / (t - b);
(*pMatr)(1, 2) = 0;
(*pMatr)(1, 3) = 0;
(*pMatr)(2, 0) = (l + r) / (r - l);
(*pMatr)(2, 1) = (t + b) / (t - b);
(*pMatr)(2, 2) = m22;
(*pMatr)(2, 3) = -1;
(*pMatr)(3, 0) = 0;
(*pMatr)(3, 1) = 0;
(*pMatr)(3, 2) = m32;
(*pMatr)(3, 3) = 0;
}
inline void mathMatrixPerspectiveOffCenterReverseDepth(Matrix44A* pMatr, f32 l, f32 r, f32 b, f32 t, f32 zn, f32 zf)
{
f32 m22 = f32(-f64(zn) / (f64(zn) - f64(zf)));
f32 m32 = f32(-f64(zn) * f64(zf) / (f64(zn) - f64(zf)));
(*pMatr)(0, 0) = 2 * zn / (r - l);
(*pMatr)(0, 1) = 0;
(*pMatr)(0, 2) = 0;
(*pMatr)(0, 3) = 0;
(*pMatr)(1, 0) = 0;
(*pMatr)(1, 1) = 2 * zn / (t - b);
(*pMatr)(1, 2) = 0;
(*pMatr)(1, 3) = 0;
(*pMatr)(2, 0) = (l + r) / (r - l);
(*pMatr)(2, 1) = (t + b) / (t - b);
(*pMatr)(2, 2) = m22;
(*pMatr)(2, 3) = -1;
(*pMatr)(3, 0) = 0;
(*pMatr)(3, 1) = 0;
(*pMatr)(3, 2) = m32;
(*pMatr)(3, 3) = 0;
}
//RH
inline void mathMatrixLookAt(Matrix44A* pMatr, const Vec3& Eye, const Vec3& At, const Vec3& Up)
{
Vec3 vLightDir = (Eye - At);
Vec3 zaxis = vLightDir.GetNormalized();
Vec3 xaxis = (Up.Cross(zaxis)).GetNormalized();
Vec3 yaxis = zaxis.Cross(xaxis);
(*pMatr)(0, 0) = xaxis.x;
(*pMatr)(0, 1) = yaxis.x;
(*pMatr)(0, 2) = zaxis.x;
(*pMatr)(0, 3) = 0;
(*pMatr)(1, 0) = xaxis.y;
(*pMatr)(1, 1) = yaxis.y;
(*pMatr)(1, 2) = zaxis.y;
(*pMatr)(1, 3) = 0;
(*pMatr)(2, 0) = xaxis.z;
(*pMatr)(2, 1) = yaxis.z;
(*pMatr)(2, 2) = zaxis.z;
(*pMatr)(2, 3) = 0;
(*pMatr)(3, 0) = -xaxis.Dot(Eye);
(*pMatr)(3, 1) = -yaxis.Dot(Eye);
(*pMatr)(3, 2) = -zaxis.Dot(Eye);
(*pMatr)(3, 3) = 1;
}
inline bool mathMatrixPerspectiveFovInverse(Matrix44_tpl<f64>* pResult, const Matrix44A* pProjFov)
{
if ((*pProjFov)(0, 1) == 0.0f && (*pProjFov)(0, 2) == 0.0f && (*pProjFov)(0, 3) == 0.0f &&
(*pProjFov)(1, 0) == 0.0f && (*pProjFov)(1, 2) == 0.0f && (*pProjFov)(1, 3) == 0.0f &&
(*pProjFov)(3, 0) == 0.0f && (*pProjFov)(3, 1) == 0.0f && (*pProjFov)(3, 2) != 0.0f)
{
(*pResult)(0, 0) = 1.0 / (*pProjFov).m00;
(*pResult)(0, 1) = 0;
(*pResult)(0, 2) = 0;
(*pResult)(0, 3) = 0;
(*pResult)(1, 0) = 0;
(*pResult)(1, 1) = 1.0 / (*pProjFov).m11;
(*pResult)(1, 2) = 0;
(*pResult)(1, 3) = 0;
(*pResult)(2, 0) = 0;
(*pResult)(2, 1) = 0;
(*pResult)(2, 2) = 0;
(*pResult)(2, 3) = 1.0 / (*pProjFov).m32;
(*pResult)(3, 0) = (*pProjFov).m20 / (*pProjFov).m00;
(*pResult)(3, 1) = (*pProjFov).m21 / (*pProjFov).m11;
(*pResult)(3, 2) = -1;
(*pResult)(3, 3) = (*pProjFov).m22 / (*pProjFov).m32;
return true;
}
return false;
}
template<class T_out, class T_in>
inline void mathMatrixLookAtInverse(Matrix44_tpl<T_out>* pResult, const Matrix44_tpl<T_in>* pLookAt)
{
(*pResult)(0, 0) = (*pLookAt).m00;
(*pResult)(0, 1) = (*pLookAt).m10;
(*pResult)(0, 2) = (*pLookAt).m20;
(*pResult)(0, 3) = (*pLookAt).m03;
(*pResult)(1, 0) = (*pLookAt).m01;
(*pResult)(1, 1) = (*pLookAt).m11;
(*pResult)(1, 2) = (*pLookAt).m21;
(*pResult)(1, 3) = (*pLookAt).m13;
(*pResult)(2, 0) = (*pLookAt).m02;
(*pResult)(2, 1) = (*pLookAt).m12;
(*pResult)(2, 2) = (*pLookAt).m22;
(*pResult)(2, 3) = (*pLookAt).m23;
(*pResult)(3, 0) = T_out(-(f64((*pLookAt).m00) * f64((*pLookAt).m30) + f64((*pLookAt).m01) * f64((*pLookAt).m31) + f64((*pLookAt).m02) * f64((*pLookAt).m32)));
(*pResult)(3, 1) = T_out(-(f64((*pLookAt).m10) * f64((*pLookAt).m30) + f64((*pLookAt).m11) * f64((*pLookAt).m31) + f64((*pLookAt).m12) * f64((*pLookAt).m32)));
(*pResult)(3, 2) = T_out(-(f64((*pLookAt).m20) * f64((*pLookAt).m30) + f64((*pLookAt).m21) * f64((*pLookAt).m31) + f64((*pLookAt).m22) * f64((*pLookAt).m32)));
(*pResult)(3, 3) = (*pLookAt).m33;
};
inline void mathVec4Transform(f32 out[4], const f32 m[16], const f32 in[4])
{
#define M(row, col) m[col * 4 + row]
out[0] = M(0, 0) * in[0] + M(0, 1) * in[1] + M(0, 2) * in[2] + M(0, 3) * in[3];
out[1] = M(1, 0) * in[0] + M(1, 1) * in[1] + M(1, 2) * in[2] + M(1, 3) * in[3];
out[2] = M(2, 0) * in[0] + M(2, 1) * in[1] + M(2, 2) * in[2] + M(2, 3) * in[3];
out[3] = M(3, 0) * in[0] + M(3, 1) * in[1] + M(3, 2) * in[2] + M(3, 3) * in[3];
#undef M
}
//fix: replace by 3x4 Matrix transformation and move to crymath
inline void mathVec3Transform(f32 out[4], const f32 m[16], const f32 in[3])
{
#define M(row, col) m[col * 4 + row]
out[0] = M(0, 0) * in[0] + M(0, 1) * in[1] + M(0, 2) * in[2] + M(0, 3) * 1.0f;
out[1] = M(1, 0) * in[0] + M(1, 1) * in[1] + M(1, 2) * in[2] + M(1, 3) * 1.0f;
out[2] = M(2, 0) * in[0] + M(2, 1) * in[1] + M(2, 2) * in[2] + M(2, 3) * 1.0f;
out[3] = M(3, 0) * in[0] + M(3, 1) * in[1] + M(3, 2) * in[2] + M(3, 3) * 1.0f;
#undef M
}
#define mathVec3TransformF(pOut, pV, pM) mathVec3Transform((f32*)pOut, (const f32*)pM, (f32*)pV)
#define mathVec4TransformF(pOut, pV, pM) mathVec4Transform((f32*)pOut, (const f32*)pM, (f32*)pV)
#define mathVec3NormalizeF(pOut, pV) (*(Vec3*)pOut) = (((Vec3*)pV)->GetNormalizedSafe())
#define mathVec2NormalizeF(pOut, pV) (*(Vec2*)pOut) = (((Vec2*)pV)->GetNormalizedSafe())
//fix replace viewport by int16 array
//fix for d3d viewport
inline f32 mathVec3Project(Vec3* pvWin, const Vec3* pvObj, const int32 pViewport[4], const Matrix44A* pProjection, const Matrix44A* pView, const Matrix44A* pWorld)
{
Vec4 in, out;
in.x = pvObj->x;
in.y = pvObj->y;
in.z = pvObj->z;
in.w = 1.0f;
mathVec4Transform((f32*)&out, (f32*)pWorld, (f32*)&in);
mathVec4Transform((f32*)&in, (f32*)pView, (f32*)&out);
mathVec4Transform((f32*)&out, (f32*)pProjection, (f32*)&in);
if (out.w == 0.0f)
{
return 0.f;
}
out.x /= out.w;
out.y /= out.w;
out.z /= out.w;
//output coords
pvWin->x = pViewport[0] + (1 + out.x) * pViewport[2] / 2;
pvWin->y = pViewport[1] + (1 - out.y) * pViewport[3] / 2; //flip coords for y axis
//FIX: update fViewportMinZ fViewportMaxZ support for Viewport everywhere
float fViewportMinZ = 0, fViewportMaxZ = 1.0f;
pvWin->z = fViewportMinZ + out.z * (fViewportMaxZ - fViewportMinZ);
return out.w;
}
inline Vec3* mathVec3UnProject(Vec3* pvObj, const Vec3* pvWin, const int32 pViewport[4], const Matrix44A* pProjection, const Matrix44A* pView, const Matrix44A* pWorld, [[maybe_unused]] int32 OptFlags)
{
Matrix44A m, mA;
Vec4 in, out;
//FIX: update fViewportMinZ fViewportMaxZ support for Viewport everywhere
float fViewportMinZ = 0, fViewportMaxZ = 1.0f;
in.x = (pvWin->x - pViewport[0]) * 2 / pViewport[2] - 1.0f;
in.y = 1.0f - ((pvWin->y - pViewport[1]) * 2 / pViewport[3]); //flip coords for y axis
in.z = (pvWin->z - fViewportMinZ) / (fViewportMaxZ - fViewportMinZ);
in.w = 1.0f;
//prepare inverse projection matrix
mA = ((*pWorld) * (*pView)) * (*pProjection);
m = mA.GetInverted();
mathVec4Transform((f32*)&out, m.GetData(), (f32*)&in);
if (out.w == 0.0f)
{
return NULL;
}
pvObj->x = out.x / out.w;
pvObj->y = out.y / out.w;
pvObj->z = out.z / out.w;
return pvObj;
}
inline Vec3* mathVec3ProjectArray(Vec3* pOut, uint32 OutStride, const Vec3* pV, uint32 VStride, const int32 pViewport[4], const Matrix44A* pProjection, const Matrix44A* pView, const Matrix44A* pWorld, uint32 n, int32)
{
Matrix44A m;
Vec4 in, out;
int8* pOutT = (int8*)pOut;
int8* pInT = (int8*)pV;
Vec3* pvWin;
Vec3* pvObj;
//FIX: update fViewportMinZ fViewportMaxZ support for Viewport everywhere
float fViewportMinZ = 0, fViewportMaxZ = 1.0f;
m = ((*pWorld) * (*pView)) * (*pProjection);
for (uint32 i = 0; i < n; i++)
{
pvObj = (Vec3*)pInT;
pvWin = (Vec3*)pOutT;
in.x = pvObj->x;
in.y = pvObj->y;
in.z = pvObj->z;
in.w = 1.0f;
mathVec4Transform((f32*)&out, m.GetData(), (f32*)&in);
if (out.w == 0.0f)
{
return NULL;
}
float fInvW = 1.0f / out.w;
out.x *= fInvW;
out.y *= fInvW;
out.z *= fInvW;
//output coords
pvWin->x = pViewport[0] + (1 + out.x) * pViewport[2] / 2;
pvWin->y = pViewport[1] + (1 - out.y) * pViewport[3] / 2; //flip coords for y axis
pvWin->z = fViewportMinZ + out.z * (fViewportMaxZ - fViewportMinZ);
pOutT += OutStride;
pInT += VStride;
}
return pOut;
}
inline Vec3* mathVec3UnprojectArray(Vec3* pOut, uint32 OutStride, const Vec3* pV, uint32 VStride, const int32 pViewport[4], const Matrix44* pProjection, const Matrix44* pView, const Matrix44* pWorld, uint32 n, [[maybe_unused]] int32 OptFlags)
{
Vec4 in, out;
Matrix44 m, mA;
int8* pOutT = (int8*)pOut;
int8* pInT = (int8*)pV;
Vec3* pvWin;
Vec3* pvObj;
//FIX: update fViewportMinZ fViewportMaxZ support for Viewport everywhere
float fViewportMinZ = 0, fViewportMaxZ = 1.0f;
mA = ((*pWorld) * (*pView)) * (*pProjection);
m = mA.GetInverted();
for (uint32 i = 0; i < n; i++)
{
pvWin = (Vec3*)pInT;
pvObj = (Vec3*)pOutT;
in.x = (pvWin->x - pViewport[0]) * 2 / pViewport[2] - 1.0f;
in.y = 1.0f - ((pvWin->y - pViewport[1]) * 2 / pViewport[3]); //flip coords for y axis
in.z = (pvWin->z - fViewportMinZ) / (fViewportMaxZ - fViewportMinZ);
in.w = 1.0f;
mathVec4Transform((f32*)&out, m.GetData(), (f32*)&in);
assert(out.w != 0.0f);
if (out.w == 0.0f)
{
return NULL;
}
pvObj->x = out.x / out.w;
pvObj->y = out.y / out.w;
pvObj->z = out.z / out.w;
pOutT += OutStride;
pInT += VStride;
}
return pOut;
}
/*****************************************************
MISC FUNCTIONS
*****************************************************/
//////////////////////////////////////////////////////////////////////////
#if defined(_CPU_X86)
inline int fastftol_positive(float f)
{
int i;
f -= 0.5f;
#if defined(_MSC_VER)
__asm fld [f]
__asm fistp [i]
#elif defined(__GNUC__)
__asm__ ("fld %[f]\n fistpl %[i]" : [i] "+m" (i) : [f] "m" (f));
#else
#error
#endif
return i;
}
#else
inline int fastftol_positive (float f)
{
assert(f >= 0.f);
return (int)floorf(f);
}
#endif
//////////////////////////////////////////////////////////////////////////
#if defined(_CPU_X86)
inline int fastround_positive(float f)
{
int i;
assert(f >= 0.f);
#if defined(_MSC_VER)
__asm fld [f]
__asm fistp [i]
#elif defined(__GNUC__)
__asm__ ("fld %[f]\n fistpl %[i]" : [i] "+m" (i) : [f] "m" (f));
#else
#error
#endif
return i;
}
#else
inline int fastround_positive(float f)
{
assert(f >= 0.f);
return (int) (f + 0.5f);
}
#endif
//////////////////////////////////////////////////////////////////////////
#if defined(_CPU_X86)
ILINE int __fastcall FtoI(float x)
{
int t;
#if defined(_MSC_VER)
__asm
{
fld x
fistp t
}
#elif defined(__GNUC__)
__asm__ ("fld %[x]\n fistpl %[t]" : [t] "+m" (t) : [x] "m" (x));
#else
#error
#endif
return t;
}
#else
inline int FtoI(float x) { return (int)x; }
#endif
#endif // CRYINCLUDE_CRYCOMMON_CRY_XOPTIMISE_H
-457
View File
@@ -1,457 +0,0 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#ifndef CRYINCLUDE_CRYCOMMON_HEAPALLOCATOR_H
#define CRYINCLUDE_CRYCOMMON_HEAPALLOCATOR_H
#pragma once
#include "Synchronization.h"
#include "Options.h"
#include <CrySizer.h>
//---------------------------------------------------------------------------
#define bMEM_ACCESS_CHECK 0
#define bMEM_HEAP_CHECK 0
namespace stl
{
class HeapSysAllocator
{
public:
static void* SysAlloc(size_t nSize)
{ return CryModuleMalloc(nSize); }
static void SysDealloc(void* ptr)
{ CryModuleFree(ptr); }
};
class GlobalHeapSysAllocator
{
public:
static void* SysAlloc(size_t nSize)
{
return CryModuleMalloc(nSize);
}
static void SysDealloc(void* ptr)
{
CryModuleFree(ptr);
}
};
// Round up to next multiple of nAlign. Handles any positive integer.
inline size_t RoundUpTo(size_t nSize, size_t nAlign)
{
assert(nAlign > 0);
nSize += nAlign - 1;
return nSize - nSize % nAlign;
}
/*---------------------------------------------------------------------------
HeapAllocator
A memory pool that can allocate arbitrary amounts of memory of arbitrary size
and alignment. The heap may be freed all at once. Individual block deallocation
is not provided.
Usable as a base class to implement more general-purpose allocators that
track, free, and reuse individual memory blocks.
The class can optionally support multi-threading, using the second
template parameter. By default it is multithread-safe.
See Synchronization.h.
Allocation details: Maintains a linked list of pages.
All pages after first are in order of most free memory first.
Allocations are from the smallest free page available.
---------------------------------------------------------------------------*/
struct SMemoryUsage
{
size_t nAlloc, nUsed;
SMemoryUsage(size_t _nAlloc = 0, size_t _nUsed = 0)
: nAlloc(_nAlloc)
, nUsed(_nUsed)
{
Validate();
}
size_t nFree() const
{
return nAlloc - nUsed;
}
void Validate() const
{
assert(nUsed <= nAlloc);
}
void Clear()
{
nAlloc = nUsed = 0;
}
void operator += (SMemoryUsage const& op)
{
nAlloc += op.nAlloc;
nUsed += op.nUsed;
}
};
//////////////////////////////////////////////////////////////////////////
struct FHeap
{
OPT_STRUCT(FHeap)
OPT_VAR(size_t, PageSize); // Pages allocated at this size, or multiple thereof if needed.
OPT_VAR(bool, SinglePage) // Only 1 page allowed (fixed alloc)
OPT_VAR(bool, FreeWhenEmpty) // Release all memory when no longer used
};
template <typename L = PSyncMultiThread, typename SysAl = HeapSysAllocator>
class HeapAllocator
: public FHeap
, public L
, private SysAl
{
public:
typedef AutoLock<L> Lock;
enum
{
DefaultAlignment = sizeof(void*)
};
enum
{
DefaultPageSize = 0x1000
};
private:
struct PageNode
{
PageNode* pNext;
char* pEndAlloc;
char* pEndUsed;
char* StartUsed() const
{
return (char*)(this + 1);
}
PageNode(size_t nAlloc)
{
pNext = 0;
pEndAlloc = (char*)this + nAlloc;
pEndUsed = StartUsed();
}
void* Allocate(size_t nSize, size_t nAlign)
{
// Align current mem.
char* pNew = Align(pEndUsed, nAlign);
if (pNew + nSize > pEndAlloc)
{
return 0;
}
pEndUsed = pNew + nSize;
return pNew;
}
bool CanAllocate(size_t nSize, size_t nAlign)
{
return Align(pEndUsed, nAlign) + nSize <= pEndAlloc;
}
void Reset()
{
pEndUsed = StartUsed();
}
size_t GetMemoryAlloc() const
{
return pEndAlloc - (char*)this;
}
size_t GetMemoryUsed() const
{
return pEndUsed - StartUsed();
}
size_t GetMemoryFree() const
{
return pEndAlloc - pEndUsed;
}
void Validate() const
{
assert(pEndAlloc >= (char*)this);
assert(pEndUsed >= StartUsed() && pEndUsed <= pEndAlloc);
}
bool CheckPtr(void* ptr) const
{
return (char*)ptr >= StartUsed() && (char*)ptr < pEndUsed;
}
};
public:
HeapAllocator(FHeap opts = 0)
: FHeap(opts)
, _pPageList(0)
{
PageSize = max<size_t>(Align(PageSize, DefaultPageSize), DefaultPageSize);
}
~HeapAllocator()
{
Clear();
}
//
// Raw memory allocation.
//
void* Allocate(const Lock& lock, size_t nSize, size_t nAlign = DefaultAlignment)
{
for (;; )
{
// Try allocating from head page first.
if (_pPageList)
{
if (void* ptr = _pPageList->Allocate(nSize, nAlign))
{
_TotalMem.nUsed += nSize;
return ptr;
}
if (_pPageList->pNext && _pPageList->pNext->GetMemoryFree() > _pPageList->GetMemoryFree())
{
SortPage(lock, _pPageList);
Validate(lock);
// Try allocating from new head, which has the most free memory.
// If this fails, we know no further pages will succeed.
if (void* ptr = _pPageList->Allocate(nSize, nAlign))
{
_TotalMem.nUsed += nSize;
return ptr;
}
}
if (SinglePage)
{
return 0;
}
}
// Allocate the new page of the required size.
size_t nAllocSize = Align(sizeof(PageNode), nAlign) + nSize;
nAllocSize = RoundUpTo(nAllocSize, PageSize);
void* pAlloc = this->SysAlloc(nAllocSize);
PageNode* pPageNode = new(pAlloc) PageNode(nAllocSize);
// Insert at head of list.
pPageNode->pNext = _pPageList;
_pPageList = pPageNode;
_TotalMem.nAlloc += nAllocSize;
Validate(lock);
}
}
void Deallocate([[maybe_unused]] const Lock& lock, [[maybe_unused]] void* ptr, size_t nSize)
{
// Just to maintain counts, can't reuse memory.
assert(CheckPtr(lock, ptr));
assert(_TotalMem.nUsed >= nSize);
_TotalMem.nUsed -= nSize;
}
//
// Templated type allocation.
//
template<typename T>
T* New(size_t nAlign = 0)
{
void* pMemory = Allocate(Lock(*this), sizeof(T), nAlign ? nAlign : alignof(T));
return pMemory ? new(pMemory) T : 0;
}
template<typename T>
T* NewArray(size_t nCount, size_t nAlign = 0)
{
void* pMemory = Allocate(Lock(*this), sizeof(T) * nCount, nAlign ? nAlign : alignof(T));
return pMemory ? new(pMemory) T[nCount] : 0;
}
//
// Maintenance.
//
SMemoryUsage GetTotalMemory(const Lock&)
{
return _TotalMem;
}
SMemoryUsage GetTotalMemory()
{
Lock lock(*this);
return _TotalMem;
}
// Facility to defer freeing of dead pages during memory release calls.
struct FreeMemLock
: Lock
{
struct PageNode* _pPageList;
FreeMemLock(L& lock)
: Lock(lock)
, _pPageList(0) {}
~FreeMemLock()
{
while (_pPageList != 0)
{
// Read the "next" pointer before deleting.
PageNode* pNext = _pPageList->pNext;
// Delete the current page.
SysAl::SysDealloc(_pPageList);
// Move to the next page in the list.
_pPageList = pNext;
}
}
};
void Clear(FreeMemLock& lock)
{
// Remove the pages from the object.
Validate(lock);
lock._pPageList = _pPageList;
_pPageList = 0;
_TotalMem.Clear();
}
void Clear()
{
FreeMemLock lock(*this);
Clear(lock);
}
void Reset(const Lock& lock)
{
// Reset all pages, allowing memory re-use.
Validate(lock);
size_t nPrevSize = ~0;
for (PageNode** ppPage = &_pPageList; *ppPage; )
{
(*ppPage)->Reset();
if ((*ppPage)->GetMemoryAlloc() > nPrevSize)
{
// Move page to sorted location near beginning.
SortPage(lock, *ppPage);
// ppPage is now next page, so continue loop.
continue;
}
nPrevSize = (*ppPage)->GetMemoryAlloc();
ppPage = &(*ppPage)->pNext;
}
_TotalMem.nUsed = 0;
Validate(lock);
}
void Reset()
{
Reset(Lock(*this));
}
//
// Validation.
//
bool CheckPtr(const Lock&, void* ptr) const
{
if (!ptr)
{
return true;
}
for (PageNode* pNode = _pPageList; pNode; pNode = pNode->pNext)
{
if (pNode->CheckPtr(ptr))
{
return true;
}
}
return false;
}
void Validate(const Lock&) const
{
#ifdef _DEBUG
// Check page validity, and memory counts.
SMemoryUsage MemCheck;
for (PageNode* pPage = _pPageList; pPage; pPage = pPage->pNext)
{
pPage->Validate();
if (pPage != _pPageList && pPage->pNext)
{
assert(pPage->GetMemoryFree() >= pPage->pNext->GetMemoryFree());
}
MemCheck.nAlloc += pPage->GetMemoryAlloc();
MemCheck.nUsed += pPage->GetMemoryUsed();
}
assert(MemCheck.nAlloc == _TotalMem.nAlloc);
assert(MemCheck.nUsed >= _TotalMem.nUsed);
#endif
#if bMEM_HEAP_CHECK
static int nCount = 0, nInterval = 0;
if (nCount++ >= nInterval)
{
nInterval++;
nCount = 0;
}
#endif
}
void GetMemoryUsage(ICrySizer* pSizer) const
{
Lock lock(non_const(*this));
for (PageNode* pNode = _pPageList; pNode; pNode = pNode->pNext)
{
pSizer->AddObject(pNode, pNode->GetMemoryAlloc());
}
}
private:
void SortPage(const Lock&, PageNode*& rpPage)
{
// Unlink rpPage.
PageNode* pPage = rpPage;
rpPage = pPage->pNext;
// Insert into list based on free memory.
PageNode** ppBefore = &_pPageList;
while (*ppBefore && (*ppBefore)->GetMemoryFree() > pPage->GetMemoryFree())
{
ppBefore = &(*ppBefore)->pNext;
}
// Link before rpList.
pPage->pNext = *ppBefore;
*ppBefore = pPage;
}
PageNode* _pPageList; // All allocated pages.
SMemoryUsage _TotalMem; // Track memory allocated and used.
};
}
#endif // CRYINCLUDE_CRYCOMMON_HEAPALLOCATOR_H
+4 -204
View File
@@ -6,21 +6,22 @@
*
*/
#ifndef CRYINCLUDE_CRYCOMMON_IENTITYRENDERSTATE_H
#define CRYINCLUDE_CRYCOMMON_IENTITYRENDERSTATE_H
#pragma once
#include "IStatObj.h"
#include <IRenderer.h>
#include <limits>
#include <AzCore/Component/EntityId.h>
namespace AZ
{
class Vector2;
}
struct IMaterial;
struct IRenderNode;
struct IVisArea;
struct SRenderingPassInfo;
struct SRendItemSorter;
@@ -576,51 +577,6 @@ struct IVoxelObject
// </interfuscator:shuffle>
};
// Summary:
// IFogVolumeRenderNode is an interface to the Fog Volume Render Node object.
struct SFogVolumeProperties
{
// Common parameters.
// Center position & rotation values are taken from the entity matrix.
int m_volumeType;
Vec3 m_size;
ColorF m_color;
bool m_useGlobalFogColor;
bool m_ignoresVisAreas;
bool m_affectsThisAreaOnly;
float m_globalDensity;
float m_densityOffset;
float m_softEdges;
float m_fHDRDynamic; // 0 to get the same results in LDR, <0 to get darker, >0 to get brighter.
float m_nearCutoff;
float m_heightFallOffDirLong; // Height based fog specifics.
float m_heightFallOffDirLati; // Height based fog specifics.
float m_heightFallOffShift; // Height based fog specifics.
float m_heightFallOffScale; // Height based fog specifics.
float m_rampStart;
float m_rampEnd;
float m_rampInfluence;
float m_windInfluence;
float m_densityNoiseScale;
float m_densityNoiseOffset;
float m_densityNoiseTimeFrequency;
Vec3 m_densityNoiseFrequency;
};
struct IFogVolumeRenderNode
: public IRenderNode
{
// <interfuscator:shuffle>
virtual void SetFogVolumeProperties(const SFogVolumeProperties& properties) = 0;
virtual const Matrix34& GetMatrix() const = 0;
virtual void FadeGlobalDensity(float fadeTime, float newGlobalDensity) = 0;
// </interfuscator:shuffle>
};
// LY renderer system spec levels.
enum class EngineSpec : AZ::u32
{
@@ -630,159 +586,3 @@ enum class EngineSpec : AZ::u32
VeryHigh,
Never = UINT_MAX,
};
struct SDecalProperties
{
SDecalProperties()
{
m_projectionType = ePlanar;
m_sortPrio = 0;
m_deferred = false;
m_pos = Vec3(0.0f, 0.0f, 0.0f);
m_normal = Vec3(0.0f, 0.0f, 1.0f);
m_explicitRightUpFront = Matrix33::CreateIdentity();
m_radius = 1.0f;
m_depth = 1.0f;
m_opacity = 1.0f;
m_angleAttenuation = 1.0f;
m_maxViewDist = 8000.0f;
m_minSpec = EngineSpec::Low;
}
enum EProjectionType : int
{
ePlanar,
eProjectOnTerrain,
eProjectOnTerrainAndStaticObjects
};
EProjectionType m_projectionType;
uint8 m_sortPrio;
uint8 m_deferred;
Vec3 m_pos;
Vec3 m_normal;
Matrix33 m_explicitRightUpFront;
float m_radius;
float m_depth;
const char* m_pMaterialName;
float m_opacity;
float m_angleAttenuation;
float m_maxViewDist;
EngineSpec m_minSpec;
};
// Description:
// IDecalRenderNode is an interface to the Decal Render Node object.
struct IDecalRenderNode
: public IRenderNode
{
// <interfuscator:shuffle>
virtual void SetDecalProperties(const SDecalProperties& properties) = 0;
virtual const SDecalProperties* GetDecalProperties() const = 0;
virtual const Matrix34& GetMatrix() = 0;
virtual void CleanUpOldDecals() = 0;
// </interfuscator:shuffle>
};
// Description:
// IWaterVolumeRenderNode is an interface to the Water Volume Render Node object.
struct IWaterVolumeRenderNode
: public IRenderNode
{
enum EWaterVolumeType
{
eWVT_Unknown,
eWVT_Ocean,
eWVT_Area,
eWVT_River
};
// <interfuscator:shuffle>
// Description:
// Sets if the render node is attached to a parent entity
// This must be called right after the object construction if it is the case
// Only supported for Areas (not rivers or ocean)
virtual void SetAreaAttachedToEntity() = 0;
virtual void SetFogDensity(float fogDensity) = 0;
virtual float GetFogDensity() const = 0;
virtual void SetFogColor(const Vec3& fogColor) = 0;
virtual void SetFogColorAffectedBySun(bool enable) = 0;
virtual void SetFogShadowing(float fogShadowing) = 0;
virtual void SetCapFogAtVolumeDepth(bool capFog) = 0;
virtual void SetVolumeDepth(float volumeDepth) = 0;
virtual void SetStreamSpeed(float streamSpeed) = 0;
virtual void SetCaustics(bool caustics) = 0;
virtual void SetCausticIntensity(float causticIntensity) = 0;
virtual void SetCausticTiling(float causticTiling) = 0;
virtual void SetCausticHeight(float causticHeight) = 0;
virtual void SetAuxPhysParams(pe_params_area*) = 0;
virtual void CreateOcean(uint64 volumeID, /* TBD */ bool keepSerializationParams = false) = 0;
virtual void CreateArea(uint64 volumeID, const Vec3* pVertices, unsigned int numVertices, const Vec2& surfUVScale, const Plane_tpl<f32>& fogPlane, bool keepSerializationParams = false, int nSID = -1) = 0;
virtual void CreateRiver(uint64 volumeID, const Vec3* pVertices, unsigned int numVertices, float uTexCoordBegin, float uTexCoordEnd, const Vec2& surfUVScale, const Plane_tpl<f32>& fogPlane, bool keepSerializationParams = false, int nSID = -1) = 0;
virtual void CreateRiver(uint64 volumeID, const AZStd::vector<AZ::Vector3>& verticies, const AZ::Transform& transform, float uTexCoordBegin, float uTexCoordEnd, const AZ::Vector2& surfUVScale, const AZ::Plane& fogPlane, bool keepSerializationParams = false, int nSID = -1) = 0;
virtual void SetAreaPhysicsArea(const Vec3* pVertices, unsigned int numVertices, bool keepSerializationParams = false) = 0;
virtual void SetRiverPhysicsArea(const Vec3* pVertices, unsigned int numVertices, bool keepSerializationParams = false) = 0;
virtual void SetRiverPhysicsArea(const AZStd::vector<AZ::Vector3>& verticies, const AZ::Transform& transform, bool keepSerializationParams = false) = 0;
// </interfuscator:shuffle>
// This flag is used to account for legacy entities which used to serialize the node without parent objects.
// Now there are runtime components which spawn the rendering node, however we need to support legacy code as well.
// Remove this flag when legacy entities are removed entirely
bool m_hasToBeSerialised = true;
};
// Description:
// IDistanceCloudRenderNode is an interface to the Distance Cloud Render Node object.
struct SDistanceCloudProperties
{
Vec3 m_pos;
float m_sizeX;
float m_sizeY;
float m_rotationZ;
const char* m_pMaterialName;
};
struct IDistanceCloudRenderNode
: public IRenderNode
{
virtual void SetProperties(const SDistanceCloudProperties& properties) = 0;
};
struct SVolumeObjectProperties
{
};
struct SVolumeObjectMovementProperties
{
bool m_autoMove;
Vec3 m_speed;
Vec3 m_spaceLoopBox;
float m_fadeDistance;
};
// Description:
// IVolumeObjectRenderNode is an interface to the Volume Object Render Node object.
struct IVolumeObjectRenderNode
: public IRenderNode
{
// <interfuscator:shuffle>
virtual void LoadVolumeData(const char* filePath) = 0;
virtual void SetProperties(const SVolumeObjectProperties& properties) = 0;
virtual void SetMovementProperties(const SVolumeObjectMovementProperties& properties) = 0;
// </interfuscator:shuffle>
};
#if !defined(EXCLUDE_DOCUMENTATION_PURPOSE)
struct IPrismRenderNode
: public IRenderNode
{
};
#endif // EXCLUDE_DOCUMENTATION_PURPOSE
#endif // CRYINCLUDE_CRYCOMMON_IENTITYRENDERSTATE_H
+1 -20
View File
@@ -15,6 +15,7 @@
#include "Cry_Color.h"
#include "StlUtils.h"
#include "CryEndian.h"
#include <CrySizer.h>
#include <Cry_Geo.h> // for AABB
#include <VertexFormats.h>
@@ -145,14 +146,6 @@ public:
a = othera;
}
explicit SMeshColor(const Vec4& otherc)
{
r = aznumeric_caster(FtoI(otherc.x));
g = aznumeric_caster(FtoI(otherc.y));
b = aznumeric_caster(FtoI(otherc.z));
a = aznumeric_caster(FtoI(otherc.w));
}
void TransferRGBTo(SMeshColor& other) const
{
other.r = r;
@@ -200,18 +193,6 @@ public:
otherc = Vec4(r, g, b, a);
}
void Lerp(const SMeshColor& other, float pos)
{
Vec4 clrA;
Vec4 clrB;
this->GetRGBA(clrA);
other.GetRGBA(clrB);
clrA.SetLerp(clrA, clrB, pos);
*this = SMeshColor(clrA);
}
AUTO_STRUCT_INFO
};
+1 -141
View File
@@ -8,10 +8,6 @@
// Description : IMaterial interface declaration.
#ifndef CRYINCLUDE_CRYCOMMON_IMATERIAL_H
#define CRYINCLUDE_CRYCOMMON_IMATERIAL_H
#pragma once
struct ISurfaceType;
@@ -19,18 +15,13 @@ struct ISurfaceTypeManager;
class ICrySizer;
enum EEfResTextures : int; // Need to specify a fixed size for the forward declare to work on clang
struct IRenderShaderResources;
struct SEfTexModificator;
struct SInputShaderResources;
struct SShaderItem;
struct SShaderParam;
struct IShader;
struct IShaderPublicParams;
struct IMaterial;
struct IMaterialManager;
struct CMaterialCGF;
struct CRenderChunk;
struct IRenderMesh;
#include <Tarray.h>
@@ -162,90 +153,6 @@ enum EMaterialCopyFlags
MTL_COPY_TEXTURES = BIT(1),
};
struct IMaterialHelpers
{
virtual ~IMaterialHelpers() {}
//////////////////////////////////////////////////////////////////////////
virtual EEfResTextures FindTexSlot(const char* texName) const = 0;
virtual const char* FindTexName(EEfResTextures texSlot) const = 0;
virtual const char* LookupTexName(EEfResTextures texSlot) const = 0;
virtual const char* LookupTexDesc(EEfResTextures texSlot) const = 0;
virtual const char* LookupTexEnum(EEfResTextures texSlot) const = 0;
virtual const char* LookupTexSuffix(EEfResTextures texSlot) const = 0;
virtual bool IsAdjustableTexSlot(EEfResTextures texSlot) const = 0;
//////////////////////////////////////////////////////////////////////////
virtual bool SetGetMaterialParamFloat(IRenderShaderResources& pShaderResources, const char* sParamName, float& v, bool bGet) const = 0;
virtual bool SetGetMaterialParamVec3(IRenderShaderResources& pShaderResources, const char* sParamName, Vec3& v, bool bGet) const = 0;
//////////////////////////////////////////////////////////////////////////
virtual void SetTexModFromXml(SEfTexModificator& pShaderResources, const XmlNodeRef& node) const = 0;
virtual void SetXmlFromTexMod(const SEfTexModificator& pShaderResources, XmlNodeRef& node) const = 0;
//////////////////////////////////////////////////////////////////////////
virtual void SetTexturesFromXml(SInputShaderResources& pShaderResources, const XmlNodeRef& node) const = 0;
virtual void SetXmlFromTextures( SInputShaderResources& pShaderResources, XmlNodeRef& node) const = 0;
//////////////////////////////////////////////////////////////////////////
virtual void SetVertexDeformFromXml(SInputShaderResources& pShaderResources, const XmlNodeRef& node) const = 0;
virtual void SetXmlFromVertexDeform(const SInputShaderResources& pShaderResources, XmlNodeRef& node) const = 0;
//////////////////////////////////////////////////////////////////////////
virtual void SetLightingFromXml(SInputShaderResources& pShaderResources, const XmlNodeRef& node) const = 0;
virtual void SetXmlFromLighting(const SInputShaderResources& pShaderResources, XmlNodeRef& node) const = 0;
//////////////////////////////////////////////////////////////////////////
virtual void SetShaderParamsFromXml(SInputShaderResources& pShaderResources, const XmlNodeRef& node) const = 0;
virtual void SetXmlFromShaderParams(const SInputShaderResources& pShaderResources, XmlNodeRef& node) const = 0;
//////////////////////////////////////////////////////////////////////////
virtual void MigrateXmlLegacyData(SInputShaderResources& pShaderResources, const XmlNodeRef& node) const = 0;
};
//////////////////////////////////////////////////////////////////////////////////////
// Description:
// IMaterialLayer is group of material layer properties.
// Each layer is composed of shader item, specific layer textures, lod info, etc
struct IMaterialLayer
{
// <interfuscator:shuffle>
virtual ~IMaterialLayer(){}
// Reference counting
virtual void AddRef() = 0;
virtual void Release() = 0;
// Description:
// - Enable/disable layer usage
virtual void Enable(bool bEnable = true) = 0;
// Description:
// - Check if layer enabled
virtual bool IsEnabled() const = 0;
// Description:
// - Enable/disable fade out
virtual void FadeOut(bool bFadeOut = true) = 0;
// Description:
// - Check if layer fades out
virtual bool DoesFadeOut() const = 0;
// Description:
// - Set shader item
virtual void SetShaderItem(const _smart_ptr<IMaterial> pParentMtl, const SShaderItem& pShaderItem) = 0;
// Description:
// - Return shader item
virtual const SShaderItem& GetShaderItem() const = 0;
virtual SShaderItem& GetShaderItem() = 0;
// Description:
// - Set layer usage flags
virtual void SetFlags(uint8 nFlags) = 0;
// Description:
// - Get layer usage flags
virtual uint8 GetFlags() const = 0;
// todo: layer specific textures support
//
// </interfuscator:shuffle>
};
struct IMaterial
{
// TODO: Remove it!
@@ -254,7 +161,7 @@ struct IMaterial
float m_fDefautMappingScale;
// <interfuscator:shuffle>
virtual ~IMaterial() {};
virtual ~IMaterial() {}
//////////////////////////////////////////////////////////////////////////
// Reference counting.
@@ -263,7 +170,6 @@ struct IMaterial
virtual void Release() = 0;
virtual int GetNumRefs() = 0;
virtual IMaterialHelpers& GetMaterialHelpers() = 0;
virtual IMaterialManager* GetMaterialManager() = 0;
//////////////////////////////////////////////////////////////////////////
@@ -295,10 +201,6 @@ struct IMaterial
virtual ISurfaceType* GetSurfaceType() = 0;
// shader item
virtual void ReleaseCurrentShaderItem() = 0;
virtual void SetShaderItem(const SShaderItem& _ShaderItem) = 0;
// [Alexey] EF_LoadShaderItem return value with RefCount = 1, so if you'll use SetShaderItem after EF_LoadShaderItem use Assign function
virtual void AssignShaderItem(const SShaderItem& _ShaderItem) = 0;
virtual SShaderItem& GetShaderItem() = 0;
virtual const SShaderItem& GetShaderItem() const = 0;
@@ -310,41 +212,6 @@ struct IMaterial
// Returns true if streamed in
virtual bool IsStreamedIn(const int nMinPrecacheRoundIds[MAX_STREAM_PREDICTION_ZONES], IRenderMesh* pRenderMesh) const = 0;
//////////////////////////////////////////////////////////////////////////
// Sub materials access.
//////////////////////////////////////////////////////////////////////////
//! Returns number of child sub materials holded by this material.
virtual void SetSubMtlCount(int numSubMtl) = 0;
//! Returns number of child sub materials holded by this material.
virtual int GetSubMtlCount() = 0;
//! Return sub material at specified index.
virtual _smart_ptr<IMaterial> GetSubMtl(int nSlot) = 0;
// Assign material to the sub mtl slot.
// Must first allocate slots using SetSubMtlCount.
virtual void SetSubMtl(int nSlot, _smart_ptr<IMaterial> pMtl) = 0;
//////////////////////////////////////////////////////////////////////////
// Layers access.
//////////////////////////////////////////////////////////////////////////
//! Returns number of layers in this material.
virtual void SetLayerCount(uint32 nCount) = 0;
//! Returns number of layers in this material.
virtual uint32 GetLayerCount() const = 0;
//! Set layer at slot id (### MUST ALOCATE SLOTS FIRST ### USING SetLayerCount)
virtual void SetLayer(uint32 nSlot, IMaterialLayer* pLayer) = 0;
//! Return active layer
virtual const IMaterialLayer* GetLayer(uint8 nLayersMask, uint8 nLayersUsageMask) const = 0;
//! Return layer at slot id
virtual const IMaterialLayer* GetLayer(uint32 nSlot) const = 0;
//! Create a new layer
virtual IMaterialLayer* CreateLayer() = 0;
//////////////////////////////////////////////////////////////////////////
// Always get a valid material.
// If not multi material return this material.
// If Multi material return Default material if wrong id.
virtual _smart_ptr<IMaterial> GetSafeSubMtl(int nSlot) = 0;
// Description:
// Fill an array of integeres representing surface ids of the sub materials or the material itself.
// Arguments:
@@ -567,12 +434,5 @@ struct IMaterialManager
// Updates material data in the renderer
virtual void RefreshMaterialRuntime() = 0;
//// Forcing to create ISurfaceTypeManager
//virtual void CreateSurfaceTypeManager() = 0;
//// Forcing to destroy ISurfaceTypeManager
//virtual void ReleaseSurfaceTypeManager() = 0;
// </interfuscator:shuffle>
};
#endif // CRYINCLUDE_CRYCOMMON_IMATERIAL_H
+4 -6
View File
@@ -20,10 +20,8 @@
#include <Range.h>
#include <AnimKey.h>
#include <ISplines.h>
#include <IRenderer.h>
#include <IRenderAuxGeom.h>
#include <Cry_Camera.h>
#include <VectorSet.h>
#include <CryName.h>
// forward declaration.
struct IAnimTrack;
@@ -116,7 +114,7 @@ public:
{
*this = name;
}
CAnimParamType(AnimParamType type)
{
*this = type;
@@ -838,7 +836,7 @@ public:
// override this method to handle explicit setting of time
virtual void TimeChanged([[maybe_unused]] float newTime) {};
// Compares all of the node's track values at the given time with the associated property value and
// Compares all of the node's track values at the given time with the associated property value and
// sets a key at that time if they are different to match the latter
// Returns the number of keys set
virtual int SetKeysForChangedTrackValues([[maybe_unused]] float time) { return 0; };
@@ -1309,7 +1307,7 @@ struct IMovieSystem
// Disable Fixed Step cvars and return to previous settings
virtual void DisableFixedStepForCapture() = 0;
// Signal the capturing start.
virtual void StartCapture(const ICaptureKey& key, int frame) = 0;
+3 -3
View File
@@ -11,10 +11,12 @@
#define CRYINCLUDE_CRYCOMMON_INAVIGATIONSYSTEM_H
#pragma once
#include "CryCommon/Cry_Geo.h"
#include <AzCore/std/functional.h>
#include <IMNM.h>
#include <physinterface.h>
#include <ISystem.h>
struct IOffMeshNavigationManager;
@@ -47,7 +49,6 @@ typedef TNavigationID<MeshIDTag> NavigationMeshID;
typedef TNavigationID<AgentTypeIDTag> NavigationAgentTypeID;
typedef TNavigationID<VolumeIDTag> NavigationVolumeID;
typedef AZStd::function<void(NavigationAgentTypeID, NavigationMeshID, uint32)> NavigationMeshChangeCallback;
typedef AZStd::function<bool(IPhysicalEntity&, uint32&)> NavigationMeshEntityCallback;
struct INavigationSystemUser
{
@@ -141,7 +142,6 @@ struct INavigationSystem
virtual NavigationMeshID CreateMesh(const char* name, NavigationAgentTypeID agentTypeID, const CreateMeshParams& params, NavigationMeshID requestedID) = 0;
virtual void DestroyMesh(NavigationMeshID meshID) = 0;
virtual void SetMeshEntityCallback(NavigationAgentTypeID agentTypeID, const NavigationMeshEntityCallback& callback) = 0;
virtual void AddMeshChangeCallback(NavigationAgentTypeID agentTypeID, const NavigationMeshChangeCallback& callback) = 0;
virtual void RemoveMeshChangeCallback(NavigationAgentTypeID agentTypeID, const NavigationMeshChangeCallback& callback) = 0;
+3 -23
View File
@@ -7,22 +7,11 @@
*/
#ifndef CRYINCLUDE_CRYCOMMON_IPHYSICS_H
#define CRYINCLUDE_CRYCOMMON_IPHYSICS_H
#pragma once
//
#ifdef PHYSICS_EXPORTS
#define CRYPHYSICS_API DLL_EXPORT
#else
#define CRYPHYSICS_API DLL_IMPORT
#endif
#define vector_class Vec3_tpl
#include <CrySizer.h>
#include "Cry_Math.h"
#include "primitives.h"
#include <physinterface.h> // <> required for Interfuscator
//////////////////////////////////////////////////////////////////////////
// IDs that can be used for foreign id.
@@ -47,12 +36,3 @@ enum EPhysicsForeignIds
PHYS_FOREIGN_ID_USER = 100, // All user defined foreign ids should start from this enum.
};
//#include "utils.h"
#include "Cry_Math.h"
#include "primitives.h"
#include <physinterface.h> // <> required for Interfuscator
#endif // CRYINCLUDE_CRYCOMMON_IPHYSICS_H
+2 -9
View File
@@ -6,16 +6,12 @@
*
*/
#ifndef CRYINCLUDE_CRYCOMMON_IRENDERAUXGEOM_H
#define CRYINCLUDE_CRYCOMMON_IRENDERAUXGEOM_H
#pragma once
struct SAuxGeomRenderFlags;
#include "Cry_Color.h"
#include "IRenderer.h"
struct SAuxGeomRenderFlags;
enum EBoundingBoxDrawStyle
{
@@ -833,6 +829,3 @@ inline CRenderAuxGeomRenderFlagsRestore::~CRenderAuxGeomRenderFlagsRestore()
{
m_pRender->SetRenderFlags(m_backuppedRenderFlags);
}
#endif // CRYINCLUDE_CRYCOMMON_IRENDERAUXGEOM_H
+11 -38
View File
@@ -13,18 +13,15 @@
#include "VertexFormats.h"
#include <IMaterial.h>
#include <IShader.h>
#include <IRenderer.h> // PublicRenderPrimitiveType
#include <Cry_Geo.h>
#include <CryArray.h>
#include <ITimer.h>
class CMesh;
struct CRenderChunk;
class CRenderObject;
struct SSkinningData;
struct IMaterial;
struct IShader;
struct IIndexedMesh;
struct SMRendTexVert;
struct UCol;
@@ -127,7 +124,7 @@ struct IRenderMesh
, pNormals(0)
, pIndices(0)
, nIndexCount(0)
, nPrimetiveType(prtTriangleList)
, nPrimetiveType(PublicRenderPrimitiveType::prtTriangleList)
, nRenderChunkCount(0)
, nClientTextureBindID(0)
, bOnlyVideoBuffer(false)
@@ -182,8 +179,6 @@ struct IRenderMesh
virtual bool CheckUpdate(uint32 nStreamMask) = 0;
virtual int GetStreamStride(int nStream) const = 0;
virtual const uintptr_t GetVBStream(int nStream) const = 0;
virtual const uintptr_t GetIBStream() const = 0;
virtual int GetNumVerts() const = 0;
virtual int GetNumInds() const = 0;
virtual const eRenderPrimitiveType GetPrimitiveType() const = 0;
@@ -207,33 +202,24 @@ struct IRenderMesh
virtual bool UpdateVertices(const void* pVertBuffer, int nVertCount, int nOffset, int nStream, uint32 copyFlags, bool requiresLock = true) = 0;
virtual bool UpdateIndices(const vtx_idx* pNewInds, int nInds, int nOffsInd, uint32 copyFlags, bool requiresLock = true) = 0;
virtual void SetCustomTexID(int nCustomTID) = 0;
virtual void SetChunk(int nIndex, CRenderChunk& chunk) = 0;
virtual void SetChunk(_smart_ptr<IMaterial> pNewMat, int nFirstVertId, int nVertCount, int nFirstIndexId, int nIndexCount, float texelAreaDensity, const AZ::Vertex::Format& vertexFormat, int nMatID = 0) = 0;
// Assign array of render chunks.
// Initializes render element for each render chunk.
virtual void SetRenderChunks(CRenderChunk* pChunksArray, int nCount, bool bSubObjectChunks) = 0;
virtual void GenerateQTangents() = 0;
virtual void CreateChunksSkinned() = 0;
virtual void NextDrawSkinned() = 0;
virtual IRenderMesh* GetVertexContainer() = 0;
virtual void SetVertexContainer(IRenderMesh* pBuf) = 0;
virtual TRenderChunkArray& GetChunks() = 0;
virtual TRenderChunkArray& GetChunksSkinned() = 0;
virtual TRenderChunkArray& GetChunksSubObjects() = 0;
virtual void SetBBox(const Vec3& vBoxMin, const Vec3& vBoxMax) = 0;
virtual void GetBBox(Vec3& vBoxMin, Vec3& vBoxMax) = 0;
virtual void UpdateBBoxFromMesh() = 0;
virtual uint32* GetPhysVertexMap() = 0;
virtual bool IsEmpty() = 0;
virtual byte* GetPosPtrNoCache(int32& nStride, uint32 nFlags) = 0;
virtual byte* GetPosPtr(int32& nStride, uint32 nFlags) = 0;
virtual byte* GetColorPtr(int32& nStride, uint32 nFlags) = 0;
virtual byte* GetNormPtr(int32& nStride, uint32 nFlags) = 0;
virtual int8* GetPosPtrNoCache(int32& nStride, uint32 nFlags) = 0;
virtual int8* GetPosPtr(int32& nStride, uint32 nFlags) = 0;
virtual int8* GetColorPtr(int32& nStride, uint32 nFlags) = 0;
virtual int8* GetNormPtr(int32& nStride, uint32 nFlags) = 0;
//! Returns a pointer to the first uv coordinate in the interleaved vertex stream
virtual byte* GetUVPtrNoCache(int32& nStride, uint32 nFlags, uint32 uvSetIndex = 0) = 0;
virtual int8* GetUVPtrNoCache(int32& nStride, uint32 nFlags, uint32 uvSetIndex = 0) = 0;
/*! Get a pointer to the mesh's uv coordinates and the stride from the beginning of one uv coordinate to the next
\param[out] nStride The stride in between successive uv coordinates.
\param nFlags Stream lock flags (FSL_READ, FSL_WRITE, etc)
@@ -242,13 +228,13 @@ struct IRenderMesh
Either way, nStride is set such that the caller can use it to iterate over the data in the same way regardless of which pointer was returned
Returns nullptr if there is no uv coordinate stream at the given index
*/
virtual byte* GetUVPtr(int32& nStride, uint32 nFlags, uint32 uvSetIndex = 0) = 0;
virtual int8* GetUVPtr(int32& nStride, uint32 nFlags, uint32 uvSetIndex = 0) = 0;
virtual byte* GetTangentPtr(int32& nStride, uint32 nFlags) = 0;
virtual byte* GetQTangentPtr(int32& nStride, uint32 nFlags) = 0;
virtual int8* GetTangentPtr(int32& nStride, uint32 nFlags) = 0;
virtual int8* GetQTangentPtr(int32& nStride, uint32 nFlags) = 0;
virtual byte* GetHWSkinPtr(int32& nStride, uint32 nFlags, bool remapped = false) = 0;
virtual byte* GetVelocityPtr(int32& nStride, uint32 nFlags) = 0;
virtual int8* GetHWSkinPtr(int32& nStride, uint32 nFlags, bool remapped = false) = 0;
virtual int8* GetVelocityPtr(int32& nStride, uint32 nFlags) = 0;
virtual void UnlockStream(int nStream) = 0;
virtual void UnlockIndexStream() = 0;
@@ -261,8 +247,6 @@ struct IRenderMesh
virtual void Render(const struct SRendParams& rParams, CRenderObject* pObj, _smart_ptr<IMaterial> pMaterial, const SRenderingPassInfo& passInfo, bool bSkinned = false) = 0;
virtual void Render(CRenderObject* pObj, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter) = 0;
virtual void AddRenderElements(_smart_ptr<IMaterial> pIMatInfo, CRenderObject* pObj, const SRenderingPassInfo& passInfo, int nSortId = EFSLIST_GENERAL, int nAW = 1) = 0;
virtual void AddRE(_smart_ptr<IMaterial> pMaterial, CRenderObject* pObj, IShader* pEf, const SRenderingPassInfo& passInfo, int nList, int nAW, const SRendItemSorter& rendItemSorter) = 0;
virtual void SetREUserData(float* pfCustomData, float fFogScale = 0, float fAlpha = 1) = 0;
// Debug draw this render mesh.
@@ -295,15 +279,4 @@ struct IRenderMesh
// </interfuscator:shuffle>
};
struct SBufferStream
{
void* m_pLocalData; // pointer to buffer data
uintptr_t m_BufferHdl;
SBufferStream()
{
m_pLocalData = NULL;
m_BufferHdl = ~0u;
}
};
#endif // CRYINCLUDE_CRYCOMMON_IRENDERMESH_H
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+1 -2
View File
@@ -11,7 +11,6 @@
#define CRYINCLUDE_CRYCOMMON_ISPLINES_H
#pragma once
#include <CrySizer.h>
#include <IXml.h>
//////////////////////////////////////////////////////////////////////////
@@ -638,7 +637,7 @@ namespace spline
//////////////////////////////////////////////////////////////////////////
static void Reflect(AZ::SerializeContext* serializeContext) {}
inline void add_ref()
{
++m_refCount;
+5 -22
View File
@@ -11,20 +11,20 @@
#include "smartptr.h" // TYPEDEF_AUTOPTR
#include "IMaterial.h"
#include "ISerialize.h"
// forward declarations
//////////////////////////////////////////////////////////////////////
struct ShadowMapFrustum;
struct SRenderingPassInfo;
struct SRendItemSorter;
struct IShader;
struct ITetrLattice;
struct SPhysGeomArray;
struct CStatObj;
class CRenderObject;
class CDLight;
class IReadStream;
class CRenderObject;
class CLodValue;
@@ -39,9 +39,11 @@ class CRenderObject;
struct SMeshLodInfo;
#include "CryHeaders.h"
#include "Cry_Color.h"
#include "Cry_Math.h"
#include "Cry_Geo.h"
#include "IPhysics.h"
#include "CrySizer.h"
#include "stridedptr.h"
#define MAX_STATOBJ_LODS_NUM 6
@@ -399,10 +401,6 @@ struct IStatObj
// Set the physic representation
virtual void SetPhysGeom(phys_geometry* pPhysGeom, int nType = 0) = 0;
// Description:
// Returns a tetrahedral lattice, if any (used for breakable objects)
virtual ITetrLattice* GetTetrLattice() = 0;
virtual float GetAIVegetationRadius() const = 0;
virtual void SetAIVegetationRadius(float radius) = 0;
@@ -635,15 +633,6 @@ struct IStatObj
// adds a new sub object
virtual IStatObj::SSubObject& AddSubObject(IStatObj* pStatObj) = 0;
// Summary:
// Adds subobjects to pent, meshes as parts, joint helpers as breakable joints
virtual int PhysicalizeSubobjects(IPhysicalEntity* pent, const Matrix34* pMtx, float mass, float density = 0.0f, int id0 = 0, strided_pointer<int> pJointsIdMap = 0, const char* szPropsOverride = 0) = 0;
// Summary:
// Adds all phys geometries to pent, assigns ids starting from id; takes mass and density from the StatObj properties if not set in pgp
// for compound objects calls PhysicalizeSubobjects
// returns the physical id of the last physicalized part
virtual int Physicalize(IPhysicalEntity* pent, pe_geomparams* pgp, int id = 0, const char* szPropsOverride = 0) = 0;
virtual bool IsDeformable() = 0;
//////////////////////////////////////////////////////////////////////////
@@ -768,12 +757,6 @@ struct IStatObj
virtual bool UpdateStreamableComponents(float fImportance, const Matrix34A& objMatrix, bool bFullUpdate, int nNewLod) = 0;
virtual void RenderInternal(CRenderObject* pRenderObject, uint64 nSubObjectHideMask, const CLodValue& lodValue, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter, bool forceStaticDraw) = 0;
virtual void RenderObjectInternal(CRenderObject* pRenderObject, int nLod, uint8 uLodDissolveRef, bool dissolveOut, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter, bool forceStaticDraw) = 0;
virtual void RenderSubObject(CRenderObject* pRenderObject, int nLod, int nSubObjId, const Matrix34A& renderTM, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter, bool forceStaticDraw) = 0;
virtual void RenderSubObjectInternal(CRenderObject* pRenderObject, int nLod, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter, bool forceStaticDraw) = 0;
virtual void RenderRenderMesh(CRenderObject* pObj, struct SInstancingInfo* pInstInfo, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter) = 0;
virtual SPhysGeomArray& GetArrPhysGeomInfo() = 0;
virtual bool IsLodsAreLoadedFromSeparateFile() = 0;
-3
View File
@@ -624,8 +624,6 @@ struct SSystemGlobalEnvironment
ISystem* pSystem = nullptr;
ILog* pLog;
IMovieSystem* pMovieSystem;
INameTable* pNameTable;
IRenderer* pRenderer;
ILyShine* pLyShine;
SharedEnvironmentInstance* pSharedEnvironment;
@@ -852,7 +850,6 @@ struct ISystem
//
virtual IViewSystem* GetIViewSystem() = 0;
virtual ILevelSystem* GetILevelSystem() = 0;
virtual INameTable* GetINameTable() = 0;
virtual ICmdLine* GetICmdLine() = 0;
virtual ILog* GetILog() = 0;
virtual AZ::IO::IArchive* GetIPak() = 0;
@@ -10,9 +10,7 @@
#include <Range.h>
#include <AnimKey.h>
#include <ITimer.h>
#include <IPhysics.h>
#include <VectorSet.h>
#include <CryName.h>
#include <LyShine/ILyShine.h>
#include <AzCore/Math/Vector2.h>
#include <AzCore/Math/Vector3.h>
@@ -191,7 +189,7 @@ public:
private:
EUiAnimParamType m_type;
CCryName m_name;
AZStd::string m_name;
};
// The data required to identify a specific parameter/property on an AZ component on an AZ entity
+2 -10
View File
@@ -8,6 +8,7 @@
#pragma once
#include <IRenderer.h>
#include <ITexture.h>
#include <LyShine/UiBase.h>
namespace AZ
@@ -48,20 +49,11 @@ namespace LyShine
//! End rendering to a texture
virtual void EndRenderToTexture() = 0;
//! Add an indexed triangle list primitive to the render graph with given render state
virtual void AddPrimitive(IRenderer::DynUiPrimitive* primitive, ITexture* texture,
bool isClampTextureMode, bool isTextureSRGB, bool isTexturePremultipliedAlpha, BlendMode blendMode) = 0;
//! Add an indexed triangle list primitive to the render graph which will use maskTexture as an alpha (gradient) mask
virtual void AddAlphaMaskPrimitive(IRenderer::DynUiPrimitive* primitive,
ITexture* texture, ITexture* maskTexture,
bool isClampTextureMode, bool isTextureSRGB, bool isTexturePremultipliedAlpha, BlendMode blendMode) = 0;
//! Get a dynamic quad primitive that can be added as an image primitive to the render graph
//! The graph handles the allocation of this DynUiPrimitive and deletes it when the graph is reset
//! This can be used if the UI component doesn't want to own the storage of the primitive. Used infrequently,
//! e.g. for the selection rect on a text component.
virtual IRenderer::DynUiPrimitive* GetDynamicQuadPrimitive(const AZ::Vector2* positions, uint32 packedColor) = 0;
virtual DynUiPrimitive* GetDynamicQuadPrimitive(const AZ::Vector2* positions, uint32 packedColor) = 0;
//---- Functions for supporting masking (used during creation of the graph, not rendering ) ----
-854
View File
@@ -1,854 +0,0 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <IRenderer.h>
#include <gmock/gmock.h>
struct SRendItemSorter {};
struct SRenderingPassInfo {};
struct SClipVolumeBlendInfo {};
struct SFogVolumeData {};
// the following was generated using google's python script to autogenerate mocks.
// however, it needed some hand-editing to make it work, so if you add functions to IRenderer,
// it will probably be better to just manually add them here than try to run the script again
// hand-edits are marked with 'hand-edit'. Everything else was autogenerated.
class IRendererMock
: public IRenderer
{
public:
MOCK_METHOD1(AddRenderDebugListener,
void(IRenderDebugListener * pRenderDebugListener));
MOCK_METHOD1(RemoveRenderDebugListener,
void(IRenderDebugListener * pRenderDebugListener));
MOCK_CONST_METHOD0(GetRenderType,
ERenderType());
// Hand-edit: Googlemock cannot handle 14 param functions.
WIN_HWND Init(int, int, int, int, unsigned int, int, int, bool, bool, WIN_HINSTANCE, WIN_HWND = 0,
bool = false, const SCustomRenderInitArgs* = 0, bool = false) override { return nullptr; }
MOCK_METHOD0(PostInit,
void());
MOCK_CONST_METHOD0(IsPost3DRendererEnabled,
bool());
MOCK_METHOD0(GetFeatures,
int());
// Hand-edit: Googlemock doesn't like 'const void' as a return type:
const void SetApiVersion(const AZStd::string&) override {}
const void SetAdapterDescription(const AZStd::string&) override {}
MOCK_CONST_METHOD0(GetApiVersion,
const AZStd::string& ());
MOCK_CONST_METHOD0(GetAdapterDescription,
const AZStd::string& ());
MOCK_METHOD3(GetVideoMemoryUsageStats,
void(size_t&, size_t&, bool));
MOCK_CONST_METHOD0(GetNumGeomInstances,
int());
MOCK_CONST_METHOD0(GetNumGeomInstanceDrawCalls,
int());
MOCK_CONST_METHOD0(GetCurrentNumberOfDrawCalls,
int());
MOCK_CONST_METHOD2(GetCurrentNumberOfDrawCalls,
void(int& nGeneral, int& nShadowGen));
MOCK_CONST_METHOD1(GetCurrentNumberOfDrawCalls,
int(uint32 EFSListMask));
MOCK_CONST_METHOD1(GetCurrentDrawCallRTTimes,
float(uint32 EFSListMask));
MOCK_METHOD1(SetDebugRenderNode,
void(IRenderNode * pRenderNode));
MOCK_CONST_METHOD1(IsDebugRenderNode,
bool(IRenderNode * pRenderNode));
MOCK_METHOD1(DeleteContext,
bool(WIN_HWND hWnd));
MOCK_METHOD4(CreateContext,
bool(WIN_HWND, bool, int, int));
MOCK_METHOD1(SetCurrentContext,
bool(WIN_HWND hWnd));
MOCK_METHOD0(MakeMainContextActive,
void());
MOCK_METHOD0(GetCurrentContextHWND,
WIN_HWND());
MOCK_METHOD0(IsCurrentContextMainVP,
bool());
MOCK_CONST_METHOD0(GetCurrentContextViewportHeight,
int());
MOCK_CONST_METHOD0(GetCurrentContextViewportWidth,
int());
MOCK_METHOD1(ShutDown,
void(bool));
MOCK_METHOD0(ShutDownFast,
void());
MOCK_METHOD1(EnumDisplayFormats,
int(SDispFormat * Formats));
MOCK_METHOD1(EnumAAFormats,
int(SAAFormat * Formats));
MOCK_METHOD6(ChangeResolution,
bool(int nNewWidth, int nNewHeight, int nNewColDepth, int nNewRefreshHZ, bool bFullScreen, bool bForceReset));
MOCK_METHOD0(BeginFrame,
void());
MOCK_METHOD1(InitSystemResources,
void(int nFlags));
MOCK_METHOD0(InitTexturesSemantics,
void());
MOCK_METHOD1(FreeResources,
void(int nFlags));
MOCK_METHOD0(Release,
void());
MOCK_METHOD1(RenderDebug,
void(bool));
MOCK_METHOD0(EndFrame,
void());
MOCK_METHOD0(ForceSwapBuffers,
void());
MOCK_METHOD0(TryFlush,
void());
MOCK_CONST_METHOD4(GetViewport,
void(int* x, int* y, int* width, int* height));
MOCK_METHOD5(SetViewport,
void(int, int, int, int, int));
MOCK_METHOD4(SetRenderTile,
void(f32, f32, f32, f32));
MOCK_METHOD4(SetScissor,
void(int, int, int, int));
MOCK_METHOD0(GetViewProjectionMatrix,
Matrix44A & ());
MOCK_METHOD1(SetTranspOrigCameraProjMatrix,
void(Matrix44A & matrix));
MOCK_METHOD2(GetScreenAspect,
EScreenAspectRatio(int nWidth, int nHeight));
MOCK_METHOD2(SetViewportDownscale,
Vec2(float xscale, float yscale));
MOCK_METHOD1(SetViewParameters,
void(const CameraViewParameters& viewParameters));
MOCK_METHOD1(ApplyViewParameters,
void(const CameraViewParameters& viewParameters));
MOCK_METHOD5(DrawDynVB,
void(SVF_P3F_C4B_T2F * pBuf, uint16 * pInds, int nVerts, int nInds, PublicRenderPrimitiveType nPrimType));
// Hand-edit: google mock has issues with DynUiPrimitiveList
void DrawDynUiPrimitiveList([[maybe_unused]] DynUiPrimitiveList& primitives, [[maybe_unused]] int totalNumVertices, [[maybe_unused]] int totalNumIndices) override { return; }
MOCK_METHOD1(SetCamera,
void(const CCamera& cam));
MOCK_METHOD0(GetCamera,
const CCamera& ());
MOCK_METHOD1(GetRenderViewForThread,
CRenderView * (int nThreadID));
MOCK_METHOD1(SetGammaDelta,
bool(float fGamma));
MOCK_METHOD0(RestoreGamma,
void(void));
MOCK_METHOD3(ChangeDisplay,
bool(unsigned int width, unsigned int height, unsigned int cbpp));
MOCK_METHOD7(ChangeViewport,
void(unsigned int, unsigned int, unsigned int, unsigned int, bool, float, float));
MOCK_CONST_METHOD6(SaveTga,
bool(unsigned char* sourcedata, int sourceformat, int w, int h, const char* filename, bool flip));
MOCK_METHOD1(SetTexture,
void(int tnum));
MOCK_METHOD2(SetTexture,
void(int tnum, int nUnit));
MOCK_METHOD0(SetWhiteTexture,
void());
MOCK_CONST_METHOD0(GetWhiteTextureId,
int());
MOCK_CONST_METHOD0(GetBlackTextureId,
int());
// Hand-edit: google mock can only do up to 10 parameters
void Draw2dImage(float, float, float, float, int, float, float, float, float, float, float, float, float, float, float) override {};
MOCK_METHOD1(Draw2dImageStretchMode,
void(bool stretch));
// Hand-edit: google mock can only do up to 10 parameters
void Push2dImage(float, float, float, float, int, float, float, float, float, float, float, float, float, float, float, float) override {};
MOCK_METHOD0(Draw2dImageList,
void());
// Hand-edit: Hand-edit: google mock can only do up to 10 parameters
void DrawImage(float, float, float, float, int, float, float, float, float, float, float, float, float, bool) override {}
// Hand-edit: google mock can only do up to 10 parameters
void DrawImageWithUV(float, float, float, float, float, int, float*, float*, float, float, float, float, bool) override {}
MOCK_METHOD1(PushWireframeMode,
void(int mode));
MOCK_METHOD0(PopWireframeMode,
void());
MOCK_CONST_METHOD0(GetHeight,
int());
MOCK_CONST_METHOD0(GetWidth,
int());
MOCK_CONST_METHOD0(GetPixelAspectRatio,
float());
MOCK_CONST_METHOD0(GetOverlayHeight,
int());
MOCK_CONST_METHOD0(GetOverlayWidth,
int());
MOCK_CONST_METHOD0(GetMaxSquareRasterDimension,
int());
MOCK_METHOD0(SwitchToNativeResolutionBackbuffer,
void());
MOCK_METHOD1(GetMemoryUsage,
void(ICrySizer * Sizer));
MOCK_METHOD1(GetBandwidthStats,
void(float* fBandwidthRequested));
MOCK_METHOD1(SetTextureStreamListener,
void(ITextureStreamListener * pListener));
MOCK_METHOD2(GetOcclusionBuffer,
int(uint16 * pOutOcclBuffer, Matrix44 * pmCamBuffer));
MOCK_METHOD2(ScreenShot,
bool(const char*, int));
MOCK_METHOD0(GetColorBpp,
int());
MOCK_METHOD0(GetDepthBpp,
int());
MOCK_METHOD0(GetStencilBpp,
int());
MOCK_CONST_METHOD0(IsStereoEnabled,
bool());
MOCK_CONST_METHOD0(GetNearestRangeMax,
float());
MOCK_METHOD0(GetPerInstanceConstantBufferPoolPointer,
PerInstanceConstantBufferPool * ());
MOCK_METHOD6(ProjectToScreen,
bool(float ptx, float pty, float ptz, float* sx, float* sy, float* sz));
MOCK_METHOD9(UnProject,
int(float sx, float sy, float sz, float* px, float* py, float* pz, const float modelMatrix[16], const float projMatrix[16], const int viewport[4]));
MOCK_METHOD6(UnProjectFromScreen,
int(float sx, float sy, float sz, float* px, float* py, float* pz));
MOCK_METHOD1(GetModelViewMatrix,
void(float* mat));
MOCK_METHOD1(GetProjectionMatrix,
void(float* mat));
MOCK_METHOD7(WriteDDS,
bool(const byte * dat, int wdt, int hgt, int Size, const char* name, ETEX_Format eF, int NumMips));
MOCK_METHOD6(WriteTGA,
bool(const byte * dat, int wdt, int hgt, const char* name, int src_bits_per_pixel, int dest_bits_per_pixel));
MOCK_METHOD6(WriteJPG,
bool(const byte*, int, int, char*, int, int));
MOCK_METHOD6(FontCreateTexture,
int(int, int, byte*, ETEX_Format, bool, const char*));
MOCK_METHOD6(FontUpdateTexture,
bool(int nTexId, int X, int Y, int USize, int VSize, byte * pData));
MOCK_METHOD2(FontSetTexture,
void(int nTexId, int nFilterMode));
MOCK_METHOD2(FontSetRenderingState,
void(bool overrideViewProjMatrices, TransformationMatrices & backupMatrices));
MOCK_METHOD3(FontSetBlending,
void(int src, int dst, int baseState));
MOCK_METHOD2(FontRestoreRenderingState,
void(bool overrideViewProjMatrices, const TransformationMatrices& restoringMatrices));
MOCK_METHOD3(FlushRTCommands,
bool(bool bWait, bool bImmediatelly, bool bForce));
MOCK_CONST_METHOD7(DrawStringU,
void(IFFont_RenderProxy * pFont, float x, float y, float z, const char* pStr, bool asciiMultiLine, const STextDrawContext& ctx));
MOCK_METHOD0(RT_CurThreadList,
int());
MOCK_METHOD6(EF_PrecacheResource,
bool(SShaderItem*, float, float, int, int, int));
MOCK_METHOD4(EF_PrecacheResource,
bool(IShader * pSH, float fMipFactor, float fTimeToReady, int Flags));
MOCK_METHOD6(EF_PrecacheResource,
bool(ITexture*, float, float, int, int, int));
MOCK_METHOD6(EF_PrecacheResource,
bool(IRenderMesh * pPB, _smart_ptr<IMaterial> pMaterial, float fMipFactor, float fTimeToReady, int Flags, int nUpdateId));
MOCK_METHOD5(EF_PrecacheResource,
bool(CDLight * pLS, float fMipFactor, float fTimeToReady, int Flags, int nUpdateId));
// Hand-edit: google mock can only do up to 10 parameters
ITexture* EF_CreateCompositeTexture([[maybe_unused]] int type, [[maybe_unused]] const char* szName, [[maybe_unused]] int nWidth, [[maybe_unused]] int nHeight, [[maybe_unused]] int nDepth, [[maybe_unused]] int nMips, [[maybe_unused]] int nFlags, [[maybe_unused]] ETEX_Format eTF, [[maybe_unused]] const STexComposition* pCompositions, [[maybe_unused]] size_t nCompositions, [[maybe_unused]] int8 nPriority = -1) override { return nullptr; }
MOCK_METHOD0(PostLevelLoading,
void());
MOCK_METHOD0(PostLevelUnload,
void());
MOCK_METHOD10(EF_AddPolygonToScene,
CRenderObject * (SShaderItem & si, int numPts, const SVF_P3F_C4B_T2F * verts, const SPipTangents * tangs, CRenderObject * obj, const SRenderingPassInfo& passInfo, uint16 * inds, int ninds, int nAW, const SRendItemSorter& rendItemSorter));
MOCK_METHOD10(EF_AddPolygonToScene,
CRenderObject * (SShaderItem & si, CRenderObject * obj, const SRenderingPassInfo& passInfo, int numPts, int ninds, SVF_P3F_C4B_T2F * &verts, SPipTangents * &tangs, uint16 * &inds, int nAW, const SRendItemSorter& rendItemSorter));
MOCK_METHOD0(ForceUpdateGlobalShaderParameters,
void());
MOCK_METHOD0(EF_GetShaderMissLogPath,
const char*());
MOCK_METHOD1(EF_GetShaderNames,
AZStd::string * (int& nNumShaders));
MOCK_METHOD1(EF_ReloadFile,
bool(const char* szFileName));
MOCK_METHOD1(EF_ReloadFile_Request,
bool(const char* szFileName));
MOCK_METHOD3(EF_GetRemapedShaderMaskGen,
uint64(const char*, uint64, bool));
MOCK_METHOD3(EF_GetShaderGlobalMaskGenFromString,
uint64(const char*, const char*, uint64));
MOCK_METHOD2(EF_GetStringFromShaderGlobalMaskGen,
AZStd::string(const char*, uint64));
MOCK_CONST_METHOD1(GetShaderProfile,
const SShaderProfile& (EShaderType eST));
MOCK_METHOD2(EF_SetShaderQuality,
void(EShaderType eST, EShaderQuality eSQ));
MOCK_CONST_METHOD0(EF_GetRenderQuality,
ERenderQuality());
MOCK_METHOD1(EF_GetShaderQuality,
EShaderQuality(EShaderType eST));
MOCK_METHOD5(EF_LoadShaderItem,
SShaderItem(const char*, bool, int, SInputShaderResources*, uint64));
MOCK_METHOD3(EF_LoadShader,
IShader * (const char*, int, uint64));
MOCK_METHOD1(EF_ReloadShaderFiles,
void(int nCategory));
MOCK_METHOD0(EF_ReloadTextures,
void());
MOCK_METHOD1(EF_GetTextureByID,
ITexture * (int Id));
MOCK_METHOD2(EF_GetTextureByName,
ITexture * (const char*, uint32));
MOCK_METHOD2(EF_LoadTexture,
ITexture * (const char*, uint32));
MOCK_METHOD2(EF_LoadCubemapTexture,
ITexture * (const char*, uint32));
MOCK_METHOD1(EF_LoadDefaultTexture,
ITexture * (const char* nameTex));
MOCK_METHOD1(EF_LoadLightmap,
int(const char* name));
MOCK_METHOD1(EF_StartEf,
void(const SRenderingPassInfo& passInfo));
MOCK_METHOD3(EF_GetObjData,
SRenderObjData * (CRenderObject * pObj, bool bCreate, int nThreadID));
MOCK_METHOD1(EF_GetObject_Temp,
CRenderObject * (int nThreadID));
MOCK_METHOD2(EF_DuplicateRO,
CRenderObject * (CRenderObject * pObj, const SRenderingPassInfo& passInfo));
MOCK_METHOD7(EF_AddEf,
void(IRenderElement * pRE, SShaderItem & pSH, CRenderObject * pObj, const SRenderingPassInfo& passInfo, int nList, int nAW, const SRendItemSorter& rendItemSorter));
MOCK_METHOD4(EF_EndEf3D,
void(int nFlags, int nPrecacheUpdateId, int nNearPrecacheUpdateId, const SRenderingPassInfo& passInfo));
MOCK_METHOD1(EF_InvokeShadowMapRenderJobs,
void(int nFlags));
MOCK_METHOD1(EF_IsFakeDLight,
bool(const CDLight * Source));
MOCK_METHOD2(EF_ADDDlight,
void(CDLight * Source, const SRenderingPassInfo& passInfo));
MOCK_METHOD1(EF_UpdateDLight,
bool(SRenderLight * pDL));
MOCK_METHOD1(EF_AddDeferredDecal,
bool(const SDeferredDecal& rDecal));
MOCK_METHOD4(EF_AddDeferredLight,
int(const CDLight& pLight, float fMult, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter));
MOCK_METHOD1(EF_GetDeferredLightsNum,
uint32(eDeferredLightType));
MOCK_METHOD0(EF_ClearDeferredLightsList,
void());
MOCK_METHOD1(EF_AddDeferredClipVolume,
uint8(const IClipVolume * pClipVolume));
MOCK_METHOD2(EF_SetDeferredClipVolumeBlendData,
bool(const IClipVolume * pClipVolume, const SClipVolumeBlendInfo& blendInfo));
MOCK_METHOD0(EF_ClearDeferredClipVolumesList,
void());
MOCK_METHOD0(EF_ReleaseDeferredData,
void());
MOCK_METHOD1(EF_ReleaseInputShaderResource,
void(SInputShaderResources * pRes));
MOCK_METHOD3(EF_SetPostEffectParam,
void(const char*, float, bool));
MOCK_METHOD3(EF_SetPostEffectParamVec4,
void(const char*, const Vec4&, bool));
MOCK_METHOD2(EF_SetPostEffectParamString,
void(const char* pParam, const char* pszArg));
MOCK_METHOD2(EF_GetPostEffectParam,
void(const char* pParam, float& fValue));
MOCK_METHOD2(EF_GetPostEffectParamVec4,
void(const char* pParam, Vec4 & pValue));
MOCK_METHOD2(EF_GetPostEffectParamString,
void(const char* pParam, const char* & pszArg));
MOCK_METHOD1(EF_GetPostEffectID,
int32(const char* pPostEffectName));
MOCK_METHOD1(EF_ResetPostEffects,
void(bool));
MOCK_METHOD0(SyncPostEffects,
void());
MOCK_METHOD0(EF_DisableTemporalEffects,
void());
MOCK_METHOD3(EF_AddWaterSimHit,
void(const Vec3& vPos, float scale, float strength));
MOCK_METHOD0(EF_DrawWaterSimHits,
void());
MOCK_METHOD1(EF_EndEf2D,
void(bool bSort));
MOCK_METHOD0(ForceGC,
void());
MOCK_CONST_METHOD0(GetPolyCount,
int());
MOCK_CONST_METHOD2(GetPolyCount,
void(int& nPolygons, int& nShadowVolPolys));
MOCK_METHOD1(SetClearColor,
void(const Vec3& vColor));
MOCK_METHOD1(SetClearBackground,
void(bool bClearBackground));
MOCK_METHOD4(CreateRenderMesh,
_smart_ptr<IRenderMesh>(const char*, const char*, IRenderMesh::SInitParamerers*, ERenderMeshType));
// Hand-edit: google mock can only do up to 10 parameters
virtual _smart_ptr<IRenderMesh> CreateRenderMeshInitialized(
const void*, int, const AZ::Vertex::Format&, const vtx_idx*, int, const PublicRenderPrimitiveType,
const char*, const char*, ERenderMeshType = eRMT_Static, int = 1, int = 0,
[[maybe_unused]] bool (*PrepareBufferCallback)(IRenderMesh*, bool) = nullptr, void* = nullptr, bool = false, bool = true,
const SPipTangents* = nullptr, bool = false, Vec3* = nullptr)
{
return _smart_ptr<IRenderMesh>();
}
MOCK_METHOD1(GetFrameID,
int(bool));
MOCK_CONST_METHOD0(GetCameraFrameID,
int());
MOCK_CONST_METHOD0(IsRenderToTextureActive,
bool());
MOCK_METHOD4(MakeMatrix,
void(const Vec3& pos, const Vec3& angles, const Vec3& scale, Matrix34 * mat));
MOCK_METHOD4(DrawTextQueued,
void(Vec3 pos, SDrawTextInfo & ti, const char* format, va_list args));
MOCK_METHOD3(DrawTextQueued,
void(Vec3 pos, SDrawTextInfo & ti, const char* text));
MOCK_CONST_METHOD1(ScaleCoordX,
float(float value));
MOCK_CONST_METHOD1(ScaleCoordY,
float(float value));
MOCK_CONST_METHOD2(ScaleCoord,
void(float& x, float& y));
MOCK_METHOD2(SetState,
void(int, int));
MOCK_METHOD1(SetCullMode,
void(int));
MOCK_METHOD5(SetStencilState,
void(int, uint32, uint32, uint32, bool));
MOCK_METHOD1(PushProfileMarker,
void(const char* label));
MOCK_METHOD1(PopProfileMarker,
void(const char* label));
MOCK_METHOD1(EnableFog,
bool(bool enable));
MOCK_METHOD1(SetFogColor,
void(const ColorF& color));
MOCK_METHOD4(SetColorOp,
void(byte eCo, byte eAo, byte eCa, byte eAa));
MOCK_METHOD1(SetSrgbWrite,
void(bool srgbWrite));
MOCK_METHOD1(RequestFlushAllPendingTextureStreamingJobs,
void(int nFrames));
MOCK_METHOD1(SetTexturesStreamingGlobalMipFactor,
void(float fFactor));
MOCK_METHOD1(GetIRenderAuxGeom,
IRenderAuxGeom * (void*));
MOCK_METHOD0(GetISvoRenderer,
ISvoRenderer * ());
MOCK_METHOD0(GetIColorGradingController,
IColorGradingController * ());
MOCK_METHOD0(GetIStereoRenderer,
IStereoRenderer * ());
MOCK_METHOD7(Create2DTexture,
ITexture * (const char* name, int width, int height, int numMips, int flags, unsigned char* data, ETEX_Format format));
void TextToScreen([[maybe_unused]] float x, [[maybe_unused]] float y, [[maybe_unused]] const char* format, ...) override {}
void TextToScreenColor([[maybe_unused]] int x, [[maybe_unused]] int y, [[maybe_unused]] float r, [[maybe_unused]] float g, [[maybe_unused]] float b, [[maybe_unused]] float a, [[maybe_unused]] const char* format, ...) override {}
MOCK_METHOD0(ResetToDefault,
void());
MOCK_METHOD4(SetMaterialColor,
void(float r, float g, float b, float a));
MOCK_METHOD0(SetDefaultRenderStates,
void());
MOCK_METHOD10(Graph,
void(byte * g, int x, int y, int wdt, int hgt, int nC, int type, const char* text, ColorF & color, float fScale));
MOCK_METHOD0(EF_RenderTextMessages,
void());
MOCK_METHOD1(ClearTargetsImmediately,
void(uint32 nFlags));
MOCK_METHOD3(ClearTargetsImmediately,
void(uint32 nFlags, const ColorF& Colors, float fDepth));
MOCK_METHOD2(ClearTargetsImmediately,
void(uint32 nFlags, const ColorF& Colors));
MOCK_METHOD2(ClearTargetsImmediately,
void(uint32 nFlags, float fDepth));
MOCK_METHOD1(ClearTargetsLater,
void(uint32 nFlags));
MOCK_METHOD3(ClearTargetsLater,
void(uint32 nFlags, const ColorF& Colors, float fDepth));
MOCK_METHOD2(ClearTargetsLater,
void(uint32 nFlags, const ColorF& Colors));
MOCK_METHOD2(ClearTargetsLater,
void(uint32 nFlags, float fDepth));
MOCK_METHOD8(ReadFrameBuffer,
void(unsigned char*, int, int, int, ERB_Type, bool, int, int));
MOCK_METHOD4(ReadFrameBufferFast,
void(uint32*, int, int, bool));
MOCK_METHOD1(EnableVSync,
void(bool enable));
MOCK_METHOD1(CreateResourceAsync,
void(SResourceAsync * Resource));
MOCK_METHOD1(ReleaseResourceAsync,
void(SResourceAsync * Resource));
MOCK_METHOD1(ReleaseResourceAsync,
void(AZStd::unique_ptr<SResourceAsync> Resource));
// Hand-edit: google mock can only do up to 10 parameters
unsigned int DownLoadToVideoMemory(const byte*, int, int, ETEX_Format, ETEX_Format, int, bool = true,
int = FILTER_BILINEAR, int = 0, const char* = nullptr, int = 0, EEndian = eLittleEndian,
RectI* = nullptr, bool = false) override { return 0; }
unsigned int DownLoadToVideoMemory3D(const byte*, int, int, [[maybe_unused]] int d, ETEX_Format, ETEX_Format, int, bool = true,
int = FILTER_BILINEAR, int = 0, const char* = nullptr, int = 0, EEndian = eLittleEndian,
RectI* = nullptr, bool = false) override { return 0; }
unsigned int DownLoadToVideoMemoryCube(const byte*, int, int, ETEX_Format, ETEX_Format, int, bool = true,
int = FILTER_BILINEAR, int = 0, const char* = nullptr, int = 0, EEndian = eLittleEndian,
RectI* = nullptr, bool = false) override { return 0; }
MOCK_METHOD9(UpdateTextureInVideoMemory,
void(uint32, const byte*, int, int, int, int, ETEX_Format, int, int));
MOCK_METHOD8(DXTCompress,
bool(const byte * raw_data, int nWidth, int nHeight, ETEX_Format eTF, bool bUseHW, bool bGenMips, int nSrcBytesPerPix, MIPDXTcallback callback));
MOCK_METHOD9(DXTDecompress,
bool(const byte * srcData, size_t srcFileSize, byte * dstData, int nWidth, int nHeight, int nMips, ETEX_Format eSrcTF, bool bUseHW, int nDstBytesPerPix));
MOCK_METHOD1(RemoveTexture,
void(unsigned int TextureId));
MOCK_METHOD1(DeleteFont,
void(IFFont * font));
MOCK_METHOD3(CaptureFrameBufferFast,
bool(unsigned char* pDstRGBA8, int destinationWidth, int destinationHeight));
MOCK_METHOD3(CopyFrameBufferFast,
bool(unsigned char* pDstRGBA8, int destinationWidth, int destinationHeight));
MOCK_METHOD1(RegisterCaptureFrame,
bool(ICaptureFrameListener * pCapture));
MOCK_METHOD1(UnRegisterCaptureFrame,
bool(ICaptureFrameListener * pCapture));
MOCK_METHOD2(InitCaptureFrameBufferFast,
bool(uint32, uint32));
MOCK_METHOD0(CloseCaptureFrameBufferFast,
void(void));
MOCK_METHOD0(CaptureFrameBufferCallBack,
void(void));
MOCK_METHOD1(RegisterSyncWithMainListener,
void(ISyncMainWithRenderListener * pListener));
MOCK_METHOD1(RemoveSyncWithMainListener,
void(const ISyncMainWithRenderListener * pListener));
MOCK_METHOD5(Set2DMode,
void(uint32, uint32, TransformationMatrices&, float, float));
MOCK_METHOD1(Unset2DMode,
void(const TransformationMatrices& restoringMatrices));
MOCK_METHOD7(Set2DModeNonZeroTopLeft,
void(float, float, float, float, TransformationMatrices&, float, float));
MOCK_METHOD1(ScreenToTexture,
int(int nTexID));
MOCK_METHOD1(EnableSwapBuffers,
void(bool bEnable));
MOCK_METHOD0(GetHWND,
WIN_HWND());
MOCK_METHOD1(SetWindowIcon,
bool(const char* path));
MOCK_METHOD1(OnEntityDeleted,
void(struct IRenderNode* pRenderNode));
MOCK_METHOD5(CreateRenderTarget,
int(const char* name, int nWidth, int nHeight, const ColorF& clearColor, ETEX_Format eTF));
MOCK_METHOD1(DestroyRenderTarget,
bool(int nHandle));
MOCK_METHOD3(ResizeRenderTarget,
bool(int nHandle, int nWidth, int nHeight));
MOCK_METHOD2(SetRenderTarget,
bool(int, SDepthTexture*));
MOCK_METHOD3(CreateDepthSurface,
SDepthTexture * (int, int, bool));
MOCK_METHOD1(DestroyDepthSurface,
void(SDepthTexture * pDepthSurf));
MOCK_METHOD1(PauseTimer,
void(bool bPause));
MOCK_METHOD0(CreateShaderPublicParams,
IShaderPublicParams * ());
MOCK_CONST_METHOD2(GetThreadIDs,
void(threadID & mainThreadID, threadID & renderThreadID));
MOCK_METHOD1(EnableGPUTimers2,
void(bool bEnabled));
MOCK_METHOD1(AllowGPUTimers2,
void(bool bAllow));
MOCK_CONST_METHOD2(GetRPPStats,
const RPProfilerStats * (ERenderPipelineProfilerStats, bool));
MOCK_CONST_METHOD1(GetRPPStatsArray,
const RPProfilerStats * (bool));
MOCK_METHOD4(GetPolygonCountByType,
int(uint32, EVertexCostTypes, uint32, bool));
MOCK_METHOD5(SetCloudShadowsParams,
void(int nTexID, const Vec3& speed, float tiling, bool invert, float brightness));
MOCK_METHOD2(PushFogVolumeContribution,
uint16(const SFogVolumeData& fogVolData, const SRenderingPassInfo& passInfo));
MOCK_METHOD2(PushFogVolume,
void(class CREFogVolume * pFogVolume, const SRenderingPassInfo& passInfo));
MOCK_METHOD0(GetMaxTextureSize,
int());
MOCK_METHOD1(GetTextureFormatName,
const char*(ETEX_Format eTF));
MOCK_METHOD5(GetTextureFormatDataSize,
int(int nWidth, int nHeight, int nDepth, int nMips, ETEX_Format eTF));
MOCK_METHOD2(SetDefaultMaterials,
void(_smart_ptr<IMaterial> pDefMat, _smart_ptr<IMaterial> pTerrainDefMat));
MOCK_CONST_METHOD0(GetGPUParticleEngine,
IGPUParticleEngine * ());
MOCK_CONST_METHOD0(GetActiveGPUCount,
uint32());
MOCK_METHOD0(GetShadowFrustumMGPUCache,
ShadowFrustumMGPUCache * ());
MOCK_CONST_METHOD0(GetCachedShadowsResolution,
const StaticArray<int, MAX_GSM_LODS_NUM>&());
MOCK_METHOD1(SetCachedShadowsResolution,
void(const StaticArray<int, MAX_GSM_LODS_NUM>&arrResolutions));
MOCK_CONST_METHOD1(UpdateCachedShadowsLodCount,
void(int nGsmLods));
MOCK_METHOD1(SetTexturePrecaching,
void(bool stat));
MOCK_METHOD2(RT_InsertGpuCallback,
void(uint32 context, GpuCallbackFunc callback));
MOCK_METHOD1(EnablePipelineProfiler,
void(bool bEnable));
MOCK_METHOD1(GetRenderTimes,
void(SRenderTimes & outTimes));
MOCK_METHOD0(GetGPUFrameTime,
float());
MOCK_METHOD1(EnableBatchMode,
void(bool enable));
MOCK_METHOD1(EnableLevelUnloading,
void(bool enable));
MOCK_METHOD0(OnLevelLoadFailed,
void());
#if !defined(_RELEASE)
MOCK_METHOD1(GetDrawCallsInfoPerMesh,
RNDrawcallsMapMesh & (bool));
MOCK_METHOD1(GetDrawCallsInfoPerMeshPreviousFrame,
RNDrawcallsMapMesh & (bool));
MOCK_METHOD1(GetDrawCallsInfoPerNodePreviousFrame,
RNDrawcallsMapNode & (bool));
MOCK_METHOD1(GetDrawCallsPerNode,
int(IRenderNode * pRenderNode));
MOCK_METHOD1(ForceRemoveNodeFromDrawCallsMap,
void(IRenderNode * pNode));
#endif
MOCK_METHOD1(CollectDrawCallsInfo,
void(bool status));
MOCK_METHOD1(CollectDrawCallsInfoPerNode,
void(bool status));
MOCK_METHOD0(HasLoadedDefaultResources,
bool());
MOCK_METHOD3(EF_CreateSkinningData,
SSkinningData * (uint32, bool, bool));
MOCK_METHOD4(EF_CreateRemappedSkinningData,
SSkinningData * (uint32 nNumBones, SSkinningData * pSourceSkinningData, uint32 nCustomDataSize, uint32 pairGuid));
MOCK_METHOD0(EF_ClearSkinningDataPool,
void());
MOCK_METHOD0(EF_GetSkinningPoolID,
int());
MOCK_METHOD1(ClearShaderItem,
void(SShaderItem * pShaderItem));
MOCK_METHOD2(UpdateShaderItem,
void(SShaderItem * pShaderItem, _smart_ptr<IMaterial> pMaterial));
MOCK_METHOD2(ForceUpdateShaderItem,
void(SShaderItem * pShaderItem, _smart_ptr<IMaterial> pMaterial));
MOCK_METHOD2(RefreshShaderResourceConstants,
void(SShaderItem * pShaderItem, IMaterial * pMaterial));
MOCK_METHOD0(IsStereoModeChangePending,
bool());
MOCK_METHOD1(LockParticleVideoMemory,
void(uint32 nId));
MOCK_METHOD1(UnLockParticleVideoMemory,
void(uint32 nId));
MOCK_METHOD1(BeginSpawningGeneratingRendItemJobs,
void(int nThreadID));
MOCK_METHOD1(BeginSpawningShadowGeneratingRendItemJobs,
void(int nThreadID));
MOCK_METHOD0(EndSpawningGeneratingRendItemJobs,
void());
MOCK_METHOD1(StartLoadtimePlayback,
void(ILoadtimeCallback* pCallback));
MOCK_METHOD0(StopLoadtimePlayback,
void());
MOCK_METHOD0(GetGenerateRendItemJobExecutor,
AZ::LegacyJobExecutor*());
MOCK_METHOD0(GetGenerateShadowRendItemJobExecutor,
AZ::LegacyJobExecutor*());
MOCK_METHOD0(GetGenerateRendItemJobExecutorPreProcess,
AZ::LegacyJobExecutor*());
MOCK_METHOD1(GetFinalizeRendItemJobExecutor,
AZ::LegacyJobExecutor*(int nThreadID));
MOCK_METHOD1(GetFinalizeShadowRendItemJobExecutor,
AZ::LegacyJobExecutor*(int nThreadID));
MOCK_METHOD0(FlushPendingTextureTasks,
void());
MOCK_METHOD1(SetShadowJittering,
void(float fShadowJittering));
MOCK_CONST_METHOD0(GetShadowJittering,
float());
MOCK_METHOD0(LoadShaderStartupCache,
bool());
MOCK_METHOD0(UnloadShaderStartupCache,
void());
MOCK_METHOD0(LoadShaderLevelCache,
bool());
MOCK_METHOD0(UnloadShaderLevelCache,
void());
MOCK_METHOD1(StartScreenShot,
void(int e_ScreenShot));
MOCK_METHOD1(EndScreenShot,
void(int e_ScreenShot));
MOCK_METHOD3(SetRendererCVar,
void(ICVar*, const char*, bool));
MOCK_METHOD0(GetRenderPipeline,
SRenderPipeline * ());
MOCK_METHOD0(GetShaderManager,
CShaderMan * ());
MOCK_METHOD0(GetRenderThread,
SRenderThread * ());
MOCK_METHOD0(GetWhiteTexture,
ITexture * ());
MOCK_METHOD3(GetTextureForName,
ITexture * (const char* name, uint32 nFlags, ETEX_Format eFormat));
MOCK_METHOD0(GetViewParameters,
const CameraViewParameters& ());
MOCK_METHOD0(GetFrameReset,
uint32());
MOCK_METHOD0(GetDepthBufferOrig,
SDepthTexture * ());
MOCK_METHOD0(GetBackBufferWidth,
uint32());
MOCK_METHOD0(GetBackBufferHeight,
uint32());
MOCK_METHOD0(GetDeviceBufferManager,
CDeviceBufferManager * ());
MOCK_CONST_METHOD0(GetRenderTileInfo,
const SRenderTileInfo * ());
MOCK_METHOD0(GetIdentityMatrix,
Matrix44A());
MOCK_CONST_METHOD0(RT_GetCurrGpuID,
int32());
MOCK_METHOD0(GenerateTextureId,
int());
MOCK_METHOD2(SetCull,
void(ECull, bool));
MOCK_METHOD10(DrawQuad,
void(float x0, float y0, float x1, float y1, const ColorF& color, float z, float s0, float t0, float s1, float t1));
MOCK_METHOD9(DrawQuad3D,
void(const Vec3& v0, const Vec3& v1, const Vec3& v2, const Vec3& v3, const ColorF& color, float ftx0, float fty0, float ftx1, float fty1));
MOCK_METHOD0(FX_ResetPipe,
void());
MOCK_METHOD4(FX_GetDepthSurface,
SDepthTexture * (int, int, bool, bool));
MOCK_METHOD5(FX_CheckOverflow,
void(int, int, IRenderElement*, int*, int*));
MOCK_METHOD1(FX_PreRender,
void(int Stage));
MOCK_METHOD0(FX_PostRender,
void());
MOCK_METHOD3(FX_SetState,
void(int, int, int));
MOCK_METHOD3(FX_CommitStates,
void(const SShaderTechnique * pTech, const SShaderPass * pPass, bool bUseMaterialState));
MOCK_METHOD1(FX_Commit,
void(bool));
MOCK_METHOD2(FX_SetVertexDeclaration,
long(int StreamMask, const AZ::Vertex::Format& vertexFormat));
MOCK_METHOD7(FX_DrawIndexedPrimitive,
void(eRenderPrimitiveType, int, int, int, int, int, bool));
MOCK_METHOD3(FX_SetIStream,
long(const void* pB, uint32 nOffs, RenderIndexType idxType));
MOCK_METHOD5(FX_SetVStream,
long(int, const void*, uint32, uint32, uint32));
MOCK_METHOD4(FX_DrawPrimitive,
void(eRenderPrimitiveType, int, int, int));
MOCK_METHOD1(FX_ClearTarget,
void(ITexture * pTex));
MOCK_METHOD1(FX_ClearTarget,
void(SDepthTexture * pTex));
MOCK_METHOD4(FX_SetRenderTarget,
bool(int, void*, SDepthTexture*, uint32));
MOCK_METHOD4(FX_PushRenderTarget,
bool(int, void*, SDepthTexture*, uint32));
MOCK_METHOD7(FX_SetRenderTarget,
bool(int, CTexture*, SDepthTexture*, bool, int, bool, uint32));
MOCK_METHOD6(FX_PushRenderTarget,
bool(int, CTexture*, SDepthTexture*, int, bool, uint32));
MOCK_METHOD1(FX_RestoreRenderTarget,
bool(int nTarget));
MOCK_METHOD1(FX_PopRenderTarget,
bool(int nTarget));
MOCK_METHOD1(FX_SetActiveRenderTargets,
void(bool bAllowDIP));
MOCK_METHOD4(FX_Start,
void(CShader * ef, int nTech, CShaderResources * Res, IRenderElement * re));
MOCK_METHOD1(RT_PopRenderTarget,
void(int nTarget));
MOCK_METHOD5(RT_SetViewport,
void(int, int, int, int, int));
MOCK_METHOD4(RT_PushRenderTarget,
void(int nTarget, CTexture * pTex, SDepthTexture * pDS, int nS));
MOCK_METHOD5(EF_Scissor,
void(bool bEnable, int sX, int sY, int sWdt, int sHgt));
#ifdef SUPPORT_HW_MOUSE_CURSOR
MOCK_METHOD0(GetIHWMouseCursor,
IHWMouseCursor * ());
#endif
MOCK_METHOD0(GetRecursionLevel,
int());
MOCK_METHOD2(GetIntegerConfigurationValue,
int(const char* varName, int defaultValue));
MOCK_METHOD2(GetFloatConfigurationValue,
float(const char* varName, float defaultValue));
MOCK_METHOD2(GetBooleanConfigurationValue,
bool(const char* varName, bool defaultValue));
MOCK_METHOD3(ApplyDepthTextureState,
void(int unit, int nFilter, bool clamp));
MOCK_METHOD0(GetZTargetTexture,
ITexture * ());
MOCK_METHOD1(GetTextureState,
int(const STexState& TS));
MOCK_METHOD7(TextureDataSize,
uint32(uint32, uint32, uint32, uint32, uint32, ETEX_Format, ETEX_TileMode));
MOCK_METHOD6(ApplyForID,
void(int nID, int nTUnit, int nTState, int nTexMaterialSlot, int nSUnit, bool useWhiteDefault));
MOCK_METHOD9(Create3DTexture,
ITexture * (const char* szName, int nWidth, int nHeight, int nDepth, int nMips, int nFlags, const byte * pData, ETEX_Format eTFSrc, ETEX_Format eTFDst));
MOCK_METHOD1(IsTextureExist,
bool(const ITexture * pTex));
MOCK_METHOD1(NameForTextureFormat,
const char*(ETEX_Format eTF));
MOCK_METHOD1(NameForTextureType,
const char*(ETEX_Type eTT));
MOCK_METHOD0(IsVideoThreadModeEnabled,
bool());
MOCK_METHOD5(CreateDynTexture2,
IDynTexture * (uint32 nWidth, uint32 nHeight, uint32 nTexFlags, const char* szSource, ETexPool eTexPool));
MOCK_METHOD0(GetCurrentTextureAtlasSize,
uint32());
MOCK_METHOD2(BeginProfilerSection,
void(const char*, uint32));
MOCK_METHOD1(EndProfilerSection,
void(const char*));
MOCK_METHOD1(AddProfilerLabel,
void(const char*));
MOCK_METHOD5(EF_QueryImpl,
void(ERenderQueryTypes eQuery, void* pInOut0, uint32 nInOutSize0, void* pInOut1, uint32 nInOutSize1));
};
@@ -60,8 +60,6 @@ public:
IViewSystem * ());
MOCK_METHOD0(GetILevelSystem,
ILevelSystem * ());
MOCK_METHOD0(GetINameTable,
INameTable * ());
MOCK_METHOD0(GetICmdLine,
ICmdLine * ());
MOCK_METHOD0(GetILog,
-507
View File
@@ -1,507 +0,0 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#ifndef CRYINCLUDE_CRYCOMMON_POOLALLOCATOR_H
#define CRYINCLUDE_CRYCOMMON_POOLALLOCATOR_H
#pragma once
//---------------------------------------------------------------------------
// Memory allocation class. Allocates, frees, and reuses fixed-size blocks of
// memory, a scheme sometimes known as Simple Segregated Memory.
//
// Allocation is amortized constant time. The normal case is very fast -
// basically just a couple of dereferences. If many blocks are allocated,
// the system may occasionally need to allocate a further bucket of blocks
// for itself. Deallocation is strictly fast constant time.
//
// Each PoolAllocator allocates blocks of a single size and alignment, specified
// by template arguments. There is no per-block space overhead, except for
// alignment. The free list mechanism uses the memory of the block itself
// when it is deallocated.
//
// In this implementation memory claimed by the system is never deallocated,
// until the entire allocator is deallocated. This is to ensure fast
// allocation/deallocation - reference counting the bucket quickly would
// require a pointer to the bucket be stored, whereas now no memory is used
// while the block is allocated.
//
// The class can optionally support multi-threading, using the second
// template parameter. By default it is multithread-safe.
// See Synchronization.h.
//
// The class is implemented using a HeapAllocator.
//---------------------------------------------------------------------------
#include "HeapAllocator.h"
namespace stl
{
//////////////////////////////////////////////////////////////////////////
// Fixed-size pool allocator, using a shared heap.
template <typename THeap>
class SharedSizePoolAllocator
{
template <typename T>
friend struct PoolCommonAllocator;
protected:
using_type(THeap, Lock);
struct ObjectNode
{
ObjectNode* pNext;
};
static size_t AllocSize(size_t nSize)
{
return max<size_t>(nSize, sizeof(ObjectNode));
}
static size_t AllocAlign(size_t nSize, size_t nAlign)
{
return nAlign > 0 ? nAlign : min<size_t>(nSize, alignof(void*));
}
public:
SharedSizePoolAllocator(THeap& heap, size_t nSize, size_t nAlign = 0)
: _pHeap(&heap)
, _nAllocSize(AllocSize(nSize))
, _nAllocAlign(AllocAlign(nSize, nAlign))
, _pFreeList(0)
{
}
~SharedSizePoolAllocator()
{
// All allocated objects should be freed by now.
Lock lock(*_pHeap);
Validate(lock);
for (ObjectNode* pFree = _pFreeList; pFree; )
{
ObjectNode* pNext = pFree->pNext;
_pHeap->Deallocate(lock, pFree, _nAllocSize);
pFree = pNext;
}
}
// Raw allocation.
void* Allocate()
{
Lock lock(*_pHeap);
if (_pFreeList)
{
ObjectNode* pFree = _pFreeList;
_pFreeList = _pFreeList->pNext;
Validate(lock);
_Counts.nUsed++;
return pFree;
}
// No free pointer, allocate a new one.
void* pNewMemory = _pHeap->Allocate(lock, _nAllocSize, _nAllocAlign);
if (pNewMemory)
{
_Counts.nUsed++;
_Counts.nAlloc++;
Validate(lock);
}
return pNewMemory;
}
void Deallocate(void* pObject)
{
Deallocate(Lock(*_pHeap), pObject);
}
SMemoryUsage GetCounts() const
{
Lock lock(*_pHeap);
return _Counts;
}
SMemoryUsage GetTotalMemory(const Lock&) const
{
return SMemoryUsage(_Counts.nAlloc * _nAllocSize, _Counts.nUsed * _nAllocSize);
}
protected:
void Deallocate(const Lock& lock, void* pObject)
{
if (pObject)
{
assert(_pHeap->CheckPtr(lock, pObject));
ObjectNode* pNode = static_cast<ObjectNode*>(pObject);
// Add the object to the front of the free list.
pNode->pNext = _pFreeList;
_pFreeList = pNode;
_Counts.nUsed--;
Validate(lock);
}
}
void Validate(const Lock& lock) const
{
_pHeap->Validate(lock);
_Counts.Validate();
assert(_Counts.nAlloc * _nAllocSize <= _pHeap->GetTotalMemory(lock).nUsed);
}
void Reset(const Lock&, [[maybe_unused]] bool bForce = false)
{
assert(bForce || _Counts.nUsed == 0);
_Counts.Clear();
_pFreeList = 0;
}
protected:
const size_t _nAllocSize, _nAllocAlign;
SMemoryUsage _Counts;
THeap* _pHeap;
ObjectNode* _pFreeList;
};
//////////////////////////////////////////////////////////////////////////
struct SPoolMemoryUsage
: SMemoryUsage
{
size_t nPool;
SPoolMemoryUsage(size_t _nAlloc = 0, size_t _nPool = 0, size_t _nUsed = 0)
: SMemoryUsage(_nAlloc, _nUsed)
, nPool(_nPool)
{
// These values are pulled from 3 atomic variables and not guaranteed to be a perfect "snapshot"
// Of the current state of the pool memory usage (e.g. Used may be > max, etc)
// Patch the values so that they make sense (it won't be wrong, just mildly out of date)
// This is done to prevent sticking expensive mutexes or potentially forever blocking semaphores in the pool
if (nUsed > nPool)
{
nPool = nUsed;
}
assert(nPool <= nAlloc);
}
size_t nPoolFree() const
{
return nPool - nUsed;
}
size_t nNonPoolFree() const
{
return nAlloc - nPool;
}
void Clear()
{
nAlloc = nUsed = nPool = 0;
}
void operator += (SPoolMemoryUsage const& op)
{
nAlloc += op.nAlloc;
nPool += op.nPool;
nUsed += op.nUsed;
}
};
//////////////////////////////////////////////////////////////////////////
// SizePoolAllocator with owned heap
template <typename THeap>
class SizePoolAllocator
: protected THeap
, public SharedSizePoolAllocator<THeap>
{
typedef SharedSizePoolAllocator<THeap> TPool;
using_type(THeap, Lock);
using_type(THeap, FreeMemLock);
using TPool::AllocSize;
using TPool::_Counts;
using TPool::_nAllocSize;
public:
SizePoolAllocator(size_t nSize, size_t nAlign = 0, FHeap opts = 0)
: THeap(opts.PageSize(opts.PageSize * AllocSize(nSize)))
, TPool(*this, nSize, nAlign)
{
}
using TPool::Allocate;
using THeap::GetMemoryUsage;
void Deallocate(void* pObject)
{
FreeMemLock lock(*this);
TPool::Deallocate(lock, pObject);
if (THeap::FreeWhenEmpty && _Counts.nUsed == 0)
{
TPool::Reset(lock);
THeap::Clear(lock);
}
}
void FreeMemoryIfEmpty()
{
FreeMemLock lock(*this);
if (_Counts.nUsed == 0)
{
TPool::Reset(lock);
THeap::Clear(lock);
}
}
void ResetMemory()
{
FreeMemLock lock(*this);
TPool::Reset(lock);
THeap::Reset(lock);
}
void FreeMemory()
{
FreeMemLock lock(*this);
TPool::Reset(lock);
THeap::Clear(lock);
}
void FreeMemoryForce()
{
FreeMemLock lock(*this);
TPool::Reset(lock, true);
THeap::Clear(lock);
}
SPoolMemoryUsage GetTotalMemory()
{
Lock lock(*this);
return SPoolMemoryUsage(THeap::GetTotalMemory(lock).nAlloc, _Counts.nAlloc * _nAllocSize, _Counts.nUsed * _nAllocSize);
}
};
//////////////////////////////////////////////////////////////////////////
// Templated size version of SizePoolAllocator
template <int S, typename L = PSyncMultiThread, int A = 0>
class PoolAllocator
: public SizePoolAllocator< HeapAllocator<L> >
{
public:
PoolAllocator(FHeap opts = 0)
: SizePoolAllocator< HeapAllocator<L> >(S, A, opts)
{
}
};
//////////////////////////////////////////////////////////////////////////
template <int S, int A = 0>
class PoolAllocatorNoMT
: public SizePoolAllocator< HeapAllocator<PSyncNone> >
{
public:
PoolAllocatorNoMT(FHeap opts = 0)
: SizePoolAllocator< HeapAllocator<PSyncNone> >(S, A, opts)
{
}
};
//////////////////////////////////////////////////////////////////////////
template<typename T, typename L = PSyncMultiThread, size_t A = 0>
class TPoolAllocator
: public SizePoolAllocator< HeapAllocator<L> >
{
typedef SizePoolAllocator< HeapAllocator<L> > TSizePool;
public:
using TSizePool::Allocate;
using TSizePool::Deallocate;
TPoolAllocator(FHeap opts = 0)
: TSizePool(sizeof(T), max<size_t>(alignof(T), A), opts)
{}
T* New()
{
return new(Allocate())T();
}
template<class I>
T* New(const I& init)
{
return new(Allocate())T(init);
}
void Delete(T* ptr)
{
if (ptr)
{
ptr->~T();
Deallocate(ptr);
}
}
};
// Legacy verbose typedefs.
typedef PSyncNone PoolAllocatorSynchronizationSinglethreaded;
typedef PSyncMultiThread PoolAllocatorSynchronizationMultithreaded;
//////////////////////////////////////////////////////////////////////////
// Allocator maintaining multiple type-specific pools, sharing a common heap source.
template<typename THeap>
struct PoolCommonAllocator
: protected THeap
{
typedef SharedSizePoolAllocator<THeap> TPool;
using_type(THeap, Lock);
using_type(THeap, FreeMemLock);
struct TPoolNode
: SharedSizePoolAllocator<THeap>
{
TPoolNode* pNext;
TPoolNode(THeap& heap, TPoolNode*& pList, size_t nSize, size_t nAlign)
: SharedSizePoolAllocator<THeap>(heap, nSize, nAlign)
{
pNext = pList;
pList = this;
}
};
public:
PoolCommonAllocator()
: _pPoolList(0)
{
}
~PoolCommonAllocator()
{
TPoolNode* pPool = _pPoolList;
while (pPool)
{
TPoolNode* pNextPool = pPool->pNext;
delete pPool;
pPool = pNextPool;
}
}
TPool* CreatePool(size_t nSize, size_t nAlign = 0)
{
return new TPoolNode(*this, _pPoolList, nSize, nAlign);
}
SPoolMemoryUsage GetTotalMemory()
{
Lock lock(*this);
SMemoryUsage mem;
for (TPoolNode* pPool = _pPoolList; pPool; pPool = pPool->pNext)
{
mem += pPool->GetTotalMemory(lock);
}
return SPoolMemoryUsage(THeap::GetTotalMemory(lock).nAlloc, mem.nAlloc, mem.nUsed);
}
bool FreeMemory(bool bDeallocate = true)
{
FreeMemLock lock(*this);
for (TPoolNode* pPool = _pPoolList; pPool; pPool = pPool->pNext)
{
if (pPool->GetTotalMemory(lock).nUsed)
{
return false;
}
}
for (TPoolNode* pPool = _pPoolList; pPool; pPool = pPool->pNext)
{
pPool->Reset(lock);
}
if (bDeallocate)
{
THeap::Clear(lock);
}
else
{
THeap::Reset(lock);
}
return true;
}
protected:
TPoolNode* _pPoolList;
};
//////////////////////////////////////////////////////////////////////////
// The additional TInstancer type provides a way of instantiating multiple instances
// of this class, without static variables.
template<typename THeap, typename TInstancer = int>
struct StaticPoolCommonAllocator
{
ILINE static PoolCommonAllocator<THeap>& StaticAllocator()
{
static PoolCommonAllocator<THeap> s_Allocator;
return s_Allocator;
}
typedef SharedSizePoolAllocator<THeap> TPool;
template<class T>
ILINE static TPool& TypeAllocator()
{
static TPool* sp_Pool = CreatePoolOnGlobalHeap(sizeof(T), alignof(T));
return *sp_Pool;
}
template<class T>
ILINE static void* Allocate(T*& p)
{ return p = (T*)TypeAllocator<T>().Allocate(); }
template<class T>
ILINE static void Deallocate(T* p)
{ return TypeAllocator<T>().Deallocate(p); }
template<class T>
static T* New()
{ return new(TypeAllocator<T>().Allocate())T(); }
template<class T, class I>
static T* New(const I& init)
{ return new(TypeAllocator<T>().Allocate())T(init); }
template<class T>
static void Delete(T* ptr)
{
if (ptr)
{
ptr->~T();
TypeAllocator<T>().Deallocate(ptr);
}
}
static SPoolMemoryUsage GetTotalMemory()
{ return StaticAllocator().GetTotalMemory(); }
private:
ILINE static TPool* CreatePoolOnGlobalHeap(size_t nSize, size_t nAlign = 0)
{
return StaticAllocator().CreatePool(nSize, nAlign);
}
};
};
#endif // CRYINCLUDE_CRYCOMMON_POOLALLOCATOR_H
+15 -4
View File
@@ -7,13 +7,24 @@
*/
#pragma once
#include <AzCore/PlatformDef.h>
#include <AzCore/std/typetraits/aligned_storage.h>
#include <AzCore/std/typetraits/is_integral.h>
#include <AzCore/std/typetraits/conditional.h>
#include <AzCore/std/typetraits/static_storage.h>
#include <AzCore/std/function/function_template.h>
#include <list>
#include <vector>
#include <set>
#include <map>
template <class T>
class StaticInstanceSpecialization
{
};
// Specializations for std::vector and std::map which allows us to modify the
// Specializations for std::vector and std::map which allows us to modify the
// least amount of legacy code by mirroring the std APIs that are in use
// These are not intended to be complete, just enough to shim existing legacy code
template <typename U, class A>
@@ -30,7 +41,7 @@ public:
using size_type = typename Container::size_type;
template <class Integral>
AZ_FORCE_INLINE
AZ_FORCE_INLINE
typename AZStd::enable_if<AZStd::is_integral<Integral>::value, reference>::type
operator[](Integral index)
{
@@ -322,7 +333,7 @@ public:
using size_type = typename Container::size_type;
using pair_iter_bool = std::pair<iterator, bool>;
AZ_FORCE_INLINE iterator begin()
{
@@ -360,7 +371,7 @@ public:
}
template <class K2>
AZ_FORCE_INLINE
AZ_FORCE_INLINE
typename AZStd::enable_if<AZStd::is_constructible<key_type, K2>::value, mapped_type&>::type
operator[](const K2& keylike)
{
@@ -80,14 +80,12 @@ set(FILES
CryHeaders_info.cpp
CryListenerSet.h
CryLegacyAllocator.h
CryName.h
CryPath.h
CryPodArray.h
CrySizer.h
CrySystemBus.h
CryTypeInfo.h
CryVersion.h
HeapAllocator.h
LegacyAllocator.cpp
LegacyAllocator.h
MetaUtils.h
@@ -95,7 +93,6 @@ set(FILES
MultiThread_Containers.h
NullAudioSystem.h
PNoise3.h
PoolAllocator.h
primitives.h
ProjectDefines.h
Range.h
@@ -120,7 +117,6 @@ set(FILES
Cry_Matrix33.h
Cry_Matrix34.h
Cry_Matrix44.h
Cry_MatrixDiag.h
Cry_Vector4.h
Cry_Camera.h
Cry_Color.h
@@ -133,7 +129,6 @@ set(FILES
Cry_ValidNumber.h
Cry_Vector2.h
Cry_Vector3.h
Cry_XOptimise.h
CryHalf_info.h
CryHalf.inl
MathConversion.h
@@ -14,7 +14,6 @@ set(FILES
Mocks/ISystemMock.h
Mocks/ITimerMock.h
Mocks/ICVarMock.h
Mocks/IRendererMock.h
Mocks/ITextureMock.h
Mocks/IRemoteConsoleMock.h
)
File diff suppressed because it is too large Load Diff
@@ -99,7 +99,6 @@ inline int RoundToClosestMB(size_t memSize)
#include <CryFile.h>
#include <ISystem.h>
#include <ITimer.h>
#include <IPhysics.h>
#include <IXml.h>
#include <ICmdLine.h>
#include <IConsole.h>
@@ -16,6 +16,7 @@
#include "CryPath.h"
#include <LoadScreenBus.h>
#include <CryCommon/StaticInstance.h>
#include <AzCore/Debug/AssetTracking.h>
#include <AzFramework/API/ApplicationAPI.h>
@@ -20,12 +20,14 @@
#include "System.h" // to access InitLocalization()
#include <CryPath.h>
#include <IConsole.h>
#include <IFont.h>
#include <locale.h>
#include <time.h>
#include <AzCore/std/string/conversions.h>
#include <AzFramework/StringFunc/StringFunc.h>
#include <AzCore/std/string/conversions.h>
#include <AzCore/Math/Crc.h>
#define MAX_CELL_COUNT 32
@@ -209,7 +211,7 @@ CLocalizedStringsManager::CLocalizedStringsManager(ISystem* pSystem)
AZStd::string sPath;
const AZStd::string sLocalizationFolder(PathUtil::GetLocalizationFolder());
ILocalizationManager::TLocalizationBitfield availableLanguages = 0;
AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance();
// test language name against supported languages
for (int i = 0; i < ILocalizationManager::ePILID_MAX_OR_INVALID; i++)
@@ -1319,7 +1321,7 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
}
//Compute the CRC32 of the key
keyCRC = CCrc32::Compute(szLowerCaseKey);
keyCRC = AZ::Crc32(szLowerCaseKey);
if (m_cvarLocalizationDebug >= 3)
{
CryLogAlways("<Localization dupe/clash detection> CRC32: 0x%8X, Key: %s", keyCRC, szLowerCaseKey);
@@ -1507,7 +1509,7 @@ bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName,
if (m_cvarLocalizationEncode == 1)
{
pEncoder->Finalize();
{
uint8 compressionBuffer[COMPRESSION_FIXED_BUFFER_LENGTH];
//uint8 decompressionBuffer[COMPRESSION_FIXED_BUFFER_LENGTH];
@@ -1647,7 +1649,7 @@ bool CLocalizedStringsManager::DoLoadAGSXmlDocument(const char* sFileName, uint8
}
lowerKey = keyString;
AZStd::to_lower(lowerKey.begin(), lowerKey.end());
keyCRC = CCrc32::Compute(lowerKey.c_str());
keyCRC = AZ::Crc32(lowerKey);
if (m_cvarLocalizationDebug >= 3)
{
CryLogAlways("<Localization dupe/clash detection> CRC32: 0%8X, Key: %s", keyCRC, lowerKey.c_str());
@@ -1755,7 +1757,7 @@ void CLocalizedStringsManager::AddLocalizedString(SLanguage* pLanguage, SLocaliz
pLanguage->m_vLocalizedStrings.push_back(pEntry);
int nId = (int)pLanguage->m_vLocalizedStrings.size() - 1;
pLanguage->m_keysMap[keyCRC32] = pEntry;
if (m_cvarLocalizationDebug >= 2)
{
CryLog("<Localization> Add new string <%u> with ID %d to <%s>", keyCRC32, nId, pLanguage->sLanguage.c_str());
@@ -1861,7 +1863,7 @@ void CLocalizedStringsManager::LocalizeAndSubstituteInternal(AZStd::string& locS
startIndex += substituteOut.length();
}
startIndex = locString.find_first_of('{', startIndex);
endIndex = locString.find_first_of('}', startIndex);
endIndex = locString.find_first_of('}', startIndex);
}
}
#if defined(LOG_DECOMP_TIMES)
@@ -2002,7 +2004,7 @@ bool CLocalizedStringsManager::LocalizeLabel(const char* sLabel, AZStd::string&
// Label sign.
if (sLabel[0] == '@')
{
uint32 labelCRC32 = CCrc32::ComputeLowercase(sLabel + 1); // skip @ character.
uint32 labelCRC32 = AZ::Crc32(sLabel + 1); // skip @ character.
{
AutoLock lock(m_cs); //Lock here, to prevent strings etc being modified underneath this lookup
SLocalizedStringEntry* entry = stl::find_in_map(m_pLanguage->m_keysMap, labelCRC32, NULL);
@@ -2051,10 +2053,10 @@ bool CLocalizedStringsManager::GetEnglishString(const char* sKey, AZStd::string&
// Label sign.
if (sKey[0] == '@')
{
uint32 keyCRC32 = CCrc32::ComputeLowercase(sKey + 1);
uint32 keyCRC32 = AZ::Crc32(sKey + 1);
{
AutoLock lock(m_cs); //Lock here, to prevent strings etc being modified underneath this lookup
SLocalizedStringEntry* entry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL); // skip @ character.
AutoLock lock(m_cs); // Lock here, to prevent strings etc being modified underneath this lookup
SLocalizedStringEntry* entry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL); // skip @ character.
if (entry != NULL && entry->pEditorExtension != NULL)
{
sLocalizedString = entry->pEditorExtension->sOriginalText;
@@ -2062,7 +2064,7 @@ bool CLocalizedStringsManager::GetEnglishString(const char* sKey, AZStd::string&
}
else
{
keyCRC32 = CCrc32::ComputeLowercase(sKey);
keyCRC32 = AZ::Crc32(sKey);
entry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL);
if (entry != NULL && entry->pEditorExtension != NULL)
{
@@ -2080,7 +2082,8 @@ bool CLocalizedStringsManager::GetEnglishString(const char* sKey, AZStd::string&
}
else
{
// CryWarning( VALIDATOR_MODULE_SYSTEM,VALIDATOR_WARNING,"Not a valid localized string Label <%s>, must start with @ symbol", sKey );
// CryWarning( VALIDATOR_MODULE_SYSTEM,VALIDATOR_WARNING,"Not a valid localized string Label <%s>, must start with @ symbol", sKey
// );
}
sLocalizedString = sKey;
@@ -2093,7 +2096,7 @@ bool CLocalizedStringsManager::IsLocalizedInfoFound(const char* sKey)
{
return false;
}
uint32 keyCRC32 = CCrc32::ComputeLowercase(sKey);
uint32 keyCRC32 = AZ::Crc32(sKey);
{
AutoLock lock(m_cs); //Lock here, to prevent strings etc being modified underneath this lookup
const SLocalizedStringEntry* entry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL);
@@ -2109,7 +2112,7 @@ bool CLocalizedStringsManager::GetLocalizedInfoByKey(const char* sKey, SLocalize
return false;
}
uint32 keyCRC32 = CCrc32::ComputeLowercase(sKey);
uint32 keyCRC32 = AZ::Crc32(sKey);
{
AutoLock lock(m_cs); //Lock here, to prevent strings etc being modified underneath this lookup
const SLocalizedStringEntry* entry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL);
@@ -2140,7 +2143,7 @@ bool CLocalizedStringsManager::GetLocalizedInfoByKey(const char* sKey, SLocalize
bool bResult = false;
uint32 keyCRC32 = CCrc32::ComputeLowercase(sKey);
uint32 keyCRC32 = AZ::Crc32(sKey);
{
AutoLock lock(m_cs); //Lock here, to prevent strings etc being modified underneath this lookup
const SLocalizedStringEntry* pEntry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL);
@@ -2293,7 +2296,7 @@ bool CLocalizedStringsManager::GetSubtitle(const char* sKeyOrLabel, AZStd::strin
++sKeyOrLabel;
}
uint32 keyCRC32 = CCrc32::ComputeLowercase(sKeyOrLabel);
uint32 keyCRC32 = AZ::Crc32(sKeyOrLabel);
{
AutoLock lock(m_cs); //Lock here, to prevent strings etc being modified underneath this lookup
const SLocalizedStringEntry* pEntry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL);
@@ -2457,7 +2460,7 @@ namespace
{ "nl-NL", 0x0413 }, // Dutch (The Netherlands)
{ "fi-FI", 0x040b }, // Finnish
{ "sv-SE", 0x041d }, // Swedish
{ "cs-CZ", 0x0405 }, // Czech
{ "cs-CZ", 0x0405 }, // Czech
{ "no-NO", 0x0414 }, // Norwegian (Norway)
{ "ar-SA", 0x0401 }, // Arabic (Saudi Arabia)
{ "da-DK", 0x0406 }, // Danish (Denmark)
@@ -11,8 +11,9 @@
#define CRYINCLUDE_CRYSYSTEM_REMOTECONSOLE_REMOTECONSOLE_H
#pragma once
#include <IConsole.h>
#include <CryListenerSet.h>
#include <CryCommon/IConsole.h>
#include <CryCommon/CryListenerSet.h>
#include <CryCommon/StaticInstance.h>
#if !defined(RELEASE) || defined(RELEASE_LOGGING) || defined(ENABLE_PROFILING_CODE)
#define USE_REMOTE_CONSOLE
+1 -1
View File
@@ -19,6 +19,7 @@
#include "CryLibrary.h"
#include <CryPath.h>
#include <CrySystemBus.h>
#include <CryCommon/IFont.h>
#include <AzFramework/API/ApplicationAPI.h>
#include <AzFramework/API/ApplicationAPI_Platform.h>
#include <AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard.h>
@@ -257,7 +258,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment)
// Initialize global environment interface pointers.
m_env.pSystem = this;
m_env.pTimer = &m_Time;
m_env.pNameTable = &m_nameTable;
m_env.bIgnoreAllAsserts = false;
m_env.bNoAssertDialog = false;
+18 -23
View File
@@ -11,13 +11,11 @@
#include <ISystem.h>
#include <IRenderer.h>
#include <IPhysics.h>
#include <IWindowMessageHandler.h>
#include "Timer.h"
#include <CryVersion.h>
#include "CmdLine.h"
#include "CryName.h"
#include <AzFramework/Archive/ArchiveVars.h>
#include "RenderBus.h"
@@ -25,6 +23,7 @@
#include <LoadScreenBus.h>
#include <AzCore/Module/DynamicModuleHandle.h>
#include <AzCore/Math/Crc.h>
namespace AzFramework
{
@@ -330,7 +329,6 @@ public:
ICryFont* GetICryFont(){ return m_env.pCryFont; }
ILog* GetILog(){ return m_env.pLog; }
ICmdLine* GetICmdLine(){ return m_pCmdLine; }
INameTable* GetINameTable() { return m_env.pNameTable; };
IViewSystem* GetIViewSystem();
ILevelSystem* GetILevelSystem();
ISystemEventDispatcher* GetISystemEventDispatcher() { return m_pSystemEventDispatcher; }
@@ -490,27 +488,27 @@ private: // ------------------------------------------------------
// System environment.
SSystemGlobalEnvironment m_env;
CTimer m_Time; //!<
bool m_bInitializedSuccessfully; //!< true if the system completed all initialization steps
bool m_bRelaunch; //!< relaunching the app or not (true beforerelaunch)
int m_iLoadingMode; //!< Game is loading w/o changing context (0 not, 1 quickloading, 2 full loading)
bool m_bTestMode; //!< If running in testing mode.
bool m_bEditor; //!< If running in Editor.
bool m_bNoCrashDialog;
bool m_bNoErrorReportWindow;
CTimer m_Time; //!<
bool m_bInitializedSuccessfully; //!< true if the system completed all initialization steps
bool m_bRelaunch; //!< relaunching the app or not (true beforerelaunch)
int m_iLoadingMode; //!< Game is loading w/o changing context (0 not, 1 quickloading, 2 full loading)
bool m_bTestMode; //!< If running in testing mode.
bool m_bEditor; //!< If running in Editor.
bool m_bNoCrashDialog;
bool m_bNoErrorReportWindow;
bool m_bPreviewMode; //!< If running in Preview mode.
bool m_bDedicatedServer; //!< If running as Dedicated server.
bool m_bIgnoreUpdates; //!< When set to true will ignore Update and Render calls,
bool m_bForceNonDevMode; //!< true when running on a cheat protected server or a client that is connected to it (not used in singlplayer)
bool m_bWasInDevMode; //!< Set to true if was in dev mode.
bool m_bInDevMode; //!< Set to true if was in dev mode.
bool m_bDedicatedServer; //!< If running as Dedicated server.
bool m_bIgnoreUpdates; //!< When set to true will ignore Update and Render calls,
bool m_bForceNonDevMode; //!< true when running on a cheat protected server or a client that is connected to it (not used in singlplayer)
bool m_bWasInDevMode; //!< Set to true if was in dev mode.
bool m_bInDevMode; //!< Set to true if was in dev mode.
bool m_bGameFolderWritable;//!< True when verified that current game folder have write access.
int m_ttMemStatSS; //!< Time to memstat screenshot
bool m_bDrawConsole; //!< Set to true if OK to draw the console.
bool m_bDrawUI; //!< Set to true if OK to draw UI.
int m_ttMemStatSS; //!< Time to memstat screenshot
bool m_bDrawConsole; //!< Set to true if OK to draw the console.
bool m_bDrawUI; //!< Set to true if OK to draw UI.
std::map<CCryNameCRC, AZStd::unique_ptr<AZ::DynamicModuleHandle> > m_moduleDLLHandles;
std::map<AZ::Crc32, AZStd::unique_ptr<AZ::DynamicModuleHandle> > m_moduleDLLHandles;
//! current active process
IProcess* m_pProcess;
@@ -632,9 +630,6 @@ private: // ------------------------------------------------------
class CLocalizedStringsManager* m_pLocalizationManager;
// Name table.
CNameTable m_nameTable;
ESystemConfigSpec m_nServerConfigSpec;
ESystemConfigSpec m_nMaxConfigSpec;
ESystemConfigPlatform m_ConfigPlatform;
+2 -2
View File
@@ -475,7 +475,7 @@ bool CSystem::UnloadDLL(const char* dllName)
{
bool isSuccess = false;
CCryNameCRC key(dllName);
AZ::Crc32 key(dllName);
AZStd::unique_ptr<AZ::DynamicModuleHandle> empty;
AZStd::unique_ptr<AZ::DynamicModuleHandle>& hModule = stl::find_in_map_ref(m_moduleDLLHandles, key, empty);
if ((hModule) && (hModule->IsLoaded()))
@@ -1184,7 +1184,7 @@ bool CSystem::Init(const SSystemInitParams& startupParams)
{
azConsole->LinkDeferredFunctors(AZ::ConsoleFunctorBase::GetDeferredHead());
}
if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry)
{
AZ::SettingsRegistryInterface::FixedValueString assetPlatform;
+2 -2
View File
@@ -20,8 +20,8 @@
#include <IRenderer.h>
#include <ISystem.h>
#include <ILog.h>
#include <IProcess.h>
#include <IRenderAuxGeom.h>
#include <IFont.h>
#include <ITexture.h>
#include "ConsoleHelpGen.h" // CConsoleHelpGen
#include <AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard.h>
+1 -23
View File
@@ -24,7 +24,6 @@
#include <md5.h>
//////////////////////////////////////////////////////////////////////////
CXmlNode_PoolAlloc* g_pCXmlNode_PoolAlloc = 0;
#ifdef CRY_COLLECT_XML_NODE_STATS
SXmlNodeStats* g_pCXmlNode_Stats = 0;
#endif
@@ -35,11 +34,9 @@ extern bool g_bEnableBinaryXmlLoading;
CXmlUtils::CXmlUtils(ISystem* pSystem)
{
m_pSystem = pSystem;
m_pSystem->GetISystemEventDispatcher()->RegisterListener(this);
// create IReadWriteXMLSink object
m_pReadWriteXMLSink = new CReadWriteXMLSink();
g_pCXmlNode_PoolAlloc = new CXmlNode_PoolAlloc;
#ifdef CRY_COLLECT_XML_NODE_STATS
g_pCXmlNode_Stats = new SXmlNodeStats();
#endif
@@ -53,8 +50,6 @@ CXmlUtils::CXmlUtils(ISystem* pSystem)
//////////////////////////////////////////////////////////////////////////
CXmlUtils::~CXmlUtils()
{
m_pSystem->GetISystemEventDispatcher()->RemoveListener(this);
delete g_pCXmlNode_PoolAlloc;
#ifdef CRY_COLLECT_XML_NODE_STATS
delete g_pCXmlNode_Stats;
#endif
@@ -200,13 +195,8 @@ IXmlSerializer* CXmlUtils::CreateXmlSerializer()
}
//////////////////////////////////////////////////////////////////////////
void CXmlUtils::GetMemoryUsage(ICrySizer* pSizer)
void CXmlUtils::GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer)
{
{
SIZER_COMPONENT_NAME(pSizer, "Nodes");
g_pCXmlNode_PoolAlloc->GetMemoryUsage(pSizer);
}
#ifdef CRY_COLLECT_XML_NODE_STATS
// yes, slow
std::vector<const CXmlNode*> rootNodes;
@@ -260,18 +250,6 @@ void CXmlUtils::GetMemoryUsage(ICrySizer* pSizer)
#endif
}
//////////////////////////////////////////////////////////////////////////
void CXmlUtils::OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_PTR wparam, [[maybe_unused]] UINT_PTR lparam)
{
switch (event)
{
case ESYSTEM_EVENT_LEVEL_POST_UNLOAD:
case ESYSTEM_EVENT_LEVEL_LOAD_END:
g_pCXmlNode_PoolAlloc->FreeMemoryIfEmpty();
break;
}
}
//////////////////////////////////////////////////////////////////////////
class CXmlBinaryDataWriterFile
: public XMLBinary::IDataWriter
-7
View File
@@ -27,7 +27,6 @@ class CXMLPatcher;
//////////////////////////////////////////////////////////////////////////
class CXmlUtils
: public IXmlUtils
, public ISystemEventListener
{
public:
CXmlUtils(ISystem* pSystem);
@@ -62,12 +61,6 @@ public:
virtual IXmlTableReader* CreateXmlTableReader();
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// ISystemEventListener
//////////////////////////////////////////////////////////////////////////
virtual void OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam);
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
virtual void GetMemoryUsage(ICrySizer* pSizer);
-39
View File
@@ -6,14 +6,10 @@
*
*/
#ifndef CRYINCLUDE_CRYSYSTEM_XML_XML_H
#define CRYINCLUDE_CRYSYSTEM_XML_XML_H
#pragma once
#include <algorithm>
#include <PoolAllocator.h>
#include <stack>
#include "IXml.h"
@@ -344,9 +340,6 @@ private:
friend class XmlParserImp;
};
typedef stl::PoolAllocatorNoMT<sizeof(CXmlNode)> CXmlNode_PoolAlloc;
extern CXmlNode_PoolAlloc* g_pCXmlNode_PoolAlloc;
#ifdef CRY_COLLECT_XML_NODE_STATS
typedef std::set<CXmlNode*> TXmlNodeSet; // yes, slow, but really only for one-shot debugging
struct SXmlNodeStats
@@ -361,35 +354,6 @@ struct SXmlNodeStats
extern SXmlNodeStats* g_pCXmlNode_Stats;
#endif
/*
//////////////////////////////////////////////////////////////////////////
inline void* CXmlNode::operator new( size_t nSize )
{
void *ptr = g_pCXmlNode_PoolAlloc->Allocate();
if (ptr)
{
memset( ptr,0,nSize ); // Clear objects memory.
#ifdef CRY_COLLECT_XML_NODE_STATS
g_pCXmlNode_Stats->nodeSet.insert(reinterpret_cast<CXmlNode*> (ptr));
++g_pCXmlNode_Stats->nAllocs;
#endif
}
return ptr;
}
//////////////////////////////////////////////////////////////////////////
inline void CXmlNode::operator delete( void *ptr )
{
if (ptr)
{
g_pCXmlNode_PoolAlloc->Deallocate(ptr);
#ifdef CRY_COLLECT_XML_NODE_STATS
g_pCXmlNode_Stats->nodeSet.erase(reinterpret_cast<CXmlNode*> (ptr));
++g_pCXmlNode_Stats->nFrees;
#endif
}
}
*/
//////////////////////////////////////////////////////////////////////////
//
@@ -434,6 +398,3 @@ private:
unsigned int m_nAllocated;
std::stack<CXmlNodeReuse*> m_pNodePool;
};
#endif // CRYINCLUDE_CRYSYSTEM_XML_XML_H
+2 -1
View File
@@ -22,7 +22,8 @@
#include <IAudioSystemImplementation.h>
#include <ISystem.h>
#include <IPhysics.h>
#include <CryCommon/StlUtils.h>
#include <algorithm>
#include <IRenderAuxGeom.h>
namespace Audio
@@ -32,7 +32,6 @@
#include <Tests/UI/UIFixture.h>
#include <Editor/ReselectingTreeView.h>
#include <Mocks/IRendererMock.h>
#include <Mocks/ISystemMock.h>
namespace EMotionFX
@@ -73,7 +72,6 @@ namespace EMotionFX
struct DataMembers
{
testing::NiceMock<IRendererMock> m_renderer;
testing::NiceMock<LODSystemMock> m_system;
};
@@ -28,7 +28,7 @@ namespace AZ
private:
using ElementInformation = ExpressionEvaluation::ElementInformation;
static const char* EmptyAnyIdentifier;
static constexpr AZStd::string_view EmptyAnyIdentifier = "Empty AZStd::any";
static bool IsEmptyAny(const rapidjson::Value& typeId)
{
@@ -43,7 +43,7 @@ namespace AZ
JsonSerializationResult::Result Load
( void* outputValue
, const Uuid& outputValueTypeId
, [[maybe_unused]] const Uuid& outputValueTypeId
, const rapidjson::Value& inputValue
, JsonDeserializerContext& context) override
{
@@ -161,8 +161,7 @@ namespace AZ
else
{
rapidjson::Value emptyAny;
AZStd::string emptyAnyName(EmptyAnyIdentifier);
emptyAny.SetString(emptyAnyName.c_str(), aznumeric_caster(emptyAnyName.size()), context.GetJsonAllocator());
emptyAny.SetString(EmptyAnyIdentifier.data(), aznumeric_caster(EmptyAnyIdentifier.size()), context.GetJsonAllocator());
outputValue.AddMember
( rapidjson::StringRef(JsonSerialization::TypeIdFieldIdentifier)
, AZStd::move(emptyAny)
@@ -176,6 +175,4 @@ namespace AZ
};
AZ_CLASS_ALLOCATOR_IMPL(ElementInformationSerializer, SystemAllocator, 0);
const char* ElementInformationSerializer::EmptyAnyIdentifier = "Empty AZStd::any";
}
@@ -30,7 +30,7 @@ namespace AZ
JsonSerializationResult::Result Load
( void* outputValue
, const Uuid& outputValueTypeId
, [[maybe_unused]] const Uuid& outputValueTypeId
, const rapidjson::Value& inputValue
, JsonDeserializerContext& context) override
{
@@ -9,6 +9,8 @@
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <CryCommon/ISystem.h>
#include <CryCommon/TimeValue.h>
#include <CryCommon/ITimer.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
inline void Gestures::RecognizerClickOrTap::Config::Reflect(AZ::ReflectContext* context)
@@ -8,6 +8,7 @@
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <CryCommon/ITimer.h>
#include <CryCommon/ISystem.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -10,6 +10,7 @@
#include "IGestureRecognizer.h"
#include <CryCommon/ISystem.h>
#include <CryCommon/ITimer.h>
#include <AzCore/RTTI/ReflectContext.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -8,6 +8,7 @@
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <CryCommon/ITimer.h>
#include <CryCommon/ISystem.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -8,6 +8,7 @@
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <CryCommon/ITimer.h>
#include <CryCommon/ISystem.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -9,6 +9,7 @@
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <CryCommon/ISystem.h>
#include <CryCommon/ITimer.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
inline void Gestures::RecognizerRotate::Config::Reflect(AZ::ReflectContext* context)

Some files were not shown because too many files have changed in this diff Show More