Merge branch 'development' of https://github.com/o3de/o3de into carlitosan/development

This commit is contained in:
chcurran
2021-08-10 10:10:40 -07:00
701 changed files with 21430 additions and 22380 deletions
@@ -12,6 +12,11 @@
################################################################################
if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS)
# Only enable AWS automated tests on Windows
if(NOT "${PAL_PLATFORM_NAME}" STREQUAL "Windows")
return()
endif()
# Enable after installing NodeJS and CDK on jenkins Windows AMI.
ly_add_pytest(
NAME AutomatedTesting::AWSTests
@@ -93,6 +93,7 @@ def run():
general.idle_wait_frames(100)
for i in range(1, 101):
benchmarker.capture_pass_timestamp(i)
benchmarker.capture_cpu_frame_time(i)
general.exit_game_mode()
helper.wait_for_condition(function=lambda: not general.is_in_game_mode(), timeout_in_seconds=2.0)
general.log("Capturing complete.")
@@ -61,6 +61,25 @@ class BenchmarkHelper(object):
general.log('Failed to capture pass timestamps.')
return self.capturedData
def capture_cpu_frame_time(self, frame_number):
"""
Capture CPU frame times and block further execution until it has been written to the disk.
"""
self.handler = azlmbr.atom.ProfilingCaptureNotificationBusHandler()
self.handler.connect()
self.handler.add_callback('OnCaptureCpuFrameTimeFinished', self.on_data_captured)
self.done = False
self.capturedData = False
success = azlmbr.atom.ProfilingCaptureRequestBus(
azlmbr.bus.Broadcast, "CaptureCpuFrameTime", f'{self.output_path}/cpu_frame{frame_number}_time.json')
if success:
self.wait_until_data()
general.log('CPU frame time captured.')
else:
general.log('Failed to capture CPU frame time.')
return self.capturedData
def on_data_captured(self, parameters):
# the parameters come in as a tuple
if parameters[0]:
@@ -99,6 +99,7 @@ class TestPerformanceBenchmarkSuite(object):
expected_lines = [
"Benchmark metadata captured.",
"Pass timestamps captured.",
"CPU frame time captured.",
"Capturing complete.",
"Captured data successfully."
]
@@ -106,6 +107,7 @@ class TestPerformanceBenchmarkSuite(object):
unexpected_lines = [
"Failed to capture data.",
"Failed to capture pass timestamps.",
"Failed to capture CPU frame time.",
"Failed to capture benchmark metadata."
]
@@ -33,20 +33,19 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS)
)
ly_add_pytest(
NAME AutomatedTesting::SandboxTest
TEST_SUITE sandbox
NAME AutomatedTesting::LoadLevelGPU
TEST_SUITE smoke
TEST_SERIAL
PATH ${CMAKE_CURRENT_LIST_DIR}
PYTEST_MARKS "SUITE_sandbox"
TIMEOUT 1500
TEST_REQUIRES gpu
PATH ${CMAKE_CURRENT_LIST_DIR}/test_RemoteConsole_GPULoadLevel_Works.py
TIMEOUT 100
RUNTIME_DEPENDENCIES
AZ::AssetProcessor
AZ::PythonBindingsExample
Legacy::Editor
AutomatedTesting.GameLauncher
AutomatedTesting.Assets
COMPONENT
Sandbox
Smoke
)
ly_add_pytest(
@@ -75,4 +74,5 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS)
AutomatedTesting.GameLauncher
AutomatedTesting.Assets
)
endif()
@@ -0,0 +1,44 @@
"""
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
UI Apps: AutomatedTesting.GameLauncher
Launch AutomatedTesting.GameLauncher with Simple level
Test should run in both gpu and non gpu
"""
import pytest
import psutil
import ly_test_tools.environment.waiter as waiter
import editor_python_test_tools.hydra_test_utils as editor_test_utils
from ly_remote_console.remote_console_commands import RemoteConsole as RemoteConsole
from ly_remote_console.remote_console_commands import (
send_command_and_expect_response as send_command_and_expect_response,
)
@pytest.mark.parametrize("launcher_platform", ["windows"])
@pytest.mark.parametrize("project", ["AutomatedTesting"])
@pytest.mark.parametrize("level", ["Simple"])
@pytest.mark.SUITE_smoke
class TestRemoteConsoleLoadLevelWorks(object):
@pytest.fixture
def remote_console_instance(self, request):
console = RemoteConsole()
def teardown():
if console.connected:
console.stop()
request.addfinalizer(teardown)
return console
def test_RemoteConsole_LoadLevel_Works(self, launcher, level, remote_console_instance, launcher_platform):
expected_lines = ['Level system is loading "Simple"']
editor_test_utils.launch_and_validate_results_launcher(launcher, level, remote_console_instance, expected_lines, null_renderer=True)
@@ -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
UI Apps: AutomatedTesting.GameLauncher
Launch AutomatedTesting.GameLauncher with Simple level
Test should run in both gpu and non gpu
"""
import pytest
import psutil
import ly_test_tools.environment.waiter as waiter
import editor_python_test_tools.hydra_test_utils as editor_test_utils
from ly_remote_console.remote_console_commands import RemoteConsole as RemoteConsole
from ly_remote_console.remote_console_commands import (
send_command_and_expect_response as send_command_and_expect_response,
)
@pytest.mark.parametrize("launcher_platform", ["windows"])
@pytest.mark.parametrize("project", ["AutomatedTesting"])
@pytest.mark.parametrize("level", ["Simple"])
class TestRemoteConsoleLoadLevelWorks(object):
@pytest.fixture
def remote_console_instance(self, request):
console = RemoteConsole()
def teardown():
if console.connected:
console.stop()
request.addfinalizer(teardown)
return console
def test_RemoteConsole_LoadLevel_Works(self, launcher, level, remote_console_instance, launcher_platform):
expected_lines = ['Level system is loading "Simple"']
editor_test_utils.launch_and_validate_results_launcher(launcher, level, remote_console_instance, expected_lines, null_renderer=False)
@@ -1,105 +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
UI Apps: AutomatedTesting.GameLauncher
Launch AutomatedTesting.GameLauncher with Simple level
Test should run in both gpu and non gpu
"""
import pytest
import psutil
# Bail on the test if ly_test_tools doesn't exist.
pytest.importorskip("ly_test_tools")
import ly_test_tools.environment.waiter as waiter
from ly_remote_console.remote_console_commands import RemoteConsole as RemoteConsole
from ly_remote_console.remote_console_commands import (
send_command_and_expect_response as send_command_and_expect_response,
)
@pytest.mark.parametrize("launcher_platform", ["windows"])
@pytest.mark.parametrize("project", ["AutomatedTesting"])
@pytest.mark.parametrize("level", ["Simple"])
@pytest.mark.SUITE_sandbox
class TestRemoteConsoleLoadLevelWorks(object):
@pytest.fixture
def remote_console_instance(self, request):
console = RemoteConsole()
def teardown():
if console.connected:
console.stop()
request.addfinalizer(teardown)
return console
def test_RemoteConsole_LoadLevel_Works(self, launcher, level, remote_console_instance, launcher_platform):
expected_lines = ['Level system is loading "Simple"']
self.launch_and_validate_results_launcher(launcher, level, remote_console_instance, expected_lines)
def launch_and_validate_results_launcher(
self,
launcher,
level,
remote_console_instance,
expected_lines,
null_renderer=False,
port_listener_timeout=120,
log_monitor_timeout=300,
remote_console_port=4600,
):
"""
Runs the launcher with the specified level, and monitors Game.log for expected lines.
:param launcher: Configured launcher object to run test against.
:param level: The level to load in the launcher.
:param remote_console_instance: Configured Remote Console object.
:param expected_lines: Expected lines to search log for.
:oaram null_renderer: Specifies the test does not require the renderer. Defaults to True.
:param port_listener_timeout: Timeout for verifying successful connection to Remote Console.
:param log_monitor_timeout: Timeout for monitoring for lines in Game.log
:param remote_console_port: The port used to communicate with the Remote Console.
"""
def _check_for_listening_port(port):
"""
Checks to see if the connection to the designated port was established.
:param port: Port to listen to.
:return: True if port is listening.
"""
port_listening = False
for conn in psutil.net_connections():
if "port={}".format(port) in str(conn):
port_listening = True
return port_listening
if null_renderer:
launcher.args.extend(["-NullRenderer"])
# Start the Launcher
with launcher.start():
# Ensure Remote Console can be reached
waiter.wait_for(
lambda: _check_for_listening_port(remote_console_port),
port_listener_timeout,
exc=AssertionError("Port {} not listening.".format(remote_console_port)),
)
remote_console_instance.start(timeout=30)
# Load the specified level in the launcher
send_command_and_expect_response(
remote_console_instance, f"loadlevel {level}", "LEVEL_LOAD_END", timeout=30
)
# Monitor the console for expected lines
for line in expected_lines:
assert remote_console_instance.expect_log_line(
line, log_monitor_timeout
), f"Expected line not found: {line}"
+1 -1
View File
@@ -28,8 +28,8 @@ include(cmake/FileUtil.cmake)
include(cmake/PAL.cmake)
include(cmake/PALTools.cmake)
include(cmake/RuntimeDependencies.cmake)
include(cmake/Install.cmake)
include(cmake/Configurations.cmake) # Requires to be after PAL so we get platform variable definitions
include(cmake/Install.cmake)
include(cmake/Dependencies.cmake)
include(cmake/Deployment.cmake)
include(cmake/3rdParty.cmake)
+24
View File
@@ -13,3 +13,27 @@ set_target_properties(Editor PROPERTIES
RESOURCE ${CMAKE_CURRENT_LIST_DIR}/Images.xcassets
XCODE_ATTRIBUTE_ASSETCATALOG_COMPILER_APPICON_NAME EditorAppIcon
)
# We cannot use ly_add_target here because we're already including this file from inside ly_add_target
# So we need to setup target, dependencies and install logic manually.
add_executable(EditorDummy Platform/Mac/main_dummy.cpp)
add_executable(AZ::EditorDummy ALIAS EditorDummy)
ly_target_link_libraries(EditorDummy
PRIVATE
AZ::AzCore
AZ::AzFramework)
ly_add_dependencies(Editor EditorDummy)
# Store the aliased target into a DIRECTORY property
set_property(DIRECTORY APPEND PROPERTY LY_DIRECTORY_TARGETS AZ::EditorDummy)
# Store the directory path in a GLOBAL property so that it can be accessed
# in the layout install logic. Skip if the directory has already been added
get_property(ly_all_target_directories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES)
if(NOT CMAKE_CURRENT_SOURCE_DIR IN_LIST ly_all_target_directories)
set_property(GLOBAL APPEND PROPERTY LY_ALL_TARGET_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR})
endif()
ly_install_add_install_path_setreg(Editor)
+1 -1
View File
@@ -3,7 +3,7 @@
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>Editor</string>
<string>EditorDummy</string>
<key>CFBundleIdentifier</key>
<string>org.O3DE.Editor</string>
<key>CFBundlePackageType</key>
+75
View File
@@ -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
*
*/
#include <AzCore/Component/ComponentApplication.h>
#include <AzCore/Memory/SystemAllocator.h>
#include <AzCore/Settings/SettingsRegistryMergeUtils.h>
#include <AzCore/Utils/Utils.h>
#include <AzFramework/Process/ProcessWatcher.h>
#include <cstdlib>
int main(int argc, char* argv[])
{
// Create a ComponentApplication to initialize the AZ::SystemAllocator and initialize the SettingsRegistry
AZ::ComponentApplication::Descriptor desc;
AZ::ComponentApplication application;
application.Create(desc);
AZStd::vector<AZStd::string> envVars;
const char* homePath = std::getenv("HOME");
envVars.push_back(AZStd::string::format("HOME=%s", homePath));
if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
{
const char* dyldLibPathOrig = std::getenv("DYLD_LIBRARY_PATH");
AZStd::string dyldSearchPath = AZStd::string::format("DYLD_LIBRARY_PATH=%s", dyldLibPathOrig);
if (AZ::IO::FixedMaxPath projectModulePath;
settingsRegistry->Get(projectModulePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectConfigurationBinPath))
{
dyldSearchPath.append(":");
dyldSearchPath.append(projectModulePath.c_str());
}
if (AZ::IO::FixedMaxPath installedBinariesFolder;
settingsRegistry->Get(installedBinariesFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_InstalledBinaryFolder))
{
if (AZ::IO::FixedMaxPath engineRootFolder;
settingsRegistry->Get(engineRootFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder))
{
installedBinariesFolder = engineRootFolder / installedBinariesFolder;
dyldSearchPath.append(":");
dyldSearchPath.append(installedBinariesFolder.c_str());
}
}
envVars.push_back(dyldSearchPath);
}
AZStd::string commandArgs;
for (int i = 1; i < argc; i++)
{
commandArgs.append(argv[i]);
commandArgs.append(" ");
}
AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo;
AZ::IO::Path processPath{ AZ::IO::PathView(AZ::Utils::GetExecutableDirectory()) };
processPath /= "Editor";
processLaunchInfo.m_processExecutableString = AZStd::move(processPath.Native());
processLaunchInfo.m_commandlineParameters = commandArgs;
processLaunchInfo.m_environmentVariables = &envVars;
processLaunchInfo.m_showWindow = true;
AzFramework::ProcessWatcher* processWatcher = AzFramework::ProcessWatcher::LaunchProcess(processLaunchInfo, AzFramework::ProcessCommunicationType::COMMUNICATOR_TYPE_NONE);
application.Destroy();
return 0;
}
@@ -28,6 +28,7 @@ namespace AZ::SettingsRegistryMergeUtils
inline static constexpr char FilePathsRootKey[] = "/Amazon/AzCore/Runtime/FilePaths";
inline static constexpr char FilePathKey_BinaryFolder[] = "/Amazon/AzCore/Runtime/FilePaths/BinaryFolder";
inline static constexpr char FilePathKey_EngineRootFolder[] = "/Amazon/AzCore/Runtime/FilePaths/EngineRootFolder";
inline static constexpr char FilePathKey_InstalledBinaryFolder[] = "/Amazon/AzCore/Runtime/FilePaths/InstalledBinariesFolder";
//! Stores the absolute path to root of a project's cache. No asset platform in this path, this is where the asset database file lives.
//! i.e. <ProjectPath>/Cache
+11 -101
View File
@@ -21,7 +21,18 @@ namespace AZStd
{
// alias std::pointer_traits into the AZStd::namespace
using std::pointer_traits;
//! Bring the names of uninitialized_default_construct and
//! uninitialized_default_construct_n into the AZStd namespace
using std::uninitialized_default_construct;
using std::uninitialized_default_construct_n;
//! uninitialized_value_construct and uninitialized_value_construct_n
//! are now brought into scope of the AZStd namespace
using std::uninitialized_value_construct;
using std::uninitialized_value_construct_n;
}
namespace AZStd::Internal
{
template <typename T, typename = void>
@@ -223,107 +234,6 @@ namespace AZStd
}
}
namespace AZStd
{
//! C++20 implementation of uninitialized_default_construct
//! Initializes objects by default-initialization via placement new
//! Ex. `new(declval<void*>()) T` - Notice no parenthesis after T
//! This performs default initialization instead of value initialization
//! Default initialization performs the following actions
//! # If T is a class type it considers constructors which can be invoked
//! with an empty argument list. The selected constructor is invoked
//! to provide the initial value of the object
//! # If T is an array type, then default initialization is performed
//! on each array element
//! # Otherwise nothing is done and objects with automatic storage duration(i.e scope)
//! are initialized with indeterminate values
//! For example given the following struct
//! struct Foo
//! {
//! int mint;
//! double bubble;
//! };
//! Invoking uninitialized_default_construct(FooPtr, FooPtr + 1)
//! Will default initialize the FooPtr object (Foo has an implicitly-defined default constructor)
//! The values of mint and bubble are indeterminate
template <typename ForwardIt>
constexpr auto uninitialized_default_construct(ForwardIt first, ForwardIt last)
-> enable_if_t<Internal::is_forward_iterator_v<ForwardIt>, void>
{
for (; first != last; ++first)
{
return ::new (AZStd::addressof(*first)) typename AZStd::iterator_traits<ForwardIt>::value_type;
}
}
// C++20 implementation of uninitialized_default_construct_n
// Constructs "n" objects starting at first via default-initialization
template <typename ForwardIt, typename Size>
constexpr auto uninitialized_default_construct_n(ForwardIt first, Size numElements)
-> enable_if_t<Internal::is_forward_iterator_v<ForwardIt>, ForwardIt>
{
for (; numElements > 0; ++first, --numElements)
{
return ::new (AZStd::addressof(*first)) typename AZStd::iterator_traits<ForwardIt>::value_type;
}
return first;
}
}
namespace AZStd
{
//! C++20 implementation of uninitialized_value_construct
//! Initializes objects by value-initialization via placement new
//! Ex. `new(declval<void*>()) T()` - Notice parenthesis are here after T
//! value-initialization of an object performs different rules depending
//! on the type of T
//! Value initialization performs the following actions
//! # If T is a class type with no default constructor or with a user-provided
//! constructor or a deleted default constructor, then default-initialization
//! is performed
//! # If T is a class type with a default constructor that is neither
//! user-provided nor deleted(i.e a class with an implicitly-defined or defaulted
//! default constructor), then the object is zero-initialized and then it is
//! default-initialized if it has a non-trivial default constructor
//! # If T is an array type, then value initialization is performed
//! on each array element
//! # Otherwise the object is zero-initialized
//! (i.e sets arithmetic and enum objects to 0, bool objects to false, pointers to nullptr)
//! For example given the following struct
//! struct Foo
//! {
//! int mint;
//! double bubble;
//! };
//! Invoking uninitialized_default_construct(FooPtr, FooPtr + 1)
//! Will value-initialize the FooPtr object.
//! The Foo has an implicitly-defined default constructor.
//! For aggregates such as int and double this will perform zero-initialization
//! which will set their values to 0
//! Therefore The values of mint will be 0 and and bubble 0.0
template <typename ForwardIt>
constexpr auto uninitialized_value_construct(ForwardIt first, ForwardIt last)
-> enable_if_t<Internal::is_forward_iterator_v<ForwardIt>, void>
{
for (; first != last; ++first)
{
return ::new (AZStd::addressof(*first)) typename AZStd::iterator_traits<ForwardIt>::value_type();
}
}
// C++20 implementation of uninitialized_default_construct_n
// Constructs "n" objects starting at the first via by value-initialization
template <typename ForwardIt, typename Size>
constexpr auto uninitialized_value_construct_n(ForwardIt first, Size numElements)
-> enable_if_t<Internal::is_forward_iterator_v<ForwardIt>, ForwardIt>
{
for (; numElements > 0; ++first, --numElements)
{
return ::new (AZStd::addressof(*first)) typename AZStd::iterator_traits<ForwardIt>::value_type();
}
return first;
}
}
namespace AZStd::Internal
{
@@ -25,29 +25,7 @@ namespace AZStd
AZStd::sys_time_t GetTimeNowTicks()
{
AZStd::sys_time_t timeNow;
struct timespec ts;
clock_serv_t cclock;
mach_timespec_t mts;
kern_return_t ret = host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
if (ret == KERN_SUCCESS)
{
ret = clock_get_time(cclock, &mts);
if (ret == KERN_SUCCESS)
{
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;
}
else
{
AZ_Assert(false, "clock_get_time error: %d\n", ret);
}
mach_port_deallocate(mach_task_self(), cclock);
}
else
{
AZ_Assert(false, "clock_get_time error: %d\n", ret);
}
timeNow = ts.tv_sec * GetTimeTicksPerSecond() + ts.tv_nsec;
timeNow = clock_gettime_nsec_np(CLOCK_UPTIME_RAW);
return timeNow;
}
@@ -62,29 +40,7 @@ namespace AZStd
AZStd::sys_time_t GetTimeNowSecond()
{
AZStd::sys_time_t timeNowSecond;
struct timespec ts;
clock_serv_t cclock;
mach_timespec_t mts;
kern_return_t ret = host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
if (ret == KERN_SUCCESS)
{
ret = clock_get_time(cclock, &mts);
if (ret == KERN_SUCCESS)
{
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;
}
else
{
AZ_Assert(false, "clock_get_time error: %d\n", ret);
}
mach_port_deallocate(mach_task_self(), cclock);
}
else
{
AZ_Assert(false, "clock_get_time error: %d\n", ret);
}
timeNowSecond = ts.tv_sec;
timeNowSecond = GetTimeNowTicks()/GetTimeTicksPerSecond();
return timeNowSecond;
}
@@ -134,4 +134,48 @@ namespace UnitTest
EXPECT_FLOAT_EQ(4.0f, resultAddress->m_floatValue);
AZStd::destroy_at(resultAddress);
}
TEST(CreateDestroy, UninitializedDefaultConstruct_IsAbleToConstructMultipleElements_Succeeds)
{
struct RefWrapper
{
RefWrapper()
{}
int m_intValue{ 2 };
};
constexpr size_t ArraySize = 2;
AZStd::aligned_storage_for_t<RefWrapper> testArray[ArraySize];
RefWrapper(&uninitializedAddress)[2] = reinterpret_cast<RefWrapper(&)[2]>(testArray);
AZStd::uninitialized_default_construct(AZStd::begin(uninitializedAddress), AZStd::end(uninitializedAddress));
EXPECT_EQ(2, uninitializedAddress[0].m_intValue);
EXPECT_EQ(2, uninitializedAddress[1].m_intValue);
// Reset uninitializedAddress to Debug pattern
memset(uninitializedAddress, 0xCD, ArraySize * sizeof(RefWrapper));
AZStd::uninitialized_default_construct_n(AZStd::data(uninitializedAddress), AZStd::size(uninitializedAddress));
EXPECT_EQ(2, uninitializedAddress[0].m_intValue);
EXPECT_EQ(2, uninitializedAddress[1].m_intValue);
}
TEST(CreateDestroy, UninitializedValueConstruct_IsAbleToConstructMultipleElements_Succeeds)
{
struct RefWrapper
{
int m_intValue;
};
constexpr size_t ArraySize = 2;
AZStd::aligned_storage_for_t<RefWrapper> testArray[ArraySize];
RefWrapper(&uninitializedAddress)[2] = reinterpret_cast<RefWrapper(&)[2]>(testArray);
AZStd::uninitialized_value_construct(AZStd::begin(uninitializedAddress), AZStd::end(uninitializedAddress));
EXPECT_EQ(0, uninitializedAddress[0].m_intValue);
EXPECT_EQ(0, uninitializedAddress[1].m_intValue);
// Reset uninitializedAddress to Debug pattern
memset(uninitializedAddress, 0xCD, ArraySize * sizeof(RefWrapper));
AZStd::uninitialized_value_construct_n(AZStd::data(uninitializedAddress), AZStd::size(uninitializedAddress));
EXPECT_EQ(0, uninitializedAddress[0].m_intValue);
EXPECT_EQ(0, uninitializedAddress[1].m_intValue);
}
}
@@ -24,7 +24,9 @@
#include <sys/ioctl.h>
#include <sys/resource.h> // for iopolicy
#include <time.h>
#include <unistd.h>
extern char **environ;
namespace AzFramework
{
@@ -45,7 +47,7 @@ namespace AzFramework
// result == 0 means child PID is still running, nothing to check
if (result == -1)
{
AZ_TracePrintf("ProcessWatcher", "IsChildProcessDone could not determine child process status (waitpid errno %d). assuming process either failed to launch or terminated unexpectedly\n", errno);
AZ_TracePrintf("ProcessWatcher", "IsChildProcessDone could not determine child process status (waitpid errno %d(%s)). assuming process either failed to launch or terminated unexpectedly\n", errno, strerror(errno));
exitCode = 0;
}
else if (result == childProcessId)
@@ -274,28 +276,27 @@ namespace AzFramework
azstrcat(commandAndArgs[i], token.size(), token.c_str());
}
commandAndArgs[commandTokens.size()] = nullptr;
char** environmentVariables = nullptr;
int numEnvironmentVars = 0;
constexpr int MaxEnvVariables = 128;
using EnvironmentVariableContainer = AZStd::fixed_vector<char*, MaxEnvVariables>;
EnvironmentVariableContainer environmentVariables;
for (char **env = ::environ; *env; env++)
{
environmentVariables.push_back(*env);
}
if (processLaunchInfo.m_environmentVariables)
{
const int numEnvironmentVars = processLaunchInfo.m_environmentVariables->size();
// Adding one more as exec expects the array to have a nullptr as the last element
environmentVariables = new char*[numEnvironmentVars + 1];
for (int i = 0; i < numEnvironmentVars; i++)
for (AZStd::string& processLaunchEnv : *processLaunchInfo.m_environmentVariables)
{
const AZStd::string& envVarString = processLaunchInfo.m_environmentVariables->at(i);
environmentVariables[i] = new char[envVarString.size() + 1];
environmentVariables[i][0] = '\0';
azstrcat(environmentVariables[i], envVarString.size(), envVarString.c_str());
environmentVariables.push_back(processLaunchEnv.data());
}
environmentVariables[numEnvironmentVars] = NULL;
}
environmentVariables.push_back(nullptr);
pid_t child_pid = fork();
if (IsIdChildProcess(child_pid))
{
ExecuteCommandAsChild(commandAndArgs, environmentVariables, processLaunchInfo, processData.m_startupInfo);
ExecuteCommandAsChild(commandAndArgs, environmentVariables.data(), processLaunchInfo, processData.m_startupInfo);
}
processData.m_childProcessId = child_pid;
@@ -303,15 +304,6 @@ namespace AzFramework
// Close these handles as they are only to be used by the child process
processData.m_startupInfo.CloseAllHandles();
if (processLaunchInfo.m_environmentVariables)
{
for (int i = 0; i < numEnvironmentVars; i++)
{
delete [] environmentVariables[i];
}
delete [] environmentVariables;
}
for (int i = 0; i < commandTokens.size(); i++)
{
delete [] commandAndArgs[i];
@@ -13,3 +13,27 @@ set_target_properties(AssetProcessor PROPERTIES
RESOURCE ${CMAKE_CURRENT_SOURCE_DIR}/Platform/Mac/Images.xcassets
XCODE_ATTRIBUTE_ASSETCATALOG_COMPILER_APPICON_NAME AssetProcessorAppIcon
)
# We cannot use ly_add_target here because we're already including this file from inside ly_add_target
# So we need to setup target, dependencies and install logic manually.
add_executable(AssetProcessorDummy Platform/Mac/main_dummy.cpp)
add_executable(AZ::AssetProcessorDummy ALIAS AssetProcessorDummy)
ly_target_link_libraries(AssetProcessorDummy
PRIVATE
AZ::AzCore
AZ::AzFramework)
ly_add_dependencies(AssetProcessor AssetProcessorDummy)
# Store the aliased target into a DIRECTORY property
set_property(DIRECTORY APPEND PROPERTY LY_DIRECTORY_TARGETS AZ::AssetProcessorDummy)
# Store the directory path in a GLOBAL property so that it can be accessed
# in the layout install logic. Skip if the directory has already been added
get_property(ly_all_target_directories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES)
if(NOT CMAKE_CURRENT_SOURCE_DIR IN_LIST ly_all_target_directories)
set_property(GLOBAL APPEND PROPERTY LY_ALL_TARGET_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR})
endif()
ly_install_add_install_path_setreg(AssetProcessor)
@@ -11,7 +11,7 @@
<key>CFBundleSignature</key>
<string>ASPR</string>
<key>CFBundleExecutable</key>
<string>AssetProcessor</string>
<string>AssetProcessorDummy</string>
<key>CFBundleIdentifier</key>
<string>com.Amazon.AssetProcessor</string>
</dict>
@@ -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
*
*/
#include <AzCore/Component/ComponentApplication.h>
#include <AzCore/Memory/SystemAllocator.h>
#include <AzCore/Settings/SettingsRegistryMergeUtils.h>
#include <AzCore/Utils/Utils.h>
#include <AzFramework/Process/ProcessWatcher.h>
#include <cstdlib>
int main(int argc, char* argv[])
{
// Create a ComponentApplication to initialize the AZ::SystemAllocator and initialize the SettingsRegistry
AZ::ComponentApplication::Descriptor desc;
AZ::ComponentApplication application;
application.Create(desc);
AZStd::vector<AZStd::string> envVars;
const char* homePath = std::getenv("HOME");
envVars.push_back(AZStd::string::format("HOME=%s", homePath));
if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
{
const char* dyldLibPathOrig = std::getenv("DYLD_LIBRARY_PATH");
AZStd::string dyldSearchPath = AZStd::string::format("DYLD_LIBRARY_PATH=%s", dyldLibPathOrig);
if (AZ::IO::FixedMaxPath projectModulePath;
settingsRegistry->Get(projectModulePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectConfigurationBinPath))
{
dyldSearchPath.append(":");
dyldSearchPath.append(projectModulePath.c_str());
}
if (AZ::IO::FixedMaxPath installedBinariesFolder;
settingsRegistry->Get(installedBinariesFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_InstalledBinaryFolder))
{
if (AZ::IO::FixedMaxPath engineRootFolder;
settingsRegistry->Get(engineRootFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder))
{
installedBinariesFolder = engineRootFolder / installedBinariesFolder;
dyldSearchPath.append(":");
dyldSearchPath.append(installedBinariesFolder.c_str());
}
}
envVars.push_back(dyldSearchPath);
}
AZStd::string commandArgs;
for (int i = 1; i < argc; i++)
{
commandArgs.append(argv[i]);
commandArgs.append(" ");
}
AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo;
AZ::IO::Path processPath{ AZ::IO::PathView(AZ::Utils::GetExecutableDirectory()) };
processPath /= "AssetProcessor";
processLaunchInfo.m_processExecutableString = AZStd::move(processPath.Native());
processLaunchInfo.m_commandlineParameters = commandArgs;
processLaunchInfo.m_environmentVariables = &envVars;
processLaunchInfo.m_showWindow = true;
AzFramework::ProcessWatcher* processWatcher = AzFramework::ProcessWatcher::LaunchProcess(processLaunchInfo, AzFramework::ProcessCommunicationType::COMMUNICATOR_TYPE_NONE);
application.Destroy();
return 0;
}
@@ -28,7 +28,7 @@ namespace AssetProcessor
//! Amount of time in seconds to wait for a builder to start up and connect
// sometimes, builders take a long time to start because of things like virus scanners scanning each
// builder DLL, so we give them a large margin.
static const int s_StartupConnectionWaitTimeS = 120;
static const int s_StartupConnectionWaitTimeS = 300;
static const int s_MillisecondsInASecond = 1000;
@@ -103,10 +103,6 @@ namespace AZ
}
}
if(!isBone)
{
return Events::ProcessingResult::Ignored;
}
// If the current scene node (our eventual parent) contains bone data, we are not a root bone
AZStd::shared_ptr<SceneData::GraphData::BoneData> createdBoneData;
@@ -135,18 +135,13 @@ namespace AZ
const aiBone* bone = FindFirstBoneByNodeName(node, boneByNameMap);
if (bone)
{
const DataTypes::MatrixType inverseOffsetMatrix = AssImpSDKWrapper::AssImpTypeConverter::ToTransform(bone->mOffsetMatrix).GetInverseFull();
const aiBone* parentBone = FindFirstBoneByNodeName(node->mParent, boneByNameMap);
if (parentBone)
{
DataTypes::MatrixType inverseOffsetMatrix = AssImpSDKWrapper::AssImpTypeConverter::ToTransform(bone->mOffsetMatrix).GetInverseFull();
const DataTypes::MatrixType parentBoneOffsetMatrix = AssImpSDKWrapper::AssImpTypeConverter::ToTransform(parentBone->mOffsetMatrix);
return parentBoneOffsetMatrix * inverseOffsetMatrix;
}
else
{
return inverseOffsetMatrix;
}
}
return AssImpSDKWrapper::AssImpTypeConverter::ToTransform(GetConcatenatedLocalTransform(node));
@@ -98,16 +98,52 @@ class TestAWSUtils(TestCase):
mocked_s3_client.list_buckets.assert_called_once()
assert not actual_buckets
def test_list_s3_buckets_return_expected_buckets(self) -> None:
def test_list_s3_buckets_return_empty_list_with_no_matching_region(self) -> None:
expected_region: str = "us-east-1"
mocked_s3_client: MagicMock = self._mock_client.return_value
expected_buckets: List[str] = [f"{TestAWSUtils._expected_bucket}1", f"{TestAWSUtils._expected_bucket}2"]
mocked_s3_client.list_buckets.return_value = {"Buckets": [{"Name": expected_buckets[0]},
{"Name": expected_buckets[1]}]}
mocked_s3_client.get_bucket_location.side_effect = [{"LocationConstraint": "us-east-2"},
{"LocationConstraint": "us-west-1"}]
actual_buckets: List[str] = aws_utils.list_s3_buckets()
self._mock_client.assert_called_once_with(aws_utils.AWSConstants.S3_SERVICE_NAME)
actual_buckets: List[str] = aws_utils.list_s3_buckets(expected_region)
self._mock_client.assert_called_once_with(aws_utils.AWSConstants.S3_SERVICE_NAME,
region_name=expected_region)
mocked_s3_client.list_buckets.assert_called_once()
assert actual_buckets == expected_buckets
assert not actual_buckets
def test_list_s3_buckets_return_expected_buckets_matching_region(self) -> None:
expected_region: str = "us-west-2"
mocked_s3_client: MagicMock = self._mock_client.return_value
expected_buckets: List[str] = [f"{TestAWSUtils._expected_bucket}1", f"{TestAWSUtils._expected_bucket}2"]
mocked_s3_client.list_buckets.return_value = {"Buckets": [{"Name": expected_buckets[0]},
{"Name": expected_buckets[1]}]}
mocked_s3_client.get_bucket_location.side_effect = [{"LocationConstraint": "us-west-2"},
{"LocationConstraint": "us-west-1"}]
actual_buckets: List[str] = aws_utils.list_s3_buckets(expected_region)
self._mock_client.assert_called_once_with(aws_utils.AWSConstants.S3_SERVICE_NAME,
region_name=expected_region)
mocked_s3_client.list_buckets.assert_called_once()
assert len(actual_buckets) == 1
assert actual_buckets[0] == expected_buckets[0]
def test_list_s3_buckets_return_expected_iad_buckets(self) -> None:
expected_region: str = "us-east-1"
mocked_s3_client: MagicMock = self._mock_client.return_value
expected_buckets: List[str] = [f"{TestAWSUtils._expected_bucket}1", f"{TestAWSUtils._expected_bucket}2"]
mocked_s3_client.list_buckets.return_value = {"Buckets": [{"Name": expected_buckets[0]},
{"Name": expected_buckets[1]}]}
mocked_s3_client.get_bucket_location.side_effect = [{"LocationConstraint": None},
{"LocationConstraint": "us-west-1"}]
actual_buckets: List[str] = aws_utils.list_s3_buckets(expected_region)
self._mock_client.assert_called_once_with(aws_utils.AWSConstants.S3_SERVICE_NAME,
region_name=expected_region)
mocked_s3_client.list_buckets.assert_called_once()
assert len(actual_buckets) == 1
assert actual_buckets[0] == expected_buckets[0]
def test_list_lambda_functions_return_empty_list(self) -> None:
mocked_lambda_client: MagicMock = self._mock_client.return_value
@@ -103,7 +103,17 @@ def list_s3_buckets(region: str = "") -> List[str]:
bucket_names: List[str] = []
bucket: Dict[str, any]
for bucket in response["Buckets"]:
bucket_names.append(bucket["Name"])
try:
bucket_name: str = bucket["Name"]
location_response: Dict[str, any] = s3_client.get_bucket_location(Bucket=bucket_name)
# Buckets in Region us-east-1 have a LocationConstraint of null .
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.get_bucket_location
if ((location_response["LocationConstraint"] == region) or
(not location_response["LocationConstraint"] and region == "us-east-1")):
bucket_names.append(bucket_name)
except ClientError as error:
raise RuntimeError(error_messages.AWS_SERVICE_REQUEST_CLIENT_ERROR_MESSAGE.format(
"get_bucket_location", error.response['Error']['Code'], error.response['Error']['Message']))
return bucket_names
@@ -22,12 +22,21 @@ namespace AZ
//! Dump the Timestamp from passes to a json file.
virtual bool CapturePassTimestamp(const AZStd::string& outputFilePath) = 0;
//! Dump the Cpu frame time statistics to a json file.
virtual bool CaptureCpuFrameTime(const AZStd::string& outputFilePath) = 0;
//! Dump the PipelineStatistics from passes to a json file.
virtual bool CapturePassPipelineStatistics(const AZStd::string& outputFilePath) = 0;
//! Dump the Cpu Profiling Statistics to a json file.
//! Dump a single frame of Cpu profiling data
virtual bool CaptureCpuProfilingStatistics(const AZStd::string& outputFilePath) = 0;
//! Start a multiframe capture of CPU profiling data.
virtual bool BeginContinuousCpuProfilingCapture() = 0;
//! End and dump an in-progress continuous capture.
virtual bool EndContinuousCpuProfilingCapture(const AZStd::string& outputFilePath) = 0;
//! Dump the benchmark metadata to a json file.
virtual bool CaptureBenchmarkMetadata(const AZStd::string& benchmarkName, const AZStd::string& outputFilePath) = 0;
};
@@ -44,6 +53,11 @@ namespace AZ
//! @param info The output file path or error information which depends on the return.
virtual void OnCaptureQueryTimestampFinished(bool result, const AZStd::string& info) = 0;
//! Notify when the current CpuFrameTimeStatistics capture is finished
//! @param result Set to true if it's finished successfully
//! @param info The output file path or error information which depends on the return.
virtual void OnCaptureCpuFrameTimeFinished(bool result, const AZStd::string& info) = 0;
//! Notify when the current PipelineStatistics query capture is finished
//! @param result Set to true if it's finished successfully
//! @param info The output file path or error information which depends on the return.
@@ -10,6 +10,9 @@
#include <Atom/RHI/CpuProfiler.h>
#include <Atom/RHI/RHIUtils.h>
#include <Atom/RHI/RHISystemInterface.h>
#include <Atom/RHI.Reflect/CpuTimingStatistics.h>
#include <AzCore/Statistics/RunningStatistic.h>
#include <Atom/RPI.Public/GpuQuery/GpuQueryTypes.h>
#include <Atom/RPI.Public/Pass/ParentPass.h>
@@ -22,6 +25,7 @@
#include <AzCore/RTTI/BehaviorContext.h>
#include <AzCore/Serialization/Json/JsonSerializationSettings.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/std/parallel/thread.h>
namespace AZ
{
@@ -34,6 +38,7 @@ namespace AZ
public:
AZ_EBUS_BEHAVIOR_BINDER(ProfilingCaptureNotificationBusHandler, "{E45E4F37-EC1F-4010-994B-4F80998BEF15}", AZ::SystemAllocator,
OnCaptureQueryTimestampFinished,
OnCaptureCpuFrameTimeFinished,
OnCaptureQueryPipelineStatisticsFinished,
OnCaptureCpuProfilingStatisticsFinished,
OnCaptureBenchmarkMetadataFinished
@@ -44,6 +49,11 @@ namespace AZ
Call(FN_OnCaptureQueryTimestampFinished, result, info);
}
void OnCaptureCpuFrameTimeFinished(bool result, const AZStd::string& info) override
{
Call(FN_OnCaptureCpuFrameTimeFinished, result, info);
}
void OnCaptureQueryPipelineStatisticsFinished(bool result, const AZStd::string& info) override
{
Call(FN_OnCaptureQueryPipelineStatisticsFinished, result, info);
@@ -95,6 +105,19 @@ namespace AZ
AZStd::vector<TimestampSerializerEntry> m_timestampEntries;
};
// Intermediate class to serialize CPU frame time statistics.
class CpuFrameTimeSerializer
{
public:
AZ_TYPE_INFO(Render::CpuFrameTimeSerializer, "{584B415E-8769-4757-AC64-EA57EDBCBC3E}");
static void Reflect(AZ::ReflectContext* context);
CpuFrameTimeSerializer() = default;
CpuFrameTimeSerializer(double frameTime);
double m_frameTime;
};
// Intermediate class to serialize pass' PipelineStatistics data.
class PipelineStatisticsSerializer
{
@@ -135,14 +158,15 @@ namespace AZ
Name m_groupName;
Name m_regionName;
uint16_t m_stackDepth;
AZStd::sys_time_t m_elapsedInNanoseconds;
AZStd::sys_time_t m_startTick;
AZStd::sys_time_t m_endTick;
};
AZ_TYPE_INFO(CpuProfilingStatisticsSerializer, "{D5B02946-0D27-474F-9A44-364C2706DD41}");
static void Reflect(AZ::ReflectContext* context);
CpuProfilingStatisticsSerializer() = default;
CpuProfilingStatisticsSerializer(const RHI::CpuProfiler::TimeRegionMap& timeRegionMap);
CpuProfilingStatisticsSerializer(const AZStd::ring_buffer<RHI::CpuProfiler::TimeRegionMap>& continuousData);
AZStd::vector<CpuProfilingStatisticsSerializerEntry> m_cpuProfilingStatisticsSerializerEntries;
};
@@ -248,6 +272,24 @@ namespace AZ
}
}
// --- CpuFrameTimeSerializer ---
CpuFrameTimeSerializer::CpuFrameTimeSerializer(double frameTime)
{
m_frameTime = frameTime;
}
void CpuFrameTimeSerializer::Reflect(AZ::ReflectContext* context)
{
if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<CpuFrameTimeSerializer>()
->Version(1)
->Field("frameTime", &CpuFrameTimeSerializer::m_frameTime)
;
}
}
// --- PipelineStatisticsSerializer ---
PipelineStatisticsSerializer::PipelineStatisticsSerializer(AZStd::vector<const RPI::Pass*>&& passes)
@@ -287,17 +329,20 @@ namespace AZ
// --- CpuProfilingStatisticsSerializer ---
CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializer(const RHI::CpuProfiler::TimeRegionMap& timeRegionMap)
CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializer(const AZStd::ring_buffer<RHI::CpuProfiler::TimeRegionMap>& continuousData)
{
// Create serializable entries
for (auto& threadEntry : timeRegionMap)
for (const auto& timeRegionMap : continuousData)
{
for (auto& cachedRegionEntry : threadEntry.second)
for (const auto& threadEntry : timeRegionMap)
{
m_cpuProfilingStatisticsSerializerEntries.insert(
m_cpuProfilingStatisticsSerializerEntries.end(),
cachedRegionEntry.second.begin(),
cachedRegionEntry.second.end());
for (const auto& cachedRegionEntry : threadEntry.second)
{
m_cpuProfilingStatisticsSerializerEntries.insert(
m_cpuProfilingStatisticsSerializerEntries.end(),
cachedRegionEntry.second.begin(),
cachedRegionEntry.second.end());
}
}
}
}
@@ -319,19 +364,11 @@ namespace AZ
CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializerEntry::CpuProfilingStatisticsSerializerEntry(const RHI::CachedTimeRegion& cachedTimeRegion)
{
// Converts ticks to Nanoseconds
static const auto ticksToNanoSeconds = [](AZStd::sys_time_t elapsedInTicks) -> AZStd::sys_time_t
{
const AZStd::sys_time_t ticksPerSecond = AZStd::GetTimeTicksPerSecond();
const AZStd::sys_time_t timeInNanoseconds = (elapsedInTicks * 1000000) / (ticksPerSecond / 1000);
return timeInNanoseconds;
};
m_groupName = cachedTimeRegion.m_groupRegionName->m_groupName;
m_regionName = cachedTimeRegion.m_groupRegionName->m_regionName;
m_stackDepth = cachedTimeRegion.m_stackDepth;
m_elapsedInNanoseconds = ticksToNanoSeconds(cachedTimeRegion.m_endTick - cachedTimeRegion.m_startTick);
m_startTick = cachedTimeRegion.m_startTick;
m_endTick = cachedTimeRegion.m_endTick;
}
void CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializerEntry::Reflect(AZ::ReflectContext* context)
@@ -343,7 +380,8 @@ namespace AZ
->Field("groupName", &CpuProfilingStatisticsSerializerEntry::m_groupName)
->Field("regionName", &CpuProfilingStatisticsSerializerEntry::m_regionName)
->Field("stackDepth", &CpuProfilingStatisticsSerializerEntry::m_stackDepth)
->Field("elapsedInNanoseconds", &CpuProfilingStatisticsSerializerEntry::m_elapsedInNanoseconds)
->Field("startTick", &CpuProfilingStatisticsSerializerEntry::m_startTick)
->Field("endTick", &CpuProfilingStatisticsSerializerEntry::m_endTick)
;
}
}
@@ -408,6 +446,7 @@ namespace AZ
->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
->Attribute(AZ::Script::Attributes::Module, "atom")
->Event("CapturePassTimestamp", &ProfilingCaptureRequestBus::Events::CapturePassTimestamp)
->Event("CaptureCpuFrameTime", &ProfilingCaptureRequestBus::Events::CaptureCpuFrameTime)
->Event("CapturePassPipelineStatistics", &ProfilingCaptureRequestBus::Events::CapturePassPipelineStatistics)
->Event("CaptureCpuProfilingStatistics", &ProfilingCaptureRequestBus::Events::CaptureCpuProfilingStatistics)
->Event("CaptureBenchmarkMetadata", &ProfilingCaptureRequestBus::Events::CaptureBenchmarkMetadata)
@@ -417,6 +456,7 @@ namespace AZ
}
TimestampSerializer::Reflect(context);
CpuFrameTimeSerializer::Reflect(context);
PipelineStatisticsSerializer::Reflect(context);
CpuProfilingStatisticsSerializer::Reflect(context);
BenchmarkMetadataSerializer::Reflect(context);
@@ -432,6 +472,12 @@ namespace AZ
TickBus::Handler::BusDisconnect();
ProfilingCaptureRequestBus::Handler::BusDisconnect();
// Block deactivation until the IO thread has finished serializing the CPU data
if (m_cpuDataSerializationThread.joinable())
{
m_cpuDataSerializationThread.join();
}
}
bool ProfilingCaptureSystemComponent::CapturePassTimestamp(const AZStd::string& outputFilePath)
@@ -484,6 +530,71 @@ namespace AZ
return captureStarted;
}
bool ProfilingCaptureSystemComponent::CaptureCpuFrameTime(const AZStd::string& outputFilePath)
{
AZ::RHI::RHISystemInterface::Get()->ModifyFrameSchedulerStatisticsFlags(
AZ::RHI::FrameSchedulerStatisticsFlags::GatherCpuTimingStatistics, true
);
bool wasEnabled = RHI::CpuProfiler::Get()->IsProfilerEnabled();
if (!wasEnabled)
{
RHI::CpuProfiler::Get()->SetProfilerEnabled(true);
}
const bool captureStarted = m_cpuFrameTimeStatisticsCapture.StartCapture([this, outputFilePath, wasEnabled]()
{
JsonSerializerSettings serializationSettings;
serializationSettings.m_keepDefaults = true;
double frameTime = 0.0;
const AZ::RHI::CpuTimingStatistics* stats = AZ::RHI::RHISystemInterface::Get()->GetCpuTimingStatistics();
if (stats)
{
frameTime = stats->GetFrameToFrameTimeMilliseconds();
}
else
{
AZStd::string warning = AZStd::string::format("Failed to get Cpu frame time");
AZ_Warning("ProfilingCaptureSystemComponent", false, warning.c_str());
}
CpuFrameTimeSerializer serializer(frameTime);
const auto saveResult = JsonSerializationUtils::SaveObjectToFile(&serializer,
outputFilePath, (CpuFrameTimeSerializer*)nullptr, &serializationSettings);
AZStd::string captureInfo = outputFilePath;
if (!saveResult.IsSuccess())
{
captureInfo = AZStd::string::format("Failed to save Cpu frame time to file '%s'. Error: %s",
outputFilePath.c_str(),
saveResult.GetError().c_str());
AZ_Warning("ProfilingCaptureSystemComponent", false, captureInfo.c_str());
}
// Disable the profiler again
if (!wasEnabled)
{
RHI::CpuProfiler::Get()->SetProfilerEnabled(false);
}
AZ::RHI::RHISystemInterface::Get()->ModifyFrameSchedulerStatisticsFlags(
AZ::RHI::FrameSchedulerStatisticsFlags::GatherCpuTimingStatistics, false
);
// Notify listeners that the Cpu frame time statistics capture has finished.
ProfilingCaptureNotificationBus::Broadcast(&ProfilingCaptureNotificationBus::Events::OnCaptureCpuFrameTimeFinished,
saveResult.IsSuccess(),
captureInfo);
});
// Start the TickBus.
if (captureStarted)
{
TickBus::Handler::BusConnect();
}
return captureStarted;
}
bool ProfilingCaptureSystemComponent::CapturePassPipelineStatistics(const AZStd::string& outputFilePath)
{
// Find the root pass.
@@ -534,6 +645,43 @@ namespace AZ
return captureStarted;
}
bool SerializeCpuProfilingData(const AZStd::ring_buffer<RHI::CpuProfiler::TimeRegionMap>& data, AZStd::string outputFilePath, bool wasEnabled)
{
AZ_TracePrintf("ProfilingCaptureSystemComponent", "Beginning serialization of %zu frames of profiling data\n", data.size());
JsonSerializerSettings serializationSettings;
serializationSettings.m_keepDefaults = true;
CpuProfilingStatisticsSerializer serializer(data);
const auto saveResult = JsonSerializationUtils::SaveObjectToFile(&serializer,
outputFilePath, (CpuProfilingStatisticsSerializer*)nullptr, &serializationSettings);
AZStd::string captureInfo = outputFilePath;
if (!saveResult.IsSuccess())
{
captureInfo = AZStd::string::format("Failed to save Cpu Profiling Statistics data to file '%s'. Error: %s",
outputFilePath.c_str(),
saveResult.GetError().c_str());
AZ_Warning("ProfilingCaptureSystemComponent", false, captureInfo.c_str());
}
else
{
AZ_Printf("ProfilingCaptureSystemComponent", "Cpu profiling statistics was saved to file [%s]\n", outputFilePath.c_str());
}
// Disable the profiler again
if (!wasEnabled)
{
RHI::CpuProfiler::Get()->SetProfilerEnabled(false);
}
// Notify listeners that the pass' PipelineStatistics queries capture has finished.
ProfilingCaptureNotificationBus::Broadcast(&ProfilingCaptureNotificationBus::Events::OnCaptureCpuProfilingStatisticsFinished,
saveResult.IsSuccess(),
captureInfo);
return saveResult.IsSuccess();
}
bool ProfilingCaptureSystemComponent::CaptureCpuProfilingStatistics(const AZStd::string& outputFilePath)
{
// Start the cpu profiling
@@ -545,40 +693,10 @@ namespace AZ
const bool captureStarted = m_cpuProfilingStatisticsCapture.StartCapture([this, outputFilePath, wasEnabled]()
{
JsonSerializerSettings serializationSettings;
serializationSettings.m_keepDefaults = true;
// Get time Cpu profiled time regions
const RHI::CpuProfiler::TimeRegionMap& timeRegionMap = RHI::CpuProfiler::Get()->GetTimeRegionMap();
CpuProfilingStatisticsSerializer serializer(timeRegionMap);
const auto saveResult = JsonSerializationUtils::SaveObjectToFile(&serializer,
outputFilePath, (CpuProfilingStatisticsSerializer*)nullptr, &serializationSettings);
AZStd::string captureInfo = outputFilePath;
if (!saveResult.IsSuccess())
{
captureInfo = AZStd::string::format("Failed to save Cpu Profiling Statistics data to file '%s'. Error: %s",
outputFilePath.c_str(),
saveResult.GetError().c_str());
AZ_Warning("ProfilingCaptureSystemComponent", false, captureInfo.c_str());
}
else
{
AZ_Printf("ProfilingCaptureSystemComponent", "Cpu profiling statistics was saved to file [%s]\n", outputFilePath.c_str());
}
// Disable the profiler again
if (!wasEnabled)
{
RHI::CpuProfiler::Get()->SetProfilerEnabled(false);
}
// Notify listeners that the pass' PipelineStatistics queries capture has finished.
ProfilingCaptureNotificationBus::Broadcast(&ProfilingCaptureNotificationBus::Events::OnCaptureCpuProfilingStatisticsFinished,
saveResult.IsSuccess(),
captureInfo);
// Blocking call for a single frame of data, avoid thread overhead
AZStd::ring_buffer<RHI::CpuProfiler::TimeRegionMap> singleFrameData;
singleFrameData.push_back(RHI::CpuProfiler::Get()->GetTimeRegionMap());
SerializeCpuProfilingData(singleFrameData, outputFilePath, wasEnabled);
});
// Start the TickBus.
@@ -590,6 +708,53 @@ namespace AZ
return captureStarted;
}
bool ProfilingCaptureSystemComponent::BeginContinuousCpuProfilingCapture()
{
return AZ::RHI::CpuProfiler::Get()->BeginContinuousCapture();
}
bool ProfilingCaptureSystemComponent::EndContinuousCpuProfilingCapture(const AZStd::string& outputFilePath)
{
bool expected = false;
if (m_cpuDataSerializationInProgress.compare_exchange_strong(expected, true))
{
AZStd::ring_buffer<RHI::CpuProfiler::TimeRegionMap> captureResult;
const bool captureEnded = AZ::RHI::CpuProfiler::Get()->EndContinuousCapture(captureResult);
if (!captureEnded)
{
AZ_TracePrintf("ProfilingCaptureSystemComponent", "Could not end the continuous capture, is one in progress?\n");
m_cpuDataSerializationInProgress.store(false);
return false;
}
// cpuProfilingData could be 1GB+ once saved, so use an IO thread to write it to disk.
auto threadIoFunction =
[data = AZStd::move(captureResult), filePath = AZStd::string(outputFilePath), &flag = m_cpuDataSerializationInProgress]()
{
SerializeCpuProfilingData(data, filePath, true);
flag.store(false);
};
// If the thread object already exists (ex. we have already serialized data), join. This will not block since
// m_cpuDataSerializationInProgress was false, meaning the IO thread has already completed execution.
// TODO Use a reusable thread implementation over repeated creation + destruction of threads [ATOM-16214]
if (m_cpuDataSerializationThread.joinable())
{
m_cpuDataSerializationThread.join();
}
auto thread = AZStd::thread(threadIoFunction);
m_cpuDataSerializationThread = AZStd::move(thread);
return true;
}
AZ_TracePrintf(
"ProfilingSystemCaptureComponent",
"Cannot end a continuous capture - another serialization is currently in progress\n");
return false;
}
bool ProfilingCaptureSystemComponent::CaptureBenchmarkMetadata(const AZStd::string& benchmarkName, const AZStd::string& outputFilePath)
{
const bool captureStarted = m_benchmarkMetadataCapture.StartCapture([this, benchmarkName, outputFilePath]()
@@ -666,12 +831,13 @@ namespace AZ
{
// Update the delayed captures
m_timestampCapture.UpdateCapture();
m_cpuFrameTimeStatisticsCapture.UpdateCapture();
m_pipelineStatisticsCapture.UpdateCapture();
m_cpuProfilingStatisticsCapture.UpdateCapture();
m_benchmarkMetadataCapture.UpdateCapture();
// Disconnect from the TickBus if all capture states are set to idle.
if (m_timestampCapture.IsIdle() && m_pipelineStatisticsCapture.IsIdle() && m_cpuProfilingStatisticsCapture.IsIdle() && m_benchmarkMetadataCapture.IsIdle())
if (m_timestampCapture.IsIdle() && m_pipelineStatisticsCapture.IsIdle() && m_cpuProfilingStatisticsCapture.IsIdle() && m_benchmarkMetadataCapture.IsIdle() && m_cpuFrameTimeStatisticsCapture.IsIdle())
{
TickBus::Handler::BusDisconnect();
}
@@ -12,6 +12,7 @@
#include <AzCore/Component/TickBus.h>
#include <Atom/Feature/Utils/ProfilingCaptureBus.h>
#include <Atom/RHI/CpuProfiler.h>
namespace AZ
{
@@ -68,8 +69,11 @@ namespace AZ
// ProfilingCaptureRequestBus overrides...
bool CapturePassTimestamp(const AZStd::string& outputFilePath) override;
bool CaptureCpuFrameTime(const AZStd::string& outputFilePath) override;
bool CapturePassPipelineStatistics(const AZStd::string& outputFilePath) override;
bool CaptureCpuProfilingStatistics(const AZStd::string& outputFilePath) override;
bool BeginContinuousCpuProfilingCapture() override;
bool EndContinuousCpuProfilingCapture(const AZStd::string& outputFilePath) override;
bool CaptureBenchmarkMetadata(const AZStd::string& benchmarkName, const AZStd::string& outputFilePath) override;
private:
@@ -81,9 +85,15 @@ namespace AZ
AZStd::vector<AZ::RPI::Pass*> FindPasses(AZStd::vector<AZStd::string>&& passHierarchy) const;
DelayedQueryCaptureHelper m_timestampCapture;
DelayedQueryCaptureHelper m_cpuFrameTimeStatisticsCapture;
DelayedQueryCaptureHelper m_pipelineStatisticsCapture;
DelayedQueryCaptureHelper m_cpuProfilingStatisticsCapture;
DelayedQueryCaptureHelper m_benchmarkMetadataCapture;
// Flag passed by reference to the CPU profiling data serialization job, blocks new continuous capture requests when set.
AZStd::atomic_bool m_cpuDataSerializationInProgress = false;
AZStd::thread m_cpuDataSerializationThread;
};
}
}
@@ -10,6 +10,7 @@
#include <AzCore/Debug/EventTrace.h>
#include <AzCore/RTTI/RTTI.h>
#include <AzCore/std/containers/ring_buffer.h>
#include <AzCore/std/containers/unordered_map.h>
#include <AzCore/std/string/string.h>
@@ -82,6 +83,14 @@ namespace AZ
//! Get the last frame's TimeRegionMap
virtual const TimeRegionMap& GetTimeRegionMap() const = 0;
//! Begin a continuous capture. Blocks the profiler from being toggled off until EndContinuousCapture is called.
[[nodiscard]] virtual bool BeginContinuousCapture() = 0;
//! Flush the CPU Profiler's saved data into the passed ring buffer .
[[nodiscard]] virtual bool EndContinuousCapture(AZStd::ring_buffer<TimeRegionMap>& flushTarget) = 0;
virtual bool IsContinuousCaptureInProgress() const = 0;
//! Enable/Disable the CpuProfiler
virtual void SetProfilerEnabled(bool enabled) = 0;
@@ -106,13 +106,18 @@ namespace AZ
void OnSystemTick() final override;
//! CpuProfiler overrides...
void BeginTimeRegion(TimeRegion& timeRegion) final;
void EndTimeRegion() final;
const TimeRegionMap& GetTimeRegionMap() const final;
void SetProfilerEnabled(bool enabled) final;
bool IsProfilerEnabled() const final;
void BeginTimeRegion(TimeRegion& timeRegion) final override;
void EndTimeRegion() final override;
const TimeRegionMap& GetTimeRegionMap() const final override;
bool BeginContinuousCapture() final override;
bool EndContinuousCapture(AZStd::ring_buffer<TimeRegionMap>& flushTarget) final override;
bool IsContinuousCaptureInProgress() const final override;
void SetProfilerEnabled(bool enabled) final override;
bool IsProfilerEnabled() const final override;
private:
static constexpr AZStd::size_t MaxFramesToSave = 2 * 60 * 120; // 2 minutes of 120fps
// Lazily create and register the local thread data
void RegisterThreadStorage();
@@ -134,6 +139,14 @@ namespace AZ
AZStd::shared_mutex m_shutdownMutex;
bool m_initialized = false;
AZStd::mutex m_continuousCaptureEndingMutex;
AZStd::atomic_bool m_continuousCaptureInProgress;
// Stores multiple frames of profiling data, size is controlled by MaxFramesToSave. Flushed when EndContinuousCapture is called.
// Ring buffer so that we can have fast append of new data + removal of old profiling data with good cache locality.
AZStd::ring_buffer<TimeRegionMap> m_continuousCaptureData;
};
}; // namespace RPI
+1 -1
View File
@@ -304,7 +304,7 @@ namespace AZ
uint32_t exitCode = 0;
bool timedOut = false;
const AZStd::sys_time_t maxWaitTimeSeconds = 120;
const AZStd::sys_time_t maxWaitTimeSeconds = 300;
const AZStd::sys_time_t startTimeSeconds = AZStd::GetTimeNowSecond();
const AZStd::sys_time_t startTime = AZStd::GetTimeNowTicks();
@@ -81,6 +81,7 @@ namespace AZ
Interface<CpuProfiler>::Register(this);
m_initialized = true;
SystemTickBus::Handler::BusConnect();
m_continuousCaptureData.set_capacity(10);
}
void CpuProfilerImpl::Shutdown()
@@ -101,6 +102,8 @@ namespace AZ
m_registeredThreads.clear();
m_timeRegionMap.clear();
m_initialized = false;
m_continuousCaptureInProgress.store(false);
m_continuousCaptureData.clear();
SystemTickBus::Handler::BusDisconnect();
}
@@ -141,12 +144,54 @@ namespace AZ
return m_timeRegionMap;
}
bool CpuProfilerImpl::BeginContinuousCapture()
{
bool expected = false;
if (m_continuousCaptureInProgress.compare_exchange_strong(expected, true))
{
m_enabled = true;
AZ_TracePrintf("Profiler", "Continuous capture started\n");
return true;
}
AZ_TracePrintf("Profiler", "Attempting to start a continuous capture while one already in progress");
return false;
}
bool CpuProfilerImpl::EndContinuousCapture(AZStd::ring_buffer<TimeRegionMap>& flushTarget)
{
if (!m_continuousCaptureInProgress.load())
{
AZ_TracePrintf("Profiler", "Attempting to end a continuous capture while one not in progress");
return false;
}
if (m_continuousCaptureEndingMutex.try_lock())
{
m_enabled = false;
flushTarget = AZStd::move(m_continuousCaptureData);
m_continuousCaptureData.clear();
AZ_TracePrintf("Profiler", "Continuous capture ended\n");
m_continuousCaptureInProgress.store(false);
m_continuousCaptureEndingMutex.unlock();
return true;
}
return false;
}
bool CpuProfilerImpl::IsContinuousCaptureInProgress() const
{
return m_continuousCaptureInProgress.load();
}
void CpuProfilerImpl::SetProfilerEnabled(bool enabled)
{
AZStd::unique_lock<AZStd::mutex> lock(m_threadRegisterMutex);
// Early out if the state is already the same
if (m_enabled == enabled)
// Early out if the state is already the same or a continuous capture is in progress
if (m_enabled == enabled || m_continuousCaptureInProgress.load())
{
return;
}
@@ -179,6 +224,20 @@ namespace AZ
{
return;
}
if (m_continuousCaptureInProgress.load() && m_continuousCaptureEndingMutex.try_lock())
{
if (m_continuousCaptureData.full() && m_continuousCaptureData.size() != MaxFramesToSave)
{
const AZStd::size_t size = m_continuousCaptureData.size();
m_continuousCaptureData.set_capacity(AZStd::min(MaxFramesToSave, size + size / 2));
}
m_continuousCaptureData.push_back(AZStd::move(m_timeRegionMap));
m_timeRegionMap.clear();
m_continuousCaptureEndingMutex.unlock();
}
AZStd::unique_lock<AZStd::mutex> lock(m_threadRegisterMutex);
// Iterate through all the threads, and collect the thread's cached time regions
@@ -110,9 +110,6 @@ namespace AZ
//! Value returned is 1.0f when an area equal to the viewport height squared is covered. Useful for accurate LOD decisions.
float CalculateSphereAreaInClipSpace(const AZ::Vector3& sphereWorldPosition, float sphereRadius) const;
//! Invalidate the view srg to rebuild the srg.
void InvalidateSrg();
const AZ::Name& GetName() const { return m_name; }
const UsageFlags GetUsageFlags() { return m_usageFlags; }
@@ -192,9 +189,6 @@ namespace AZ
// Clip space offset for camera jitter with taa
Vector2 m_clipSpaceOffset = Vector2(0.0f, 0.0f);
// Flags whether view matrices are dirty which requires rebuild srg
bool m_needBuildSrg = true;
MatrixChangedEvent m_onWorldToClipMatrixChange;
MatrixChangedEvent m_onWorldToViewMatrixChange;
+39 -55
View File
@@ -126,8 +126,6 @@ namespace AZ
m_onWorldToViewMatrixChange.Signal(m_worldToViewMatrix);
m_onWorldToClipMatrixChange.Signal(m_worldToClipMatrix);
InvalidateSrg();
}
AZ::Transform View::GetCameraTransform() const
@@ -170,8 +168,6 @@ namespace AZ
m_onWorldToViewMatrixChange.Signal(m_worldToViewMatrix);
}
m_onWorldToClipMatrixChange.Signal(m_worldToClipMatrix);
InvalidateSrg();
}
void View::SetViewToClipMatrix(const AZ::Matrix4x4& viewToClip)
@@ -202,14 +198,11 @@ namespace AZ
m_unprojectionConstants.SetW(float(tanHalfFovY));
m_onWorldToClipMatrixChange.Signal(m_worldToClipMatrix);
InvalidateSrg();
}
void View::SetClipSpaceOffset(float xOffset, float yOffset)
{
m_clipSpaceOffset.Set(xOffset, yOffset);
InvalidateSrg();
}
const AZ::Matrix4x4& View::GetWorldToViewMatrix() const
@@ -362,58 +355,49 @@ namespace AZ
return -0.25f * cotHalfFovYSq * AZ::Constants::Pi * radiusSq * sqrt(fabsf((distanceSq - radiusSq)/radiusSqSubDepthSq))/radiusSqSubDepthSq;
}
void View::InvalidateSrg()
{
m_needBuildSrg = true;
}
void View::UpdateSrg()
{
if (m_needBuildSrg)
if (m_clipSpaceOffset.IsZero())
{
if (m_clipSpaceOffset.IsZero())
{
Matrix4x4 worldToClipPrevMatrix = m_viewToClipPrevMatrix * m_worldToViewPrevMatrix;
m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, worldToClipPrevMatrix);
m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, m_worldToClipMatrix);
m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, m_viewToClipMatrix);
m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, m_clipToWorldMatrix);
m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, m_viewToClipMatrix.GetInverseFull());
}
else
{
// Offset the current and previous frame clip matricies
Matrix4x4 offsetViewToClipMatrix = m_viewToClipMatrix;
offsetViewToClipMatrix.SetElement(0, 2, m_clipSpaceOffset.GetX());
offsetViewToClipMatrix.SetElement(1, 2, m_clipSpaceOffset.GetY());
Matrix4x4 offsetViewToClipPrevMatrix = m_viewToClipPrevMatrix;
offsetViewToClipPrevMatrix.SetElement(0, 2, m_clipSpaceOffset.GetX());
offsetViewToClipPrevMatrix.SetElement(1, 2, m_clipSpaceOffset.GetY());
// Build other matricies dependent on the view to clip matricies
Matrix4x4 offsetWorldToClipMatrix = offsetViewToClipMatrix * m_worldToViewMatrix;
Matrix4x4 offsetWorldToClipPrevMatrix = offsetViewToClipPrevMatrix * m_worldToViewPrevMatrix;
Matrix4x4 offsetClipToViewMatrix = offsetViewToClipMatrix.GetInverseFull();
Matrix4x4 offsetClipToWorldMatrix = m_viewToWorldMatrix * offsetClipToViewMatrix;
m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, offsetWorldToClipPrevMatrix);
m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, offsetWorldToClipMatrix);
m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, offsetViewToClipMatrix);
m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, offsetClipToWorldMatrix);
m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, offsetViewToClipMatrix.GetInverseFull());
}
m_shaderResourceGroup->SetConstant(m_worldPositionConstantIndex, m_position);
m_shaderResourceGroup->SetConstant(m_viewMatrixConstantIndex, m_worldToViewMatrix);
m_shaderResourceGroup->SetConstant(m_viewMatrixInverseConstantIndex, m_worldToViewMatrix.GetInverseFull());
m_shaderResourceGroup->SetConstant(m_zConstantsConstantIndex, m_nearZ_farZ_farZTimesNearZ_farZMinusNearZ);
m_shaderResourceGroup->SetConstant(m_unprojectionConstantsIndex, m_unprojectionConstants);
m_shaderResourceGroup->Compile();
m_needBuildSrg = false;
Matrix4x4 worldToClipPrevMatrix = m_viewToClipPrevMatrix * m_worldToViewPrevMatrix;
m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, worldToClipPrevMatrix);
m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, m_worldToClipMatrix);
m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, m_viewToClipMatrix);
m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, m_clipToWorldMatrix);
m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, m_viewToClipMatrix.GetInverseFull());
}
else
{
// Offset the current and previous frame clip matricies
Matrix4x4 offsetViewToClipMatrix = m_viewToClipMatrix;
offsetViewToClipMatrix.SetElement(0, 2, m_clipSpaceOffset.GetX());
offsetViewToClipMatrix.SetElement(1, 2, m_clipSpaceOffset.GetY());
Matrix4x4 offsetViewToClipPrevMatrix = m_viewToClipPrevMatrix;
offsetViewToClipPrevMatrix.SetElement(0, 2, m_clipSpaceOffset.GetX());
offsetViewToClipPrevMatrix.SetElement(1, 2, m_clipSpaceOffset.GetY());
// Build other matricies dependent on the view to clip matricies
Matrix4x4 offsetWorldToClipMatrix = offsetViewToClipMatrix * m_worldToViewMatrix;
Matrix4x4 offsetWorldToClipPrevMatrix = offsetViewToClipPrevMatrix * m_worldToViewPrevMatrix;
Matrix4x4 offsetClipToViewMatrix = offsetViewToClipMatrix.GetInverseFull();
Matrix4x4 offsetClipToWorldMatrix = m_viewToWorldMatrix * offsetClipToViewMatrix;
m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, offsetWorldToClipPrevMatrix);
m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, offsetWorldToClipMatrix);
m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, offsetViewToClipMatrix);
m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, offsetClipToWorldMatrix);
m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, offsetViewToClipMatrix.GetInverseFull());
}
m_shaderResourceGroup->SetConstant(m_worldPositionConstantIndex, m_position);
m_shaderResourceGroup->SetConstant(m_viewMatrixConstantIndex, m_worldToViewMatrix);
m_shaderResourceGroup->SetConstant(m_viewMatrixInverseConstantIndex, m_worldToViewMatrix.GetInverseFull());
m_shaderResourceGroup->SetConstant(m_zConstantsConstantIndex, m_nearZ_farZ_farZTimesNearZ_farZMinusNearZ);
m_shaderResourceGroup->SetConstant(m_unprojectionConstantsIndex, m_unprojectionConstants);
m_shaderResourceGroup->Compile();
m_viewToClipPrevMatrix = m_viewToClipMatrix;
m_worldToViewPrevMatrix = m_worldToViewMatrix;
@@ -129,6 +129,34 @@ namespace AZ
m_captureToFile = true;
}
ImGui::SameLine();
bool isInProgress = RHI::CpuProfiler::Get()->IsContinuousCaptureInProgress();
if (ImGui::Button(isInProgress ? "End" : "Begin"))
{
if (isInProgress)
{
AZStd::sys_time_t timeNow = AZStd::GetTimeNowSecond();
AZStd::string timeString;
AZStd::to_string(timeString, timeNow);
u64 currentTick = AZ::RPI::RPISystemInterface::Get()->GetCurrentTick();
const AZStd::string frameDataFilePath = AZStd::string::format(
"@user@/CpuProfiler/%s_%llu.json",
timeString.c_str(),
currentTick);
char resolvedPath[AZ::IO::MaxPathLength];
AZ::IO::FileIOBase::GetInstance()->ResolvePath(frameDataFilePath.c_str(), resolvedPath, AZ::IO::MaxPathLength);
m_lastCapturedFilePath = resolvedPath;
AZ::Render::ProfilingCaptureRequestBus::Broadcast(
&AZ::Render::ProfilingCaptureRequestBus::Events::EndContinuousCpuProfilingCapture, frameDataFilePath);
}
else
{
AZ::Render::ProfilingCaptureRequestBus::Broadcast(
&AZ::Render::ProfilingCaptureRequestBus::Events::BeginContinuousCpuProfilingCapture);
}
}
if (!m_lastCapturedFilePath.empty())
{
ImGui::SameLine();
@@ -562,8 +562,8 @@ namespace AZ
for (size_t i = 0; i < numBoneTransforms; ++i)
{
MCore::DualQuaternion dualQuat = MCore::DualQuaternion::ConvertFromTransform(AZ::Transform::CreateFromMatrix3x4(skinningMatrices[i]));
dualQuat.mReal.StoreToFloat4(&boneTransforms[i * DualQuaternionSkinningFloatsPerBone]);
dualQuat.mDual.StoreToFloat4(&boneTransforms[i * DualQuaternionSkinningFloatsPerBone + 4]);
dualQuat.m_real.StoreToFloat4(&boneTransforms[i * DualQuaternionSkinningFloatsPerBone]);
dualQuat.m_dual.StoreToFloat4(&boneTransforms[i * DualQuaternionSkinningFloatsPerBone + 4]);
}
}
}
@@ -151,10 +151,10 @@ namespace AZ
continue;
}
const AZ::Vector3 parentPos = pose->GetWorldSpaceTransform(parentIndex).mPosition;
const AZ::Vector3 parentPos = pose->GetWorldSpaceTransform(parentIndex).m_position;
m_auxVertices.emplace_back(parentPos);
const AZ::Vector3 bonePos = pose->GetWorldSpaceTransform(jointIndex).mPosition;
const AZ::Vector3 bonePos = pose->GetWorldSpaceTransform(jointIndex).m_position;
m_auxVertices.emplace_back(bonePos);
}
@@ -615,7 +615,7 @@ namespace AZ
{
// Morph targets that don't deform any vertices (e.g. joint-based morph targets) are not registered in the render proxy. Skip adding their weights.
const EMotionFX::MorphTargetStandard::DeformData* deformData = morphTargetStandard->GetDeformData(deformDataIndex);
if (deformData->mNumVerts > 0)
if (deformData->m_numVerts > 0)
{
float weight = morphTargetSetupInstance->GetWeight();
m_morphTargetWeights.push_back(weight);
@@ -57,7 +57,7 @@ namespace CommandSystem
// Set motion extraction node.
if (parameters.CheckIfHasParameter("motionExtractionNodeName"))
{
mOldMotionExtractionNodeIndex = actor->GetMotionExtractionNodeIndex();
m_oldMotionExtractionNodeIndex = actor->GetMotionExtractionNodeIndex();
AZStd::string motionExtractionNodeName;
parameters.GetValue("motionExtractionNodeName", this, motionExtractionNodeName);
@@ -91,7 +91,7 @@ namespace CommandSystem
// Set retarget root node.
if (parameters.CheckIfHasParameter("retargetRootNodeName"))
{
mOldRetargetRootNodeIndex = actor->GetRetargetRootNodeIndex();
m_oldRetargetRootNodeIndex = actor->GetRetargetRootNodeIndex();
AZStd::string retargetRootNodeName = parameters.GetValue("retargetRootNodeName", this);
if (retargetRootNodeName.empty() || retargetRootNodeName == "$NULL$")
@@ -108,7 +108,7 @@ namespace CommandSystem
// Set actor name.
if (parameters.CheckIfHasParameter("name"))
{
mOldName = actor->GetName();
m_oldName = actor->GetName();
AZStd::string actorName;
parameters.GetValue("name", this, actorName);
@@ -119,7 +119,7 @@ namespace CommandSystem
if (parameters.CheckIfHasParameter("attachmentNodes"))
{
// Store old attachment nodes for undo.
mOldAttachmentNodes = "";
m_oldAttachmentNodes = "";
const size_t numNodes = actor->GetNumNodes();
for (size_t i = 0; i < numNodes; ++i)
{
@@ -132,8 +132,8 @@ namespace CommandSystem
// Check if the node has the attachment flag enabled and add it.
if (node->GetIsAttachmentNode())
{
mOldAttachmentNodes += node->GetName();
mOldAttachmentNodes += ";";
m_oldAttachmentNodes += node->GetName();
m_oldAttachmentNodes += ";";
}
}
@@ -198,7 +198,7 @@ namespace CommandSystem
if (parameters.CheckIfHasParameter("nodesExcludedFromBounds"))
{
// Store old nodes for undo.
mOldExcludedFromBoundsNodes = "";
m_oldExcludedFromBoundsNodes = "";
const size_t numNodes = actor->GetNumNodes();
for (size_t i = 0; i < numNodes; ++i)
{
@@ -211,8 +211,8 @@ namespace CommandSystem
// Check if the node has the attachment flag enabled and add it.
if (!node->GetIncludeInBoundsCalc())
{
mOldExcludedFromBoundsNodes += node->GetName();
mOldExcludedFromBoundsNodes += ";";
m_oldExcludedFromBoundsNodes += node->GetName();
m_oldExcludedFromBoundsNodes += ";";
}
}
@@ -276,7 +276,7 @@ namespace CommandSystem
// Adjust the mirror setup.
if (parameters.CheckIfHasParameter("mirrorSetup"))
{
mOldMirrorSetup = actor->GetNodeMirrorInfos();
m_oldMirrorSetup = actor->GetNodeMirrorInfos();
AZStd::string mirrorSetupString;
parameters.GetValue("mirrorSetup", this, mirrorSetupString);
@@ -308,8 +308,8 @@ namespace CommandSystem
EMotionFX::Node* nodeB = actor->GetSkeleton()->FindNodeByName(pairValues[1]);
if (nodeA && nodeB)
{
actor->GetNodeMirrorInfo(nodeA->GetNodeIndex()).mSourceNode = static_cast<uint16>(nodeB->GetNodeIndex());
actor->GetNodeMirrorInfo(nodeB->GetNodeIndex()).mSourceNode = static_cast<uint16>(nodeA->GetNodeIndex());
actor->GetNodeMirrorInfo(nodeA->GetNodeIndex()).m_sourceNode = static_cast<uint16>(nodeB->GetNodeIndex());
actor->GetNodeMirrorInfo(nodeB->GetNodeIndex()).m_sourceNode = static_cast<uint16>(nodeA->GetNodeIndex());
}
}
@@ -318,7 +318,7 @@ namespace CommandSystem
}
}
mOldDirtyFlag = actor->GetDirtyFlag();
m_oldDirtyFlag = actor->GetDirtyFlag();
actor->SetDirtyFlag(true);
return true;
}
@@ -338,29 +338,29 @@ namespace CommandSystem
if (parameters.CheckIfHasParameter("motionExtractionNodeName"))
{
actor->SetMotionExtractionNodeIndex(mOldMotionExtractionNodeIndex);
actor->SetMotionExtractionNodeIndex(m_oldMotionExtractionNodeIndex);
}
if (parameters.CheckIfHasParameter("retargetRootNodeName"))
{
actor->SetRetargetRootNodeIndex(mOldRetargetRootNodeIndex);
actor->SetRetargetRootNodeIndex(m_oldRetargetRootNodeIndex);
}
if (parameters.CheckIfHasParameter("name"))
{
actor->SetName(mOldName.c_str());
actor->SetName(m_oldName.c_str());
}
if (parameters.CheckIfHasParameter("mirrorSetup"))
{
actor->SetNodeMirrorInfos(mOldMirrorSetup);
actor->SetNodeMirrorInfos(m_oldMirrorSetup);
actor->AutoDetectMirrorAxes();
}
// Set the attachment nodes.
if (parameters.CheckIfHasParameter("attachmentNodes"))
{
const AZStd::string command = AZStd::string::format("AdjustActor -actorID %i -nodeAction \"select\" -attachmentNodes \"%s\"", actorID, mOldAttachmentNodes.c_str());
const AZStd::string command = AZStd::string::format("AdjustActor -actorID %i -nodeAction \"select\" -attachmentNodes \"%s\"", actorID, m_oldAttachmentNodes.c_str());
if (!GetCommandManager()->ExecuteCommandInsideCommand(command, outResult))
{
@@ -372,7 +372,7 @@ namespace CommandSystem
// Set the nodes that are not taken into account in the bounding volume calculations.
if (parameters.CheckIfHasParameter("nodesExcludedFromBounds"))
{
const AZStd::string command = AZStd::string::format("AdjustActor -actorID %i -nodeAction \"select\" -nodesExcludedFromBounds \"%s\"", actorID, mOldExcludedFromBoundsNodes.c_str());
const AZStd::string command = AZStd::string::format("AdjustActor -actorID %i -nodeAction \"select\" -nodesExcludedFromBounds \"%s\"", actorID, m_oldExcludedFromBoundsNodes.c_str());
if (!GetCommandManager()->ExecuteCommandInsideCommand(command, outResult))
{
@@ -382,7 +382,7 @@ namespace CommandSystem
}
// Set the dirty flag back to the old value.
actor->SetDirtyFlag(mOldDirtyFlag);
actor->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -479,18 +479,18 @@ namespace CommandSystem
EMotionFX::Skeleton* skeleton = actor->GetSkeleton();
// Store the old nodes for the undo.
mOldNodeList = "";
m_oldNodeList = "";
for (size_t i = 0; i < numNodes; ++i)
{
EMotionFX::Mesh* mesh = actor->GetMesh(lod, i);
if (mesh && mesh->GetIsCollisionMesh())
{
if (!mOldNodeList.empty())
if (!m_oldNodeList.empty())
{
mOldNodeList += ";";
m_oldNodeList += ";";
}
mOldNodeList += skeleton->GetNode(i)->GetName();
m_oldNodeList += skeleton->GetNode(i)->GetName();
}
}
@@ -517,7 +517,7 @@ namespace CommandSystem
}
// Save the current dirty flag and tell the actor that something changed.
mOldDirtyFlag = actor->GetDirtyFlag();
m_oldDirtyFlag = actor->GetDirtyFlag();
actor->SetDirtyFlag(true);
// Reinit the renderable actors.
@@ -542,11 +542,11 @@ namespace CommandSystem
const uint32 lod = parameters.GetValueAsInt("lod", MCORE_INVALIDINDEX32);
// Undo command.
const AZStd::string command = AZStd::string::format("ActorSetCollisionMeshes -actorID %i -lod %i -nodeList %s", actorID, lod, mOldNodeList.c_str());
const AZStd::string command = AZStd::string::format("ActorSetCollisionMeshes -actorID %i -lod %i -nodeList %s", actorID, lod, m_oldNodeList.c_str());
GetCommandManager()->ExecuteCommandInsideCommand(command, outResult);
// Set the dirty flag back to the old value
actor->SetDirtyFlag(mOldDirtyFlag);
actor->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -686,7 +686,7 @@ namespace CommandSystem
CommandRemoveActor::CommandRemoveActor(MCore::Command* orgCommand)
: MCore::Command("RemoveActor", orgCommand)
{
mPreviouslyUsedID = MCORE_INVALIDINDEX32;
m_previouslyUsedId = MCORE_INVALIDINDEX32;
}
@@ -725,10 +725,10 @@ namespace CommandSystem
}
// store the previously used id and the actor filename
mPreviouslyUsedID = actor->GetID();
mOldFileName = actor->GetFileName();
mOldDirtyFlag = actor->GetDirtyFlag();
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_previouslyUsedId = actor->GetID();
m_oldFileName = actor->GetFileName();
m_oldDirtyFlag = actor->GetDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
// get rid of the actor
EMotionFX::GetActorManager().UnregisterActor(EMotionFX::GetActorManager().FindSharedActorByID(actor->GetID()));
@@ -747,7 +747,7 @@ namespace CommandSystem
{
MCORE_UNUSED(parameters);
const AZStd::string command = AZStd::string::format("ImportActor -filename \"%s\" -actorID %i", mOldFileName.c_str(), mPreviouslyUsedID);
const AZStd::string command = AZStd::string::format("ImportActor -filename \"%s\" -actorID %i", m_oldFileName.c_str(), m_previouslyUsedId);
if (!GetCommandManager()->ExecuteCommandInsideCommand(command, outResult))
{
return false;
@@ -761,7 +761,7 @@ namespace CommandSystem
}
// restore the workspace dirty flag
GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag);
GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag);
return true;
}
@@ -973,10 +973,10 @@ namespace CommandSystem
CommandScaleActorData::CommandScaleActorData(MCore::Command* orgCommand)
: MCore::Command("ScaleActorData", orgCommand)
{
mActorID = MCORE_INVALIDINDEX32;
mScaleFactor = 1.0f;
mOldActorDirtyFlag = false;
mUseUnitType = false;
m_actorId = MCORE_INVALIDINDEX32;
m_scaleFactor = 1.0f;
m_oldActorDirtyFlag = false;
m_useUnitType = false;
}
@@ -1020,32 +1020,32 @@ namespace CommandSystem
return false;
}
mActorID = actor->GetID();
mScaleFactor = parameters.GetValueAsFloat("scaleFactor", this);
m_actorId = actor->GetID();
m_scaleFactor = parameters.GetValueAsFloat("scaleFactor", this);
AZStd::string targetUnitTypeString;
parameters.GetValue("unitType", this, &targetUnitTypeString);
mUseUnitType = parameters.CheckIfHasParameter("unitType");
m_useUnitType = parameters.CheckIfHasParameter("unitType");
MCore::Distance::EUnitType targetUnitType;
bool stringConvertSuccess = MCore::Distance::StringToUnitType(targetUnitTypeString, &targetUnitType);
if (mUseUnitType && stringConvertSuccess == false)
if (m_useUnitType && stringConvertSuccess == false)
{
outResult = AZStd::string::format("The passed unitType '%s' is not a valid unit type.", targetUnitTypeString.c_str());
return false;
}
MCore::Distance::EUnitType beforeUnitType = actor->GetUnitType();
mOldUnitType = MCore::Distance::UnitTypeToString(beforeUnitType);
m_oldUnitType = MCore::Distance::UnitTypeToString(beforeUnitType);
mOldActorDirtyFlag = actor->GetDirtyFlag();
m_oldActorDirtyFlag = actor->GetDirtyFlag();
actor->SetDirtyFlag(true);
// perform the scaling
if (mUseUnitType == false)
if (m_useUnitType == false)
{
actor->Scale(mScaleFactor);
actor->Scale(m_scaleFactor);
}
else
{
@@ -1083,21 +1083,21 @@ namespace CommandSystem
{
MCORE_UNUSED(parameters);
if (!mUseUnitType)
if (!m_useUnitType)
{
const AZStd::string command = AZStd::string::format("ScaleActorData -id %d -scaleFactor %.8f", mActorID, 1.0f / mScaleFactor);
const AZStd::string command = AZStd::string::format("ScaleActorData -id %d -scaleFactor %.8f", m_actorId, 1.0f / m_scaleFactor);
GetCommandManager()->ExecuteCommandInsideCommand(command, outResult);
}
else
{
const AZStd::string command = AZStd::string::format("ScaleActorData -id %d -unitType \"%s\"", mActorID, mOldUnitType.c_str());
const AZStd::string command = AZStd::string::format("ScaleActorData -id %d -unitType \"%s\"", m_actorId, m_oldUnitType.c_str());
GetCommandManager()->ExecuteCommandInsideCommand(command, outResult);
}
EMotionFX::Actor* actor = EMotionFX::GetActorManager().FindActorByID(mActorID);
EMotionFX::Actor* actor = EMotionFX::GetActorManager().FindActorByID(m_actorId);
if (actor)
{
actor->SetDirtyFlag(mOldActorDirtyFlag);
actor->SetDirtyFlag(m_oldActorDirtyFlag);
}
return true;
@@ -19,14 +19,14 @@ namespace CommandSystem
{
// Adjust the given actor.
MCORE_DEFINECOMMAND_START(CommandAdjustActor, "Adjust actor", true)
size_t mOldMotionExtractionNodeIndex;
size_t mOldRetargetRootNodeIndex;
size_t mOldTrajectoryNodeIndex;
AZStd::string mOldAttachmentNodes;
AZStd::string mOldExcludedFromBoundsNodes;
AZStd::string mOldName;
AZStd::vector<EMotionFX::Actor::NodeMirrorInfo> mOldMirrorSetup;
bool mOldDirtyFlag;
size_t m_oldMotionExtractionNodeIndex;
size_t m_oldRetargetRootNodeIndex;
size_t m_oldTrajectoryNodeIndex;
AZStd::string m_oldAttachmentNodes;
AZStd::string m_oldExcludedFromBoundsNodes;
AZStd::string m_oldName;
AZStd::vector<EMotionFX::Actor::NodeMirrorInfo> m_oldMirrorSetup;
bool m_oldDirtyFlag;
void SetIsAttachmentNode(EMotionFX::Actor* actor, bool isAttachmentNode);
void SetIsExcludedFromBoundsNode(EMotionFX::Actor* actor, bool excludedFromBounds);
@@ -34,8 +34,8 @@ namespace CommandSystem
// Set the collision meshes of the given actor.
MCORE_DEFINECOMMAND_START(CommandActorSetCollisionMeshes, "Actor set collison meshes", true)
AZStd::string mOldNodeList;
bool mOldDirtyFlag;
AZStd::string m_oldNodeList;
bool m_oldDirtyFlag;
MCORE_DEFINECOMMAND_END
// Reset actor instance to bind pose.
@@ -50,21 +50,21 @@ namespace CommandSystem
// Remove actor.
MCORE_DEFINECOMMAND_START(CommandRemoveActor, "Remove actor", true)
public:
uint32 mPreviouslyUsedID;
AZStd::string mOldFileName;
bool mOldDirtyFlag;
bool mOldWorkspaceDirtyFlag;
uint32 m_previouslyUsedId;
AZStd::string m_oldFileName;
bool m_oldDirtyFlag;
bool m_oldWorkspaceDirtyFlag;
MCORE_DEFINECOMMAND_END
// Scale actor data.
MCORE_DEFINECOMMAND_START(CommandScaleActorData, "Scale actor data", true)
public:
AZStd::string mOldUnitType;
uint32 mActorID;
float mScaleFactor;
bool mOldActorDirtyFlag;
bool mUseUnitType;
AZStd::string m_oldUnitType;
uint32 m_actorId;
float m_scaleFactor;
bool m_oldActorDirtyFlag;
bool m_useUnitType;
MCORE_DEFINECOMMAND_END
//////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -25,7 +25,7 @@ namespace CommandSystem
CommandCreateActorInstance::CommandCreateActorInstance(MCore::Command* orgCommand)
: MCore::Command("CreateActorInstance", orgCommand)
{
mPreviouslyUsedID = MCORE_INVALIDINDEX32;
m_previouslyUsedId = MCORE_INVALIDINDEX32;
}
@@ -109,15 +109,15 @@ namespace CommandSystem
}
// in case of redoing the command set the previously used id
if (mPreviouslyUsedID != MCORE_INVALIDINDEX32)
if (m_previouslyUsedId != MCORE_INVALIDINDEX32)
{
newInstance->SetID(mPreviouslyUsedID);
newInstance->SetID(m_previouslyUsedId);
}
mPreviouslyUsedID = newInstance->GetID();
m_previouslyUsedId = newInstance->GetID();
// setup the position, rotation and scale
AZ::Vector3 newPos = newInstance->GetLocalSpaceTransform().mPosition;
AZ::Vector3 newPos = newInstance->GetLocalSpaceTransform().m_position;
if (parameters.CheckIfHasParameter("xPos"))
{
newPos.SetX(parameters.GetValueAsFloat("xPos", this));
@@ -155,7 +155,7 @@ namespace CommandSystem
}
// mark the workspace as dirty
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
GetCommandManager()->SetWorkspaceDirtyFlag(true);
// return the id of the newly created actor instance
@@ -174,7 +174,7 @@ namespace CommandSystem
uint32 actorInstanceID = parameters.GetValueAsInt("actorInstanceID", MCORE_INVALIDINDEX32);
if (actorInstanceID == MCORE_INVALIDINDEX32)
{
actorInstanceID = mPreviouslyUsedID;
actorInstanceID = m_previouslyUsedId;
}
// find the actor intance based on the given id
@@ -202,7 +202,7 @@ namespace CommandSystem
}
// restore the workspace dirty flag
GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag);
GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag);
// get rid of the actor instance
if (actorInstance)
@@ -274,7 +274,7 @@ namespace CommandSystem
if (parameters.CheckIfHasParameter("pos"))
{
AZ::Vector3 value = parameters.GetValueAsVector3("pos", this);
mOldPosition = actorInstance->GetLocalSpaceTransform().mPosition;
m_oldPosition = actorInstance->GetLocalSpaceTransform().m_position;
actorInstance->SetLocalSpacePosition(value);
}
@@ -282,7 +282,7 @@ namespace CommandSystem
if (parameters.CheckIfHasParameter("rot"))
{
AZ::Vector4 value = parameters.GetValueAsVector4("rot", this);
mOldRotation = actorInstance->GetLocalSpaceTransform().mRotation;
m_oldRotation = actorInstance->GetLocalSpaceTransform().m_rotation;
actorInstance->SetLocalSpaceRotation(AZ::Quaternion(value.GetX(), value.GetY(), value.GetZ(), value.GetW()));
}
@@ -292,7 +292,7 @@ namespace CommandSystem
if (parameters.CheckIfHasParameter("scale"))
{
AZ::Vector3 value = parameters.GetValueAsVector3("scale", this);
mOldScale = actorInstance->GetLocalSpaceTransform().mScale;
m_oldScale = actorInstance->GetLocalSpaceTransform().m_scale;
actorInstance->SetLocalSpaceScale(value);
}
)
@@ -301,7 +301,7 @@ namespace CommandSystem
if (parameters.CheckIfHasParameter("lodLevel"))
{
uint32 value = parameters.GetValueAsInt("lodLevel", this);
mOldLODLevel = actorInstance->GetLODLevel();
m_oldLodLevel = actorInstance->GetLODLevel();
actorInstance->SetLODLevel(value);
}
@@ -309,7 +309,7 @@ namespace CommandSystem
if (parameters.CheckIfHasParameter("isVisible"))
{
bool value = parameters.GetValueAsBool("isVisible", this);
mOldIsVisible = actorInstance->GetIsVisible();
m_oldIsVisible = actorInstance->GetIsVisible();
actorInstance->SetIsVisible(value);
}
@@ -317,12 +317,12 @@ namespace CommandSystem
if (parameters.CheckIfHasParameter("doRender"))
{
bool value = parameters.GetValueAsBool("doRender", this);
mOldDoRender = actorInstance->GetRender();
m_oldDoRender = actorInstance->GetRender();
actorInstance->SetRender(value);
}
// mark the workspace as dirty
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
GetCommandManager()->SetWorkspaceDirtyFlag(true);
return true;
@@ -345,13 +345,13 @@ namespace CommandSystem
// set the position
if (parameters.CheckIfHasParameter("pos"))
{
actorInstance->SetLocalSpacePosition(mOldPosition);
actorInstance->SetLocalSpacePosition(m_oldPosition);
}
// set the rotation
if (parameters.CheckIfHasParameter("rot"))
{
actorInstance->SetLocalSpaceRotation(mOldRotation);
actorInstance->SetLocalSpaceRotation(m_oldRotation);
}
// set the scale
@@ -359,30 +359,30 @@ namespace CommandSystem
(
if (parameters.CheckIfHasParameter("scale"))
{
actorInstance->SetLocalSpaceScale(mOldScale);
actorInstance->SetLocalSpaceScale(m_oldScale);
}
)
// set the LOD level
if (parameters.CheckIfHasParameter("lodLevel"))
{
actorInstance->SetLODLevel(mOldLODLevel);
actorInstance->SetLODLevel(m_oldLodLevel);
}
// set the visibility flag
if (parameters.CheckIfHasParameter("isVisible"))
{
actorInstance->SetIsVisible(mOldIsVisible);
actorInstance->SetIsVisible(m_oldIsVisible);
}
// set the rendering flag
if (parameters.CheckIfHasParameter("doRender"))
{
actorInstance->SetRender(mOldDoRender);
actorInstance->SetRender(m_oldDoRender);
}
// restore the workspace dirty flag
GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag);
GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag);
return true;
}
@@ -440,15 +440,15 @@ namespace CommandSystem
}
// store the old values before removing the instance
mOldPosition = actorInstance->GetLocalSpaceTransform().mPosition;
mOldRotation = actorInstance->GetLocalSpaceTransform().mRotation;
m_oldPosition = actorInstance->GetLocalSpaceTransform().m_position;
m_oldRotation = actorInstance->GetLocalSpaceTransform().m_rotation;
EMFX_SCALECODE
(
mOldScale = actorInstance->GetLocalSpaceTransform().mScale;
m_oldScale = actorInstance->GetLocalSpaceTransform().m_scale;
)
mOldLODLevel = actorInstance->GetLODLevel();
mOldIsVisible = actorInstance->GetIsVisible();
mOldDoRender = actorInstance->GetRender();
m_oldLodLevel = actorInstance->GetLODLevel();
m_oldIsVisible = actorInstance->GetIsVisible();
m_oldDoRender = actorInstance->GetRender();
// remove the actor instance from the selection
if (GetCommandManager()->GetLockSelection())
@@ -458,7 +458,7 @@ namespace CommandSystem
// get the id from the corresponding actor and save it for undo
EMotionFX::Actor* actor = actorInstance->GetActor();
mOldActorID = actor->GetID();
m_oldActorId = actor->GetID();
// get rid of the actor instance
if (actorInstance)
@@ -467,7 +467,7 @@ namespace CommandSystem
}
// mark the workspace as dirty
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
GetCommandManager()->SetWorkspaceDirtyFlag(true);
return true;
@@ -489,17 +489,17 @@ namespace CommandSystem
AZStd::string commandString;
MCore::CommandGroup commandGroup("Undo remove actor instance", 2);
commandString = AZStd::string::format("CreateActorInstance -actorID %i -actorInstanceID %i", mOldActorID, actorInstanceID);
commandString = AZStd::string::format("CreateActorInstance -actorID %i -actorInstanceID %i", m_oldActorId, actorInstanceID);
commandGroup.AddCommandString(commandString.c_str());
commandString = AZStd::string::format("AdjustActorInstance -actorInstanceID %i -pos \"%s\" -rot \"%s\" -scale \"%s\" -lodLevel %zu -isVisible \"%s\" -doRender \"%s\"",
actorInstanceID,
AZStd::to_string(mOldPosition).c_str(),
AZStd::to_string(mOldRotation).c_str(),
AZStd::to_string(mOldScale).c_str(),
mOldLODLevel,
AZStd::to_string(mOldIsVisible).c_str(),
AZStd::to_string(mOldDoRender).c_str()
AZStd::to_string(m_oldPosition).c_str(),
AZStd::to_string(m_oldRotation).c_str(),
AZStd::to_string(m_oldScale).c_str(),
m_oldLodLevel,
AZStd::to_string(m_oldIsVisible).c_str(),
AZStd::to_string(m_oldDoRender).c_str()
);
commandGroup.AddCommandString(commandString);
@@ -507,7 +507,7 @@ namespace CommandSystem
bool result = GetCommandManager()->ExecuteCommandGroupInsideCommand(commandGroup, outResult);
// restore the workspace dirty flag
GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag);
GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag);
return result;
}
@@ -538,10 +538,10 @@ namespace CommandSystem
return;
}
const AZ::Vector3& pos = actorInstance->GetLocalSpaceTransform().mPosition;
const AZ::Quaternion& rot = actorInstance->GetLocalSpaceTransform().mRotation;
const AZ::Vector3& pos = actorInstance->GetLocalSpaceTransform().m_position;
const AZ::Quaternion& rot = actorInstance->GetLocalSpaceTransform().m_rotation;
#ifndef EMFX_SCALE_DISABLED
const AZ::Vector3& scale = actorInstance->GetLocalSpaceTransform().mScale;
const AZ::Vector3& scale = actorInstance->GetLocalSpaceTransform().m_scale;
#else
const AZ::Vector3 scale = AZ::Vector3::CreateOne();
#endif
@@ -20,34 +20,34 @@ namespace CommandSystem
// create a new actor instance
MCORE_DEFINECOMMAND_START(CommandCreateActorInstance, "Create actor instance", true)
public:
uint32 mPreviouslyUsedID;
bool mOldWorkspaceDirtyFlag;
uint32 m_previouslyUsedId;
bool m_oldWorkspaceDirtyFlag;
MCORE_DEFINECOMMAND_END
// adjust a given actor instance
MCORE_DEFINECOMMAND_START(CommandAdjustActorInstance, "Adjust actor instance", true)
public:
AZ::Vector3 mOldPosition;
AZ::Quaternion mOldRotation;
AZ::Vector3 mOldScale;
size_t mOldLODLevel;
bool mOldIsVisible;
bool mOldDoRender;
bool mOldWorkspaceDirtyFlag;
AZ::Vector3 m_oldPosition;
AZ::Quaternion m_oldRotation;
AZ::Vector3 m_oldScale;
size_t m_oldLodLevel;
bool m_oldIsVisible;
bool m_oldDoRender;
bool m_oldWorkspaceDirtyFlag;
MCORE_DEFINECOMMAND_END
// remove an actor instance
MCORE_DEFINECOMMAND_START(CommandRemoveActorInstance, "Remove actor instance", true)
uint32 mOldActorID;
AZ::Vector3 mOldPosition;
AZ::Quaternion mOldRotation;
AZ::Vector3 mOldScale;
size_t mOldLODLevel;
bool mOldIsVisible;
bool mOldDoRender;
bool mOldWorkspaceDirtyFlag;
uint32 m_oldActorId;
AZ::Vector3 m_oldPosition;
AZ::Quaternion m_oldRotation;
AZ::Vector3 m_oldScale;
size_t m_oldLodLevel;
bool m_oldIsVisible;
bool m_oldDoRender;
bool m_oldWorkspaceDirtyFlag;
MCORE_DEFINECOMMAND_END
//////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -39,7 +39,7 @@ namespace CommandSystem
CommandLoadAnimGraph::CommandLoadAnimGraph(MCore::Command* orgCommand)
: MCore::Command("LoadAnimGraph", orgCommand)
{
mOldAnimGraphID = MCORE_INVALIDINDEX32;
m_oldAnimGraphId = MCORE_INVALIDINDEX32;
}
@@ -107,11 +107,11 @@ namespace CommandSystem
}
// in case we are in a redo call assign the previously used id
if (mOldAnimGraphID != MCORE_INVALIDINDEX32)
if (m_oldAnimGraphId != MCORE_INVALIDINDEX32)
{
animGraph->SetID(mOldAnimGraphID);
animGraph->SetID(m_oldAnimGraphId);
}
mOldAnimGraphID = animGraph->GetID();
m_oldAnimGraphId = animGraph->GetID();
animGraph->RecursiveInvalidateUniqueDatas();
@@ -126,7 +126,7 @@ namespace CommandSystem
}
// mark the workspace as dirty
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
GetCommandManager()->SetWorkspaceDirtyFlag(true);
// automatically select the anim graph after loading it
@@ -144,18 +144,18 @@ namespace CommandSystem
MCORE_UNUSED(parameters);
// get the anim graph the command created
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mOldAnimGraphID);
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_oldAnimGraphId);
if (animGraph == nullptr)
{
outResult = AZStd::string::format("Cannot undo load anim graph command. Previously used anim graph id '%i' is not valid.", mOldAnimGraphID);
outResult = AZStd::string::format("Cannot undo load anim graph command. Previously used anim graph id '%i' is not valid.", m_oldAnimGraphId);
return false;
}
// Remove the newly created anim graph.
const bool result = GetCommandManager()->ExecuteCommandInsideCommand(AZStd::string::format("RemoveAnimGraph -animGraphID %i", mOldAnimGraphID), outResult);
const bool result = GetCommandManager()->ExecuteCommandInsideCommand(AZStd::string::format("RemoveAnimGraph -animGraphID %i", m_oldAnimGraphId), outResult);
// restore the workspace dirty flag
GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag);
GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag);
return result;
}
@@ -184,7 +184,7 @@ namespace CommandSystem
CommandCreateAnimGraph::CommandCreateAnimGraph(MCore::Command* orgCommand)
: MCore::Command("CreateAnimGraph", orgCommand)
{
mPreviouslyUsedID = MCORE_INVALIDINDEX32;
m_previouslyUsedId = MCORE_INVALIDINDEX32;
}
@@ -221,11 +221,11 @@ namespace CommandSystem
{
animGraph->SetID(parameters.GetValueAsInt("animGraphID", this));
}
if (mPreviouslyUsedID != MCORE_INVALIDINDEX32)
if (m_previouslyUsedId != MCORE_INVALIDINDEX32)
{
animGraph->SetID(mPreviouslyUsedID);
animGraph->SetID(m_previouslyUsedId);
}
mPreviouslyUsedID = animGraph->GetID();
m_previouslyUsedId = animGraph->GetID();
animGraph->RecursiveReinit();
animGraph->RecursiveInvalidateUniqueDatas();
@@ -238,7 +238,7 @@ namespace CommandSystem
AZStd::to_string(outResult, animGraph->GetID());
// mark the workspace as dirty
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
GetCommandManager()->SetWorkspaceDirtyFlag(true);
return true;
@@ -251,18 +251,18 @@ namespace CommandSystem
MCORE_UNUSED(parameters);
// get the anim graph the command created
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mPreviouslyUsedID);
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_previouslyUsedId);
if (animGraph == nullptr)
{
outResult = AZStd::string::format("Cannot undo create anim graph command. Previously used anim graph id '%i' is not valid.", mPreviouslyUsedID);
outResult = AZStd::string::format("Cannot undo create anim graph command. Previously used anim graph id '%i' is not valid.", m_previouslyUsedId);
return false;
}
// remove the newly created anim graph again
const bool result = GetCommandManager()->ExecuteCommandInsideCommand(AZStd::string::format("RemoveAnimGraph -animGraphID %i", mPreviouslyUsedID), outResult);
const bool result = GetCommandManager()->ExecuteCommandInsideCommand(AZStd::string::format("RemoveAnimGraph -animGraphID %i", m_previouslyUsedId), outResult);
// restore the workspace dirty flag
GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag);
GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag);
return result;
}
@@ -334,7 +334,7 @@ namespace CommandSystem
if (someAnimGraphRemoved)
{
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
GetCommandManager()->SetWorkspaceDirtyFlag(true);
}
@@ -388,7 +388,7 @@ namespace CommandSystem
}
// mark the workspace as dirty
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
GetCommandManager()->SetWorkspaceDirtyFlag(true);
return true;
@@ -414,7 +414,7 @@ namespace CommandSystem
}
// restore the workspace dirty flag
GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag);
GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag);
return result;
}
@@ -440,9 +440,9 @@ namespace CommandSystem
CommandActivateAnimGraph::CommandActivateAnimGraph(MCore::Command* orgCommand)
: MCore::Command(s_activateAnimGraphCmdName, orgCommand)
{
mActorInstanceID = MCORE_INVALIDINDEX32;
mOldAnimGraphUsed = MCORE_INVALIDINDEX32;
mOldMotionSetUsed = MCORE_INVALIDINDEX32;
m_actorInstanceId = MCORE_INVALIDINDEX32;
m_oldAnimGraphUsed = MCORE_INVALIDINDEX32;
m_oldMotionSetUsed = MCORE_INVALIDINDEX32;
}
CommandActivateAnimGraph::~CommandActivateAnimGraph()
@@ -509,7 +509,7 @@ namespace CommandSystem
}
// store the actor instance ID
mActorInstanceID = actorInstance->GetID();
m_actorInstanceId = actorInstance->GetID();
// get the motion system from the actor instance
EMotionFX::MotionSystem* motionSystem = actorInstance->GetMotionSystem();
@@ -533,9 +533,9 @@ namespace CommandSystem
EMotionFX::MotionSet* animGraphInstanceMotionSet = animGraphInstance->GetMotionSet();
// store the currently used anim graph ID, motion set ID and the visualize scale
mOldAnimGraphUsed = animGraphInstanceAnimGraph->GetID();
mOldMotionSetUsed = (animGraphInstanceMotionSet) ? animGraphInstanceMotionSet->GetID() : MCORE_INVALIDINDEX32;
mOldVisualizeScaleUsed = animGraphInstance->GetVisualizeScale();
m_oldAnimGraphUsed = animGraphInstanceAnimGraph->GetID();
m_oldMotionSetUsed = (animGraphInstanceMotionSet) ? animGraphInstanceMotionSet->GetID() : MCORE_INVALIDINDEX32;
m_oldVisualizeScaleUsed = animGraphInstance->GetVisualizeScale();
// check if the anim graph is valid
if (animGraph)
@@ -566,8 +566,8 @@ namespace CommandSystem
else // no one anim graph instance set on the actor instance, create a new one
{
// store the currently used ID as invalid
mOldAnimGraphUsed = MCORE_INVALIDINDEX32;
mOldMotionSetUsed = MCORE_INVALIDINDEX32;
m_oldAnimGraphUsed = MCORE_INVALIDINDEX32;
m_oldMotionSetUsed = MCORE_INVALIDINDEX32;
// check if the anim graph is valid
if (animGraph)
@@ -585,7 +585,7 @@ namespace CommandSystem
AZStd::to_string(outResult, animGraph ? animGraph->GetID() : MCORE_INVALIDINDEX32);
// mark the workspace as dirty
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
GetCommandManager()->SetWorkspaceDirtyFlag(true);
AZStd::string resultString;
@@ -598,12 +598,12 @@ namespace CommandSystem
if (parameters.GetValueAsBool("startRecording", this))
{
EMotionFX::Recorder::RecordSettings settings;
settings.mFPS = 1000000;
settings.mRecordTransforms = true;
settings.mRecordAnimGraphStates = true;
settings.mRecordNodeHistory = true;
settings.mRecordScale = true;
settings.mInitialAnimGraphAnimBytes = 4 * 1024 * 1024; // 4 mb
settings.m_fps = 1000000;
settings.m_recordTransforms = true;
settings.m_recordAnimGraphStates = true;
settings.m_recordNodeHistory = true;
settings.m_recordScale = true;
settings.m_initialAnimGraphAnimBytes = 4 * 1024 * 1024; // 4 mb
EMotionFX::GetRecorder().StartRecording(settings);
}
@@ -616,41 +616,41 @@ namespace CommandSystem
MCORE_UNUSED(parameters);
// get the actor instance id and check if it is valid
EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(mActorInstanceID);
EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(m_actorInstanceId);
if (actorInstance == nullptr)
{
outResult = AZStd::string::format("Cannot undo activate anim graph. Actor instance id '%i' is not valid.", mActorInstanceID);
outResult = AZStd::string::format("Cannot undo activate anim graph. Actor instance id '%i' is not valid.", m_actorInstanceId);
return false;
}
// get the anim graph, invalid index is a special case to allow the anim graph to be nullptr
EMotionFX::AnimGraph* animGraph;
if (mOldAnimGraphUsed == MCORE_INVALIDINDEX32)
if (m_oldAnimGraphUsed == MCORE_INVALIDINDEX32)
{
animGraph = nullptr;
}
else
{
animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mOldAnimGraphUsed);
animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_oldAnimGraphUsed);
if (animGraph == nullptr)
{
outResult = AZStd::string::format("Cannot undo activate anim graph. Anim graph id '%i' is not valid.", mOldAnimGraphUsed);
outResult = AZStd::string::format("Cannot undo activate anim graph. Anim graph id '%i' is not valid.", m_oldAnimGraphUsed);
return false;
}
}
// get the motion set, invalid index is a special case to allow the motion set to be nullptr
EMotionFX::MotionSet* motionSet;
if (mOldMotionSetUsed == MCORE_INVALIDINDEX32)
if (m_oldMotionSetUsed == MCORE_INVALIDINDEX32)
{
motionSet = nullptr;
}
else
{
motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(mOldMotionSetUsed);
motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(m_oldMotionSetUsed);
if (motionSet == nullptr)
{
outResult = AZStd::string::format("Cannot undo activate anim graph. Motion set id '%i' is not valid.", mOldMotionSetUsed);
outResult = AZStd::string::format("Cannot undo activate anim graph. Motion set id '%i' is not valid.", m_oldMotionSetUsed);
return false;
}
}
@@ -683,7 +683,7 @@ namespace CommandSystem
// create a new anim graph instance
animGraphInstance = EMotionFX::AnimGraphInstance::Create(animGraph, actorInstance, motionSet);
animGraphInstance->SetVisualizeScale(mOldVisualizeScaleUsed);
animGraphInstance->SetVisualizeScale(m_oldVisualizeScaleUsed);
actorInstance->SetAnimGraphInstance(animGraphInstance);
animGraphInstance->RecursiveInvalidateUniqueDatas();
@@ -702,7 +702,7 @@ namespace CommandSystem
{
// create a new anim graph instance
animGraphInstance = EMotionFX::AnimGraphInstance::Create(animGraph, actorInstance, motionSet);
animGraphInstance->SetVisualizeScale(mOldVisualizeScaleUsed);
animGraphInstance->SetVisualizeScale(m_oldVisualizeScaleUsed);
actorInstance->SetAnimGraphInstance(animGraphInstance);
animGraphInstance->RecursiveInvalidateUniqueDatas();
@@ -713,7 +713,7 @@ namespace CommandSystem
AZStd::to_string(outResult, animGraph ? animGraph->GetID() : MCORE_INVALIDINDEX32);
// restore the workspace dirty flag
GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag);
GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag);
AZStd::string resultString;
GetCommandManager()->ExecuteCommandInsideCommand("Unselect -animGraphIndex SELECT_ALL", resultString);
@@ -23,16 +23,16 @@ namespace CommandSystem
public:
using RelocateFilenameFunction = AZStd::function<void(AZStd::string&)>;
RelocateFilenameFunction m_relocateFilenameFunction;
uint32 mOldAnimGraphID;
bool mOldWorkspaceDirtyFlag;
uint32 m_oldAnimGraphId;
bool m_oldWorkspaceDirtyFlag;
MCORE_DEFINECOMMAND_END
// create a new anim graph
MCORE_DEFINECOMMAND_START(CommandCreateAnimGraph, "Create a anim graph", true)
public:
uint32 mPreviouslyUsedID;
bool mOldWorkspaceDirtyFlag;
uint32 m_previouslyUsedId;
bool m_oldWorkspaceDirtyFlag;
MCORE_DEFINECOMMAND_END
@@ -40,18 +40,18 @@ public:
MCORE_DEFINECOMMAND_START(CommandRemoveAnimGraph, "Remove a anim graph", true)
public:
AZStd::vector<AZStd::pair<AZStd::string, uint32>> m_oldFileNamesAndIds;
bool mOldWorkspaceDirtyFlag;
bool m_oldWorkspaceDirtyFlag;
MCORE_DEFINECOMMAND_END
// Activate the given anim graph.
MCORE_DEFINECOMMAND_START(CommandActivateAnimGraph, "Activate a anim graph", true)
public:
uint32 mActorInstanceID;
uint32 mOldAnimGraphUsed;
uint32 mOldMotionSetUsed;
float mOldVisualizeScaleUsed;
bool mOldWorkspaceDirtyFlag;
uint32 m_actorInstanceId;
uint32 m_oldAnimGraphUsed;
uint32 m_oldMotionSetUsed;
float m_oldVisualizeScaleUsed;
bool m_oldWorkspaceDirtyFlag;
static const char* s_activateAnimGraphCmdName;
MCORE_DEFINECOMMAND_END
@@ -63,7 +63,7 @@ namespace CommandSystem
CommandAnimGraphCreateConnection::CommandAnimGraphCreateConnection(MCore::Command* orgCommand)
: MCore::Command("AnimGraphCreateConnection", orgCommand)
{
mTransitionType = AZ::TypeId::CreateNull();
m_transitionType = AZ::TypeId::CreateNull();
}
// destructor
@@ -83,13 +83,13 @@ namespace CommandSystem
}
// store the anim graph id for undo
mAnimGraphID = animGraph->GetID();
m_animGraphId = animGraph->GetID();
// get the transition type
AZ::Outcome<AZStd::string> transitionTypeString = parameters.GetValueIfExists("transitionType", this);
if (transitionTypeString.IsSuccess())
{
mTransitionType = AZ::TypeId::CreateString(transitionTypeString.GetValue().c_str());
m_transitionType = AZ::TypeId::CreateString(transitionTypeString.GetValue().c_str());
}
// get the node names
@@ -116,18 +116,18 @@ namespace CommandSystem
}
// get the ports
mSourcePort = parameters.GetValueAsInt("sourcePort", 0);
mTargetPort = parameters.GetValueAsInt("targetPort", 0);
parameters.GetValue("sourcePortName", this, mSourcePortName);
parameters.GetValue("targetPortName", this, mTargetPortName);
m_sourcePort = parameters.GetValueAsInt("sourcePort", 0);
m_targetPort = parameters.GetValueAsInt("targetPort", 0);
parameters.GetValue("sourcePortName", this, m_sourcePortName);
parameters.GetValue("targetPortName", this, m_targetPortName);
// in case the source port got specified by name, overwrite the source port number
if (!mSourcePortName.empty())
if (!m_sourcePortName.empty())
{
mSourcePort = sourceNode->FindOutputPortIndex(mSourcePortName);
m_sourcePort = sourceNode->FindOutputPortIndex(m_sourcePortName);
// in case we want to add this connection to a parameter node while the parameter name doesn't exist, still return true so that copy paste doesn't fail
if (azrtti_typeid(sourceNode) == azrtti_typeid<EMotionFX::BlendTreeParameterNode>() && mSourcePort == InvalidIndex)
if (azrtti_typeid(sourceNode) == azrtti_typeid<EMotionFX::BlendTreeParameterNode>() && m_sourcePort == InvalidIndex)
{
m_connectionId.SetInvalid();
return true;
@@ -135,9 +135,9 @@ namespace CommandSystem
}
// in case the target port got specified by name, overwrite the target port number
if (!mTargetPortName.empty())
if (!m_targetPortName.empty())
{
mTargetPort = targetNode->FindInputPortIndex(mTargetPortName.c_str());
m_targetPort = targetNode->FindInputPortIndex(m_targetPortName.c_str());
}
// get the parent of the source node
@@ -157,27 +157,27 @@ namespace CommandSystem
}
// verify port ranges
if (mSourcePort >= sourceNode->GetOutputPorts().size())
if (m_sourcePort >= sourceNode->GetOutputPorts().size())
{
outResult = AZStd::string::format("The output port number is not valid for the given node. Node '%s' only has %zu output ports.", sourceNode->GetName(), sourceNode->GetOutputPorts().size());
return false;
}
if (mTargetPort >= targetNode->GetInputPorts().size())
if (m_targetPort >= targetNode->GetInputPorts().size())
{
outResult = AZStd::string::format("The input port number is not valid for the given node. Node '%s' only has %zu input ports.", targetNode->GetName(), targetNode->GetInputPorts().size());
return false;
}
// check if connection already exists
if (targetNode->GetHasConnection(sourceNode, static_cast<uint16>(mSourcePort), static_cast<uint16>(mTargetPort)))
if (targetNode->GetHasConnection(sourceNode, static_cast<uint16>(m_sourcePort), static_cast<uint16>(m_targetPort)))
{
outResult = AZStd::string::format("The connection you are trying to create already exists!");
return false;
}
// create the connection and auto assign an id first of all
EMotionFX::BlendTreeConnection* connection = targetNode->AddConnection(sourceNode, static_cast<uint16>(mSourcePort), static_cast<uint16>(mTargetPort));
EMotionFX::BlendTreeConnection* connection = targetNode->AddConnection(sourceNode, static_cast<uint16>(m_sourcePort), static_cast<uint16>(m_targetPort));
// Overwrite the connection id if specified by a command parameter.
if (parameters.CheckIfHasParameter("id"))
@@ -201,8 +201,8 @@ namespace CommandSystem
if (azrtti_istypeof<EMotionFX::BlendTreeBlendNNode>(targetNode))
{
EMotionFX::BlendTreeBlendNNode* blendTreeBlendNNode = static_cast<EMotionFX::BlendTreeBlendNNode*>(targetNode);
mUpdateParamFlag = parameters.GetValueAsBool("updateParam", true);
if (mUpdateParamFlag)
m_updateParamFlag = parameters.GetValueAsBool("updateParam", true);
if (m_updateParamFlag)
{
blendTreeBlendNNode->UpdateParamWeights();
}
@@ -214,17 +214,17 @@ namespace CommandSystem
EMotionFX::AnimGraphStateMachine* machine = (EMotionFX::AnimGraphStateMachine*)targetNode->GetParentNode();
// try to create the anim graph node
EMotionFX::AnimGraphObject* object = EMotionFX::AnimGraphObjectFactory::Create(mTransitionType, animGraph);
EMotionFX::AnimGraphObject* object = EMotionFX::AnimGraphObjectFactory::Create(m_transitionType, animGraph);
if (!object)
{
outResult = AZStd::string::format("Cannot create transition of type %s", mTransitionType.ToString<AZStd::string>().c_str());
outResult = AZStd::string::format("Cannot create transition of type %s", m_transitionType.ToString<AZStd::string>().c_str());
return false;
}
// check if this is really a transition
if (!azrtti_istypeof<EMotionFX::AnimGraphStateTransition>(object))
{
outResult = AZStd::string::format("Cannot create state transition of type %s, because this object type is not inherited from AnimGraphStateTransition.", mTransitionType.ToString<AZStd::string>().c_str());
outResult = AZStd::string::format("Cannot create state transition of type %s, because this object type is not inherited from AnimGraphStateTransition.", m_transitionType.ToString<AZStd::string>().c_str());
return false;
}
@@ -255,13 +255,13 @@ namespace CommandSystem
transition->SetTargetNode(targetNode);
// get the offsets
mStartOffsetX = parameters.GetValueAsInt("startOffsetX", 0);
mStartOffsetY = parameters.GetValueAsInt("startOffsetY", 0);
mEndOffsetX = parameters.GetValueAsInt("endOffsetX", 0);
mEndOffsetY = parameters.GetValueAsInt("endOffsetY", 0);
m_startOffsetX = parameters.GetValueAsInt("startOffsetX", 0);
m_startOffsetY = parameters.GetValueAsInt("startOffsetY", 0);
m_endOffsetX = parameters.GetValueAsInt("endOffsetX", 0);
m_endOffsetY = parameters.GetValueAsInt("endOffsetY", 0);
if (parameters.CheckIfHasValue("startOffsetX") || parameters.CheckIfHasValue("startOffsetY") || parameters.CheckIfHasValue("endOffsetX") || parameters.CheckIfHasValue("endOffsetY"))
{
transition->SetVisualOffsets(mStartOffsetX, mStartOffsetY, mEndOffsetX, mEndOffsetY);
transition->SetVisualOffsets(m_startOffsetX, m_startOffsetY, m_endOffsetX, m_endOffsetY);
}
transition->SetIsWildcardTransition(isWildcardTransition);
@@ -290,19 +290,19 @@ namespace CommandSystem
transition->Reinit();
}
mTargetNodeId.SetInvalid();
mSourceNodeId.SetInvalid();
m_targetNodeId.SetInvalid();
m_sourceNodeId.SetInvalid();
if (targetNode)
{
mTargetNodeId = targetNode->GetId();
m_targetNodeId = targetNode->GetId();
}
if (sourceNode)
{
mSourceNodeId = sourceNode->GetId();
m_sourceNodeId = sourceNode->GetId();
}
// save the current dirty flag and tell the anim graph that something got changed
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
// set the command result to the connection id
@@ -319,16 +319,16 @@ namespace CommandSystem
MCORE_UNUSED(parameters);
// get the anim graph
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mAnimGraphID);
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_animGraphId);
if (animGraph == nullptr)
{
outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", mAnimGraphID);
outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", m_animGraphId);
return false;
}
// in case of a wildcard transition the source node is the invalid index, so that's all fine
EMotionFX::AnimGraphNode* sourceNode = animGraph->RecursiveFindNodeById(mSourceNodeId);
EMotionFX::AnimGraphNode* targetNode = animGraph->RecursiveFindNodeById(mTargetNodeId);
EMotionFX::AnimGraphNode* sourceNode = animGraph->RecursiveFindNodeById(m_sourceNodeId);
EMotionFX::AnimGraphNode* targetNode = animGraph->RecursiveFindNodeById(m_targetNodeId);
// NOTE: When source node is a nullptr, we are dealing with a wildcard transition, so there a nullptr is allowed.
if (!targetNode)
@@ -348,9 +348,9 @@ namespace CommandSystem
const AZStd::string commandString = AZStd::string::format("AnimGraphRemoveConnection -animGraphID %i -targetNode \"%s\" -targetPort %zu -sourceNode \"%s\" -sourcePort %zu -id %s",
animGraph->GetID(),
targetNode->GetName(),
mTargetPort,
m_targetPort,
sourceNodeName.c_str(),
mSourcePort,
m_sourcePort,
m_connectionId.ToString().c_str());
// execute the command without putting it in the history
@@ -365,11 +365,11 @@ namespace CommandSystem
}
// reset the data used for undo and redo
mSourceNodeId.SetInvalid();
mTargetNodeId.SetInvalid();
m_sourceNodeId.SetInvalid();
m_targetNodeId.SetInvalid();
// set the dirty flag back to the old value
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -414,13 +414,13 @@ namespace CommandSystem
CommandAnimGraphRemoveConnection::CommandAnimGraphRemoveConnection(MCore::Command* orgCommand)
: MCore::Command("AnimGraphRemoveConnection", orgCommand)
{
mSourcePort = InvalidIndex;
mTargetPort = InvalidIndex;
mTransitionType = AZ::TypeId::CreateNull();
mStartOffsetX = 0;
mStartOffsetY = 0;
mEndOffsetX = 0;
mEndOffsetY = 0;
m_sourcePort = InvalidIndex;
m_targetPort = InvalidIndex;
m_transitionType = AZ::TypeId::CreateNull();
m_startOffsetX = 0;
m_startOffsetY = 0;
m_endOffsetX = 0;
m_endOffsetY = 0;
}
@@ -441,7 +441,7 @@ namespace CommandSystem
}
// store the anim graph id for undo
mAnimGraphID = animGraph->GetID();
m_animGraphId = animGraph->GetID();
// get the node names
AZStd::string sourceNodeName;
@@ -466,19 +466,19 @@ namespace CommandSystem
}
// get the ids from the source and destination nodes
mSourceNodeId.SetInvalid();
mSourceNodeName.clear();
m_sourceNodeId.SetInvalid();
m_sourceNodeName.clear();
if (sourceNode)
{
mSourceNodeId = sourceNode->GetId();
mSourceNodeName = sourceNode->GetName();
m_sourceNodeId = sourceNode->GetId();
m_sourceNodeName = sourceNode->GetName();
}
mTargetNodeId = targetNode->GetId();
mTargetNodeName = targetNode->GetName();
m_targetNodeId = targetNode->GetId();
m_targetNodeName = targetNode->GetName();
// get the ports
mSourcePort = parameters.GetValueAsInt("sourcePort", 0);
mTargetPort = parameters.GetValueAsInt("targetPort", 0);
m_sourcePort = parameters.GetValueAsInt("sourcePort", 0);
m_targetPort = parameters.GetValueAsInt("targetPort", 0);
// get the parent of the source node
if (targetNode->GetParentNode() == nullptr)
@@ -497,34 +497,34 @@ namespace CommandSystem
}
// verify port ranges
if (mSourcePort >= static_cast<int32>(sourceNode->GetOutputPorts().size()) || mSourcePort < 0)
if (m_sourcePort >= static_cast<int32>(sourceNode->GetOutputPorts().size()) || m_sourcePort < 0)
{
outResult = AZStd::string::format("The output port number is not valid for the given node. Node '%s' only has %zu output ports.", sourceNode->GetName(), sourceNode->GetOutputPorts().size());
return false;
}
if (mTargetPort >= static_cast<int32>(targetNode->GetInputPorts().size()) || mTargetPort < 0)
if (m_targetPort >= static_cast<int32>(targetNode->GetInputPorts().size()) || m_targetPort < 0)
{
outResult = AZStd::string::format("The input port number is not valid for the given node. Node '%s' only has %zu input ports.", targetNode->GetName(), targetNode->GetInputPorts().size());
return false;
}
// check if connection already exists
if (!targetNode->GetHasConnection(sourceNode, static_cast<uint16>(mSourcePort), static_cast<uint16>(mTargetPort)))
if (!targetNode->GetHasConnection(sourceNode, static_cast<uint16>(m_sourcePort), static_cast<uint16>(m_targetPort)))
{
outResult = AZStd::string::format("The connection you are trying to remove doesn't exist!");
return false;
}
// get the connection ID and store it
EMotionFX::BlendTreeConnection* connection = targetNode->FindConnection(sourceNode, static_cast<uint16>(mSourcePort), static_cast<uint16>(mTargetPort));
EMotionFX::BlendTreeConnection* connection = targetNode->FindConnection(sourceNode, static_cast<uint16>(m_sourcePort), static_cast<uint16>(m_targetPort));
if (connection)
{
m_connectionId = connection->GetId();
}
// create the connection
targetNode->RemoveConnection(sourceNode, static_cast<uint16>(mSourcePort), static_cast<uint16>(mTargetPort));
targetNode->RemoveConnection(sourceNode, static_cast<uint16>(m_sourcePort), static_cast<uint16>(m_targetPort));
if (azrtti_istypeof<EMotionFX::BlendTreeBlendNNode>(targetNode))
{
@@ -558,13 +558,13 @@ namespace CommandSystem
// save the transition information for undo
EMotionFX::AnimGraphStateTransition* transition = stateMachine->GetTransition(transitionIndex.GetValue());
mStartOffsetX = transition->GetVisualStartOffsetX();
mStartOffsetY = transition->GetVisualStartOffsetY();
mEndOffsetX = transition->GetVisualEndOffsetX();
mEndOffsetY = transition->GetVisualEndOffsetY();
mTransitionType = azrtti_typeid(transition);
m_startOffsetX = transition->GetVisualStartOffsetX();
m_startOffsetY = transition->GetVisualStartOffsetY();
m_endOffsetX = transition->GetVisualEndOffsetX();
m_endOffsetY = transition->GetVisualEndOffsetY();
m_transitionType = azrtti_typeid(transition);
m_connectionId = transition->GetId();
mOldContents = MCore::ReflectionSerializer::Serialize(transition).GetValue();
m_oldContents = MCore::ReflectionSerializer::Serialize(transition).GetValue();
// remove all unique datas for the transition itself
animGraph->RemoveAllObjectData(transition, true);
@@ -574,7 +574,7 @@ namespace CommandSystem
}
// save the current dirty flag and tell the anim graph that something got changed
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
if(parameters.GetValueAsBool("updateUniqueData", true))
@@ -591,34 +591,34 @@ namespace CommandSystem
const AZStd::string updateUniqueData = parameters.GetValue("updateUniqueData", this);
// get the anim graph
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mAnimGraphID);
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_animGraphId);
if (animGraph == nullptr)
{
outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", mAnimGraphID);
outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", m_animGraphId);
return false;
}
if (!mTargetNodeId.IsValid())
if (!m_targetNodeId.IsValid())
{
return false;
}
AZStd::string commandString = AZStd::string::format("AnimGraphCreateConnection -animGraphID %i -sourceNode \"%s\" -targetNode \"%s\" -sourcePort %zu -targetPort %zu -startOffsetX %d -startOffsetY %d -endOffsetX %d -endOffsetY %d -id %s -transitionType \"%s\" -updateUniqueData %s",
animGraph->GetID(),
mSourceNodeName.c_str(),
mTargetNodeName.c_str(),
mSourcePort,
mTargetPort,
mStartOffsetX, mStartOffsetY,
mEndOffsetX, mEndOffsetY,
m_sourceNodeName.c_str(),
m_targetNodeName.c_str(),
m_sourcePort,
m_targetPort,
m_startOffsetX, m_startOffsetY,
m_endOffsetX, m_endOffsetY,
m_connectionId.ToString().c_str(),
mTransitionType.ToString<AZStd::string>().c_str(),
m_transitionType.ToString<AZStd::string>().c_str(),
updateUniqueData.c_str());
// add the old attributes
if (mOldContents.empty() == false)
if (m_oldContents.empty() == false)
{
commandString += AZStd::string::format(" -contents {%s}", mOldContents.c_str());
commandString += AZStd::string::format(" -contents {%s}", m_oldContents.c_str());
}
if (!GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult))
@@ -631,18 +631,18 @@ namespace CommandSystem
return false;
}
mTargetNodeId.SetInvalid();
mSourceNodeId.SetInvalid();
m_targetNodeId.SetInvalid();
m_sourceNodeId.SetInvalid();
m_connectionId.SetInvalid();
mSourcePort = InvalidIndex;
mTargetPort = InvalidIndex;
mStartOffsetX = 0;
mStartOffsetY = 0;
mEndOffsetX = 0;
mEndOffsetY = 0;
m_sourcePort = InvalidIndex;
m_targetPort = InvalidIndex;
m_startOffsetX = 0;
m_startOffsetY = 0;
m_endOffsetX = 0;
m_endOffsetY = 0;
// set the dirty flag back to the old value
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -839,7 +839,7 @@ namespace CommandSystem
}
// save the current dirty flag and tell the anim graph that something got changed
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
transition->Reinit();
@@ -865,14 +865,14 @@ namespace CommandSystem
}
AdjustTransition(transition,
/*mOldDisabledFlag=*/AZStd::nullopt,
/*sourceNodeName=*/AZStd::nullopt, /*targetNodeName=*/AZStd::nullopt,
/*isDisabled=*/AZStd::nullopt,
/*sourceNode=*/AZStd::nullopt, /*targetNode=*/AZStd::nullopt,
/*startOffsetX=*/AZStd::nullopt, /*startOffsetY=*/AZStd::nullopt,
/*endOffsetX=*/AZStd::nullopt, /*endOffsetY=*/AZStd::nullopt,
/*attributesString=*/AZStd::nullopt, /*serializedMembers=*/m_oldSerializedMembers.GetValue(),
/*commandGroup*/nullptr, /*executeInsideCommand*/true);
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -26,64 +26,64 @@ namespace CommandSystem
{
// create a connection
MCORE_DEFINECOMMAND_START(CommandAnimGraphCreateConnection, "Connect two anim graph nodes", true)
uint32 mAnimGraphID;
EMotionFX::AnimGraphNodeId mTargetNodeId;
EMotionFX::AnimGraphNodeId mSourceNodeId;
uint32 m_animGraphId;
EMotionFX::AnimGraphNodeId m_targetNodeId;
EMotionFX::AnimGraphNodeId m_sourceNodeId;
EMotionFX::AnimGraphConnectionId m_connectionId;
AZ::TypeId mTransitionType;
int32 mStartOffsetX;
int32 mStartOffsetY;
int32 mEndOffsetX;
int32 mEndOffsetY;
size_t mSourcePort;
size_t mTargetPort;
AZStd::string mSourcePortName;
AZStd::string mTargetPortName;
bool mOldDirtyFlag;
bool mUpdateParamFlag;
AZ::TypeId m_transitionType;
int32 m_startOffsetX;
int32 m_startOffsetY;
int32 m_endOffsetX;
int32 m_endOffsetY;
size_t m_sourcePort;
size_t m_targetPort;
AZStd::string m_sourcePortName;
AZStd::string m_targetPortName;
bool m_oldDirtyFlag;
bool m_updateParamFlag;
public:
EMotionFX::AnimGraphConnectionId GetConnectionId() const{ return m_connectionId; }
EMotionFX::AnimGraphNodeId GetTargetNodeId() const { return mTargetNodeId; }
EMotionFX::AnimGraphNodeId GetSourceNodeId() const { return mSourceNodeId; }
AZ::TypeId GetTransitionType() const { return mTransitionType; }
size_t GetSourcePort() const { return mSourcePort; }
size_t GetTargetPort() const { return mTargetPort; }
int32 GetStartOffsetX() const { return mStartOffsetX; }
int32 GetStartOffsetY() const { return mStartOffsetY; }
int32 GetEndOffsetX() const { return mEndOffsetX; }
int32 GetEndOffsetY() const { return mEndOffsetY; }
EMotionFX::AnimGraphNodeId GetTargetNodeId() const { return m_targetNodeId; }
EMotionFX::AnimGraphNodeId GetSourceNodeId() const { return m_sourceNodeId; }
AZ::TypeId GetTransitionType() const { return m_transitionType; }
size_t GetSourcePort() const { return m_sourcePort; }
size_t GetTargetPort() const { return m_targetPort; }
int32 GetStartOffsetX() const { return m_startOffsetX; }
int32 GetStartOffsetY() const { return m_startOffsetY; }
int32 GetEndOffsetX() const { return m_endOffsetX; }
int32 GetEndOffsetY() const { return m_endOffsetY; }
MCORE_DEFINECOMMAND_END
// remove a connection
MCORE_DEFINECOMMAND_START(CommandAnimGraphRemoveConnection, "Remove a anim graph connection", true)
uint32 mAnimGraphID;
EMotionFX::AnimGraphNodeId mTargetNodeId;
AZStd::string mTargetNodeName;
EMotionFX::AnimGraphNodeId mSourceNodeId;
AZStd::string mSourceNodeName;
uint32 m_animGraphId;
EMotionFX::AnimGraphNodeId m_targetNodeId;
AZStd::string m_targetNodeName;
EMotionFX::AnimGraphNodeId m_sourceNodeId;
AZStd::string m_sourceNodeName;
EMotionFX::AnimGraphConnectionId m_connectionId;
AZ::TypeId mTransitionType;
int32 mStartOffsetX;
int32 mStartOffsetY;
int32 mEndOffsetX;
int32 mEndOffsetY;
size_t mSourcePort;
size_t mTargetPort;
bool mOldDirtyFlag;
AZStd::string mOldContents;
AZ::TypeId m_transitionType;
int32 m_startOffsetX;
int32 m_startOffsetY;
int32 m_endOffsetX;
int32 m_endOffsetY;
size_t m_sourcePort;
size_t m_targetPort;
bool m_oldDirtyFlag;
AZStd::string m_oldContents;
public:
EMotionFX::AnimGraphNodeId GetTargetNodeID() const { return mTargetNodeId; }
EMotionFX::AnimGraphNodeId GetSourceNodeID() const { return mSourceNodeId; }
AZ::TypeId GetTransitionType() const { return mTransitionType; }
size_t GetSourcePort() const { return mSourcePort; }
size_t GetTargetPort() const { return mTargetPort; }
int32 GetStartOffsetX() const { return mStartOffsetX; }
int32 GetStartOffsetY() const { return mStartOffsetY; }
int32 GetEndOffsetX() const { return mEndOffsetX; }
int32 GetEndOffsetY() const { return mEndOffsetY; }
EMotionFX::AnimGraphNodeId GetTargetNodeID() const { return m_targetNodeId; }
EMotionFX::AnimGraphNodeId GetSourceNodeID() const { return m_sourceNodeId; }
AZ::TypeId GetTransitionType() const { return m_transitionType; }
size_t GetSourcePort() const { return m_sourcePort; }
size_t GetTargetPort() const { return m_targetPort; }
int32 GetStartOffsetX() const { return m_startOffsetX; }
int32 GetStartOffsetY() const { return m_startOffsetY; }
int32 GetEndOffsetX() const { return m_endOffsetX; }
int32 GetEndOffsetY() const { return m_endOffsetY; }
EMotionFX::AnimGraphConnectionId GetConnectionId() const{ return m_connectionId; }
MCORE_DEFINECOMMAND_END
@@ -127,7 +127,7 @@ namespace CommandSystem
private:
AZ::Outcome<AZStd::string> m_oldSerializedMembers; // Without actions and conditions.
bool mOldDirtyFlag = false;
bool m_oldDirtyFlag = false;
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -54,7 +54,7 @@ namespace CommandSystem
{
// Get the parameter name.
const AZStd::string& name = parameters.GetValue("name", this);
mOldName = name;
m_oldName = name;
// Find the anim graph by using the id from command parameter.
const uint32 animGraphID = parameters.GetValueAsInt("animGraphID", this);
@@ -108,7 +108,7 @@ namespace CommandSystem
}
const size_t numParameters = parameterNames.size();
mOldGroupParameterNames.resize(numParameters);
m_oldGroupParameterNames.resize(numParameters);
EMotionFX::ValueParameterVector valueParametersBeforeChange = animGraph->RecursivelyGetValueParameters();
@@ -118,13 +118,13 @@ namespace CommandSystem
const EMotionFX::Parameter* parameter = animGraph->FindParameterByName(parameterNames[i]);
if (!parameter)
{
mOldGroupParameterNames[i].clear();
m_oldGroupParameterNames[i].clear();
continue;
}
// Save the group parameter (for undo) to which the parameter belonged before command execution.
const EMotionFX::GroupParameter* parentParameter = animGraph->FindParentGroupParameter(parameter);
mOldGroupParameterNames[i] = parentParameter ? parentParameter->GetName() : "";
m_oldGroupParameterNames[i] = parentParameter ? parentParameter->GetName() : "";
// Make sure the parameter is not in any other group.
animGraph->TakeParameterFromParent(parameter);
@@ -175,7 +175,7 @@ namespace CommandSystem
}
// save the current dirty flag and tell the anim graph that something got changed
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
animGraph->RecursiveInvalidateUniqueDatas();
@@ -196,13 +196,13 @@ namespace CommandSystem
MCore::CommandGroup commandGroup;
// Undo the group name as first step. All commands afterwards have to use mOldName as group name.
// Undo the group name as first step. All commands afterwards have to use m_oldName as group name.
if (parameters.CheckIfHasParameter("newName"))
{
const AZStd::string& newName = parameters.GetValue("newName", this);
const AZStd::string command = AZStd::string::format("AnimGraphAdjustGroupParameter -animGraphID %i -name \"%s\" -newName \"%s\"",
animGraph->GetID(), newName.c_str(), mOldName.c_str());
animGraph->GetID(), newName.c_str(), m_oldName.c_str());
commandGroup.AddCommandString(command);
}
@@ -210,7 +210,7 @@ namespace CommandSystem
if (parameters.CheckIfHasParameter("description"))
{
const AZStd::string command = AZStd::string::format("AnimGraphAdjustGroupParameter -animGraphID %i -name \"%s\" -description \"%s\"",
animGraph->GetID(), mOldName.c_str(), m_oldDescription.c_str());
animGraph->GetID(), m_oldName.c_str(), m_oldDescription.c_str());
commandGroup.AddCommandString(command);
}
@@ -225,12 +225,12 @@ namespace CommandSystem
AzFramework::StringFunc::Tokenize(parametersString.c_str(), parameterNames, ";", false, true);
const size_t parameterCount = parameterNames.size();
AZ_Assert(parameterCount == mOldGroupParameterNames.size(), "The number of parameter names has to match the saved group parameter info for undo.");
AZ_Assert(parameterCount == m_oldGroupParameterNames.size(), "The number of parameter names has to match the saved group parameter info for undo.");
for (size_t i = 0; i < parameterCount; ++i)
{
const AZStd::string& parameterName = parameterNames[i];
const AZStd::string& oldGroupName = mOldGroupParameterNames[i];
const AZStd::string& oldGroupName = m_oldGroupParameterNames[i];
switch (action)
{
@@ -240,7 +240,7 @@ namespace CommandSystem
{
// An empty old group name means that the parameter was in the Default group before, so in this case just remove the parameter from the group.
const AZStd::string command = AZStd::string::format("AnimGraphAdjustGroupParameter -animGraphID %i -name \"%s\" -action \"remove\" -parameterNames \"%s\"",
animGraph->GetID(), mOldName.c_str(), parameterName.c_str());
animGraph->GetID(), m_oldName.c_str(), parameterName.c_str());
commandGroup.AddCommandString(command);
}
@@ -277,7 +277,7 @@ namespace CommandSystem
}
// Set the dirty flag back to the old value.
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -364,8 +364,8 @@ namespace CommandSystem
}
// save the current dirty flag and tell the anim graph that something got changed
mOldDirtyFlag = animGraph->GetDirtyFlag();
mOldName = groupParameter->GetName();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
m_oldName = groupParameter->GetName();
animGraph->SetDirtyFlag(true);
animGraph->RecursiveInvalidateUniqueDatas();
@@ -385,7 +385,7 @@ namespace CommandSystem
}
// Construct and execute the command.
const AZStd::string command = AZStd::string::format("AnimGraphRemoveGroupParameter -animGraphID %i -name \"%s\"", animGraphID, mOldName.c_str());
const AZStd::string command = AZStd::string::format("AnimGraphRemoveGroupParameter -animGraphID %i -name \"%s\"", animGraphID, m_oldName.c_str());
AZStd::string result;
if (!GetCommandManager()->ExecuteCommandInsideCommand(command, result))
@@ -394,7 +394,7 @@ namespace CommandSystem
}
// Set the dirty flag back to the old value.
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -457,23 +457,23 @@ namespace CommandSystem
}
// read out information for the command undo
mOldName = parameter->GetName();
m_oldName = parameter->GetName();
const EMotionFX::GroupParameter* parentGroup = animGraph->FindParentGroupParameter(parameter);
if (parentGroup)
{
mOldParent = parentGroup->GetName();
mOldIndex = parentGroup->FindParameterIndex(parameter).GetValue();
m_oldParent = parentGroup->GetName();
m_oldIndex = parentGroup->FindParameterIndex(parameter).GetValue();
}
else
{
mOldParent = "";
mOldIndex = animGraph->FindParameterIndex(parameter).GetValue();
m_oldParent = "";
m_oldIndex = animGraph->FindParameterIndex(parameter).GetValue();
}
mOldParameterNames.clear();
m_oldParameterNames.clear();
// Collect all child parameters and move them to the default group. Keep the child hierarchy as it is.
// Add the immediate child ones to mOldParameterNames so they get moved back on undo
// Add the immediate child ones to m_oldParameterNames so they get moved back on undo
const EMotionFX::GroupParameter* groupParameter = static_cast<const EMotionFX::GroupParameter*>(parameter);
const EMotionFX::ParameterVector childParameters = groupParameter->RecursivelyGetChildParameters();
AZStd::vector<const EMotionFX::GroupParameter*> childParents;
@@ -497,7 +497,7 @@ namespace CommandSystem
const EMotionFX::GroupParameter* parent = childParents[i];
if (parent == groupParameter)
{
mOldParameterNames += childParameters[i]->GetName() + ";";
m_oldParameterNames += childParameters[i]->GetName() + ";";
animGraph->AddParameter(childParameters[i]); // add to default group
}
else
@@ -505,9 +505,9 @@ namespace CommandSystem
animGraph->AddParameter(childParameters[i], parent); // add to default group
}
}
if (!mOldParameterNames.empty())
if (!m_oldParameterNames.empty())
{
mOldParameterNames.pop_back(); // remove trailing ";"
m_oldParameterNames.pop_back(); // remove trailing ";"
}
// remove the group parameter
@@ -529,7 +529,7 @@ namespace CommandSystem
}
// save the current dirty flag and tell the anim graph that something got changed
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
animGraph->RecursiveInvalidateUniqueDatas();
@@ -555,18 +555,18 @@ namespace CommandSystem
command = AZStd::string::format("AnimGraphAddGroupParameter -animGraphID %i -name \"%s\" -index %zu -parent \"%s\" -updateUI %s",
animGraph->GetID(),
mOldName.c_str(),
mOldIndex,
mOldParent.c_str(),
m_oldName.c_str(),
m_oldIndex,
m_oldParent.c_str(),
updateWindow.c_str());
commandGroup.AddCommandString(command);
if (!mOldParameterNames.empty())
if (!m_oldParameterNames.empty())
{
command = AZStd::string::format("AnimGraphAdjustGroupParameter -animGraphID %i -name \"%s\" -parameterNames \"%s\" -action \"add\" -updateUI %s",
animGraph->GetID(),
mOldName.c_str(),
mOldParameterNames.c_str(),
m_oldName.c_str(),
m_oldParameterNames.c_str(),
updateWindow.c_str());
commandGroup.AddCommandString(command);
}
@@ -579,7 +579,7 @@ namespace CommandSystem
}
// Set the dirty flag back to the old value.
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -27,25 +27,25 @@ namespace CommandSystem
};
Action GetAction(const MCore::CommandLine& parameters);
AZStd::string mOldName; //! group parameter name before command execution.
AZStd::vector<AZStd::string> mOldGroupParameterNames;
bool mOldDirtyFlag;
AZStd::string m_oldName; //! group parameter name before command execution.
AZStd::vector<AZStd::string> m_oldGroupParameterNames;
bool m_oldDirtyFlag;
AZStd::string m_oldDescription;
MCORE_DEFINECOMMAND_END
// Add a group parameter.
MCORE_DEFINECOMMAND_START(CommandAnimGraphAddGroupParameter, "Add anim graph group parameter", true)
bool mOldDirtyFlag;
AZStd::string mOldName;
bool m_oldDirtyFlag;
AZStd::string m_oldName;
MCORE_DEFINECOMMAND_END
// Remove a group parameter.
MCORE_DEFINECOMMAND_START(CommandAnimGraphRemoveGroupParameter, "Remove anim graph group parameter", true)
AZStd::string mOldName;
AZStd::string mOldParameterNames;
AZStd::string mOldParent;
size_t mOldIndex;
bool mOldDirtyFlag;
AZStd::string m_oldName;
AZStd::string m_oldParameterNames;
AZStd::string m_oldParent;
size_t m_oldIndex;
bool m_oldDirtyFlag;
MCORE_DEFINECOMMAND_END
// helper functions
@@ -113,7 +113,7 @@ namespace CommandSystem
return EMotionFX::AnimGraphNodeId::CreateFromString(nodeIdString);
}
return mNodeId;
return m_nodeId;
}
void CommandAnimGraphCreateNode::DeleteGraphNode(EMotionFX::AnimGraphNode* node)
@@ -142,7 +142,7 @@ namespace CommandSystem
}
// store the anim graph id for undo
mAnimGraphID = animGraph->GetID();
m_animGraphId = animGraph->GetID();
// find the graph
EMotionFX::AnimGraphNode* parentNode = nullptr;
@@ -204,7 +204,7 @@ namespace CommandSystem
EMotionFX::AnimGraphNode* node = static_cast<EMotionFX::AnimGraphNode*>(object);
// store the node id for the callbacks
mNodeId = node->GetId();
m_nodeId = node->GetId();
if (parameters.CheckIfHasParameter("contents"))
{
@@ -213,7 +213,7 @@ namespace CommandSystem
MCore::ReflectionSerializer::DeserializeMembers(node, contents);
// The deserialize method will deserialize back the old id
node->SetId(mNodeId);
node->SetId(m_nodeId);
// Verify we have not serialized connections, child nodes and transitions
AZ_Assert(node->GetNumConnections() == 0, "Unexpected serialized connections");
@@ -232,7 +232,7 @@ namespace CommandSystem
const EMotionFX::AnimGraphNodeId nodeId = EMotionFX::AnimGraphNodeId::CreateFromString(nodeIdString);
node->SetId(nodeId);
mNodeId = nodeId;
m_nodeId = nodeId;
}
// if the name is not empty, set it
@@ -317,7 +317,7 @@ namespace CommandSystem
node->SetIsCollapsed(collapsed);
// store the anim graph id for undo
mAnimGraphID = animGraph->GetID();
m_animGraphId = animGraph->GetID();
// check if the parent is valid
if (parentNode)
@@ -357,7 +357,7 @@ namespace CommandSystem
}
// save the current dirty flag and tell the anim graph that something got changed
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
// return the node name
@@ -397,21 +397,21 @@ namespace CommandSystem
MCORE_UNUSED(parameters);
// get the anim graph
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mAnimGraphID);
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_animGraphId);
if (animGraph == nullptr)
{
outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", mAnimGraphID);
outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", m_animGraphId);
return false;
}
// locate the node
EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(mNodeId);
EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(m_nodeId);
if (node == nullptr)
{
return false;
}
mNodeId.SetInvalid();
m_nodeId.SetInvalid();
const AZStd::string commandString = AZStd::string::format("AnimGraphRemoveNode -animGraphID %i -name \"%s\"", animGraph->GetID(), node->GetName());
if (GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult) == false)
@@ -424,7 +424,7 @@ namespace CommandSystem
}
// set the dirty flag back to the old value
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -463,8 +463,8 @@ namespace CommandSystem
CommandAnimGraphAdjustNode::CommandAnimGraphAdjustNode(MCore::Command* orgCommand)
: MCore::Command("AnimGraphAdjustNode", orgCommand)
{
mOldPosX = 0;
mOldPosY = 0;
m_oldPosX = 0;
m_oldPosY = 0;
}
// destructor
@@ -483,7 +483,7 @@ namespace CommandSystem
}
// store the anim graph id for undo
mAnimGraphID = animGraph->GetID();
m_animGraphId = animGraph->GetID();
// get the name of the node
AZStd::string name;
@@ -506,8 +506,8 @@ namespace CommandSystem
// get the x and y pos
int32 xPos = node->GetVisualPosX();
int32 yPos = node->GetVisualPosY();
mOldPosX = xPos;
mOldPosY = yPos;
m_oldPosX = xPos;
m_oldPosY = yPos;
// get the new position values
if (parameters.CheckIfHasParameter("xPos"))
@@ -529,17 +529,17 @@ namespace CommandSystem
{
// find the node group the node was in before the name change
EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->FindNodeGroupForNode(node);
mNodeGroupName.clear();
m_nodeGroupName.clear();
if (nodeGroup)
{
// remember the node group name for undo
mNodeGroupName = nodeGroup->GetName();
m_nodeGroupName = nodeGroup->GetName();
// remove the node from the node group as its id is going to change
nodeGroup->RemoveNodeById(node->GetId());
}
mOldName = node->GetName();
m_oldName = node->GetName();
node->SetName(newName.c_str());
// as the id of the node changed after renaming it, we have to readd the node with the new id
@@ -549,27 +549,27 @@ namespace CommandSystem
}
// call the post rename node event
EMotionFX::GetEventManager().OnRenamedNode(animGraph, node, mOldName.c_str());
EMotionFX::GetEventManager().OnRenamedNode(animGraph, node, m_oldName.c_str());
}
// remember and set the new value to the enabled flag
mOldEnabled = node->GetIsEnabled();
m_oldEnabled = node->GetIsEnabled();
if (parameters.CheckIfHasParameter("enabled"))
{
node->SetIsEnabled(parameters.GetValueAsBool("enabled", this));
}
// remember and set the new value to the visualization flag
mOldVisualized = node->GetIsVisualizationEnabled();
m_oldVisualized = node->GetIsVisualizationEnabled();
if (parameters.CheckIfHasParameter("visualize"))
{
node->SetVisualization(parameters.GetValueAsBool("visualize", this));
}
mNodeId = node->GetId();
m_nodeId = node->GetId();
// save the current dirty flag and tell the anim graph that something got changed
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
// only update attributes in case it is wanted
@@ -586,22 +586,22 @@ namespace CommandSystem
bool CommandAnimGraphAdjustNode::Undo(const MCore::CommandLine& parameters, AZStd::string& outResult)
{
// get the anim graph
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mAnimGraphID);
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_animGraphId);
if (animGraph == nullptr)
{
outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", mAnimGraphID);
outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", m_animGraphId);
return false;
}
EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(mNodeId);
EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(m_nodeId);
if (node == nullptr)
{
outResult = AZStd::string::format("Cannot find node with ID %s.", mNodeId.ToString().c_str());
outResult = AZStd::string::format("Cannot find node with ID %s.", m_nodeId.ToString().c_str());
return false;
}
// restore the name
if (!mOldName.empty())
if (!m_oldName.empty())
{
AZStd::string currentName = node->GetName();
@@ -614,7 +614,7 @@ namespace CommandSystem
nodeGroup->RemoveNodeById(node->GetId());
}
node->SetName(mOldName.c_str());
node->SetName(m_oldName.c_str());
// as the id of the node changed after renaming it, we have to readd the node with the new id
if (nodeGroup)
@@ -626,12 +626,12 @@ namespace CommandSystem
EMotionFX::GetEventManager().OnRenamedNode(animGraph, node, node->GetName());
}
mNodeId = node->GetId();
node->SetVisualPos(mOldPosX, mOldPosY);
m_nodeId = node->GetId();
node->SetVisualPos(m_oldPosX, m_oldPosY);
// set the old values to the enabled flag and the visualization flag
node->SetIsEnabled(mOldEnabled);
node->SetVisualization(mOldVisualized);
node->SetIsEnabled(m_oldEnabled);
node->SetVisualization(m_oldVisualized);
// do only for parameter nodes
if (azrtti_typeid(node) == azrtti_typeid<EMotionFX::BlendTreeParameterNode>() && parameters.CheckIfHasParameter("parameterMask"))
@@ -640,11 +640,11 @@ namespace CommandSystem
EMotionFX::BlendTreeParameterNode* parameterNode = static_cast<EMotionFX::BlendTreeParameterNode*>(node);
// get the parameter mask attribute and update the mask
parameterNode->SetParameters(mOldParameterMask);
parameterNode->SetParameters(m_oldParameterMask);
}
// set the dirty flag back to the old value
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
node->Reinit();
animGraph->RecursiveInvalidateUniqueDatas();
@@ -681,7 +681,7 @@ namespace CommandSystem
CommandAnimGraphRemoveNode::CommandAnimGraphRemoveNode(MCore::Command* orgCommand)
: MCore::Command("AnimGraphRemoveNode", orgCommand)
{
mIsEntryNode = false;
m_isEntryNode = false;
}
// destructor
@@ -700,7 +700,7 @@ namespace CommandSystem
}
// store the anim graph id for undo
mAnimGraphID = animGraph->GetID();
m_animGraphId = animGraph->GetID();
// find the emfx node
AZStd::string name;
@@ -712,20 +712,20 @@ namespace CommandSystem
return false;
}
mType = azrtti_typeid(emfxNode);
mName = emfxNode->GetName();
mPosX = emfxNode->GetVisualPosX();
mPosY = emfxNode->GetVisualPosY();
mCollapsed = emfxNode->GetIsCollapsed();
mOldContents = MCore::ReflectionSerializer::SerializeMembersExcept(emfxNode, { "childNodes", "connections", "transitions" }).GetValue();
mNodeId = emfxNode->GetId();
m_type = azrtti_typeid(emfxNode);
m_name = emfxNode->GetName();
m_posX = emfxNode->GetVisualPosX();
m_posY = emfxNode->GetVisualPosY();
m_collapsed = emfxNode->GetIsCollapsed();
m_oldContents = MCore::ReflectionSerializer::SerializeMembersExcept(emfxNode, { "childNodes", "connections", "transitions" }).GetValue();
m_nodeId = emfxNode->GetId();
// remember the node group for the node for undo
mNodeGroupName.clear();
m_nodeGroupName.clear();
EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->FindNodeGroupForNode(emfxNode);
if (nodeGroup)
{
mNodeGroupName = nodeGroup->GetName();
m_nodeGroupName = nodeGroup->GetName();
}
// get the parent node
@@ -737,7 +737,7 @@ namespace CommandSystem
EMotionFX::AnimGraphStateMachine* stateMachine = static_cast<EMotionFX::AnimGraphStateMachine*>(parentNode);
if (stateMachine->GetEntryState() == emfxNode)
{
mIsEntryNode = true;
m_isEntryNode = true;
// Find a new entry node if we can
//--------------------------
@@ -766,8 +766,8 @@ namespace CommandSystem
}
}
mParentName = parentNode->GetName();
mParentNodeId = parentNode->GetId();
m_parentName = parentNode->GetName();
m_parentNodeId = parentNode->GetId();
// call the pre remove node event
EMotionFX::GetEventManager().OnRemoveNode(animGraph, emfxNode);
@@ -780,15 +780,15 @@ namespace CommandSystem
}
else
{
mParentNodeId.SetInvalid();
mParentName.clear();
m_parentNodeId.SetInvalid();
m_parentName.clear();
MCore::LogError("Cannot remove root state machine.");
MCORE_ASSERT(false);
return false;
}
// save the current dirty flag and tell the anim graph that something got changed
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
animGraph->RecursiveInvalidateUniqueDatas();
@@ -801,34 +801,34 @@ namespace CommandSystem
{
MCORE_UNUSED(parameters);
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mAnimGraphID);
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_animGraphId);
if (!animGraph)
{
outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", mAnimGraphID);
outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", m_animGraphId);
return false;
}
// create the node again
MCore::CommandGroup group("Recreating node");
AZStd::string commandString;
if (!mParentName.empty())
if (!m_parentName.empty())
{
commandString = AZStd::string::format("AnimGraphCreateNode -animGraphID %i -type \"%s\" -parentName \"%s\" -name \"%s\" -nodeId \"%s\" -xPos %d -yPos %d -collapsed %s -center false -contents {%s}",
animGraph->GetID(),
mType.ToString<AZStd::string>().c_str(),
mParentName.c_str(),
mName.c_str(),
mNodeId.ToString().c_str(),
mPosX,
mPosY,
AZStd::to_string(mCollapsed).c_str(),
mOldContents.c_str());
m_type.ToString<AZStd::string>().c_str(),
m_parentName.c_str(),
m_name.c_str(),
m_nodeId.ToString().c_str(),
m_posX,
m_posY,
AZStd::to_string(m_collapsed).c_str(),
m_oldContents.c_str());
group.AddCommandString(commandString);
if (mIsEntryNode)
if (m_isEntryNode)
{
commandString = AZStd::string::format("AnimGraphSetEntryState -animGraphID %i -entryNodeName \"%s\"", animGraph->GetID(), mName.c_str());
commandString = AZStd::string::format("AnimGraphSetEntryState -animGraphID %i -entryNodeName \"%s\"", animGraph->GetID(), m_name.c_str());
group.AddCommandString(commandString);
}
}
@@ -836,13 +836,13 @@ namespace CommandSystem
{
commandString = AZStd::string::format("AnimGraphCreateNode -animGraphID %i -type \"%s\" -name \"%s\" -nodeId \"%s\" -xPos %d -yPos %d -collapsed %s -center false -contents {%s}",
animGraph->GetID(),
mType.ToString<AZStd::string>().c_str(),
mName.c_str(),
mNodeId.ToString().c_str(),
mPosX,
mPosY,
AZStd::to_string(mCollapsed).c_str(),
mOldContents.c_str());
m_type.ToString<AZStd::string>().c_str(),
m_name.c_str(),
m_nodeId.ToString().c_str(),
m_posX,
m_posY,
AZStd::to_string(m_collapsed).c_str(),
m_oldContents.c_str());
group.AddCommandString(commandString);
}
@@ -857,15 +857,15 @@ namespace CommandSystem
}
// add it to the old node group if it was assigned to one before
if (!mNodeGroupName.empty())
if (!m_nodeGroupName.empty())
{
auto* command = aznew CommandSystem::CommandAnimGraphAdjustNodeGroup(
GetCommandManager()->FindCommand(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName),
/*animGraphId = */ animGraph->GetID(),
/*name = */ mNodeGroupName,
/*name = */ m_nodeGroupName,
/*visible = */ AZStd::nullopt,
/*newName = */ AZStd::nullopt,
/*nodeNames = */ {{mName}},
/*nodeNames = */ {{m_name}},
/*nodeAction = */ CommandSystem::CommandAnimGraphAdjustNodeGroup::NodeAction::Add
);
if (GetCommandManager()->ExecuteCommandInsideCommand(command, outResult) == false)
@@ -880,7 +880,7 @@ namespace CommandSystem
}
// set the dirty flag back to the old value
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -925,7 +925,7 @@ namespace CommandSystem
}
// store the anim graph id for undo
mAnimGraphID = animGraph->GetID();
m_animGraphId = animGraph->GetID();
AZStd::string entryNodeName;
parameters.GetValue("entryNodeName", this, entryNodeName);
@@ -960,21 +960,21 @@ namespace CommandSystem
EMotionFX::AnimGraphNode* oldEntryNode = stateMachine->GetEntryState();
if (oldEntryNode)
{
mOldEntryStateNodeId = oldEntryNode->GetId();
m_oldEntryStateNodeId = oldEntryNode->GetId();
}
else
{
mOldEntryStateNodeId.SetInvalid();
m_oldEntryStateNodeId.SetInvalid();
}
// store the id of the state machine
mOldStateMachineNodeId = stateMachineNode->GetId();
m_oldStateMachineNodeId = stateMachineNode->GetId();
// set the new entry state for the state machine
stateMachine->SetEntryState(entryNode);
// save the current dirty flag and tell the anim graph that something got changed
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
stateMachine->Reinit();
@@ -989,15 +989,15 @@ namespace CommandSystem
MCORE_UNUSED(parameters);
// get the anim graph
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mAnimGraphID);
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_animGraphId);
if (animGraph == nullptr)
{
outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", mAnimGraphID);
outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", m_animGraphId);
return false;
}
// get the state machine
EMotionFX::AnimGraphNode* stateMachineNode = animGraph->RecursiveFindNodeById(mOldStateMachineNodeId);
EMotionFX::AnimGraphNode* stateMachineNode = animGraph->RecursiveFindNodeById(m_oldStateMachineNodeId);
if (stateMachineNode == nullptr || azrtti_typeid(stateMachineNode) != azrtti_typeid<EMotionFX::AnimGraphStateMachine>())
{
outResult = "Cannot undo set entry node. Parent node is not a state machine or not valid at all.";
@@ -1008,9 +1008,9 @@ namespace CommandSystem
EMotionFX::AnimGraphStateMachine* stateMachine = (EMotionFX::AnimGraphStateMachine*)stateMachineNode;
// find the entry anim graph node
if (mOldEntryStateNodeId.IsValid())
if (m_oldEntryStateNodeId.IsValid())
{
EMotionFX::AnimGraphNode* entryNode = animGraph->RecursiveFindNodeById(mOldEntryStateNodeId);
EMotionFX::AnimGraphNode* entryNode = animGraph->RecursiveFindNodeById(m_oldEntryStateNodeId);
if (!entryNode)
{
outResult = "Cannot undo set entry node. Old entry node cannot be found.";
@@ -1027,7 +1027,7 @@ namespace CommandSystem
}
// set the dirty flag back to the old value
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
stateMachine->Reinit();
animGraph->RecursiveInvalidateUniqueDatas();
@@ -25,60 +25,60 @@ public:
EMotionFX::AnimGraphNodeId GetNodeId(const MCore::CommandLine& parameters);
void DeleteGraphNode(EMotionFX::AnimGraphNode* node);
uint32 mAnimGraphID;
bool mOldDirtyFlag;
EMotionFX::AnimGraphNodeId mNodeId;
uint32 m_animGraphId;
bool m_oldDirtyFlag;
EMotionFX::AnimGraphNodeId m_nodeId;
MCORE_DEFINECOMMAND_END
// adjust a node
MCORE_DEFINECOMMAND_START(CommandAnimGraphAdjustNode, "Adjust a anim graph node", true)
EMotionFX::AnimGraphNodeId mNodeId;
int32 mOldPosX;
int32 mOldPosY;
AZStd::string mOldName;
AZStd::string mOldParameterMask;
bool mOldDirtyFlag;
bool mOldEnabled;
bool mOldVisualized;
AZStd::string mNodeGroupName;
EMotionFX::AnimGraphNodeId m_nodeId;
int32 m_oldPosX;
int32 m_oldPosY;
AZStd::string m_oldName;
AZStd::string m_oldParameterMask;
bool m_oldDirtyFlag;
bool m_oldEnabled;
bool m_oldVisualized;
AZStd::string m_nodeGroupName;
public:
EMotionFX::AnimGraphNodeId GetNodeId() const { return mNodeId; }
const AZStd::string& GetOldName() const { return mOldName; }
uint32 mAnimGraphID;
EMotionFX::AnimGraphNodeId GetNodeId() const { return m_nodeId; }
const AZStd::string& GetOldName() const { return m_oldName; }
uint32 m_animGraphId;
MCORE_DEFINECOMMAND_END
// remove a node
MCORE_DEFINECOMMAND_START(CommandAnimGraphRemoveNode, "Remove a anim graph node", true)
EMotionFX::AnimGraphNodeId mNodeId;
uint32 mAnimGraphID;
EMotionFX::AnimGraphNodeId mParentNodeId;
AZ::TypeId mType;
AZStd::string mParentName;
AZStd::string mName;
AZStd::string mNodeGroupName;
int32 mPosX;
int32 mPosY;
AZStd::string mOldContents;
bool mCollapsed;
bool mOldDirtyFlag;
bool mIsEntryNode;
EMotionFX::AnimGraphNodeId m_nodeId;
uint32 m_animGraphId;
EMotionFX::AnimGraphNodeId m_parentNodeId;
AZ::TypeId m_type;
AZStd::string m_parentName;
AZStd::string m_name;
AZStd::string m_nodeGroupName;
int32 m_posX;
int32 m_posY;
AZStd::string m_oldContents;
bool m_collapsed;
bool m_oldDirtyFlag;
bool m_isEntryNode;
public:
EMotionFX::AnimGraphNodeId GetNodeId() const { return mNodeId; }
EMotionFX::AnimGraphNodeId GetParentNodeId() const { return mParentNodeId; }
EMotionFX::AnimGraphNodeId GetNodeId() const { return m_nodeId; }
EMotionFX::AnimGraphNodeId GetParentNodeId() const { return m_parentNodeId; }
MCORE_DEFINECOMMAND_END
// set the entry state of a state machine
MCORE_DEFINECOMMAND_START(CommandAnimGraphSetEntryState, "Set entry state", true)
public:
uint32 mAnimGraphID;
EMotionFX::AnimGraphNodeId mOldEntryStateNodeId;
EMotionFX::AnimGraphNodeId mOldStateMachineNodeId;
bool mOldDirtyFlag;
uint32 m_animGraphId;
EMotionFX::AnimGraphNodeId m_oldEntryStateNodeId;
EMotionFX::AnimGraphNodeId m_oldStateMachineNodeId;
bool m_oldDirtyFlag;
MCORE_DEFINECOMMAND_END
@@ -334,8 +334,8 @@ namespace CommandSystem
nodeGroup->SetColor(color.ToU32());
// save the current dirty flag and tell the anim graph that something got changed
mOldDirtyFlag = animGraph->GetDirtyFlag();
mOldName = nodeGroup->GetName();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
m_oldName = nodeGroup->GetName();
animGraph->SetDirtyFlag(true);
return true;
}
@@ -349,7 +349,7 @@ namespace CommandSystem
return false;
}
AZStd::string commandString = AZStd::string::format("AnimGraphRemoveNodeGroup -animGraphID %i -name \"%s\"", animGraph->GetID(), mOldName.c_str());
AZStd::string commandString = AZStd::string::format("AnimGraphRemoveNodeGroup -animGraphID %i -name \"%s\"", animGraph->GetID(), m_oldName.c_str());
// execute the command
AZStd::string result;
@@ -359,7 +359,7 @@ namespace CommandSystem
}
// set the dirty flag back to the old value
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -413,16 +413,16 @@ namespace CommandSystem
// read out information for the command undo
EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->GetNodeGroup(groupIndex);
mOldName = nodeGroup->GetName();
mOldColor = nodeGroup->GetColor();
mOldIsVisible = nodeGroup->GetIsVisible();
mOldNodeIds = CommandAnimGraphAdjustNodeGroup::CollectNodeIdsFromGroup(nodeGroup);
m_oldName = nodeGroup->GetName();
m_oldColor = nodeGroup->GetColor();
m_oldIsVisible = nodeGroup->GetIsVisible();
m_oldNodeIds = CommandAnimGraphAdjustNodeGroup::CollectNodeIdsFromGroup(nodeGroup);
// remove the node group
animGraph->RemoveNodeGroup(groupIndex);
// save the current dirty flag and tell the anim graph that something got changed
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
return true;
}
@@ -439,17 +439,17 @@ namespace CommandSystem
MCore::CommandGroup commandGroup;
commandGroup.AddCommandString(AZStd::string::format("AnimGraphAddNodeGroup -animGraphID %i -name \"%s\" -updateUI %s",animGraph->GetID(), mOldName.c_str(), updateWindow.c_str()));
commandGroup.AddCommandString(AZStd::string::format("AnimGraphAddNodeGroup -animGraphID %i -name \"%s\" -updateUI %s",animGraph->GetID(), m_oldName.c_str(), updateWindow.c_str()));
auto* command = aznew CommandAnimGraphAdjustNodeGroup(
GetCommandManager()->FindCommand(CommandAnimGraphAdjustNodeGroup::s_commandName),
/*animGraphId = */ animGraph->GetID(),
/*name = */ mOldName,
/*visible = */ mOldIsVisible,
/*name = */ m_oldName,
/*visible = */ m_oldIsVisible,
/*newName = */ AZStd::nullopt,
/*nodeNames = */ CommandAnimGraphAdjustNodeGroup::GenerateNodeNameVector(animGraph, mOldNodeIds),
/*nodeNames = */ CommandAnimGraphAdjustNodeGroup::GenerateNodeNameVector(animGraph, m_oldNodeIds),
/*nodeAction = */ CommandAnimGraphAdjustNodeGroup::NodeAction::Add,
/*color = */ mOldColor
/*color = */ m_oldColor
);
commandGroup.AddCommand(command);
@@ -461,7 +461,7 @@ namespace CommandSystem
}
// set the dirty flag back to the old value
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -83,18 +83,18 @@ namespace CommandSystem
// add node group
MCORE_DEFINECOMMAND_START(CommandAnimGraphAddNodeGroup, "Add anim graph node group", true)
bool mOldDirtyFlag;
AZStd::string mOldName;
bool m_oldDirtyFlag;
AZStd::string m_oldName;
MCORE_DEFINECOMMAND_END
// remove a node group
MCORE_DEFINECOMMAND_START(CommandAnimGraphRemoveNodeGroup, "Remove anim graph node group", true)
AZStd::string mOldName;
bool mOldIsVisible;
AZ::u32 mOldColor;
AZStd::vector<EMotionFX::AnimGraphNodeId> mOldNodeIds;
bool mOldDirtyFlag;
AZStd::string m_oldName;
bool m_oldIsVisible;
AZ::u32 m_oldColor;
AZStd::vector<EMotionFX::AnimGraphNodeId> m_oldNodeIds;
bool m_oldDirtyFlag;
MCORE_DEFINECOMMAND_END
// helper function
@@ -188,7 +188,7 @@ namespace CommandSystem
outResult = name.c_str();
// Save the current dirty flag and tell the anim graph that something got changed.
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
return true;
@@ -219,7 +219,7 @@ namespace CommandSystem
}
// Set the dirty flag back to the old value.
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -258,22 +258,22 @@ namespace CommandSystem
bool CommandAnimGraphRemoveParameter::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult)
{
// Get the parameter name.
parameters.GetValue("name", this, mName);
parameters.GetValue("name", this, m_name);
// Find the anim graph by using the id from command parameter.
const uint32 animGraphID = parameters.GetValueAsInt("animGraphID", this);
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(animGraphID);
if (!animGraph)
{
outResult = AZStd::string::format("Cannot remove parameter '%s' from anim graph. Anim graph id '%i' is not valid.", mName.c_str(), animGraphID);
outResult = AZStd::string::format("Cannot remove parameter '%s' from anim graph. Anim graph id '%i' is not valid.", m_name.c_str(), animGraphID);
return false;
}
// Check if there is a parameter with the given name.
const EMotionFX::Parameter* parameter = animGraph->FindParameterByName(mName);
const EMotionFX::Parameter* parameter = animGraph->FindParameterByName(m_name);
if (!parameter)
{
outResult = AZStd::string::format("Cannot remove parameter '%s' from anim graph. There is no parameter with the given name.", mName.c_str());
outResult = AZStd::string::format("Cannot remove parameter '%s' from anim graph. There is no parameter with the given name.", m_name.c_str());
return false;
}
AZ_Assert(azrtti_typeid(parameter) != azrtti_typeid<EMotionFX::GroupParameter>(), "CommmandAnimGraphRemoveParameter called for a group parameter");
@@ -284,13 +284,13 @@ namespace CommandSystem
AZ_Assert(parameterIndex.IsSuccess(), "Expected valid parameter index");
// Store undo info before we remove it, so that we can recreate it later.
mType = azrtti_typeid(parameter);
mIndex = parameterIndex.GetValue();
mParent = parentGroup ? parentGroup->GetName() : "";
mContents = MCore::ReflectionSerializer::Serialize(parameter).GetValue();
m_type = azrtti_typeid(parameter);
m_index = parameterIndex.GetValue();
m_parent = parentGroup ? parentGroup->GetName() : "";
m_contents = MCore::ReflectionSerializer::Serialize(parameter).GetValue();
AZ::Outcome<size_t> valueParameterIndex = AZ::Failure();
if (mType != azrtti_typeid<EMotionFX::GroupParameter>())
if (m_type != azrtti_typeid<EMotionFX::GroupParameter>())
{
valueParameterIndex = animGraph->FindValueParameterIndex(static_cast<const EMotionFX::ValueParameter*>(parameter));
}
@@ -299,7 +299,7 @@ namespace CommandSystem
if (animGraph->RemoveParameter(const_cast<EMotionFX::Parameter*>(parameter)))
{
// Remove the parameter from all corresponding anim graph instances if it is a value parameter
if (mType != azrtti_typeid<EMotionFX::GroupParameter>())
if (m_type != azrtti_typeid<EMotionFX::GroupParameter>())
{
AZStd::vector<EMotionFX::AnimGraphObject*> affectedObjects;
animGraph->RecursiveCollectObjectsOfType(azrtti_typeid<EMotionFX::ObjectAffectedByParameterChanges>(), affectedObjects);
@@ -308,7 +308,7 @@ namespace CommandSystem
for (EMotionFX::AnimGraphObject* affectedObject : affectedObjects)
{
EMotionFX::ObjectAffectedByParameterChanges* parameterDriven = azdynamic_cast<EMotionFX::ObjectAffectedByParameterChanges*>(affectedObject);
parameterDriven->ParameterRemoved(mName);
parameterDriven->ParameterRemoved(m_name);
}
const size_t numInstances = animGraph->GetNumAnimGraphInstances();
@@ -320,7 +320,7 @@ namespace CommandSystem
}
// Save the current dirty flag and tell the anim graph that something got changed.
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
}
return true;
@@ -336,7 +336,7 @@ namespace CommandSystem
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(animGraphID);
if (!animGraph)
{
outResult = AZStd::string::format("Cannot undo remove parameter '%s' from anim graph. Anim graph id '%i' is not valid.", mName.c_str(), animGraphID);
outResult = AZStd::string::format("Cannot undo remove parameter '%s' from anim graph. Anim graph id '%i' is not valid.", m_name.c_str(), animGraphID);
return false;
}
@@ -347,11 +347,11 @@ namespace CommandSystem
commandString = AZStd::string::format("AnimGraphCreateParameter -animGraphID %i -name \"%s\" -index %zu -type \"%s\" -contents {%s} -parent \"%s\" -updateUI %s",
animGraph->GetID(),
mName.c_str(),
mIndex,
mType.ToString<AZStd::string>().c_str(),
mContents.c_str(),
mParent.c_str(),
m_name.c_str(),
m_index,
m_type.ToString<AZStd::string>().c_str(),
m_contents.c_str(),
m_parent.c_str(),
updateUI.c_str());
// The parameter will be restored to the right parent group because the index is absolute
@@ -364,7 +364,7 @@ namespace CommandSystem
}
// Set the dirty flag back to the old value.
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -399,21 +399,21 @@ namespace CommandSystem
bool CommandAnimGraphAdjustParameter::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult)
{
// Get the parameter name.
parameters.GetValue("name", this, mOldName);
parameters.GetValue("name", this, m_oldName);
// Find the anim graph by using the id from command parameter.
const uint32 animGraphID = parameters.GetValueAsInt("animGraphID", this);
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(animGraphID);
if (!animGraph)
{
outResult = AZStd::string::format("Cannot adjust parameter '%s'. Anim graph with id '%d' not found.", mOldName.c_str(), animGraphID);
outResult = AZStd::string::format("Cannot adjust parameter '%s'. Anim graph with id '%d' not found.", m_oldName.c_str(), animGraphID);
return false;
}
const EMotionFX::Parameter* parameter = animGraph->FindParameterByName(mOldName);
const EMotionFX::Parameter* parameter = animGraph->FindParameterByName(m_oldName);
if (!parameter)
{
outResult = AZStd::string::format("There is no parameter with the name '%s'.", mOldName.c_str());
outResult = AZStd::string::format("There is no parameter with the name '%s'.", m_oldName.c_str());
return false;
}
AZ::Outcome<size_t> oldValueParameterIndex = AZ::Failure();
@@ -426,15 +426,15 @@ namespace CommandSystem
const EMotionFX::GroupParameter* currentParent = animGraph->FindParentGroupParameter(parameter);
// Store the undo info.
mOldType = azrtti_typeid(parameter);
mOldContents = MCore::ReflectionSerializer::Serialize(parameter).GetValue();
m_oldType = azrtti_typeid(parameter);
m_oldContents = MCore::ReflectionSerializer::Serialize(parameter).GetValue();
// Get the new name and check if it is valid.
AZStd::string newName;
parameters.GetValue("newName", this, newName);
if (!newName.empty())
{
if (newName == mOldName)
if (newName == m_oldName)
{
newName.clear();
}
@@ -461,10 +461,10 @@ namespace CommandSystem
outResult = AZStd::string::format("The type is not a valid UUID type. Please use -help or use the command browser to see a list of valid options.");
return false;
}
if (type != mOldType)
if (type != m_oldType)
{
AZStd::unique_ptr<EMotionFX::Parameter> newParameter(EMotionFX::ParameterFactory::Create(type));
newParameter->SetName(newName.empty() ? mOldName : newName);
newParameter->SetName(newName.empty() ? m_oldName : newName);
newParameter->SetDescription(parameter->GetDescription());
const AZ::Outcome<size_t> paramIndexRelativeToParent = currentParent ? currentParent->FindRelativeParameterIndex(parameter) : animGraph->FindRelativeParameterIndex(parameter);
@@ -472,7 +472,7 @@ namespace CommandSystem
if (!animGraph->RemoveParameter(const_cast<EMotionFX::Parameter*>(parameter)))
{
outResult = AZStd::string::format("Could not remove current parameter '%s' to change its type.", mOldName.c_str());
outResult = AZStd::string::format("Could not remove current parameter '%s' to change its type.", m_oldName.c_str());
return false;
}
if (!animGraph->InsertParameter(paramIndexRelativeToParent.GetValue(), newParameter.get(), currentParent))
@@ -525,7 +525,7 @@ namespace CommandSystem
{
EMotionFX::AnimGraphInstance* animGraphInstance = animGraph->GetAnimGraphInstance(i);
// reinit the modified parameters
if (mOldType != azrtti_typeid<EMotionFX::GroupParameter>())
if (m_oldType != azrtti_typeid<EMotionFX::GroupParameter>())
{
animGraphInstance->ReInitParameterValue(valueParameterIndex.GetValue());
}
@@ -547,7 +547,7 @@ namespace CommandSystem
for (EMotionFX::AnimGraphObject* affectedObject : affectedObjects)
{
EMotionFX::ObjectAffectedByParameterChanges* affectedObjectByParameterChanges = azdynamic_cast<EMotionFX::ObjectAffectedByParameterChanges*>(affectedObject);
affectedObjectByParameterChanges->ParameterRenamed(mOldName, newName);
affectedObjectByParameterChanges->ParameterRenamed(m_oldName, newName);
}
}
}
@@ -561,16 +561,16 @@ namespace CommandSystem
for (EMotionFX::AnimGraphObject* affectedObject : affectedObjects)
{
EMotionFX::ObjectAffectedByParameterChanges* affectedObjectByParameterChanges = azdynamic_cast<EMotionFX::ObjectAffectedByParameterChanges*>(affectedObject);
affectedObjectByParameterChanges->ParameterRemoved(mOldName);
affectedObjectByParameterChanges->ParameterRemoved(m_oldName);
affectedObjectByParameterChanges->ParameterAdded(newName);
}
}
// Save the current dirty flag and tell the anim graph that something got changed.
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
}
else if (mOldType != azrtti_typeid<EMotionFX::GroupParameter>())
else if (m_oldType != azrtti_typeid<EMotionFX::GroupParameter>())
{
AZ_Assert(oldValueParameterIndex.IsSuccess(), "Unable to find parameter index when changing parameter to a group");
@@ -582,11 +582,11 @@ namespace CommandSystem
for (EMotionFX::AnimGraphObject* affectedObject : affectedObjects)
{
EMotionFX::ObjectAffectedByParameterChanges* affectedObjectByParameterChanges = azdynamic_cast<EMotionFX::ObjectAffectedByParameterChanges*>(affectedObject);
affectedObjectByParameterChanges->ParameterRemoved(mOldName);
affectedObjectByParameterChanges->ParameterRemoved(m_oldName);
}
// Save the current dirty flag and tell the anim graph that something got changed.
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
}
@@ -638,15 +638,15 @@ namespace CommandSystem
animGraph->GetID(),
newName.c_str(),
name.c_str(),
mOldType.ToString<AZStd::string>().c_str(),
mOldContents.c_str());
m_oldType.ToString<AZStd::string>().c_str(),
m_oldContents.c_str());
if (!GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult))
{
AZ_Error("EMotionFX", false, outResult.c_str());
}
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -728,13 +728,13 @@ namespace CommandSystem
const EMotionFX::GroupParameter* currentParent = animGraph->FindParentGroupParameter(parameter);
if (currentParent)
{
mOldParent = currentParent->GetName();
mOldIndex = currentParent->FindRelativeParameterIndex(parameter).GetValue();
m_oldParent = currentParent->GetName();
m_oldIndex = currentParent->FindRelativeParameterIndex(parameter).GetValue();
}
else
{
mOldParent.clear(); // means the root
mOldIndex = animGraph->FindRelativeParameterIndex(parameter).GetValue();
m_oldParent.clear(); // means the root
m_oldIndex = animGraph->FindRelativeParameterIndex(parameter).GetValue();
}
EMotionFX::ValueParameterVector valueParametersBeforeChange = animGraph->RecursivelyGetValueParameters();
@@ -789,7 +789,7 @@ namespace CommandSystem
}
// Save the current dirty flag and tell the anim graph that something got changed.
mOldDirtyFlag = animGraph->GetDirtyFlag();
m_oldDirtyFlag = animGraph->GetDirtyFlag();
animGraph->SetDirtyFlag(true);
return true;
@@ -813,10 +813,10 @@ namespace CommandSystem
AZStd::string commandString = AZStd::string::format("AnimGraphMoveParameter -animGraphID %i -name \"%s\" -index %zu",
animGraphID,
name.c_str(),
mOldIndex);
if (!mOldParent.empty())
m_oldIndex);
if (!m_oldParent.empty())
{
commandString += AZStd::string::format(" -parent \"%s\"", mOldParent.c_str());
commandString += AZStd::string::format(" -parent \"%s\"", m_oldParent.c_str());
}
if (!GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult))
@@ -825,7 +825,7 @@ namespace CommandSystem
return false;
}
animGraph->SetDirtyFlag(mOldDirtyFlag);
animGraph->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -22,35 +22,35 @@ namespace CommandSystem
{
// Create a new anim graph parameter.
MCORE_DEFINECOMMAND_START(CommandAnimGraphCreateParameter, "Create an anim graph parameter", true)
bool mOldDirtyFlag;
bool m_oldDirtyFlag;
MCORE_DEFINECOMMAND_END
// Remove a given anim graph parameter.
MCORE_DEFINECOMMAND_START(CommandAnimGraphRemoveParameter, "Remove an anim graph parameter", true)
size_t mIndex;
AZ::TypeId mType;
AZStd::string mName;
AZStd::string mContents;
AZStd::string mParent;
bool mOldDirtyFlag;
size_t m_index;
AZ::TypeId m_type;
AZStd::string m_name;
AZStd::string m_contents;
AZStd::string m_parent;
bool m_oldDirtyFlag;
MCORE_DEFINECOMMAND_END
// Adjust a given anim graph parameter.
MCORE_DEFINECOMMAND_START(CommandAnimGraphAdjustParameter, "Adjust an anim graph parameter", true)
AZ::TypeId mOldType;
AZStd::string mOldName;
AZStd::string mOldContents;
bool mOldDirtyFlag;
AZ::TypeId m_oldType;
AZStd::string m_oldName;
AZStd::string m_oldContents;
bool m_oldDirtyFlag;
MCORE_DEFINECOMMAND_END
// Move the parameter to another position.
MCORE_DEFINECOMMAND_START(CommandAnimGraphMoveParameter, "Move an anim graph parameter", true)
AZStd::string mOldParent;
size_t mOldIndex;
bool mOldDirtyFlag;
AZStd::string m_oldParent;
size_t m_oldIndex;
bool m_oldDirtyFlag;
MCORE_DEFINECOMMAND_END
//////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -59,18 +59,18 @@ namespace CommandSystem
struct COMMANDSYSTEM_API ParameterConnectionItem
{
void SetParameterNodeName(const char* name) { mParameterNodeNameID = MCore::GetStringIdPool().GenerateIdForString(name); }
void SetTargetNodeName(const char* name) { mTargetNodeNameID = MCore::GetStringIdPool().GenerateIdForString(name); }
void SetParameterName(const char* name) { mParameterNameID = MCore::GetStringIdPool().GenerateIdForString(name); }
void SetParameterNodeName(const char* name) { m_parameterNodeNameId = MCore::GetStringIdPool().GenerateIdForString(name); }
void SetTargetNodeName(const char* name) { m_targetNodeNameId = MCore::GetStringIdPool().GenerateIdForString(name); }
void SetParameterName(const char* name) { m_parameterNameId = MCore::GetStringIdPool().GenerateIdForString(name); }
const char* GetParameterNodeName() const { return MCore::GetStringIdPool().GetName(mParameterNodeNameID).c_str(); }
const char* GetTargetNodeName() const { return MCore::GetStringIdPool().GetName(mTargetNodeNameID).c_str(); }
const char* GetParameterName() const { return MCore::GetStringIdPool().GetName(mParameterNameID).c_str(); }
const char* GetParameterNodeName() const { return MCore::GetStringIdPool().GetName(m_parameterNodeNameId).c_str(); }
const char* GetTargetNodeName() const { return MCore::GetStringIdPool().GetName(m_targetNodeNameId).c_str(); }
const char* GetParameterName() const { return MCore::GetStringIdPool().GetName(m_parameterNameId).c_str(); }
private:
uint32 mParameterNodeNameID;
uint32 mTargetNodeNameID;
uint32 mParameterNameID;
uint32 m_parameterNodeNameId;
uint32 m_targetNodeNameId;
uint32 m_parameterNameId;
};
COMMANDSYSTEM_API void RemoveConnectionsForParameter(EMotionFX::AnimGraph* animGraph, const char* parameterName, MCore::CommandGroup& commandGroup);
@@ -147,8 +147,8 @@ namespace CommandSystem
RegisterCommand(new CommandRecorderClear());
gCommandManager = this;
mLockSelection = false;
mWorkspaceDirtyFlag = false;
m_lockSelection = false;
m_workspaceDirtyFlag = false;
}
CommandManager::~CommandManager()
@@ -33,28 +33,28 @@ namespace CommandSystem
* Get current selection.
* @return The selection list containing all selected actors, motions and nodes.
*/
MCORE_INLINE SelectionList& GetCurrentSelection() { mCurrentSelection.MakeValid(); return mCurrentSelection; }
MCORE_INLINE SelectionList& GetCurrentSelection() { m_currentSelection.MakeValid(); return m_currentSelection; }
/**
* Set current selection.
* @param selection The selection list containing all selected actors, motions and nodes.
*/
MCORE_INLINE void SetCurrentSelection(SelectionList& selection) { mCurrentSelection.Clear(); mCurrentSelection.Add(selection); }
MCORE_INLINE void SetCurrentSelection(SelectionList& selection) { m_currentSelection.Clear(); m_currentSelection.Add(selection); }
MCORE_INLINE bool GetLockSelection() const { return mLockSelection; }
void SetLockSelection(bool lockSelection) { mLockSelection = lockSelection; }
MCORE_INLINE bool GetLockSelection() const { return m_lockSelection; }
void SetLockSelection(bool lockSelection) { m_lockSelection = lockSelection; }
void SetWorkspaceDirtyFlag(bool dirty) { mWorkspaceDirtyFlag = dirty; }
MCORE_INLINE bool GetWorkspaceDirtyFlag() const { return mWorkspaceDirtyFlag; }
void SetWorkspaceDirtyFlag(bool dirty) { m_workspaceDirtyFlag = dirty; }
MCORE_INLINE bool GetWorkspaceDirtyFlag() const { return m_workspaceDirtyFlag; }
// Only true when user create or open a workspace.
void SetUserOpenedWorkspaceFlag(bool flag);
bool GetUserOpenedWorkspaceFlag() const { return m_userOpenedWorkspaceFlag; }
private:
SelectionList mCurrentSelection; /**< The current selected actors, motions and nodes. */
bool mLockSelection;
bool mWorkspaceDirtyFlag;
SelectionList m_currentSelection; /**< The current selected actors, motions and nodes. */
bool m_lockSelection;
bool m_workspaceDirtyFlag;
bool m_userOpenedWorkspaceFlag = false;
};
@@ -29,7 +29,7 @@ namespace CommandSystem
CommandImportActor::CommandImportActor(MCore::Command* orgCommand)
: MCore::Command("ImportActor", orgCommand)
{
mPreviouslyUsedID = MCORE_INVALIDINDEX32;
m_previouslyUsedId = MCORE_INVALIDINDEX32;
}
@@ -77,10 +77,10 @@ namespace CommandSystem
EMotionFX::Importer::ActorSettings settings;
// extract default values from the command syntax automatically, if they aren't specified explicitly
settings.mLoadLimits = parameters.GetValueAsBool("loadLimits", this);
settings.mLoadMorphTargets = parameters.GetValueAsBool("loadMorphTargets", this);
settings.mLoadSkeletalLODs = parameters.GetValueAsBool("loadSkeletalLODs", this);
settings.mDualQuatSkinning = parameters.GetValueAsBool("dualQuatSkinning", this);
settings.m_loadLimits = parameters.GetValueAsBool("loadLimits", this);
settings.m_loadMorphTargets = parameters.GetValueAsBool("loadMorphTargets", this);
settings.m_loadSkeletalLoDs = parameters.GetValueAsBool("loadSkeletalLODs", this);
settings.m_dualQuatSkinning = parameters.GetValueAsBool("dualQuatSkinning", this);
// try to load the actor
AZStd::shared_ptr<EMotionFX::Actor> actor {EMotionFX::GetImporter().LoadActor(filename.c_str(), &settings)};
@@ -101,11 +101,11 @@ namespace CommandSystem
}
// in case we are in a redo call assign the previously used id
if (mPreviouslyUsedID != MCORE_INVALIDINDEX32)
if (m_previouslyUsedId != MCORE_INVALIDINDEX32)
{
actor->SetID(mPreviouslyUsedID);
actor->SetID(m_previouslyUsedId);
}
mPreviouslyUsedID = actor->GetID();
m_previouslyUsedId = actor->GetID();
// select the actor automatically
if (parameters.GetValueAsBool("autoSelect", this))
@@ -115,7 +115,7 @@ namespace CommandSystem
// mark the workspace as dirty
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
GetCommandManager()->SetWorkspaceDirtyFlag(true);
// return the id of the newly created actor
@@ -134,7 +134,7 @@ namespace CommandSystem
uint32 actorID = parameters.GetValueAsInt("actorID", MCORE_INVALIDINDEX32);
if (actorID == MCORE_INVALIDINDEX32)
{
actorID = mPreviouslyUsedID;
actorID = m_previouslyUsedId;
}
// check if we have to unselect the actors created by this command
@@ -159,7 +159,7 @@ namespace CommandSystem
GetCommandManager()->ExecuteCommandInsideCommand("UpdateRenderActors", updateRenderActorsResult);
// restore the workspace dirty flag
GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag);
GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag);
return true;
}
@@ -203,7 +203,7 @@ namespace CommandSystem
CommandImportMotion::CommandImportMotion(MCore::Command* orgCommand)
: MCore::Command("ImportMotion", orgCommand)
{
mOldMotionID = MCORE_INVALIDINDEX32;
m_oldMotionId = MCORE_INVALIDINDEX32;
}
@@ -255,7 +255,7 @@ namespace CommandSystem
if (AzFramework::StringFunc::Equal(extension.c_str(), "motion", false /* no case */))
{
EMotionFX::Importer::MotionSettings settings;
settings.mLoadMotionEvents = parameters.GetValueAsBool("loadMotionEvents", this);
settings.m_loadMotionEvents = parameters.GetValueAsBool("loadMotionEvents", this);
motion = EMotionFX::GetImporter().LoadMotion(filename.c_str(), &settings);
}
@@ -273,12 +273,12 @@ namespace CommandSystem
}
// in case we are in a redo call assign the previously used id
if (mOldMotionID != MCORE_INVALIDINDEX32)
if (m_oldMotionId != MCORE_INVALIDINDEX32)
{
motion->SetID(mOldMotionID);
motion->SetID(m_oldMotionId);
}
mOldMotionID = motion->GetID();
mOldFileName = motion->GetFileName();
m_oldMotionId = motion->GetID();
m_oldFileName = motion->GetFileName();
// set the motion name
AZStd::string motionName;
@@ -292,7 +292,7 @@ namespace CommandSystem
}
// mark the workspace as dirty
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
GetCommandManager()->SetWorkspaceDirtyFlag(true);
// reset the dirty flag
@@ -308,11 +308,11 @@ namespace CommandSystem
// execute the group command
AZStd::string commandString;
commandString = AZStd::string::format("RemoveMotion -filename \"%s\"", mOldFileName.c_str());
commandString = AZStd::string::format("RemoveMotion -filename \"%s\"", m_oldFileName.c_str());
bool result = GetCommandManager()->ExecuteCommandInsideCommand(commandString.c_str(), outResult);
// restore the workspace dirty flag
GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag);
GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag);
return result;
}
@@ -21,17 +21,17 @@ namespace CommandSystem
// add actor
MCORE_DEFINECOMMAND_START(CommandImportActor, "Import actor", true)
public:
uint32 mPreviouslyUsedID;
uint32 mOldIndex;
bool mOldWorkspaceDirtyFlag;
uint32 m_previouslyUsedId;
uint32 m_oldIndex;
bool m_oldWorkspaceDirtyFlag;
MCORE_DEFINECOMMAND_END
// add motion
MCORE_DEFINECOMMAND_START(CommandImportMotion, "Import motion", true)
public:
uint32 mOldMotionID;
AZStd::string mOldFileName;
bool mOldWorkspaceDirtyFlag;
uint32 m_oldMotionId;
AZStd::string m_oldFileName;
bool m_oldWorkspaceDirtyFlag;
MCORE_DEFINECOMMAND_END
} // namespace CommandSystem
@@ -153,7 +153,7 @@ namespace CommandSystem
for (uint32 i = 0; i < actor->GetNumNodes(); ++i)
{
const EMotionFX::Actor::NodeMirrorInfo& mirrorInfo = actor->GetNodeMirrorInfo(i);
uint16 sourceNode = mirrorInfo.mSourceNode;
uint16 sourceNode = mirrorInfo.m_sourceNode;
if (sourceNode != MCORE_INVALIDINDEX16 && sourceNode != static_cast<uint16>(i))
{
outMetaDataString += actor->GetSkeleton()->GetNode(i)->GetNameString();
@@ -122,7 +122,7 @@ namespace CommandSystem
if (parameters.CheckIfHasParameter("weight") && morphTargetInstance)
{
const float value = parameters.GetValueAsFloat("weight", this);
mOldWeight = morphTargetInstance->GetWeight();
m_oldWeight = morphTargetInstance->GetWeight();
morphTargetInstance->SetWeight(value);
}
@@ -130,7 +130,7 @@ namespace CommandSystem
if (parameters.CheckIfHasParameter("manualMode") && morphTargetInstance)
{
const bool value = parameters.GetValueAsBool("manualMode", this);
mOldManualModeEnabled = morphTargetInstance->GetIsInManualMode();
m_oldManualModeEnabled = morphTargetInstance->GetIsInManualMode();
morphTargetInstance->SetManualMode(value);
}
@@ -138,7 +138,7 @@ namespace CommandSystem
if (parameters.CheckIfHasParameter("rangeMin") && morphTarget)
{
const float value = parameters.GetValueAsFloat("rangeMin", this);
mOldRangeMin = morphTarget->GetRangeMin();
m_oldRangeMin = morphTarget->GetRangeMin();
morphTarget->SetRangeMin(value);
}
@@ -146,7 +146,7 @@ namespace CommandSystem
if (parameters.CheckIfHasParameter("rangeMax") && morphTarget)
{
const float value = parameters.GetValueAsFloat("rangeMax", this);
mOldRangeMax = morphTarget->GetRangeMax();
m_oldRangeMax = morphTarget->GetRangeMax();
morphTarget->SetRangeMax(value);
}
@@ -159,7 +159,7 @@ namespace CommandSystem
parameters.GetValue("phonemeSets", this, &phonemeSetsString);
// store old phoneme sets
mOldPhonemeSets = morphTarget->GetPhonemeSets();
m_oldPhonemeSets = morphTarget->GetPhonemeSets();
// remove the phoneme set
if (AzFramework::StringFunc::Equal(valueString.c_str(), "remove", false /* no case */))
@@ -203,7 +203,7 @@ namespace CommandSystem
}
// save the current dirty flag and tell the actor that something got changed
mOldDirtyFlag = actor->GetDirtyFlag();
m_oldDirtyFlag = actor->GetDirtyFlag();
actor->SetDirtyFlag(true);
return true;
}
@@ -240,35 +240,35 @@ namespace CommandSystem
// set the old weight of the morph target
if (parameters.CheckIfHasParameter("weight") && morphTargetInstance)
{
morphTargetInstance->SetWeight(mOldWeight);
morphTargetInstance->SetWeight(m_oldWeight);
}
// set the old manual mode
if (parameters.CheckIfHasParameter("manualMode") && morphTargetInstance)
{
morphTargetInstance->SetManualMode(mOldManualModeEnabled);
morphTargetInstance->SetManualMode(m_oldManualModeEnabled);
}
// set the old range min
if (parameters.CheckIfHasParameter("rangeMin") && morphTarget)
{
morphTarget->SetRangeMin(mOldRangeMin);
morphTarget->SetRangeMin(m_oldRangeMin);
}
// set the old range max
if (parameters.CheckIfHasParameter("rangeMax") && morphTarget)
{
morphTarget->SetRangeMax(mOldRangeMax);
morphTarget->SetRangeMax(m_oldRangeMax);
}
// set the old phoneme sets
if (parameters.CheckIfHasParameter("phonemeAction") && morphTarget)
{
morphTarget->SetPhonemeSets(mOldPhonemeSets);
morphTarget->SetPhonemeSets(m_oldPhonemeSets);
}
// set the dirty flag back to the old value
actor->SetDirtyFlag(mOldDirtyFlag);
actor->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -20,12 +20,12 @@ namespace CommandSystem
{
// adjust a given morph target of an actor
MCORE_DEFINECOMMAND_START(CommandAdjustMorphTarget, "Adjust morph target", true)
float mOldWeight;
float mOldRangeMin;
float mOldRangeMax;
bool mOldManualModeEnabled;
EMotionFX::MorphTarget::EPhonemeSet mOldPhonemeSets;
bool mOldDirtyFlag;
float m_oldWeight;
float m_oldRangeMin;
float m_oldRangeMax;
bool m_oldManualModeEnabled;
EMotionFX::MorphTarget::EPhonemeSet m_oldPhonemeSets;
bool m_oldDirtyFlag;
bool GetMorphTarget(EMotionFX::Actor* actor, EMotionFX::ActorInstance* actorInstance, uint32 lodLevel, const char* morphTargetName, EMotionFX::MorphTarget** outMorphTarget, EMotionFX::MorphSetupInstance::MorphTarget** outMorphTargetInstance, AZStd::string& outResult);
MCORE_DEFINECOMMAND_END
@@ -79,27 +79,27 @@ namespace CommandSystem
AZStd::string CommandPlayMotion::PlayBackInfoToCommandParameters(const EMotionFX::PlayBackInfo* playbackInfo)
{
return AZStd::string::format("-blendInTime %f -blendOutTime %f -playSpeed %f -targetWeight %f -eventWeightThreshold %f -maxPlayTime %f -numLoops %i -priorityLevel %i -blendMode %i -playMode %i -mirrorMotion %s -mix %s -playNow %s -motionExtraction %s -retarget %s -freezeAtLastFrame %s -enableMotionEvents %s -blendOutBeforeEnded %s -canOverwrite %s -deleteOnZeroWeight %s -inPlace %s",
playbackInfo->mBlendInTime,
playbackInfo->mBlendOutTime,
playbackInfo->mPlaySpeed,
playbackInfo->mTargetWeight,
playbackInfo->mEventWeightThreshold,
playbackInfo->mMaxPlayTime,
playbackInfo->mNumLoops,
playbackInfo->mPriorityLevel,
static_cast<AZ::u8>(playbackInfo->mBlendMode),
static_cast<AZ::u8>(playbackInfo->mPlayMode),
AZStd::to_string(playbackInfo->mMirrorMotion).c_str(),
AZStd::to_string(playbackInfo->mMix).c_str(),
AZStd::to_string(playbackInfo->mPlayNow).c_str(),
AZStd::to_string(playbackInfo->mMotionExtractionEnabled).c_str(),
AZStd::to_string(playbackInfo->mRetarget).c_str(),
AZStd::to_string(playbackInfo->mFreezeAtLastFrame).c_str(),
AZStd::to_string(playbackInfo->mEnableMotionEvents).c_str(),
AZStd::to_string(playbackInfo->mBlendOutBeforeEnded).c_str(),
AZStd::to_string(playbackInfo->mCanOverwrite).c_str(),
AZStd::to_string(playbackInfo->mDeleteOnZeroWeight).c_str(),
AZStd::to_string(playbackInfo->mInPlace).c_str());
playbackInfo->m_blendInTime,
playbackInfo->m_blendOutTime,
playbackInfo->m_playSpeed,
playbackInfo->m_targetWeight,
playbackInfo->m_eventWeightThreshold,
playbackInfo->m_maxPlayTime,
playbackInfo->m_numLoops,
playbackInfo->m_priorityLevel,
static_cast<AZ::u8>(playbackInfo->m_blendMode),
static_cast<AZ::u8>(playbackInfo->m_playMode),
AZStd::to_string(playbackInfo->m_mirrorMotion).c_str(),
AZStd::to_string(playbackInfo->m_mix).c_str(),
AZStd::to_string(playbackInfo->m_playNow).c_str(),
AZStd::to_string(playbackInfo->m_motionExtractionEnabled).c_str(),
AZStd::to_string(playbackInfo->m_retarget).c_str(),
AZStd::to_string(playbackInfo->m_freezeAtLastFrame).c_str(),
AZStd::to_string(playbackInfo->m_enableMotionEvents).c_str(),
AZStd::to_string(playbackInfo->m_blendOutBeforeEnded).c_str(),
AZStd::to_string(playbackInfo->m_canOverwrite).c_str(),
AZStd::to_string(playbackInfo->m_deleteOnZeroWeight).c_str(),
AZStd::to_string(playbackInfo->m_inPlace).c_str());
}
@@ -108,87 +108,87 @@ namespace CommandSystem
{
if (parameters.CheckIfHasParameter("blendInTime") == true)
{
outPlaybackInfo->mBlendInTime = parameters.GetValueAsFloat("blendInTime", command);
outPlaybackInfo->m_blendInTime = parameters.GetValueAsFloat("blendInTime", command);
}
if (parameters.CheckIfHasParameter("blendOutTime"))
{
outPlaybackInfo->mBlendOutTime = parameters.GetValueAsFloat("blendOutTime", command);
outPlaybackInfo->m_blendOutTime = parameters.GetValueAsFloat("blendOutTime", command);
}
if (parameters.CheckIfHasParameter("playSpeed"))
{
outPlaybackInfo->mPlaySpeed = parameters.GetValueAsFloat("playSpeed", command);
outPlaybackInfo->m_playSpeed = parameters.GetValueAsFloat("playSpeed", command);
}
if (parameters.CheckIfHasParameter("targetWeight"))
{
outPlaybackInfo->mTargetWeight = parameters.GetValueAsFloat("targetWeight", command);
outPlaybackInfo->m_targetWeight = parameters.GetValueAsFloat("targetWeight", command);
}
if (parameters.CheckIfHasParameter("eventWeightThreshold"))
{
outPlaybackInfo->mEventWeightThreshold = parameters.GetValueAsFloat("eventWeightThreshold", command);
outPlaybackInfo->m_eventWeightThreshold = parameters.GetValueAsFloat("eventWeightThreshold", command);
}
if (parameters.CheckIfHasParameter("maxPlayTime"))
{
outPlaybackInfo->mMaxPlayTime = parameters.GetValueAsFloat("maxPlayTime", command);
outPlaybackInfo->m_maxPlayTime = parameters.GetValueAsFloat("maxPlayTime", command);
}
if (parameters.CheckIfHasParameter("numLoops"))
{
outPlaybackInfo->mNumLoops = parameters.GetValueAsInt("numLoops", command);
outPlaybackInfo->m_numLoops = parameters.GetValueAsInt("numLoops", command);
}
if (parameters.CheckIfHasParameter("priorityLevel"))
{
outPlaybackInfo->mPriorityLevel = parameters.GetValueAsInt("priorityLevel", command);
outPlaybackInfo->m_priorityLevel = parameters.GetValueAsInt("priorityLevel", command);
}
if (parameters.CheckIfHasParameter("blendMode"))
{
outPlaybackInfo->mBlendMode = (EMotionFX::EMotionBlendMode)parameters.GetValueAsInt("blendMode", command);
outPlaybackInfo->m_blendMode = (EMotionFX::EMotionBlendMode)parameters.GetValueAsInt("blendMode", command);
}
if (parameters.CheckIfHasParameter("playMode"))
{
outPlaybackInfo->mPlayMode = (EMotionFX::EPlayMode)parameters.GetValueAsInt("playMode", command);
outPlaybackInfo->m_playMode = (EMotionFX::EPlayMode)parameters.GetValueAsInt("playMode", command);
}
if (parameters.CheckIfHasParameter("mirrorMotion"))
{
outPlaybackInfo->mMirrorMotion = parameters.GetValueAsBool("mirrorMotion", command);
outPlaybackInfo->m_mirrorMotion = parameters.GetValueAsBool("mirrorMotion", command);
}
if (parameters.CheckIfHasParameter("mix"))
{
outPlaybackInfo->mMix = parameters.GetValueAsBool("mix", command);
outPlaybackInfo->m_mix = parameters.GetValueAsBool("mix", command);
}
if (parameters.CheckIfHasParameter("playNow"))
{
outPlaybackInfo->mPlayNow = parameters.GetValueAsBool("playNow", command);
outPlaybackInfo->m_playNow = parameters.GetValueAsBool("playNow", command);
}
if (parameters.CheckIfHasParameter("motionExtraction"))
{
outPlaybackInfo->mMotionExtractionEnabled = parameters.GetValueAsBool("motionExtraction", command);
outPlaybackInfo->m_motionExtractionEnabled = parameters.GetValueAsBool("motionExtraction", command);
}
if (parameters.CheckIfHasParameter("retarget"))
{
outPlaybackInfo->mRetarget = parameters.GetValueAsBool("retarget", command);
outPlaybackInfo->m_retarget = parameters.GetValueAsBool("retarget", command);
}
if (parameters.CheckIfHasParameter("freezeAtLastFrame"))
{
outPlaybackInfo->mFreezeAtLastFrame = parameters.GetValueAsBool("freezeAtLastFrame", command);
outPlaybackInfo->m_freezeAtLastFrame = parameters.GetValueAsBool("freezeAtLastFrame", command);
}
if (parameters.CheckIfHasParameter("enableMotionEvents"))
{
outPlaybackInfo->mEnableMotionEvents = parameters.GetValueAsBool("enableMotionEvents", command);
outPlaybackInfo->m_enableMotionEvents = parameters.GetValueAsBool("enableMotionEvents", command);
}
if (parameters.CheckIfHasParameter("blendOutBeforeEnded"))
{
outPlaybackInfo->mBlendOutBeforeEnded = parameters.GetValueAsBool("blendOutBeforeEnded", command);
outPlaybackInfo->m_blendOutBeforeEnded = parameters.GetValueAsBool("blendOutBeforeEnded", command);
}
if (parameters.CheckIfHasParameter("canOverwrite"))
{
outPlaybackInfo->mCanOverwrite = parameters.GetValueAsBool("canOverwrite", command);
outPlaybackInfo->m_canOverwrite = parameters.GetValueAsBool("canOverwrite", command);
}
if (parameters.CheckIfHasParameter("deleteOnZeroWeight"))
{
outPlaybackInfo->mDeleteOnZeroWeight = parameters.GetValueAsBool("deleteOnZeroWeight", command);
outPlaybackInfo->m_deleteOnZeroWeight = parameters.GetValueAsBool("deleteOnZeroWeight", command);
}
if (parameters.CheckIfHasParameter("inPlace"))
{
outPlaybackInfo->mInPlace = parameters.GetValueAsBool("inPlace", command);
outPlaybackInfo->m_inPlace = parameters.GetValueAsBool("inPlace", command);
}
}
@@ -327,7 +327,7 @@ namespace CommandSystem
#define SYNTAX_MOTIONCOMMANDS \
GetSyntax().ReserveParameters(30); \
GetSyntax().AddRequiredParameter("filename", "The filename of the motion file to play.", MCore::CommandSyntax::PARAMTYPE_STRING); \
/*GetSyntax().AddParameter( "mirrorPlaneNormal", "The motion mirror plane normal, which is (1,0,0) on default. This setting is only used when mMirrorMotion is set to true.", MCore::CommandSyntax::PARAMTYPE_VECTOR3, "(1, 0, 0)" );*/ \
/*GetSyntax().AddParameter( "mirrorPlaneNormal", "The motion mirror plane normal, which is (1,0,0) on default. This setting is only used when mirrorMotion is set to true.", MCore::CommandSyntax::PARAMTYPE_VECTOR3, "(1, 0, 0)" );*/ \
GetSyntax().AddParameter("blendInTime", "The time, in seconds, which it will take to fully have blended to the target weight.", MCore::CommandSyntax::PARAMTYPE_FLOAT, "0.3"); \
GetSyntax().AddParameter("blendOutTime", "The time, in seconds, which it takes to smoothly fadeout the motion, after it has been stopped playing.", MCore::CommandSyntax::PARAMTYPE_FLOAT, "0.3"); \
GetSyntax().AddParameter("playSpeed", "The playback speed factor. A value of 1 stands for the original speed, while for example 2 means twice the original speed.", MCore::CommandSyntax::PARAMTYPE_FLOAT, "1.0"); \
@@ -340,7 +340,7 @@ namespace CommandSystem
GetSyntax().AddParameter("retargetRootIndex", "The retargeting root node index.", MCore::CommandSyntax::PARAMTYPE_INT, "0"); \
GetSyntax().AddParameter("blendMode", "The motion blend mode. Please read the MotionInstance::SetBlendMode(...) method for more information.", MCore::CommandSyntax::PARAMTYPE_INT, "0"); /* 4294967296 == MCORE_INVALIDINDEX32 */ \
GetSyntax().AddParameter("playMode", "The motion playback mode. This means forward or backward playback.", MCore::CommandSyntax::PARAMTYPE_INT, "0"); \
GetSyntax().AddParameter("mirrorMotion", "Is motion mirroring enabled or not? When set to true, the mMirrorPlaneNormal is used as mirroring axis.", MCore::CommandSyntax::PARAMTYPE_BOOLEAN, "false"); \
GetSyntax().AddParameter("mirrorMotion", "Is motion mirroring enabled or not? When set to true, the mirrorPlaneNormal is used as mirroring axis.", MCore::CommandSyntax::PARAMTYPE_BOOLEAN, "false"); \
GetSyntax().AddParameter("mix", "Set to true if you want this motion to mix or not.", MCore::CommandSyntax::PARAMTYPE_BOOLEAN, "false"); \
GetSyntax().AddParameter("playNow", "Set to true if you want to start playing the motion right away. If set to false it will be scheduled for later by inserting it into the motion queue.", MCore::CommandSyntax::PARAMTYPE_BOOLEAN, "true"); \
GetSyntax().AddParameter("motionExtraction", "Set to true when you want to use motion extraction.", MCore::CommandSyntax::PARAMTYPE_BOOLEAN, "true"); \
@@ -546,13 +546,13 @@ namespace CommandSystem
EMotionFX::PlayBackInfo* defaultPlayBackInfo = motion->GetDefaultPlayBackInfo();
// copy the current playback info to the undo data
mOldPlaybackInfo = *defaultPlayBackInfo;
m_oldPlaybackInfo = *defaultPlayBackInfo;
// adjust the playback info based on the parameters
CommandPlayMotion::CommandParametersToPlaybackInfo(this, parameters, defaultPlayBackInfo);
// save the current dirty flag and tell the motion that something got changed
mOldDirtyFlag = motion->GetDirtyFlag();
m_oldDirtyFlag = motion->GetDirtyFlag();
return true;
}
@@ -585,10 +585,10 @@ namespace CommandSystem
}
// copy the saved playback info to the actual one
*defaultPlayBackInfo = mOldPlaybackInfo;
*defaultPlayBackInfo = m_oldPlaybackInfo;
// set the dirty flag back to the old value
motion->SetDirtyFlag(mOldDirtyFlag);
motion->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -614,9 +614,6 @@ namespace CommandSystem
// execute
bool CommandStopMotionInstances::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult)
{
// clear our old data so that we start fresh in case of a redo
//mOldData.Clear();
// get the number of selected actor instances
const size_t numSelectedActorInstances = GetCommandManager()->GetCurrentSelection().GetNumSelectedActorInstances();
@@ -716,9 +713,6 @@ namespace CommandSystem
MCORE_UNUSED(parameters);
MCORE_UNUSED(outResult);
// clear our old data so that we start fresh in case of a redo
//mOldData.Clear();
// iterate through all actor instances and stop all selected motion instances
const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances();
for (size_t i = 0; i < numActorInstances; ++i)
@@ -823,26 +817,26 @@ namespace CommandSystem
// adjust the dirty flag
if (m_dirtyFlag)
{
mOldDirtyFlag = motion->GetDirtyFlag();
m_oldDirtyFlag = motion->GetDirtyFlag();
motion->SetDirtyFlag(m_dirtyFlag.value());
}
// adjust the name
if (m_name)
{
mOldName = motion->GetName();
m_oldName = motion->GetName();
motion->SetName(m_name.value().c_str());
mOldDirtyFlag = motion->GetDirtyFlag();
m_oldDirtyFlag = motion->GetDirtyFlag();
motion->SetDirtyFlag(true);
}
// Adjust the motion extraction flags.
if (m_extractionFlags)
{
mOldExtractionFlags = motion->GetMotionExtractionFlags();
m_oldExtractionFlags = motion->GetMotionExtractionFlags();
motion->SetMotionExtractionFlags(m_extractionFlags.value());
mOldDirtyFlag = motion->GetDirtyFlag();
m_oldDirtyFlag = motion->GetDirtyFlag();
motion->SetDirtyFlag(true);
}
@@ -866,20 +860,20 @@ namespace CommandSystem
// adjust the dirty flag
if (m_dirtyFlag)
{
motion->SetDirtyFlag(mOldDirtyFlag);
motion->SetDirtyFlag(m_oldDirtyFlag);
}
// adjust the name
if (m_name)
{
motion->SetName(mOldName.c_str());
motion->SetDirtyFlag(mOldDirtyFlag);
motion->SetName(m_oldName.c_str());
motion->SetDirtyFlag(m_oldDirtyFlag);
}
if (m_extractionFlags)
{
motion->SetMotionExtractionFlags(mOldExtractionFlags);
motion->SetDirtyFlag(mOldDirtyFlag);
motion->SetMotionExtractionFlags(m_oldExtractionFlags);
motion->SetDirtyFlag(m_oldDirtyFlag);
}
return true;
@@ -933,7 +927,7 @@ namespace CommandSystem
CommandRemoveMotion::CommandRemoveMotion(MCore::Command* orgCommand)
: MCore::Command("RemoveMotion", orgCommand)
{
mOldMotionID = MCORE_INVALIDINDEX32;
m_oldMotionId = MCORE_INVALIDINDEX32;
}
@@ -992,12 +986,12 @@ namespace CommandSystem
GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult);
// store the previously used id and remove the motion
mOldIndex = EMotionFX::GetMotionManager().FindMotionIndex(motion);
mOldMotionID = motion->GetID();
mOldFileName = motion->GetFileName();
m_oldIndex = EMotionFX::GetMotionManager().FindMotionIndex(motion);
m_oldMotionId = motion->GetID();
m_oldFileName = motion->GetFileName();
// mark the workspace as dirty
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
GetCommandManager()->SetWorkspaceDirtyFlag(true);
EMotionFX::GetMotionManager().RemoveMotionByID(motion->GetID());
@@ -1012,11 +1006,11 @@ namespace CommandSystem
// execute the group command
AZStd::string commandString;
commandString = AZStd::string::format("ImportMotion -filename \"%s\" -motionID %i", mOldFileName.c_str(), mOldMotionID);
commandString = AZStd::string::format("ImportMotion -filename \"%s\" -motionID %i", m_oldFileName.c_str(), m_oldMotionId);
bool result = GetCommandManager()->ExecuteCommandInsideCommand(commandString.c_str(), outResult);
// restore the workspace dirty flag
GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag);
GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag);
return result;
}
@@ -1045,9 +1039,9 @@ namespace CommandSystem
CommandScaleMotionData::CommandScaleMotionData(MCore::Command* orgCommand)
: MCore::Command("ScaleMotionData", orgCommand)
{
mMotionID = MCORE_INVALIDINDEX32;
mScaleFactor = 1.0f;
mOldDirtyFlag = false;
m_motionId = MCORE_INVALIDINDEX32;
m_scaleFactor = 1.0f;
m_oldDirtyFlag = false;
}
@@ -1092,29 +1086,29 @@ namespace CommandSystem
return false;
}
mMotionID = motion->GetID();
mScaleFactor = parameters.GetValueAsFloat("scaleFactor", 1.0f);
m_motionId = motion->GetID();
m_scaleFactor = parameters.GetValueAsFloat("scaleFactor", 1.0f);
AZStd::string targetUnitTypeString;
parameters.GetValue("unitType", this, &targetUnitTypeString);
mUseUnitType = parameters.CheckIfHasParameter("unitType");
m_useUnitType = parameters.CheckIfHasParameter("unitType");
MCore::Distance::EUnitType targetUnitType;
bool stringConvertSuccess = MCore::Distance::StringToUnitType(targetUnitTypeString, &targetUnitType);
if (mUseUnitType && stringConvertSuccess == false)
if (m_useUnitType && stringConvertSuccess == false)
{
outResult = AZStd::string::format("The passed unitType '%s' is not a valid unit type.", targetUnitTypeString.c_str());
return false;
}
mOldUnitType = MCore::Distance::UnitTypeToString(motion->GetUnitType());
m_oldUnitType = MCore::Distance::UnitTypeToString(motion->GetUnitType());
mOldDirtyFlag = motion->GetDirtyFlag();
m_oldDirtyFlag = motion->GetDirtyFlag();
motion->SetDirtyFlag(true);
// perform the scaling
if (mUseUnitType == false)
if (m_useUnitType == false)
{
motion->Scale(mScaleFactor);
motion->Scale(m_scaleFactor);
}
else
{
@@ -1130,23 +1124,23 @@ namespace CommandSystem
{
MCORE_UNUSED(parameters);
if (mUseUnitType == false)
if (m_useUnitType == false)
{
AZStd::string commandString;
commandString = AZStd::string::format("ScaleMotionData -id %d -scaleFactor %.8f", mMotionID, 1.0f / mScaleFactor);
commandString = AZStd::string::format("ScaleMotionData -id %d -scaleFactor %.8f", m_motionId, 1.0f / m_scaleFactor);
GetCommandManager()->ExecuteCommandInsideCommand(commandString.c_str(), outResult);
}
else
{
AZStd::string commandString;
commandString = AZStd::string::format("ScaleMotionData -id %d -unitType \"%s\"", mMotionID, mOldUnitType.c_str());
commandString = AZStd::string::format("ScaleMotionData -id %d -unitType \"%s\"", m_motionId, m_oldUnitType.c_str());
GetCommandManager()->ExecuteCommandInsideCommand(commandString.c_str(), outResult);
}
EMotionFX::Motion* motion = EMotionFX::GetMotionManager().FindMotionByID(mMotionID);
EMotionFX::Motion* motion = EMotionFX::GetMotionManager().FindMotionByID(m_motionId);
if (motion)
{
motion->SetDirtyFlag(mOldDirtyFlag);
motion->SetDirtyFlag(m_oldDirtyFlag);
}
return true;
@@ -69,33 +69,33 @@ namespace CommandSystem
private:
AZStd::optional<bool> m_dirtyFlag;
bool mOldDirtyFlag;
bool m_oldDirtyFlag;
AZStd::optional<EMotionFX::EMotionExtractionFlags> m_extractionFlags;
EMotionFX::EMotionExtractionFlags mOldExtractionFlags;
EMotionFX::EMotionExtractionFlags m_oldExtractionFlags;
AZStd::optional<AZStd::string> m_name;
AZStd::string mOldName;
AZStd::string mOldMotionExtractionNodeName;
AZStd::string m_oldName;
AZStd::string m_oldMotionExtractionNodeName;
};
// Remove motion command.
MCORE_DEFINECOMMAND_START(CommandRemoveMotion, "Remove motion", true)
public:
uint32 mOldMotionID;
AZStd::string mOldFileName;
size_t mOldIndex;
bool mOldWorkspaceDirtyFlag;
uint32 m_oldMotionId;
AZStd::string m_oldFileName;
size_t m_oldIndex;
bool m_oldWorkspaceDirtyFlag;
MCORE_DEFINECOMMAND_END
// Scale motion data.
MCORE_DEFINECOMMAND_START(CommandScaleMotionData, "Scale motion data", true)
public:
AZStd::string mOldUnitType;
uint32 mMotionID;
float mScaleFactor;
bool mOldDirtyFlag;
bool mUseUnitType;
AZStd::string m_oldUnitType;
uint32 m_motionId;
float m_scaleFactor;
bool m_oldDirtyFlag;
bool m_useUnitType;
MCORE_DEFINECOMMAND_END
@@ -129,8 +129,8 @@ namespace CommandSystem
// Adjust default playback info command.
MCORE_DEFINECOMMAND_START(CommandAdjustDefaultPlayBackInfo, "Adjust default playback info", true)
EMotionFX::PlayBackInfo mOldPlaybackInfo;
bool mOldDirtyFlag;
EMotionFX::PlayBackInfo m_oldPlaybackInfo;
bool m_oldDirtyFlag;
MCORE_DEFINECOMMAND_END
@@ -293,7 +293,7 @@ namespace CommandSystem
CommandRemoveMotionEventTrack::CommandRemoveMotionEventTrack(MCore::Command* orgCommand)
: MCore::Command("RemoveMotionEventTrack", orgCommand)
{
mOldTrackIndex = InvalidIndex;
m_oldTrackIndex = InvalidIndex;
}
@@ -332,8 +332,8 @@ namespace CommandSystem
}
// store information for undo
mOldTrackIndex = eventTrackIndex.GetValue();
mOldEnabled = eventTable->GetTrack(eventTrackIndex.GetValue())->GetIsEnabled();
m_oldTrackIndex = eventTrackIndex.GetValue();
m_oldEnabled = eventTable->GetTrack(eventTrackIndex.GetValue())->GetIsEnabled();
// remove the motion event track
eventTable->RemoveTrack(eventTrackIndex.GetValue());
@@ -353,7 +353,7 @@ namespace CommandSystem
const int32 motionID = parameters.GetValueAsInt("motionID", this);
AZStd::string command;
command = AZStd::string::format("CreateMotionEventTrack -motionID %i -eventTrackName \"%s\" -index %zu -enabled %s", motionID, eventTrackName.c_str(), mOldTrackIndex, mOldEnabled ? "true" : "false");
command = AZStd::string::format("CreateMotionEventTrack -motionID %i -eventTrackName \"%s\" -index %zu -enabled %s", motionID, eventTrackName.c_str(), m_oldTrackIndex, m_oldEnabled ? "true" : "false");
return GetCommandManager()->ExecuteCommandInsideCommand(command.c_str(), outResult);
}
@@ -586,9 +586,9 @@ namespace CommandSystem
}
// add the motion event and check if everything worked fine
mMotionEventNr = eventTrack->AddEvent(m_startTime, m_endTime, m_eventDatas.value_or(EMotionFX::EventDataSet()));
m_motionEventNr = eventTrack->AddEvent(m_startTime, m_endTime, m_eventDatas.value_or(EMotionFX::EventDataSet()));
if (mMotionEventNr == InvalidIndex)
if (m_motionEventNr == InvalidIndex)
{
outResult = AZStd::string::format("Cannot create motion event. The returned motion event index is not valid.");
return false;
@@ -604,7 +604,7 @@ namespace CommandSystem
{
AZ_UNUSED(parameters);
const AZStd::string command = AZStd::string::format("RemoveMotionEvent -motionID %i -eventTrackName \"%s\" -eventNr %zu", m_motionID, m_eventTrackName.c_str(), mMotionEventNr);
const AZStd::string command = AZStd::string::format("RemoveMotionEvent -motionID %i -eventTrackName \"%s\" -eventNr %zu", m_motionID, m_eventTrackName.c_str(), m_motionEventNr);
return GetCommandManager()->ExecuteCommandInsideCommand(command.c_str(), outResult);
}
@@ -700,8 +700,8 @@ namespace CommandSystem
// get the motion event and store the old values of the motion event for undo
const EMotionFX::MotionEvent& motionEvent = eventTrack->GetEvent(eventNr);
mOldStartTime = motionEvent.GetStartTime();
mOldEndTime = motionEvent.GetEndTime();
m_oldStartTime = motionEvent.GetStartTime();
m_oldEndTime = motionEvent.GetEndTime();
m_oldEventDatas = motionEvent.GetEventDatas();
// remove the motion event
@@ -728,7 +728,7 @@ namespace CommandSystem
}
MCore::CommandGroup commandGroup;
CommandHelperAddMotionEvent(motion, eventTrackName.c_str(), mOldStartTime, mOldEndTime, m_oldEventDatas, &commandGroup);
CommandHelperAddMotionEvent(motion, eventTrackName.c_str(), m_oldStartTime, m_oldEndTime, m_oldEventDatas, &commandGroup);
return GetCommandManager()->ExecuteCommandGroupInsideCommand(commandGroup, outResult);
}
@@ -60,8 +60,8 @@ namespace CommandSystem
};
MCORE_DEFINECOMMAND_START(CommandRemoveMotionEventTrack, "Remove motion event track", true)
size_t mOldTrackIndex;
bool mOldEnabled;
size_t m_oldTrackIndex;
bool m_oldEnabled;
MCORE_DEFINECOMMAND_END
class DEFINECOMMAND_API CommandAdjustMotionEventTrack
@@ -151,12 +151,12 @@ namespace CommandSystem
AZStd::optional<EMotionFX::EventDataSet> m_eventDatas;
float m_startTime = 0.0f;
float m_endTime = 0.0f;
size_t mMotionEventNr;
size_t m_motionEventNr;
};
MCORE_DEFINECOMMAND_START(CommandRemoveMotionEvent, "Remove motion event", true)
float mOldStartTime;
float mOldEndTime;
float m_oldStartTime;
float m_oldEndTime;
EMotionFX::EventDataSet m_oldEventDatas;
MCORE_DEFINECOMMAND_END
@@ -68,7 +68,7 @@ namespace CommandSystem
CommandCreateMotionSet::CommandCreateMotionSet(MCore::Command* orgCommand)
: MCore::Command("CreateMotionSet", orgCommand)
{
mPreviouslyUsedID = MCORE_INVALIDINDEX32;
m_previouslyUsedId = MCORE_INVALIDINDEX32;
}
@@ -130,9 +130,9 @@ namespace CommandSystem
}
// In case of redoing the command set the previously used id.
if (mPreviouslyUsedID != MCORE_INVALIDINDEX32)
if (m_previouslyUsedId != MCORE_INVALIDINDEX32)
{
motionSet->SetID(mPreviouslyUsedID);
motionSet->SetID(m_previouslyUsedId);
}
// Set the filename.
@@ -145,14 +145,14 @@ namespace CommandSystem
}
// Store info for undo.
mPreviouslyUsedID = motionSet->GetID();
AZStd::to_string(outResult, mPreviouslyUsedID);
m_previouslyUsedId = motionSet->GetID();
AZStd::to_string(outResult, m_previouslyUsedId);
// Set the motion set callback for custom motion loading.
motionSet->SetCallback(aznew CommandSystemMotionSetCallback(motionSet), true);
// Set the dirty flag.
const AZStd::string commandString = AZStd::string::format("AdjustMotionSet -motionSetID %i -dirtyFlag true", mPreviouslyUsedID);
const AZStd::string commandString = AZStd::string::format("AdjustMotionSet -motionSetID %i -dirtyFlag true", m_previouslyUsedId);
GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult);
// Seturn the id of the newly created motion set.
@@ -176,7 +176,7 @@ namespace CommandSystem
EMotionFX::GetAnimGraphManager().InvalidateInstanceUniqueDataUsingMotionSet(motionSet);
// Mark the workspace as dirty
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
GetCommandManager()->SetWorkspaceDirtyFlag(true);
return true;
}
@@ -186,11 +186,11 @@ namespace CommandSystem
{
MCORE_UNUSED(parameters);
const AZStd::string commandString = AZStd::string::format("RemoveMotionSet -motionSetID %i", mPreviouslyUsedID);
const AZStd::string commandString = AZStd::string::format("RemoveMotionSet -motionSetID %i", m_previouslyUsedId);
bool result = GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult);
// Restore the workspace dirty flag.
GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag);
GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag);
return result;
}
@@ -218,7 +218,7 @@ namespace CommandSystem
CommandRemoveMotionSet::CommandRemoveMotionSet(MCore::Command* orgCommand)
: MCore::Command("RemoveMotionSet", orgCommand)
{
mPreviouslyUsedID = MCORE_INVALIDINDEX32;
m_previouslyUsedId = MCORE_INVALIDINDEX32;
}
@@ -240,20 +240,20 @@ namespace CommandSystem
}
// Store information used by undo.
mPreviouslyUsedID = motionSet->GetID();
mOldName = motionSet->GetName();
mOldFileName = motionSet->GetFilename();
m_previouslyUsedId = motionSet->GetID();
m_oldName = motionSet->GetName();
m_oldFileName = motionSet->GetFilename();
if (!motionSet->GetParentSet())
{
mOldParentSetID = MCORE_INVALIDINDEX32;
m_oldParentSetId = MCORE_INVALIDINDEX32;
}
else
{
mOldParentSetID = motionSet->GetParentSet()->GetID();
m_oldParentSetId = motionSet->GetParentSet()->GetID();
// Set the dirty flag on the parent.
const AZStd::string commandString = AZStd::string::format("AdjustMotionSet -motionSetID %i -dirtyFlag true", mOldParentSetID);
const AZStd::string commandString = AZStd::string::format("AdjustMotionSet -motionSetID %i -dirtyFlag true", m_oldParentSetId);
GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult);
}
@@ -280,7 +280,7 @@ namespace CommandSystem
}
// Mark the workspace as dirty.
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
GetCommandManager()->SetWorkspaceDirtyFlag(true);
return true;
@@ -291,22 +291,22 @@ namespace CommandSystem
{
MCORE_UNUSED(parameters);
AZStd::string commandString = AZStd::string::format("CreateMotionSet -name \"%s\" -motionSetID %i", mOldName.c_str(), mPreviouslyUsedID);
AZStd::string commandString = AZStd::string::format("CreateMotionSet -name \"%s\" -motionSetID %i", m_oldName.c_str(), m_previouslyUsedId);
if (!mOldFileName.empty())
if (!m_oldFileName.empty())
{
commandString += AZStd::string::format(" -fileName \"%s\"", mOldFileName.c_str());
commandString += AZStd::string::format(" -fileName \"%s\"", m_oldFileName.c_str());
}
if (mOldParentSetID != MCORE_INVALIDINDEX32)
if (m_oldParentSetId != MCORE_INVALIDINDEX32)
{
commandString += AZStd::string::format(" -parentSetID %i", mOldParentSetID);
commandString += AZStd::string::format(" -parentSetID %i", m_oldParentSetId);
}
const bool result = GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult);
// Restore the workspace dirty flag.
GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag);
GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag);
return result;
}
@@ -353,7 +353,7 @@ namespace CommandSystem
// Adjust the dirty flag.
if (parameters.CheckIfHasParameter("dirtyFlag"))
{
mOldDirtyFlag = motionSet->GetDirtyFlag();
m_oldDirtyFlag = motionSet->GetDirtyFlag();
const bool dirtyFlag = parameters.GetValueAsBool("dirtyFlag", this);
motionSet->SetDirtyFlag(dirtyFlag);
}
@@ -361,12 +361,12 @@ namespace CommandSystem
// Set the new name in case the name parameter is specified.
if (parameters.CheckIfHasParameter("newName"))
{
mOldSetName = motionSet->GetName();
m_oldSetName = motionSet->GetName();
AZStd::string name;
parameters.GetValue("newName", this, name);
motionSet->SetName(name.c_str());
mOldDirtyFlag = motionSet->GetDirtyFlag();
m_oldDirtyFlag = motionSet->GetDirtyFlag();
motionSet->SetDirtyFlag(true);
}
@@ -389,13 +389,13 @@ namespace CommandSystem
// Adjust the dirty flag
if (parameters.CheckIfHasParameter("dirtyFlag"))
{
motionSet->SetDirtyFlag(mOldDirtyFlag);
motionSet->SetDirtyFlag(m_oldDirtyFlag);
}
// Adjust the name.
if (parameters.CheckIfHasParameter("newName"))
{
motionSet->SetName(mOldSetName.c_str());
motionSet->SetName(m_oldSetName.c_str());
}
return true;
@@ -719,8 +719,8 @@ namespace CommandSystem
}
// Save the old infos for undo.
mOldIdString = motionEntry->GetId();
mOldMotionFilename = motionEntry->GetFilename();
m_oldIdString = motionEntry->GetId();
m_oldMotionFilename = motionEntry->GetFilename();
if (parameters.CheckIfHasParameter("motionFileName"))
{
@@ -782,7 +782,7 @@ namespace CommandSystem
// Update all motion nodes and link them to the new motion id.
if (parameters.GetValueAsBool("updateMotionNodeStringIDs", this))
{
UpdateMotionNodes(mOldIdString.c_str(), newId.c_str());
UpdateMotionNodes(m_oldIdString.c_str(), newId.c_str());
}
}
@@ -833,12 +833,12 @@ namespace CommandSystem
if (idStringChanged)
{
command += AZStd::string::format(" -newIDString \"%s\"", mOldIdString.c_str());
command += AZStd::string::format(" -newIDString \"%s\"", m_oldIdString.c_str());
}
if (parameters.CheckIfHasParameter("motionFileName"))
{
command += AZStd::string::format(" -motionFileName \"%s\"", mOldMotionFilename.c_str());
command += AZStd::string::format(" -motionFileName \"%s\"", m_oldMotionFilename.c_str());
}
return GetCommandManager()->ExecuteCommandInsideCommand(command, outResult);
@@ -869,7 +869,7 @@ namespace CommandSystem
CommandLoadMotionSet::CommandLoadMotionSet(MCore::Command* orgCommand)
: MCore::Command("LoadMotionSet", orgCommand)
{
mOldMotionSetID = MCORE_INVALIDINDEX32;
m_oldMotionSetId = MCORE_INVALIDINDEX32;
}
@@ -910,11 +910,11 @@ namespace CommandSystem
}
// In case we are in a redo call assign the previously used id.
if (mOldMotionSetID != MCORE_INVALIDINDEX32)
if (m_oldMotionSetId != MCORE_INVALIDINDEX32)
{
motionSet->SetID(mOldMotionSetID);
motionSet->SetID(m_oldMotionSetId);
}
mOldMotionSetID = motionSet->GetID();
m_oldMotionSetId = motionSet->GetID();
// Set the custom loading callback and preload all motions.
motionSet->SetCallback(aznew CommandSystemMotionSetCallback(motionSet), true);
@@ -924,7 +924,7 @@ namespace CommandSystem
AZStd::to_string(outResult, motionSet->GetID());
// Mark the workspace as dirty.
mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag();
GetCommandManager()->SetWorkspaceDirtyFlag(true);
// Restore original log levels.
@@ -938,10 +938,10 @@ namespace CommandSystem
MCORE_UNUSED(parameters);
// Get the motion set the command created earlier by id.
EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(mOldMotionSetID);
EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(m_oldMotionSetId);
if (motionSet == nullptr)
{
outResult = AZStd::string::format("Cannot undo load motion set command. Previously used motion set id '%i' is not valid.", mOldMotionSetID);
outResult = AZStd::string::format("Cannot undo load motion set command. Previously used motion set id '%i' is not valid.", m_oldMotionSetId);
return false;
}
@@ -952,7 +952,7 @@ namespace CommandSystem
const bool result = GetCommandManager()->ExecuteCommandGroupInsideCommand(commandGroup, outResult);
// Restore the workspace dirty flag.
GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag);
GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag);
return result;
}
@@ -40,22 +40,22 @@ namespace CommandSystem
//////////////////////////////////////////////////////////////////////////////////////////////////////////
MCORE_DEFINECOMMAND_START(CommandCreateMotionSet, "Create motion set", true)
public:
uint32 mPreviouslyUsedID;
bool mOldWorkspaceDirtyFlag;
uint32 m_previouslyUsedId;
bool m_oldWorkspaceDirtyFlag;
MCORE_DEFINECOMMAND_END
MCORE_DEFINECOMMAND_START(CommandRemoveMotionSet, "Remove motion set", true)
public:
AZStd::string mOldName;
AZStd::string mOldFileName;
uint32 mOldParentSetID;
uint32 mPreviouslyUsedID;
bool mOldWorkspaceDirtyFlag;
AZStd::string m_oldName;
AZStd::string m_oldFileName;
uint32 m_oldParentSetId;
uint32 m_previouslyUsedId;
bool m_oldWorkspaceDirtyFlag;
MCORE_DEFINECOMMAND_END
MCORE_DEFINECOMMAND_START(CommandAdjustMotionSet, "Adjust motion set", true)
AZStd::string mOldSetName;
bool mOldDirtyFlag;
AZStd::string m_oldSetName;
bool m_oldDirtyFlag;
MCORE_DEFINECOMMAND_END
//////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -73,8 +73,8 @@ namespace CommandSystem
MCORE_DEFINECOMMAND_START(CommandMotionSetAdjustMotion, "Adjust motion set", true)
public:
AZStd::string mOldIdString;
AZStd::string mOldMotionFilename;
AZStd::string m_oldIdString;
AZStd::string m_oldMotionFilename;
void UpdateMotionNodes(const char* oldID, const char* newID);
MCORE_DEFINECOMMAND_END
@@ -85,8 +85,8 @@ namespace CommandSystem
public:
using RelocateFilenameFunction = AZStd::function<void(AZStd::string&)>;
RelocateFilenameFunction m_relocateFilenameFunction;
uint32 mOldMotionSetID;
bool mOldWorkspaceDirtyFlag;
uint32 m_oldMotionSetId;
bool m_oldWorkspaceDirtyFlag;
MCORE_DEFINECOMMAND_END
//////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -264,7 +264,7 @@ namespace CommandSystem
actor->AddNodeGroup(nodeGroup);
// save the current dirty flag and tell the actor that something got changed
mOldDirtyFlag = actor->GetDirtyFlag();
m_oldDirtyFlag = actor->GetDirtyFlag();
actor->SetDirtyFlag(true);
return true;
}
@@ -295,7 +295,7 @@ namespace CommandSystem
}
// set the dirty flag back to the old value
actor->SetDirtyFlag(mOldDirtyFlag);
actor->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -322,7 +322,7 @@ namespace CommandSystem
// constructor
CommandRemoveNodeGroup::CommandRemoveNodeGroup(MCore::Command* orgCommand)
: MCore::Command("RemoveNodeGroup", orgCommand)
, mOldNodeGroup(nullptr)
, m_oldNodeGroup(nullptr)
{
}
@@ -330,7 +330,7 @@ namespace CommandSystem
// destructor
CommandRemoveNodeGroup::~CommandRemoveNodeGroup()
{
delete mOldNodeGroup;
delete m_oldNodeGroup;
}
@@ -360,14 +360,14 @@ namespace CommandSystem
}
// copy the old node group for undo
delete mOldNodeGroup;
mOldNodeGroup = aznew EMotionFX::NodeGroup(*nodeGroup);
delete m_oldNodeGroup;
m_oldNodeGroup = aznew EMotionFX::NodeGroup(*nodeGroup);
// remove the node group
actor->RemoveNodeGroup(nodeGroup);
// save the current dirty flag and tell the actor that something got changed
mOldDirtyFlag = actor->GetDirtyFlag();
m_oldDirtyFlag = actor->GetDirtyFlag();
actor->SetDirtyFlag(true);
return true;
}
@@ -377,7 +377,7 @@ namespace CommandSystem
bool CommandRemoveNodeGroup::Undo(const MCore::CommandLine& parameters, AZStd::string& outResult)
{
// check if old node group exists
if (!mOldNodeGroup)
if (!m_oldNodeGroup)
{
return false;
}
@@ -397,13 +397,13 @@ namespace CommandSystem
}
// add the node to the group again
if (name == mOldNodeGroup->GetName())
if (name == m_oldNodeGroup->GetName())
{
actor->AddNodeGroup(aznew EMotionFX::NodeGroup(*mOldNodeGroup));
actor->AddNodeGroup(aznew EMotionFX::NodeGroup(*m_oldNodeGroup));
}
// set the dirty flag back to the old value
actor->SetDirtyFlag(mOldDirtyFlag);
actor->SetDirtyFlag(m_oldDirtyFlag);
return true;
}
@@ -79,14 +79,14 @@ namespace CommandSystem
// add node group
MCORE_DEFINECOMMAND_START(CommandAddNodeGroup, "Add node group", true)
bool mOldDirtyFlag;
bool m_oldDirtyFlag;
MCORE_DEFINECOMMAND_END
// remove a node group
MCORE_DEFINECOMMAND_START(CommandRemoveNodeGroup, "Remove node group", true)
EMotionFX::NodeGroup * mOldNodeGroup;
bool mOldDirtyFlag;
EMotionFX::NodeGroup * m_oldNodeGroup;
bool m_oldDirtyFlag;
MCORE_DEFINECOMMAND_END
@@ -90,8 +90,8 @@ namespace EMotionFX
const Transform& parentBindTransform = node->GetParentNode()
? bindPose->GetModelSpaceTransform(node->GetParentIndex())
: Transform::CreateIdentity();
const AZ::Quaternion& nodeBindRotationWorld = nodeBindTransform.mRotation;
const AZ::Quaternion& parentBindRotationWorld = parentBindTransform.mRotation;
const AZ::Quaternion& nodeBindRotationWorld = nodeBindTransform.m_rotation;
const AZ::Quaternion& parentBindRotationWorld = parentBindTransform.m_rotation;
AZ::Vector3 boneDirection = GetBoneDirection(skeleton, node);
AZStd::vector<AZ::Quaternion> exampleRotationsLocal;
@@ -547,7 +547,7 @@ namespace CommandSystem
bool CommandSelect::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult)
{
// store the old selection list for undo
mData = GetCommandManager()->GetCurrentSelection();
m_data = GetCommandManager()->GetCurrentSelection();
// selection add mode
return Select(this, parameters, outResult, false);
@@ -561,7 +561,7 @@ namespace CommandSystem
MCORE_UNUSED(outResult);
// restore the old selection and return success
GetCommandManager()->SetCurrentSelection(mData);
GetCommandManager()->SetCurrentSelection(m_data);
return true;
}
@@ -604,7 +604,7 @@ namespace CommandSystem
bool CommandUnselect::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult)
{
// store the old selection list for undo
mData = GetCommandManager()->GetCurrentSelection();
m_data = GetCommandManager()->GetCurrentSelection();
// unselect mode
return CommandSelect::Select(this, parameters, outResult, true);
@@ -618,7 +618,7 @@ namespace CommandSystem
MCORE_UNUSED(outResult);
// restore the old selection and return success
GetCommandManager()->SetCurrentSelection(mData);
GetCommandManager()->SetCurrentSelection(m_data);
return true;
}
@@ -665,7 +665,7 @@ namespace CommandSystem
// get the current selection, store it for the undo function and unselect everything
SelectionList& selection = GetCommandManager()->GetCurrentSelection();
mData = selection;
m_data = selection;
// if we are in selection lock mode return directly
//if (GetCommandManager()->GetLockSelection())
@@ -686,7 +686,7 @@ namespace CommandSystem
MCORE_UNUSED(outResult);
// restore the old selection and return success
GetCommandManager()->SetCurrentSelection(mData);
GetCommandManager()->SetCurrentSelection(m_data);
return true;
}
@@ -721,10 +721,10 @@ namespace CommandSystem
MCORE_UNUSED(outResult);
// store the selection locked flag for the undo function
mData = GetCommandManager()->GetLockSelection();
m_data = GetCommandManager()->GetLockSelection();
// toggle the flag
GetCommandManager()->SetLockSelection(!mData);
GetCommandManager()->SetLockSelection(!m_data);
return true;
}
@@ -737,7 +737,7 @@ namespace CommandSystem
MCORE_UNUSED(outResult);
// restore the old selection locked flag and return success
GetCommandManager()->SetLockSelection(mData);
GetCommandManager()->SetLockSelection(m_data);
return true;
}
@@ -19,7 +19,7 @@
namespace CommandSystem
{
MCORE_DEFINECOMMAND_START(CommandSelect, "Select object", true)
SelectionList mData;
SelectionList m_data;
public:
static const char* s_SelectCmdName;
static bool Select(MCore::Command* command, const MCore::CommandLine& parameters, AZStd::string& outResult, bool unselect);
@@ -27,39 +27,39 @@ namespace CommandSystem
size_t SelectionList::GetNumTotalItems() const
{
return mSelectedNodes.size() +
mSelectedActors.size() +
mSelectedActorInstances.size() +
mSelectedMotions.size() +
mSelectedMotionInstances.size() +
mSelectedAnimGraphs.size();
return m_selectedNodes.size() +
m_selectedActors.size() +
m_selectedActorInstances.size() +
m_selectedMotions.size() +
m_selectedMotionInstances.size() +
m_selectedAnimGraphs.size();
}
bool SelectionList::GetIsEmpty() const
{
return (mSelectedNodes.empty() &&
mSelectedActors.empty() &&
mSelectedActorInstances.empty() &&
mSelectedMotions.empty() &&
mSelectedMotionInstances.empty() &&
mSelectedAnimGraphs.empty());
return (m_selectedNodes.empty() &&
m_selectedActors.empty() &&
m_selectedActorInstances.empty() &&
m_selectedMotions.empty() &&
m_selectedMotionInstances.empty() &&
m_selectedAnimGraphs.empty());
}
void SelectionList::Clear()
{
mSelectedNodes.clear();
mSelectedActors.clear();
mSelectedActorInstances.clear();
mSelectedMotions.clear();
mSelectedMotionInstances.clear();
mSelectedAnimGraphs.clear();
m_selectedNodes.clear();
m_selectedActors.clear();
m_selectedActorInstances.clear();
m_selectedMotions.clear();
m_selectedMotionInstances.clear();
m_selectedAnimGraphs.clear();
}
void SelectionList::AddNode(EMotionFX::Node* node)
{
if (!CheckIfHasNode(node))
{
mSelectedNodes.emplace_back(node);
m_selectedNodes.emplace_back(node);
}
}
@@ -67,7 +67,7 @@ namespace CommandSystem
{
if (!CheckIfHasActor(actor))
{
mSelectedActors.emplace_back(actor);
m_selectedActors.emplace_back(actor);
}
}
@@ -76,7 +76,7 @@ namespace CommandSystem
{
if (!CheckIfHasActorInstance(actorInstance))
{
mSelectedActorInstances.emplace_back(actorInstance);
m_selectedActorInstances.emplace_back(actorInstance);
}
}
@@ -86,7 +86,7 @@ namespace CommandSystem
{
if (!CheckIfHasMotion(motion))
{
mSelectedMotions.emplace_back(motion);
m_selectedMotions.emplace_back(motion);
}
}
@@ -96,7 +96,7 @@ namespace CommandSystem
{
if (!CheckIfHasMotionInstance(motionInstance))
{
mSelectedMotionInstances.emplace_back(motionInstance);
m_selectedMotionInstances.emplace_back(motionInstance);
}
}
@@ -106,7 +106,7 @@ namespace CommandSystem
{
if (!CheckIfHasAnimGraph(animGraph))
{
mSelectedAnimGraphs.emplace_back(animGraph);
m_selectedAnimGraphs.emplace_back(animGraph);
}
}
@@ -209,52 +209,52 @@ namespace CommandSystem
void SelectionList::RemoveNode(EMotionFX::Node* node)
{
mSelectedNodes.erase(AZStd::remove(mSelectedNodes.begin(), mSelectedNodes.end(), node), mSelectedNodes.end());
m_selectedNodes.erase(AZStd::remove(m_selectedNodes.begin(), m_selectedNodes.end(), node), m_selectedNodes.end());
}
void SelectionList::RemoveActor(EMotionFX::Actor* actor)
{
mSelectedActors.erase(AZStd::remove(mSelectedActors.begin(), mSelectedActors.end(), actor), mSelectedActors.end());
m_selectedActors.erase(AZStd::remove(m_selectedActors.begin(), m_selectedActors.end(), actor), m_selectedActors.end());
}
// remove the actor from the selection list
void SelectionList::RemoveActorInstance(EMotionFX::ActorInstance* actorInstance)
{
mSelectedActorInstances.erase(AZStd::remove(mSelectedActorInstances.begin(), mSelectedActorInstances.end(), actorInstance), mSelectedActorInstances.end());
m_selectedActorInstances.erase(AZStd::remove(m_selectedActorInstances.begin(), m_selectedActorInstances.end(), actorInstance), m_selectedActorInstances.end());
}
// remove the motion from the selection list
void SelectionList::RemoveMotion(EMotionFX::Motion* motion)
{
mSelectedMotions.erase(AZStd::remove(mSelectedMotions.begin(), mSelectedMotions.end(), motion), mSelectedMotions.end());
m_selectedMotions.erase(AZStd::remove(m_selectedMotions.begin(), m_selectedMotions.end(), motion), m_selectedMotions.end());
}
// remove the motion instance from the selection list
void SelectionList::RemoveMotionInstance(EMotionFX::MotionInstance* motionInstance)
{
mSelectedMotionInstances.erase(AZStd::remove(mSelectedMotionInstances.begin(), mSelectedMotionInstances.end(), motionInstance), mSelectedMotionInstances.end());
m_selectedMotionInstances.erase(AZStd::remove(m_selectedMotionInstances.begin(), m_selectedMotionInstances.end(), motionInstance), m_selectedMotionInstances.end());
}
// remove the anim graph
void SelectionList::RemoveAnimGraph(EMotionFX::AnimGraph* animGraph)
{
mSelectedAnimGraphs.erase(AZStd::remove(mSelectedAnimGraphs.begin(), mSelectedAnimGraphs.end(), animGraph), mSelectedAnimGraphs.end());
m_selectedAnimGraphs.erase(AZStd::remove(m_selectedAnimGraphs.begin(), m_selectedAnimGraphs.end(), animGraph), m_selectedAnimGraphs.end());
}
// make the selection valid
void SelectionList::MakeValid()
{
// iterate through all actor instances and remove the invalid ones
for (size_t i = 0; i < mSelectedActorInstances.size();)
for (size_t i = 0; i < m_selectedActorInstances.size();)
{
EMotionFX::ActorInstance* actorInstance = mSelectedActorInstances[i];
EMotionFX::ActorInstance* actorInstance = m_selectedActorInstances[i];
if (EMotionFX::GetActorManager().CheckIfIsActorInstanceRegistered(actorInstance) == false)
{
mSelectedActorInstances.erase(mSelectedActorInstances.begin() + i);
m_selectedActorInstances.erase(m_selectedActorInstances.begin() + i);
}
else
{
@@ -263,13 +263,13 @@ namespace CommandSystem
}
// iterate through all anim graphs and remove all valid ones
for (size_t i = 0; i < mSelectedAnimGraphs.size();)
for (size_t i = 0; i < m_selectedAnimGraphs.size();)
{
EMotionFX::AnimGraph* animGraph = mSelectedAnimGraphs[i];
EMotionFX::AnimGraph* animGraph = m_selectedAnimGraphs[i];
if (EMotionFX::GetAnimGraphManager().FindAnimGraphIndex(animGraph) == MCORE_INVALIDINDEX32)
{
mSelectedAnimGraphs.erase(mSelectedAnimGraphs.begin() + i);
m_selectedAnimGraphs.erase(m_selectedAnimGraphs.begin() + i);
}
else
{
@@ -294,7 +294,7 @@ namespace CommandSystem
return nullptr;
}
return mSelectedActors[0];
return m_selectedActors[0];
}
@@ -313,7 +313,7 @@ namespace CommandSystem
return nullptr;
}
EMotionFX::ActorInstance* actorInstance = mSelectedActorInstances[0];
EMotionFX::ActorInstance* actorInstance = m_selectedActorInstances[0];
if (!actorInstance)
{
return nullptr;
@@ -324,7 +324,7 @@ namespace CommandSystem
return nullptr;
}
return mSelectedActorInstances[0];
return m_selectedActorInstances[0];
}
@@ -341,7 +341,7 @@ namespace CommandSystem
return nullptr;
}
EMotionFX::Motion* motion = mSelectedMotions[0];
EMotionFX::Motion* motion = m_selectedMotions[0];
if (!motion)
{
return nullptr;
@@ -45,36 +45,36 @@ namespace CommandSystem
* Get the number of selected nodes.
* @return The number of selected nodes.
*/
MCORE_INLINE size_t GetNumSelectedNodes() const { return mSelectedNodes.size(); }
MCORE_INLINE size_t GetNumSelectedNodes() const { return m_selectedNodes.size(); }
/**
* Get the number of selected actors
*/
MCORE_INLINE size_t GetNumSelectedActors() const { return mSelectedActors.size(); }
MCORE_INLINE size_t GetNumSelectedActors() const { return m_selectedActors.size(); }
/**
* Get the number of selected actor instances.
* @return The number of selected actor instances.
*/
MCORE_INLINE size_t GetNumSelectedActorInstances() const { return mSelectedActorInstances.size(); }
MCORE_INLINE size_t GetNumSelectedActorInstances() const { return m_selectedActorInstances.size(); }
/**
* Get the number of selected motion instances.
* @return The number of selected motion instances.
*/
MCORE_INLINE size_t GetNumSelectedMotionInstances() const { return mSelectedMotionInstances.size(); }
MCORE_INLINE size_t GetNumSelectedMotionInstances() const { return m_selectedMotionInstances.size(); }
/**
* Get the number of selected motions.
* @return The number of selected motions.
*/
MCORE_INLINE size_t GetNumSelectedMotions() const { return mSelectedMotions.size(); }
MCORE_INLINE size_t GetNumSelectedMotions() const { return m_selectedMotions.size(); }
/**
* Get the number of selected anim graphs.
* @return The number of selected anim graphs.
*/
MCORE_INLINE size_t GetNumSelectedAnimGraphs() const { return mSelectedAnimGraphs.size(); }
MCORE_INLINE size_t GetNumSelectedAnimGraphs() const { return m_selectedAnimGraphs.size(); }
/**
* Get the total number of selected objects.
@@ -139,7 +139,7 @@ namespace CommandSystem
* @param index The index of the node to get from the selection list.
* @return A pointer to the given node from the selection list.
*/
MCORE_INLINE EMotionFX::Node* GetNode(size_t index) const { return mSelectedNodes[index]; }
MCORE_INLINE EMotionFX::Node* GetNode(size_t index) const { return m_selectedNodes[index]; }
/**
* Get the first node from the selection list.
@@ -147,11 +147,11 @@ namespace CommandSystem
*/
MCORE_INLINE EMotionFX::Node* GetFirstNode() const
{
if (mSelectedNodes.empty())
if (m_selectedNodes.empty())
{
return nullptr;
}
return mSelectedNodes[0];
return m_selectedNodes[0];
}
/**
@@ -159,7 +159,7 @@ namespace CommandSystem
* @param index The index of the actor to get from the selection list.
* @return A pointer to the given actor from the selection list.
*/
MCORE_INLINE EMotionFX::Actor* GetActor(size_t index) const { return mSelectedActors[index]; }
MCORE_INLINE EMotionFX::Actor* GetActor(size_t index) const { return m_selectedActors[index]; }
/**
* Get the first actor from the selection list.
@@ -167,11 +167,11 @@ namespace CommandSystem
*/
MCORE_INLINE EMotionFX::Actor* GetFirstActor() const
{
if (mSelectedActors.empty())
if (m_selectedActors.empty())
{
return nullptr;
}
return mSelectedActors[0];
return m_selectedActors[0];
}
/**
@@ -179,7 +179,7 @@ namespace CommandSystem
* @param index The index of the actor instance to get from the selection list.
* @return A pointer to the given actor instance from the selection list.
*/
MCORE_INLINE EMotionFX::ActorInstance* GetActorInstance(size_t index) const { return mSelectedActorInstances[index]; }
MCORE_INLINE EMotionFX::ActorInstance* GetActorInstance(size_t index) const { return m_selectedActorInstances[index]; }
/**
* Get the first actor instance from the selection list.
@@ -187,11 +187,11 @@ namespace CommandSystem
*/
MCORE_INLINE EMotionFX::ActorInstance* GetFirstActorInstance() const
{
if (mSelectedActorInstances.empty())
if (m_selectedActorInstances.empty())
{
return nullptr;
}
return mSelectedActorInstances[0];
return m_selectedActorInstances[0];
}
/**
@@ -199,7 +199,7 @@ namespace CommandSystem
* @param index The index of the anim graph to get from the selection list.
* @return A pointer to the given anim graph from the selection list.
*/
MCORE_INLINE EMotionFX::AnimGraph* GetAnimGraph(size_t index) const { return mSelectedAnimGraphs[index]; }
MCORE_INLINE EMotionFX::AnimGraph* GetAnimGraph(size_t index) const { return m_selectedAnimGraphs[index]; }
/**
* Get the first anim graph from the selection list.
@@ -207,11 +207,11 @@ namespace CommandSystem
*/
MCORE_INLINE EMotionFX::AnimGraph* GetFirstAnimGraph() const
{
if (mSelectedAnimGraphs.empty())
if (m_selectedAnimGraphs.empty())
{
return nullptr;
}
return mSelectedAnimGraphs[0];
return m_selectedAnimGraphs[0];
}
/**
@@ -231,7 +231,7 @@ namespace CommandSystem
* @param index The index of the motion to get from the selection list.
* @return A pointer to the given motion from the selection list.
*/
MCORE_INLINE EMotionFX::Motion* GetMotion(size_t index) const { return mSelectedMotions[index]; }
MCORE_INLINE EMotionFX::Motion* GetMotion(size_t index) const { return m_selectedMotions[index]; }
/**
* Get the first motion from the selection list.
@@ -239,11 +239,11 @@ namespace CommandSystem
*/
MCORE_INLINE EMotionFX::Motion* GetFirstMotion() const
{
if (mSelectedMotions.empty())
if (m_selectedMotions.empty())
{
return nullptr;
}
return mSelectedMotions[0];
return m_selectedMotions[0];
}
/**
@@ -257,7 +257,7 @@ namespace CommandSystem
* @param index The index of the motion instance to get from the selection list.
* @return A pointer to the given motion instance from the selection list.
*/
MCORE_INLINE EMotionFX::MotionInstance* GetMotionInstance(size_t index) const { return mSelectedMotionInstances[index]; }
MCORE_INLINE EMotionFX::MotionInstance* GetMotionInstance(size_t index) const { return m_selectedMotionInstances[index]; }
/**
* Get the first motion instance from the selection list.
@@ -265,48 +265,48 @@ namespace CommandSystem
*/
MCORE_INLINE EMotionFX::MotionInstance* GetFirstMotionInstance() const
{
if (mSelectedMotionInstances.empty())
if (m_selectedMotionInstances.empty())
{
return nullptr;
}
return mSelectedMotionInstances[0];
return m_selectedMotionInstances[0];
}
/**
* Remove the given node from the selection list.
* @param index The index of the node to be removed from the selection list.
*/
MCORE_INLINE void RemoveNode(size_t index) { mSelectedNodes.erase(mSelectedNodes.begin() + index); }
MCORE_INLINE void RemoveNode(size_t index) { m_selectedNodes.erase(m_selectedNodes.begin() + index); }
/**
* Remove the given actor instance from the selection list.
* @param index The index of the actor instance to be removed from the selection list.
*/
MCORE_INLINE void RemoveActor(size_t index) { mSelectedActors.erase(mSelectedActors.begin() + index); }
MCORE_INLINE void RemoveActor(size_t index) { m_selectedActors.erase(m_selectedActors.begin() + index); }
/**
* Remove the given actor instance from the selection list.
* @param index The index of the actor instance to be removed from the selection list.
*/
MCORE_INLINE void RemoveActorInstance(size_t index) { mSelectedActorInstances.erase(mSelectedActorInstances.begin() + index); }
MCORE_INLINE void RemoveActorInstance(size_t index) { m_selectedActorInstances.erase(m_selectedActorInstances.begin() + index); }
/**
* Remove the given motion from the selection list.
* @param index The index of the motion to be removed from the selection list.
*/
MCORE_INLINE void RemoveMotion(size_t index) { mSelectedMotions.erase(mSelectedMotions.begin() + index); }
MCORE_INLINE void RemoveMotion(size_t index) { m_selectedMotions.erase(m_selectedMotions.begin() + index); }
/**
* Remove the given motion instance from the selection list.
* @param index The index of the motion instance to be removed from the selection list.
*/
MCORE_INLINE void RemoveMotionInstance(size_t index) { mSelectedMotionInstances.erase(mSelectedMotionInstances.begin() + index); }
MCORE_INLINE void RemoveMotionInstance(size_t index) { m_selectedMotionInstances.erase(m_selectedMotionInstances.begin() + index); }
/**
* Remove the given anim graph from the selection list.
* @param index The index of the anim graph to remove from the selection list.
*/
MCORE_INLINE void RemoveAnimGraph(size_t index) { mSelectedAnimGraphs.erase(mSelectedAnimGraphs.begin() + index); }
MCORE_INLINE void RemoveAnimGraph(size_t index) { m_selectedAnimGraphs.erase(m_selectedAnimGraphs.begin() + index); }
/**
* Remove the given node from the selection list.
@@ -349,47 +349,47 @@ namespace CommandSystem
* @param node A pointer to the node to be checked.
* @return True if the node is inside this selection list, false if not.
*/
MCORE_INLINE bool CheckIfHasNode(EMotionFX::Node* node) const { return(AZStd::find(mSelectedNodes.begin(), mSelectedNodes.end(), node) != mSelectedNodes.end()); }
MCORE_INLINE bool CheckIfHasNode(EMotionFX::Node* node) const { return(AZStd::find(m_selectedNodes.begin(), m_selectedNodes.end(), node) != m_selectedNodes.end()); }
/**
* Has actor
*/
MCORE_INLINE bool CheckIfHasActor(EMotionFX::Actor* actor) const { return (AZStd::find(mSelectedActors.begin(), mSelectedActors.end(), actor) != mSelectedActors.end()); }
MCORE_INLINE bool CheckIfHasActor(EMotionFX::Actor* actor) const { return (AZStd::find(m_selectedActors.begin(), m_selectedActors.end(), actor) != m_selectedActors.end()); }
/**
* Check if a given actor instance is selected / is in this selection list.
* @param node A pointer to the actor instance to be checked.
* @return True if the actor instance is inside this selection list, false if not.
*/
MCORE_INLINE bool CheckIfHasActorInstance(EMotionFX::ActorInstance* actorInstance) const { return (AZStd::find(mSelectedActorInstances.begin(), mSelectedActorInstances.end(), actorInstance) != mSelectedActorInstances.end()); }
MCORE_INLINE bool CheckIfHasActorInstance(EMotionFX::ActorInstance* actorInstance) const { return (AZStd::find(m_selectedActorInstances.begin(), m_selectedActorInstances.end(), actorInstance) != m_selectedActorInstances.end()); }
/**
* Check if a given motion is selected / is in this selection list.
* @param node A pointer to the motion to be checked.
* @return True if the motion is inside this selection list, false if not.
*/
MCORE_INLINE bool CheckIfHasMotion(EMotionFX::Motion* motion) const { return (AZStd::find(mSelectedMotions.begin(), mSelectedMotions.end(), motion) != mSelectedMotions.end()); }
MCORE_INLINE bool CheckIfHasMotion(EMotionFX::Motion* motion) const { return (AZStd::find(m_selectedMotions.begin(), m_selectedMotions.end(), motion) != m_selectedMotions.end()); }
/**
* Check if a given anim graph is in this selection list.
* @param animGraph The anim graph to check for.
* @return True if the anim graph is selected inside the selection list, otherwise false is returned.
*/
MCORE_INLINE bool CheckIfHasAnimGraph(EMotionFX::AnimGraph* animGraph) const { return (AZStd::find(mSelectedAnimGraphs.begin(), mSelectedAnimGraphs.end(), animGraph) != mSelectedAnimGraphs.end()); }
MCORE_INLINE bool CheckIfHasAnimGraph(EMotionFX::AnimGraph* animGraph) const { return (AZStd::find(m_selectedAnimGraphs.begin(), m_selectedAnimGraphs.end(), animGraph) != m_selectedAnimGraphs.end()); }
/**
* Check if a given motion instance is selected / is in this selection list.
* @param node A pointer to the motion instance to be checked.
* @return True if the motion instance is inside this selection list, false if not.
*/
MCORE_INLINE bool CheckIfHasMotionInstance(EMotionFX::MotionInstance* motionInstance) const { return (AZStd::find(mSelectedMotionInstances.begin(), mSelectedMotionInstances.end(), motionInstance) != mSelectedMotionInstances.end()); }
MCORE_INLINE bool CheckIfHasMotionInstance(EMotionFX::MotionInstance* motionInstance) const { return (AZStd::find(m_selectedMotionInstances.begin(), m_selectedMotionInstances.end(), motionInstance) != m_selectedMotionInstances.end()); }
MCORE_INLINE void ClearActorSelection() { mSelectedActors.clear(); }
MCORE_INLINE void ClearActorInstanceSelection() { mSelectedActorInstances.clear(); }
MCORE_INLINE void ClearNodeSelection() { mSelectedNodes.clear(); }
MCORE_INLINE void ClearMotionSelection() { mSelectedMotions.clear(); }
MCORE_INLINE void ClearMotionInstanceSelection() { mSelectedMotionInstances.clear(); }
MCORE_INLINE void ClearAnimGraphSelection() { mSelectedAnimGraphs.clear(); }
MCORE_INLINE void ClearActorSelection() { m_selectedActors.clear(); }
MCORE_INLINE void ClearActorInstanceSelection() { m_selectedActorInstances.clear(); }
MCORE_INLINE void ClearNodeSelection() { m_selectedNodes.clear(); }
MCORE_INLINE void ClearMotionSelection() { m_selectedMotions.clear(); }
MCORE_INLINE void ClearMotionInstanceSelection() { m_selectedMotionInstances.clear(); }
MCORE_INLINE void ClearAnimGraphSelection() { m_selectedAnimGraphs.clear(); }
void Log();
void MakeValid();
@@ -401,11 +401,11 @@ namespace CommandSystem
// ActorInstanceNotificationBus overrides
void OnActorInstanceDestroyed(EMotionFX::ActorInstance* actorInstance) override;
AZStd::vector<EMotionFX::Node*> mSelectedNodes; /**< Array of selected nodes. */
AZStd::vector<EMotionFX::Actor*> mSelectedActors; /**< The selected actors. */
AZStd::vector<EMotionFX::ActorInstance*> mSelectedActorInstances; /**< Array of selected actor instances. */
AZStd::vector<EMotionFX::MotionInstance*> mSelectedMotionInstances; /**< Array of selected motion instances. */
AZStd::vector<EMotionFX::Motion*> mSelectedMotions; /**< Array of selected motions. */
AZStd::vector<EMotionFX::AnimGraph*> mSelectedAnimGraphs; /**< Array of selected anim graphs. */
AZStd::vector<EMotionFX::Node*> m_selectedNodes; /**< Array of selected nodes. */
AZStd::vector<EMotionFX::Actor*> m_selectedActors; /**< The selected actors. */
AZStd::vector<EMotionFX::ActorInstance*> m_selectedActorInstances; /**< Array of selected actor instances. */
AZStd::vector<EMotionFX::MotionInstance*> m_selectedMotionInstances; /**< Array of selected motion instances. */
AZStd::vector<EMotionFX::Motion*> m_selectedMotions; /**< Array of selected motions. */
AZStd::vector<EMotionFX::AnimGraph*> m_selectedAnimGraphs; /**< Array of selected anim graphs. */
};
} // namespace CommandSystem
@@ -14,15 +14,15 @@ namespace ExporterLib
{
void CopyVector2(EMotionFX::FileFormat::FileVector2& to, const AZ::Vector2& from)
{
to.mX = from.GetX();
to.mY = from.GetY();
to.m_x = from.GetX();
to.m_y = from.GetY();
}
void CopyVector(EMotionFX::FileFormat::FileVector3& to, const AZ::PackedVector3f& from)
{
to.mX = from.GetX();
to.mY = from.GetY();
to.mZ = from.GetZ();
to.m_x = from.GetX();
to.m_y = from.GetY();
to.m_z = from.GetZ();
}
void CopyQuaternion(EMotionFX::FileFormat::FileQuaternion& to, const AZ::Quaternion& from)
@@ -33,10 +33,10 @@ namespace ExporterLib
q = -q;
}
to.mX = q.GetX();
to.mY = q.GetY();
to.mZ = q.GetZ();
to.mW = q.GetW();
to.m_x = q.GetX();
to.m_y = q.GetY();
to.m_z = q.GetZ();
to.m_w = q.GetW();
}
@@ -49,37 +49,37 @@ namespace ExporterLib
}
const MCore::Compressed16BitQuaternion compressedQuat(q);
to.mX = compressedQuat.mX;
to.mY = compressedQuat.mY;
to.mZ = compressedQuat.mZ;
to.mW = compressedQuat.mW;
to.m_x = compressedQuat.m_x;
to.m_y = compressedQuat.m_y;
to.m_z = compressedQuat.m_z;
to.m_w = compressedQuat.m_w;
}
void Copy16BitQuaternion(EMotionFX::FileFormat::File16BitQuaternion& to, const MCore::Compressed16BitQuaternion& from)
{
MCore::Compressed16BitQuaternion q = from;
if (q.mW < 0)
if (q.m_w < 0)
{
q.mX = -q.mX;
q.mY = -q.mY;
q.mZ = -q.mZ;
q.mW = -q.mW;
q.m_x = -q.m_x;
q.m_y = -q.m_y;
q.m_z = -q.m_z;
q.m_w = -q.m_w;
}
to.mX = q.mX;
to.mY = q.mY;
to.mZ = q.mZ;
to.mW = q.mW;
to.m_x = q.m_x;
to.m_y = q.m_y;
to.m_z = q.m_z;
to.m_w = q.m_w;
}
void CopyColor(const MCore::RGBAColor& from, EMotionFX::FileFormat::FileColor& to)
{
to.mR = from.r;
to.mG = from.g;
to.mB = from.b;
to.mA = from.a;
to.m_r = from.m_r;
to.m_g = from.m_g;
to.m_b = from.m_b;
to.m_a = from.m_a;
}
@@ -114,87 +114,87 @@ namespace ExporterLib
void ConvertFileChunk(EMotionFX::FileFormat::FileChunk* value, MCore::Endian::EEndianType targetEndianType)
{
MCore::Endian::ConvertUnsignedInt32(&value->mChunkID, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->mSizeInBytes, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->mVersion, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->m_chunkId, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->m_sizeInBytes, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->m_version, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
}
void ConvertFileColor(EMotionFX::FileFormat::FileColor* value, MCore::Endian::EEndianType targetEndianType)
{
MCore::Endian::ConvertFloat(&value->mR, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->mG, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->mB, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->mA, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_r, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_g, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_b, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_a, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
}
void ConvertFileVector2(EMotionFX::FileFormat::FileVector2* value, MCore::Endian::EEndianType targetEndianType)
{
MCore::Endian::ConvertFloat(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_x, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_y, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
}
void ConvertFileVector3(EMotionFX::FileFormat::FileVector3* value, MCore::Endian::EEndianType targetEndianType)
{
MCore::Endian::ConvertFloat(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->mZ, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_x, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_y, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_z, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
}
void ConvertFile16BitVector3(EMotionFX::FileFormat::File16BitVector3* value, MCore::Endian::EEndianType targetEndianType)
{
MCore::Endian::ConvertUnsignedInt16(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt16(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt16(&value->mZ, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt16(&value->m_x, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt16(&value->m_y, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt16(&value->m_z, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
}
void ConvertFileQuaternion(EMotionFX::FileFormat::FileQuaternion* value, MCore::Endian::EEndianType targetEndianType)
{
MCore::Endian::ConvertFloat(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->mZ, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->mW, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_x, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_y, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_z, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_w, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
}
void ConvertFile16BitQuaternion(EMotionFX::FileFormat::File16BitQuaternion* value, MCore::Endian::EEndianType targetEndianType)
{
MCore::Endian::ConvertSignedInt16(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertSignedInt16(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertSignedInt16(&value->mZ, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertSignedInt16(&value->mW, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertSignedInt16(&value->m_x, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertSignedInt16(&value->m_y, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertSignedInt16(&value->m_z, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertSignedInt16(&value->m_w, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
}
void ConvertFileMotionEvent(EMotionFX::FileFormat::FileMotionEvent* value, MCore::Endian::EEndianType targetEndianType)
{
MCore::Endian::ConvertFloat(&value->mStartTime, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->mEndTime, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->mEventTypeIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->mMirrorTypeIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt16(&value->mParamIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_startTime, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_endTime, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->m_eventTypeIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->m_mirrorTypeIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt16(&value->m_paramIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
}
void ConvertFileMotionEventTable(EMotionFX::FileFormat::FileMotionEventTrack* value, MCore::Endian::EEndianType targetEndianType)
{
MCore::Endian::ConvertUnsignedInt32(&value->mNumEvents, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->mNumTypeStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->mNumParamStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->mNumMirrorTypeStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->m_numEvents, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->m_numTypeStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->m_numParamStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertUnsignedInt32(&value->m_numMirrorTypeStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
}
void ConvertRGBAColor(MCore::RGBAColor* value, MCore::Endian::EEndianType targetEndianType)
{
MCore::Endian::ConvertFloat(&value->r, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->g, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->b, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->a, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_r, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_g, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_b, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
MCore::Endian::ConvertFloat(&value->m_a, EXPLIB_PLATFORM_ENDIAN, targetEndianType);
}
@@ -52,9 +52,9 @@ namespace ExporterLib
const AZ::u32 bufferSize = static_cast<AZ::u32>(buffer.size());
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_PHYSICSSETUP;
chunkHeader.mVersion = 1;
chunkHeader.mSizeInBytes = bufferSize + sizeof(AZ::u32);
chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_PHYSICSSETUP;
chunkHeader.m_version = 1;
chunkHeader.m_sizeInBytes = bufferSize + sizeof(AZ::u32);
ConvertFileChunk(&chunkHeader, targetEndianType);
file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk));
@@ -90,9 +90,9 @@ namespace ExporterLib
const AZ::u32 bufferSize = static_cast<AZ::u32>(buffer.size());
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_SIMULATEDOBJECTSETUP;
chunkHeader.mVersion = 1;
chunkHeader.mSizeInBytes = bufferSize + sizeof(AZ::u32);
chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_SIMULATEDOBJECTSETUP;
chunkHeader.m_version = 1;
chunkHeader.m_sizeInBytes = bufferSize + sizeof(AZ::u32);
ConvertFileChunk(&chunkHeader, targetEndianType);
file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk));
@@ -122,9 +122,9 @@ namespace ExporterLib
// Write the chunk header
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_MESHASSET;
chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_MeshAsset) + GetStringChunkSize(meshAssetIdString.c_str());
chunkHeader.mVersion = 1;
chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_MESHASSET;
chunkHeader.m_sizeInBytes = sizeof(EMotionFX::FileFormat::Actor_MeshAsset) + GetStringChunkSize(meshAssetIdString.c_str());
chunkHeader.m_version = 1;
ConvertFileChunk(&chunkHeader, targetEndianType);
file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk));
@@ -23,14 +23,13 @@ namespace ExporterLib
// the header information
EMotionFX::FileFormat::Actor_Header header;
memset(&header, 0, sizeof(EMotionFX::FileFormat::Actor_Header));
header.mFourcc[0] = 'A';
header.mFourcc[1] = 'C';
header.mFourcc[2] = 'T';
header.mFourcc[3] = 'R';
header.mHiVersion = static_cast<uint8>(GetFileHighVersion());
header.mLoVersion = static_cast<uint8>(GetFileLowVersion());
header.mEndianType = static_cast<uint8>(targetEndianType);
//header.mMulOrder = EMotionFX::FileFormat::MULORDER_ROT_SCALE_TRANS;
header.m_fourcc[0] = 'A';
header.m_fourcc[1] = 'C';
header.m_fourcc[2] = 'T';
header.m_fourcc[3] = 'R';
header.m_hiVersion = static_cast<uint8>(GetFileHighVersion());
header.m_loVersion = static_cast<uint8>(GetFileLowVersion());
header.m_endianType = static_cast<uint8>(targetEndianType);
// write the header to the stream
file->Write(&header, sizeof(EMotionFX::FileFormat::Actor_Header));
@@ -50,42 +49,42 @@ namespace ExporterLib
{
// chunk header
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_INFO;
chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_INFO;
chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_Info3);
chunkHeader.mSizeInBytes += GetStringChunkSize(sourceApp);
chunkHeader.mSizeInBytes += GetStringChunkSize(orgFileName);
chunkHeader.mSizeInBytes += GetStringChunkSize(GetCompilationDate());
chunkHeader.mSizeInBytes += GetStringChunkSize(actorName);
chunkHeader.m_sizeInBytes = sizeof(EMotionFX::FileFormat::Actor_Info3);
chunkHeader.m_sizeInBytes += GetStringChunkSize(sourceApp);
chunkHeader.m_sizeInBytes += GetStringChunkSize(orgFileName);
chunkHeader.m_sizeInBytes += GetStringChunkSize(GetCompilationDate());
chunkHeader.m_sizeInBytes += GetStringChunkSize(actorName);
chunkHeader.mVersion = 3;
chunkHeader.m_version = 3;
EMotionFX::FileFormat::Actor_Info3 infoChunk;
memset(&infoChunk, 0, sizeof(EMotionFX::FileFormat::Actor_Info3));
infoChunk.mNumLODs = aznumeric_caster(numLODLevels);
infoChunk.mMotionExtractionNodeIndex = aznumeric_caster(motionExtractionNodeIndex);
infoChunk.mRetargetRootNodeIndex = aznumeric_caster(retargetRootNodeIndex);
infoChunk.mExporterHighVersion = static_cast<uint8>(EMotionFX::GetEMotionFX().GetHighVersion());
infoChunk.mExporterLowVersion = static_cast<uint8>(EMotionFX::GetEMotionFX().GetLowVersion());
infoChunk.mUnitType = static_cast<uint8>(unitType);
infoChunk.mOptimizeSkeleton = optimizeSkeleton ? 1 : 0;
infoChunk.m_numLoDs = aznumeric_caster(numLODLevels);
infoChunk.m_motionExtractionNodeIndex = aznumeric_caster(motionExtractionNodeIndex);
infoChunk.m_retargetRootNodeIndex = aznumeric_caster(retargetRootNodeIndex);
infoChunk.m_exporterHighVersion = static_cast<uint8>(EMotionFX::GetEMotionFX().GetHighVersion());
infoChunk.m_exporterLowVersion = static_cast<uint8>(EMotionFX::GetEMotionFX().GetLowVersion());
infoChunk.m_unitType = static_cast<uint8>(unitType);
infoChunk.m_optimizeSkeleton = optimizeSkeleton ? 1 : 0;
// print repositioning node information
MCore::LogDetailedInfo("- File Info");
MCore::LogDetailedInfo(" + Actor Name: '%s'", actorName);
MCore::LogDetailedInfo(" + Source Application: '%s'", sourceApp);
MCore::LogDetailedInfo(" + Original File: '%s'", orgFileName);
MCore::LogDetailedInfo(" + Exporter Version: v%d.%d", infoChunk.mExporterHighVersion, infoChunk.mExporterLowVersion);
MCore::LogDetailedInfo(" + Exporter Version: v%d.%d", infoChunk.m_exporterHighVersion, infoChunk.m_exporterLowVersion);
MCore::LogDetailedInfo(" + Exporter Compilation Date: '%s'", GetCompilationDate());
MCore::LogDetailedInfo(" + Num LODs = %d", infoChunk.mNumLODs);
MCore::LogDetailedInfo(" + Motion extraction node index = %d", infoChunk.mMotionExtractionNodeIndex);
MCore::LogDetailedInfo(" + Retarget root node index = %d", infoChunk.mRetargetRootNodeIndex);
MCore::LogDetailedInfo(" + Num LODs = %d", infoChunk.m_numLoDs);
MCore::LogDetailedInfo(" + Motion extraction node index = %d", infoChunk.m_motionExtractionNodeIndex);
MCore::LogDetailedInfo(" + Retarget root node index = %d", infoChunk.m_retargetRootNodeIndex);
// endian conversion
ConvertFileChunk(&chunkHeader, targetEndianType);
ConvertUnsignedInt(&infoChunk.mMotionExtractionNodeIndex, targetEndianType);
ConvertUnsignedInt(&infoChunk.mRetargetRootNodeIndex, targetEndianType);
ConvertUnsignedInt(&infoChunk.mNumLODs, targetEndianType);
ConvertUnsignedInt(&infoChunk.m_motionExtractionNodeIndex, targetEndianType);
ConvertUnsignedInt(&infoChunk.m_retargetRootNodeIndex, targetEndianType);
ConvertUnsignedInt(&infoChunk.m_numLoDs, targetEndianType);
file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk));
file->Write(&infoChunk, sizeof(EMotionFX::FileFormat::Actor_Info3));
@@ -104,14 +103,14 @@ namespace ExporterLib
EMotionFX::FileFormat::Motion_Header header;
memset(&header, 0, sizeof(EMotionFX::FileFormat::Motion_Header));
header.mFourcc[0] = 'M';
header.mFourcc[1] = 'O';
header.mFourcc[2] = 'T';
header.mFourcc[3] = ' ';
header.m_fourcc[0] = 'M';
header.m_fourcc[1] = 'O';
header.m_fourcc[2] = 'T';
header.m_fourcc[3] = ' ';
header.mHiVersion = static_cast<uint8>(GetFileHighVersion());
header.mLoVersion = static_cast<uint8>(GetFileLowVersion());
header.mEndianType = static_cast<uint8>(targetEndianType);
header.m_hiVersion = static_cast<uint8>(GetFileHighVersion());
header.m_loVersion = static_cast<uint8>(GetFileLowVersion());
header.m_endianType = static_cast<uint8>(targetEndianType);
// write the header to the stream
file->Write(&header, sizeof(EMotionFX::FileFormat::Motion_Header));
@@ -122,26 +121,26 @@ namespace ExporterLib
{
// chunk header
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::MOTION_CHUNK_INFO;
chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Motion_Info3);
chunkHeader.mVersion = 3;
chunkHeader.m_chunkId = EMotionFX::FileFormat::MOTION_CHUNK_INFO;
chunkHeader.m_sizeInBytes = sizeof(EMotionFX::FileFormat::Motion_Info3);
chunkHeader.m_version = 3;
EMotionFX::FileFormat::Motion_Info3 infoChunk;
memset(&infoChunk, 0, sizeof(EMotionFX::FileFormat::Motion_Info3));
infoChunk.mMotionExtractionFlags = motion->GetMotionExtractionFlags();
infoChunk.mMotionExtractionNodeIndex= MCORE_INVALIDINDEX32; // not used anymore
infoChunk.mUnitType = static_cast<uint8>(motion->GetUnitType());
infoChunk.mIsAdditive = motion->GetMotionData()->IsAdditive() ? 1 : 0;
infoChunk.m_motionExtractionFlags = motion->GetMotionExtractionFlags();
infoChunk.m_motionExtractionNodeIndex= MCORE_INVALIDINDEX32; // not used anymore
infoChunk.m_unitType = static_cast<uint8>(motion->GetUnitType());
infoChunk.m_isAdditive = motion->GetMotionData()->IsAdditive() ? 1 : 0;
MCore::LogDetailedInfo("- File Info");
MCore::LogDetailedInfo(" + Exporter Compilation Date = '%s'", GetCompilationDate());
MCore::LogDetailedInfo(" + Motion Extraction Flags = 0x%x [capZ=%d]", infoChunk.mMotionExtractionFlags, (infoChunk.mMotionExtractionFlags & EMotionFX::MOTIONEXTRACT_CAPTURE_Z) ? 1 : 0);
MCore::LogDetailedInfo(" + Motion Extraction Flags = 0x%x [capZ=%d]", infoChunk.m_motionExtractionFlags, (infoChunk.m_motionExtractionFlags & EMotionFX::MOTIONEXTRACT_CAPTURE_Z) ? 1 : 0);
// endian conversion
ConvertFileChunk(&chunkHeader, targetEndianType);
ConvertUnsignedInt(&infoChunk.mMotionExtractionFlags, targetEndianType);
ConvertUnsignedInt(&infoChunk.mMotionExtractionNodeIndex, targetEndianType);
ConvertUnsignedInt(&infoChunk.m_motionExtractionFlags, targetEndianType);
ConvertUnsignedInt(&infoChunk.m_motionExtractionNodeIndex, targetEndianType);
file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk));
file->Write(&infoChunk, sizeof(EMotionFX::FileFormat::Motion_Info2));
@@ -1,298 +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
*
*/
#include "Exporter.h"
#include <EMotionFX/Source/StandardMaterial.h>
#include <EMotionFX/Source/Actor.h>
#include <EMotionFX/Source/Importer/ActorFileFormat.h>
#include <MCore/Source/AttributeFloat.h>
#include <MCore/Source/LogManager.h>
namespace ExporterLib
{
// write the material attribute set
void SaveMaterialAttributeSet(MCore::Stream* file, EMotionFX::Material* material, uint32 lodLevel, uint32 materialNumber, MCore::Endian::EEndianType targetEndianType)
{
AZ_UNUSED(material);
// write the chunk header
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_MATERIALATTRIBUTESET;
chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_MaterialAttributeSet);
chunkHeader.mVersion = 1;
ConvertFileChunk(&chunkHeader, targetEndianType);
file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk));
// write the attribute set info header
EMotionFX::FileFormat::Actor_MaterialAttributeSet setInfo;
setInfo.mMaterialIndex = materialNumber;
setInfo.mLODLevel = lodLevel;
ConvertUnsignedInt(&setInfo.mMaterialIndex, targetEndianType);
ConvertUnsignedInt(&setInfo.mLODLevel, targetEndianType);
file->Write(&setInfo, sizeof(EMotionFX::FileFormat::Actor_MaterialAttributeSet));
// Write a former empty attribute set.
uint8 version = 1;
file->Write(&version, sizeof(uint8));
uint32 numAttributes = 0;
ConvertUnsignedInt(&numAttributes, targetEndianType);
file->Write(&numAttributes, sizeof(uint32));
}
// save the given material for the given LOD level
void SaveMaterial(MCore::Stream* file, EMotionFX::Material* material, uint32 lodLevel, uint32 materialNumber, MCore::Endian::EEndianType targetEndianType)
{
//----------------------------------------
// Generic EMotionFX::Material
//----------------------------------------
if (material->GetType() == EMotionFX::Material::TYPE_ID)
{
// chunk header
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_GENERICMATERIAL;
chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_GenericMaterial) + GetStringChunkSize(material->GetName());
chunkHeader.mVersion = 1;
EMotionFX::FileFormat::Actor_GenericMaterial materialChunk;
materialChunk.mLOD = lodLevel;
ConvertFileChunk(&chunkHeader, targetEndianType);
ConvertUnsignedInt(&materialChunk.mLOD, targetEndianType);
// write header and material
file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk));
file->Write(&materialChunk, sizeof(EMotionFX::FileFormat::Actor_GenericMaterial));
// followed by:
SaveString(material->GetName(), file, targetEndianType);
MCore::LogDetailedInfo("- Generic material:");
MCore::LogDetailedInfo(" + Name: '%s'", material->GetName());
MCore::LogDetailedInfo(" + LOD: %d", lodLevel);
}
//----------------------------------------
// Standard EMotionFX::Material
//----------------------------------------
if (material->GetType() == EMotionFX::StandardMaterial::TYPE_ID)
{
// typecast to a standard material
EMotionFX::StandardMaterial* standardMaterial = (EMotionFX::StandardMaterial*)material;
// chunk header
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_STDMATERIAL;
chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_StandardMaterial) + GetStringChunkSize(standardMaterial->GetName());
chunkHeader.mVersion = 1;
const uint32 numLayers = standardMaterial->GetNumLayers();
for (uint32 i = 0; i < numLayers; ++i)
{
chunkHeader.mSizeInBytes += sizeof(EMotionFX::FileFormat::Actor_StandardMaterialLayer);
chunkHeader.mSizeInBytes += GetStringChunkSize(standardMaterial->GetLayer(i)->GetFileName());
}
EMotionFX::FileFormat::Actor_StandardMaterial materialChunk;
CopyColor(standardMaterial->GetAmbient(), materialChunk.mAmbient);
CopyColor(standardMaterial->GetDiffuse(), materialChunk.mDiffuse);
CopyColor(standardMaterial->GetSpecular(), materialChunk.mSpecular);
CopyColor(standardMaterial->GetEmissive(), materialChunk.mEmissive);
materialChunk.mDoubleSided = standardMaterial->GetDoubleSided();
materialChunk.mIOR = standardMaterial->GetIOR();
materialChunk.mOpacity = standardMaterial->GetOpacity();
materialChunk.mShine = standardMaterial->GetShine();
materialChunk.mShineStrength = standardMaterial->GetShineStrength();
materialChunk.mTransparencyType = 'F';//standardMaterial->GetTransparencyType();
materialChunk.mWireFrame = standardMaterial->GetWireFrame();
materialChunk.mNumLayers = static_cast<uint8>(standardMaterial->GetNumLayers());
materialChunk.mLOD = lodLevel;
// add it to the log file
MCore::LogDetailedInfo("- Standard material:");
MCore::LogDetailedInfo(" + Name: '%s'", standardMaterial->GetName());
MCore::LogDetailedInfo(" + LOD: %d", lodLevel);
MCore::LogDetailedInfo(" + Ambient: r=%f g=%f b=%f", materialChunk.mAmbient.mR, materialChunk.mAmbient.mG, materialChunk.mAmbient.mB);
MCore::LogDetailedInfo(" + Diffuse: r=%f g=%f b=%f", materialChunk.mDiffuse.mR, materialChunk.mDiffuse.mG, materialChunk.mDiffuse.mB);
MCore::LogDetailedInfo(" + Specular: r=%f g=%f b=%f", materialChunk.mSpecular.mR, materialChunk.mSpecular.mG, materialChunk.mSpecular.mB);
MCore::LogDetailedInfo(" + Emissive: r=%f g=%f b=%f", materialChunk.mEmissive.mR, materialChunk.mEmissive.mG, materialChunk.mEmissive.mB);
MCore::LogDetailedInfo(" + Shine: %f", materialChunk.mShine);
MCore::LogDetailedInfo(" + ShineStrength: %f", materialChunk.mShineStrength);
MCore::LogDetailedInfo(" + Opacity: %f", materialChunk.mOpacity);
MCore::LogDetailedInfo(" + IndexOfRefraction: %f", materialChunk.mIOR);
MCore::LogDetailedInfo(" + DoubleSided: %i", (int)materialChunk.mDoubleSided);
MCore::LogDetailedInfo(" + WireFrame: %i", (int)materialChunk.mWireFrame);
MCore::LogDetailedInfo(" + TransparencyType: %c", (char)materialChunk.mTransparencyType);
MCore::LogDetailedInfo(" + NumLayers: %i", materialChunk.mNumLayers);
// endian conversion
ConvertFileChunk(&chunkHeader, targetEndianType);
ConvertFileColor(&materialChunk.mAmbient, targetEndianType);
ConvertFileColor(&materialChunk.mDiffuse, targetEndianType);
ConvertFileColor(&materialChunk.mSpecular, targetEndianType);
ConvertFileColor(&materialChunk.mEmissive, targetEndianType);
ConvertFloat(&materialChunk.mIOR, targetEndianType);
ConvertFloat(&materialChunk.mOpacity, targetEndianType);
ConvertFloat(&materialChunk.mShine, targetEndianType);
ConvertFloat(&materialChunk.mShineStrength, targetEndianType);
ConvertUnsignedInt(&materialChunk.mLOD, targetEndianType);
// write header and material
file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk));
file->Write(&materialChunk, sizeof(EMotionFX::FileFormat::Actor_StandardMaterial));
// followed by:
SaveString(standardMaterial->GetName(), file, targetEndianType);
// save all material layers
for (uint32 i = 0; i < numLayers; ++i)
{
// get the layer
EMotionFX::StandardMaterialLayer* layer = standardMaterial->GetLayer(i);
EMotionFX::FileFormat::Actor_StandardMaterialLayer materialChunkLayer;
materialChunkLayer.mAmount = layer->GetAmount();
materialChunkLayer.mMapType = static_cast<uint8>(layer->GetType());
materialChunkLayer.mMaterialNumber = (uint16)materialNumber;
materialChunkLayer.mRotationRadians = layer->GetRotationRadians();
materialChunkLayer.mUOffset = layer->GetUOffset();
materialChunkLayer.mVOffset = layer->GetVOffset();
materialChunkLayer.mUTiling = layer->GetUTiling();
materialChunkLayer.mVTiling = layer->GetVTiling();
materialChunkLayer.mBlendMode = layer->GetBlendMode();
// add to log file
MCore::LogDetailedInfo(" - Material layer #%d:", i);
MCore::LogDetailedInfo(" + Name: '%s' (MatNr=%i)", layer->GetFileName(), materialNumber);
MCore::LogDetailedInfo(" + Amount: %f", materialChunkLayer.mAmount);
MCore::LogDetailedInfo(" + Type: %i", (int)materialChunkLayer.mMapType);
MCore::LogDetailedInfo(" + BlendMode: %i", (int)materialChunkLayer.mBlendMode);
MCore::LogDetailedInfo(" + MaterialNumber: %i", (uint32)materialChunkLayer.mMaterialNumber);
MCore::LogDetailedInfo(" + UOffset: %f", materialChunkLayer.mUOffset);
MCore::LogDetailedInfo(" + VOffset: %f", materialChunkLayer.mVOffset);
MCore::LogDetailedInfo(" + UTiling: %f", materialChunkLayer.mUTiling);
MCore::LogDetailedInfo(" + VTiling: %f", materialChunkLayer.mVTiling);
MCore::LogDetailedInfo(" + RotationRadians: %f", materialChunkLayer.mRotationRadians);
// endian conversion
ConvertFloat(&materialChunkLayer.mAmount, targetEndianType);
ConvertUnsignedShort(&materialChunkLayer.mMaterialNumber, targetEndianType);
ConvertFloat(&materialChunkLayer.mRotationRadians, targetEndianType);
ConvertFloat(&materialChunkLayer.mUOffset, targetEndianType);
ConvertFloat(&materialChunkLayer.mVOffset, targetEndianType);
ConvertFloat(&materialChunkLayer.mUTiling, targetEndianType);
ConvertFloat(&materialChunkLayer.mVTiling, targetEndianType);
// write header and material layer
file->Write(&materialChunkLayer, sizeof(EMotionFX::FileFormat::Actor_StandardMaterialLayer));
SaveString(layer->GetFileName(), file, targetEndianType);
}
}
}
// save the given materials
void SaveMaterials(MCore::Stream* file, AZStd::vector<EMotionFX::Material*>& materials, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType)
{
// get the number of materials
const uint32 numMaterials = materials.size();
// chunk header
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_MATERIALINFO;
chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_MaterialInfo);
chunkHeader.mVersion = 1;
// convert endian and write to file
ConvertFileChunk(&chunkHeader, targetEndianType);
file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk));
EMotionFX::FileFormat::Actor_MaterialInfo materialInfoChunk;
materialInfoChunk.mLOD = lodLevel;
materialInfoChunk.mNumTotalMaterials = numMaterials;
materialInfoChunk.mNumStandardMaterials = 0;
materialInfoChunk.mNumFXMaterials = 0;
materialInfoChunk.mNumGenericMaterials = 0;
for (uint32 i = 0; i < numMaterials; i++)
{
if (materials[i]->GetType() == EMotionFX::Material::TYPE_ID)
{
materialInfoChunk.mNumGenericMaterials++;
}
if (materials[i]->GetType() == EMotionFX::StandardMaterial::TYPE_ID)
{
materialInfoChunk.mNumStandardMaterials++;
}
}
MCore::LogDetailedInfo("============================================================");
MCore::LogInfo("Materials (%d)", numMaterials);
MCore::LogDetailedInfo("============================================================");
MCORE_ASSERT(materialInfoChunk.mNumTotalMaterials == materialInfoChunk.mNumStandardMaterials + materialInfoChunk.mNumFXMaterials + materialInfoChunk.mNumGenericMaterials);
// convert endian and write to disk
ConvertUnsignedInt(&materialInfoChunk.mNumTotalMaterials, targetEndianType);
ConvertUnsignedInt(&materialInfoChunk.mNumStandardMaterials, targetEndianType);
ConvertUnsignedInt(&materialInfoChunk.mNumFXMaterials, targetEndianType);
ConvertUnsignedInt(&materialInfoChunk.mNumGenericMaterials, targetEndianType);
ConvertUnsignedInt(&materialInfoChunk.mLOD, targetEndianType);
file->Write(&materialInfoChunk, sizeof(EMotionFX::FileFormat::Actor_MaterialInfo));
// export all materials
for (uint32 i = 0; i < numMaterials; i++)
{
SaveMaterial(file, materials[i], lodLevel, i, targetEndianType);
}
// save all material attribute sets
for (uint32 i = 0; i < numMaterials; i++)
{
SaveMaterialAttributeSet(file, materials[i], lodLevel, i, targetEndianType);
}
}
// save out all materials for a given LOD level
void SaveMaterials(MCore::Stream* file, EMotionFX::Actor* actor, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType)
{
// get the number of materials in the given lod level
const uint32 numMaterials = actor->GetNumMaterials(lodLevel);
// create our materials array and reserve some elements
AZStd::vector<EMotionFX::Material*> materials;
materials.reserve(numMaterials);
// iterate through the materials
for (uint32 j = 0; j < numMaterials; j++)
{
// get the base material
EMotionFX::Material* baseMaterial = actor->GetMaterial(lodLevel, j);
materials.emplace_back(baseMaterial);
}
// save the materials
SaveMaterials(file, materials, lodLevel, targetEndianType);
}
// save all materials for all LOD levels
void SaveMaterials(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType)
{
// get the number of LOD levels and iterate through them
const uint32 numLODLevels = actor->GetNumLODLevels();
for (uint32 i = 0; i < numLODLevels; ++i)
{
SaveMaterials(file, actor, i, targetEndianType);
}
}
} // namespace ExporterLib
@@ -1,270 +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
*
*/
#include "Exporter.h"
#include <EMotionFX/Source/Mesh.h>
#include <EMotionFX/Source/SubMesh.h>
#include <EMotionFX/Source/VertexAttributeLayerAbstractData.h>
#include <EMotionFX/Source/Importer/Importer.h>
#include <EMotionFX/Source/Importer/ActorFileFormat.h>
#include <EMotionFX/Source/Node.h>
#include <MCore/Source/LogManager.h>
namespace ExporterLib
{
// save the given mesh
void SaveMesh(MCore::Stream* file, EMotionFX::Mesh* mesh, uint32 nodeIndex, bool isCollisionMesh, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType)
{
// convert endian for abstract layers
for (uint32 i = 0; i < mesh->GetNumVertexAttributeLayers(); ++i)
{
EMotionFX::VertexAttributeLayer* layer = mesh->GetVertexAttributeLayer(i);
if (!layer->GetIsAbstractDataClass())
{
continue;
}
EMotionFX::VertexAttributeLayerAbstractData* abstractLayer = static_cast<EMotionFX::VertexAttributeLayerAbstractData*>(layer);
const uint32 type = abstractLayer->GetType();
EMotionFX::Importer::AbstractLayerConverter layerConvertFunction;
layerConvertFunction = EMotionFX::Importer::StandardLayerConvert;
// convert endian and coordinate systems of all data
if (layerConvertFunction(abstractLayer, targetEndianType) == false)
{
MCore::LogError("Don't know how to endian and/or coordinate system convert layer with type %d (%s)", type, EMotionFX::Importer::ActorVertexAttributeLayerTypeToString(type));
}
}
uint32 totalSize = sizeof(EMotionFX::FileFormat::Actor_Mesh);
// add all layers to the total size
uint32 numMeshVerts = mesh->GetNumVertices();
for (uint32 i = 0; i < mesh->GetNumVertexAttributeLayers(); ++i)
{
EMotionFX::VertexAttributeLayer* layer = mesh->GetVertexAttributeLayer(i);
if (!layer->GetIsAbstractDataClass())
{
continue;
}
EMotionFX::VertexAttributeLayerAbstractData* abstractLayer = static_cast<EMotionFX::VertexAttributeLayerAbstractData*>(layer);
totalSize += sizeof(EMotionFX::FileFormat::Actor_VertexAttributeLayer);
totalSize += numMeshVerts * abstractLayer->GetAttributeSizeInBytes();
totalSize += GetStringChunkSize(layer->GetNameString());
}
// add the submeshes
for (uint32 i = 0; i < mesh->GetNumSubMeshes(); ++i)
{
EMotionFX::SubMesh* subMesh = mesh->GetSubMesh(i);
totalSize += sizeof(EMotionFX::FileFormat::Actor_SubMesh);
totalSize += sizeof(uint32) * subMesh->GetNumIndices();
totalSize += sizeof(uint8) * subMesh->GetNumPolygons();
totalSize += sizeof(uint32) * subMesh->GetNumBones();
}
// write the chunk header
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_MESH;
chunkHeader.mSizeInBytes = totalSize;
chunkHeader.mVersion = 1;
ConvertFileChunk(&chunkHeader, targetEndianType);
file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk));
// write the mesh header
EMotionFX::FileFormat::Actor_Mesh meshHeader;
memset(&meshHeader, 0, sizeof(EMotionFX::FileFormat::Actor_Mesh));
meshHeader.mIsCollisionMesh = isCollisionMesh ? 1 : 0;
meshHeader.mNodeIndex = nodeIndex;
meshHeader.mNumLayers = mesh->GetNumVertexAttributeLayers();
meshHeader.mNumOrgVerts = mesh->GetNumOrgVertices();
meshHeader.mNumSubMeshes = mesh->GetNumSubMeshes();
meshHeader.mNumPolygons = mesh->GetNumPolygons();
meshHeader.mTotalIndices = mesh->GetNumIndices();
meshHeader.mLOD = lodLevel;
meshHeader.mTotalVerts = (mesh->GetNumVertexAttributeLayers() > 0) ? mesh->GetNumVertices() : 0;
meshHeader.mIsTriangleMesh = mesh->CheckIfIsTriangleMesh();
MCore::LogDetailedInfo("- Mesh for node with node number %d:", meshHeader.mNodeIndex);
MCore::LogDetailedInfo(" + LOD: %d", meshHeader.mLOD);
MCore::LogDetailedInfo(" + Num original vertices: %d", meshHeader.mNumOrgVerts);
MCore::LogDetailedInfo(" + Total vertices: %d", meshHeader.mTotalVerts);
MCore::LogDetailedInfo(" + Total polygons: %d", meshHeader.mNumPolygons);
MCore::LogDetailedInfo(" + Total indices: %d", meshHeader.mTotalIndices);
MCore::LogDetailedInfo(" + Num submeshes: %d", meshHeader.mNumSubMeshes);
MCore::LogDetailedInfo(" + Num attribute layers: %d", meshHeader.mNumLayers);
MCore::LogDetailedInfo(" + Is collision mesh: %s", meshHeader.mIsCollisionMesh ? "Yes" : "No");
MCore::LogDetailedInfo(" + Is triangle mesh: %s", meshHeader.mIsTriangleMesh ? "Yes" : "No");
//for (uint32 i=0; i<mesh->GetNumPolygons(); ++i)
//MCore::LogInfo("poly %d = %d verts", i, mesh->GetPolygonVertexCounts()[i] );
// convert endian
ConvertUnsignedInt(&meshHeader.mNodeIndex, targetEndianType);
ConvertUnsignedInt(&meshHeader.mNumLayers, targetEndianType);
ConvertUnsignedInt(&meshHeader.mNumSubMeshes, targetEndianType);
ConvertUnsignedInt(&meshHeader.mNumPolygons, targetEndianType);
ConvertUnsignedInt(&meshHeader.mTotalIndices, targetEndianType);
ConvertUnsignedInt(&meshHeader.mTotalVerts, targetEndianType);
ConvertUnsignedInt(&meshHeader.mNumOrgVerts, targetEndianType);
ConvertUnsignedInt(&meshHeader.mLOD, targetEndianType);
// write to file
file->Write(&meshHeader, sizeof(EMotionFX::FileFormat::Actor_Mesh));
// now save all layers
const uint32 numLayers = mesh->GetNumVertexAttributeLayers();
for (uint32 layerNr = 0; layerNr < numLayers; ++layerNr)
{
EMotionFX::VertexAttributeLayer* layer = mesh->GetVertexAttributeLayer(layerNr);
if (!layer->GetIsAbstractDataClass())
{
continue;
}
EMotionFX::VertexAttributeLayerAbstractData* abstractLayer = static_cast<EMotionFX::VertexAttributeLayerAbstractData*>(layer);
EMotionFX::FileFormat::Actor_VertexAttributeLayer fileLayer;
memset(&fileLayer, 0, sizeof(EMotionFX::FileFormat::Actor_VertexAttributeLayer));
fileLayer.mLayerTypeID = layer->GetType();
fileLayer.mAttribSizeInBytes = abstractLayer->GetAttributeSizeInBytes();
fileLayer.mEnableDeformations = layer->GetKeepOriginals() ? 1 : 0;
fileLayer.mIsScale = 0;// TODO: not used
MCore::LogDetailedInfo(" - Layer #%d (%s):", layerNr, EMotionFX::Importer::ActorVertexAttributeLayerTypeToString(fileLayer.mLayerTypeID));
MCore::LogDetailedInfo(" + Type ID: %d", fileLayer.mLayerTypeID);
MCore::LogDetailedInfo(" + Attrib size: %d bytes", fileLayer.mAttribSizeInBytes);
MCore::LogDetailedInfo(" + Enable deforms: %s", fileLayer.mEnableDeformations ? "Yes" : "No");
MCore::LogDetailedInfo(" + Name: %s", layer->GetName());
// convert endian
ConvertUnsignedInt(&fileLayer.mAttribSizeInBytes, targetEndianType);
ConvertUnsignedInt(&fileLayer.mLayerTypeID, targetEndianType);
// write the layer header
file->Write(&fileLayer, sizeof(EMotionFX::FileFormat::Actor_VertexAttributeLayer));
// write the name
SaveString(layer->GetNameString(), file, targetEndianType);
// write the layer
file->Write((uint8*)abstractLayer->GetOriginalData(), abstractLayer->CalcTotalDataSizeInBytes(false));
}
// and finally save all submeshes
const uint32 numSubMeshes = mesh->GetNumSubMeshes();
for (uint32 s = 0; s < numSubMeshes; ++s)
{
EMotionFX::SubMesh* subMesh = mesh->GetSubMesh(s);
EMotionFX::FileFormat::Actor_SubMesh fileSubMesh;
fileSubMesh.mMaterialIndex = subMesh->GetMaterial();
fileSubMesh.mNumBones = subMesh->GetNumBones();
fileSubMesh.mNumIndices = subMesh->GetNumIndices();
fileSubMesh.mNumVerts = subMesh->GetNumVertices();
fileSubMesh.mNumPolygons = subMesh->GetNumPolygons();
MCore::LogDetailedInfo(" - SubMesh #%d:", s);
MCore::LogDetailedInfo(" + Material: %d", fileSubMesh.mMaterialIndex);
MCore::LogDetailedInfo(" + Num vertices: %d", fileSubMesh.mNumVerts);
MCore::LogDetailedInfo(" + Num indices: %d (%d polygons)", fileSubMesh.mNumIndices, fileSubMesh.mNumPolygons);
MCore::LogDetailedInfo(" + Num bones: %d", fileSubMesh.mNumBones);
// convert endian
ConvertUnsignedInt(&fileSubMesh.mMaterialIndex, targetEndianType);
ConvertUnsignedInt(&fileSubMesh.mNumBones, targetEndianType);
ConvertUnsignedInt(&fileSubMesh.mNumIndices, targetEndianType);
ConvertUnsignedInt(&fileSubMesh.mNumPolygons, targetEndianType);
ConvertUnsignedInt(&fileSubMesh.mNumVerts, targetEndianType);
// write the submesh header
file->Write(&fileSubMesh, sizeof(EMotionFX::FileFormat::Actor_SubMesh));
// write the index data
const uint32 numIndices = subMesh->GetNumIndices();
const uint32 numPolygons = subMesh->GetNumPolygons();
const uint32 startVertex = subMesh->GetStartVertex();
uint32* indices = subMesh->GetIndices();
uint8* polyVertCounts = subMesh->GetPolygonVertexCounts();
for (uint32 i = 0; i < numIndices; ++i)
{
uint32 index = indices[i] - startVertex;
ConvertUnsignedInt(&index, targetEndianType);
file->Write(&index, sizeof(uint32));
}
for (uint32 i = 0; i < numPolygons; ++i)
{
uint8 numPolyVerts = polyVertCounts[i];
file->Write(&numPolyVerts, sizeof(uint8));
}
// write the bone numbers
const uint32 numBones = subMesh->GetNumBones();
for (uint32 i = 0; i < numBones; ++i)
{
uint32 value = subMesh->GetBone(i);
ConvertUnsignedInt(&value, targetEndianType);
file->Write(&value, sizeof(uint32));
}
}
}
// save meshes for all nodes for a given LOD level
void SaveMeshes(MCore::Stream* file, EMotionFX::Actor* actor, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType)
{
MCORE_ASSERT(file);
MCORE_ASSERT(actor);
MCore::LogDetailedInfo("============================================================");
MCore::LogInfo("Meshes (LOD=%i", lodLevel);
MCore::LogDetailedInfo("============================================================");
// get the number of nodes
const uint32 numNodes = actor->GetNumNodes();
// iterate through all nodes
for (uint32 i = 0; i < numNodes; i++)
{
// get the node from the actor
//EMotionFX::Node* node = actor->GetSkeleton()->GetNode(i);
// get the mesh and save it
EMotionFX::Mesh* mesh = actor->GetMesh(lodLevel, i);
if (mesh)
{
SaveMesh(file, mesh, i, mesh->GetIsCollisionMesh(), lodLevel, targetEndianType);
}
// get the collision mesh and save it
/* EMotionFX::Mesh* collisionMesh = actor->GetCollisionMesh(lodLevel, i);
if (collisionMesh)
SaveMesh( file, collisionMesh, i, true, lodLevel, targetEndianType );*/
}
}
// save all meshes for all nodes and all LOD levels
void SaveMeshes(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType)
{
// get the number of LOD levels, iterate through them and save all meshes
const uint32 numLODLevels = actor->GetNumLODLevels();
for (uint32 i = 0; i < numLODLevels; ++i)
{
SaveMeshes(file, actor, i, targetEndianType);
}
}
} // namespace ExporterLib
@@ -32,11 +32,11 @@ namespace ExporterLib
// copy over the information to the chunk
EMotionFX::FileFormat::Actor_MorphTarget morphTargetChunk;
morphTargetChunk.mLOD = aznumeric_caster(lodLevel);
morphTargetChunk.mNumTransformations = aznumeric_caster(numTransformations);
morphTargetChunk.mRangeMin = morphTarget->GetRangeMin();
morphTargetChunk.mRangeMax = morphTarget->GetRangeMax();
morphTargetChunk.mPhonemeSets = morphTarget->GetPhonemeSets();
morphTargetChunk.m_lod = aznumeric_caster(lodLevel);
morphTargetChunk.m_numTransformations = aznumeric_caster(numTransformations);
morphTargetChunk.m_rangeMin = morphTarget->GetRangeMin();
morphTargetChunk.m_rangeMax = morphTarget->GetRangeMax();
morphTargetChunk.m_phonemeSets = morphTarget->GetPhonemeSets();
// log it
MCore::LogDetailedInfo(" - Morph Target: Name='%s'", morphTarget->GetName());
@@ -47,11 +47,11 @@ namespace ExporterLib
MCore::LogDetailedInfo(" + PhonemesSets: %s", EMotionFX::MorphTarget::GetPhonemeSetString((EMotionFX::MorphTarget::EPhonemeSet)morphTarget->GetPhonemeSets()).c_str());
// convert endian
ConvertFloat(&morphTargetChunk.mRangeMin, targetEndianType);
ConvertFloat(&morphTargetChunk.mRangeMax, targetEndianType);
ConvertUnsignedInt(&morphTargetChunk.mLOD, targetEndianType);
ConvertUnsignedInt(&morphTargetChunk.mNumTransformations, targetEndianType);
ConvertUnsignedInt(&morphTargetChunk.mPhonemeSets, targetEndianType);
ConvertFloat(&morphTargetChunk.m_rangeMin, targetEndianType);
ConvertFloat(&morphTargetChunk.m_rangeMax, targetEndianType);
ConvertUnsignedInt(&morphTargetChunk.m_lod, targetEndianType);
ConvertUnsignedInt(&morphTargetChunk.m_numTransformations, targetEndianType);
ConvertUnsignedInt(&morphTargetChunk.m_phonemeSets, targetEndianType);
// write the bones expression part
file->Write(&morphTargetChunk, sizeof(EMotionFX::FileFormat::Actor_MorphTarget));
@@ -63,34 +63,34 @@ namespace ExporterLib
for (size_t i = 0; i < numTransformations; i++)
{
EMotionFX::MorphTargetStandard::Transformation transform = morphTarget->GetTransformation(i);
EMotionFX::Node* node = actor->GetSkeleton()->GetNode(transform.mNodeIndex);
EMotionFX::Node* node = actor->GetSkeleton()->GetNode(transform.m_nodeIndex);
if (node == nullptr)
{
MCore::LogError("Can't get node '%i'. File is corrupt!", transform.mNodeIndex);
MCore::LogError("Can't get node '%i'. File is corrupt!", transform.m_nodeIndex);
continue;
}
// create and fill the transformation
EMotionFX::FileFormat::Actor_MorphTargetTransform transformChunk;
transformChunk.mNodeIndex = aznumeric_caster(transform.mNodeIndex);
CopyVector(transformChunk.mPosition, AZ::PackedVector3f(transform.mPosition));
CopyVector(transformChunk.mScale, AZ::PackedVector3f(transform.mScale));
CopyQuaternion(transformChunk.mRotation, transform.mRotation);
CopyQuaternion(transformChunk.mScaleRotation, transform.mScaleRotation);
transformChunk.m_nodeIndex = aznumeric_caster(transform.m_nodeIndex);
CopyVector(transformChunk.m_position, AZ::PackedVector3f(transform.m_position));
CopyVector(transformChunk.m_scale, AZ::PackedVector3f(transform.m_scale));
CopyQuaternion(transformChunk.m_rotation, transform.m_rotation);
CopyQuaternion(transformChunk.m_scaleRotation, transform.m_scaleRotation);
MCore::LogDetailedInfo(" - EMotionFX::Transform #%i: Node='%s' NodeNr=#%i", i, node->GetName(), node->GetNodeIndex());
MCore::LogDetailedInfo(" + Pos: %f, %f, %f", transformChunk.mPosition.mX, transformChunk.mPosition.mY, transformChunk.mPosition.mZ);
MCore::LogDetailedInfo(" + Rotation: %f, %f, %f %f", transformChunk.mRotation.mX, transformChunk.mRotation.mY, transformChunk.mRotation.mZ, transformChunk.mRotation.mW);
MCore::LogDetailedInfo(" + Scale: %f, %f, %f", transformChunk.mScale.mX, transformChunk.mScale.mY, transformChunk.mScale.mZ);
MCore::LogDetailedInfo(" + ScaleRot: %f, %f, %f %f", transformChunk.mScaleRotation.mX, transformChunk.mScaleRotation.mY, transformChunk.mScaleRotation.mZ, transformChunk.mScaleRotation.mW);
MCore::LogDetailedInfo(" + Pos: %f, %f, %f", transformChunk.m_position.m_x, transformChunk.m_position.m_y, transformChunk.m_position.m_z);
MCore::LogDetailedInfo(" + Rotation: %f, %f, %f %f", transformChunk.m_rotation.m_x, transformChunk.m_rotation.m_y, transformChunk.m_rotation.m_z, transformChunk.m_rotation.m_w);
MCore::LogDetailedInfo(" + Scale: %f, %f, %f", transformChunk.m_scale.m_x, transformChunk.m_scale.m_y, transformChunk.m_scale.m_z);
MCore::LogDetailedInfo(" + ScaleRot: %f, %f, %f %f", transformChunk.m_scaleRotation.m_x, transformChunk.m_scaleRotation.m_y, transformChunk.m_scaleRotation.m_z, transformChunk.m_scaleRotation.m_w);
// convert endian and coordinate system
ConvertUnsignedInt(&transformChunk.mNodeIndex, targetEndianType);
ConvertFileVector3(&transformChunk.mPosition, targetEndianType);
ConvertFileVector3(&transformChunk.mScale, targetEndianType);
ConvertFileQuaternion(&transformChunk.mRotation, targetEndianType);
ConvertFileQuaternion(&transformChunk.mScaleRotation, targetEndianType);
ConvertUnsignedInt(&transformChunk.m_nodeIndex, targetEndianType);
ConvertFileVector3(&transformChunk.m_position, targetEndianType);
ConvertFileVector3(&transformChunk.m_scale, targetEndianType);
ConvertFileQuaternion(&transformChunk.m_rotation, targetEndianType);
ConvertFileQuaternion(&transformChunk.m_scaleRotation, targetEndianType);
// write the transformation
file->Write(&transformChunk, sizeof(EMotionFX::FileFormat::Actor_MorphTargetTransform));
@@ -175,9 +175,9 @@ namespace ExporterLib
// fill in the chunk header
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_STDPMORPHTARGETS;
chunkHeader.mSizeInBytes = aznumeric_caster(GetMorphSetupChunkSize(morphSetup));
chunkHeader.mVersion = 2;
chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_STDPMORPHTARGETS;
chunkHeader.m_sizeInBytes = aznumeric_caster(GetMorphSetupChunkSize(morphSetup));
chunkHeader.m_version = 2;
// endian convert the chunk and write it to the file
ConvertFileChunk(&chunkHeader, targetEndianType);
@@ -185,16 +185,16 @@ namespace ExporterLib
// fill in the chunk header
EMotionFX::FileFormat::Actor_MorphTargets morphTargetsChunk;
morphTargetsChunk.mNumMorphTargets = aznumeric_caster(numSavedMorphTargets);
morphTargetsChunk.mLOD = aznumeric_caster(lodLevel);
morphTargetsChunk.m_numMorphTargets = aznumeric_caster(numSavedMorphTargets);
morphTargetsChunk.m_lod = aznumeric_caster(lodLevel);
MCore::LogDetailedInfo("============================================================");
MCore::LogInfo("Morph Targets (%i, LOD=%d)", morphTargetsChunk.mNumMorphTargets, morphTargetsChunk.mLOD);
MCore::LogInfo("Morph Targets (%i, LOD=%d)", morphTargetsChunk.m_numMorphTargets, morphTargetsChunk.m_lod);
MCore::LogDetailedInfo("============================================================");
// endian convert the chunk and write it to the file
ConvertUnsignedInt(&morphTargetsChunk.mNumMorphTargets, targetEndianType);
ConvertUnsignedInt(&morphTargetsChunk.mLOD, targetEndianType);
ConvertUnsignedInt(&morphTargetsChunk.m_numMorphTargets, targetEndianType);
ConvertUnsignedInt(&morphTargetsChunk.m_lod, targetEndianType);
file->Write(&morphTargetsChunk, sizeof(EMotionFX::FileFormat::Actor_MorphTargets));
// save morph targets
@@ -66,10 +66,10 @@ namespace ExporterLib
// the motion event table chunk header
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::SHARED_CHUNK_MOTIONEVENTTABLE;
chunkHeader.mVersion = 3;
chunkHeader.m_chunkId = EMotionFX::FileFormat::SHARED_CHUNK_MOTIONEVENTTABLE;
chunkHeader.m_version = 3;
chunkHeader.mSizeInBytes = static_cast<uint32>(serializedTableSizeInBytes + sizeof(EMotionFX::FileFormat::FileMotionEventTableSerialized));
chunkHeader.m_sizeInBytes = static_cast<uint32>(serializedTableSizeInBytes + sizeof(EMotionFX::FileFormat::FileMotionEventTableSerialized));
EMotionFX::FileFormat::FileMotionEventTableSerialized tableHeader;
tableHeader.m_size = serializedTableSizeInBytes;
@@ -29,11 +29,11 @@ namespace ExporterLib
const size_t parentIndex = node->GetParentIndex();
const size_t numChilds = node->GetNumChildNodes();
const EMotionFX::Transform& transform = actor->GetBindPose()->GetLocalSpaceTransform(nodeIndex);
AZ::PackedVector3f position = AZ::PackedVector3f(transform.mPosition);
AZ::Quaternion rotation = transform.mRotation.GetNormalized();
AZ::PackedVector3f position = AZ::PackedVector3f(transform.m_position);
AZ::Quaternion rotation = transform.m_rotation.GetNormalized();
#ifndef EMFX_SCALE_DISABLED
AZ::PackedVector3f scale = AZ::PackedVector3f(transform.mScale);
AZ::PackedVector3f scale = AZ::PackedVector3f(transform.m_scale);
#else
AZ::PackedVector3f scale(1.0f, 1.0f, 1.0f);
#endif
@@ -42,12 +42,12 @@ namespace ExporterLib
EMotionFX::FileFormat::Actor_Node2 nodeChunk;
memset(&nodeChunk, 0, sizeof(EMotionFX::FileFormat::Actor_Node2));
CopyVector(nodeChunk.mLocalPos, position);
CopyQuaternion(nodeChunk.mLocalQuat, rotation);
CopyVector(nodeChunk.mLocalScale, scale);
CopyVector(nodeChunk.m_localPos, position);
CopyQuaternion(nodeChunk.m_localQuat, rotation);
CopyVector(nodeChunk.m_localScale, scale);
nodeChunk.mNumChilds = aznumeric_caster(numChilds);
nodeChunk.mParentIndex = aznumeric_caster(parentIndex);
nodeChunk.m_numChilds = aznumeric_caster(numChilds);
nodeChunk.m_parentIndex = aznumeric_caster(parentIndex);
// calculate and copy over the skeletal LODs
uint32 skeletalLODs = 0;
@@ -58,26 +58,26 @@ namespace ExporterLib
skeletalLODs |= (1 << l);
}
}
nodeChunk.mSkeletalLODs = skeletalLODs;
nodeChunk.m_skeletalLoDs = skeletalLODs;
// will this node be involved in the bounding volume calculations?
if (node->GetIncludeInBoundsCalc())
{
nodeChunk.mNodeFlags |= EMotionFX::Node::ENodeFlags::FLAG_INCLUDEINBOUNDSCALC;// first bit
nodeChunk.m_nodeFlags |= EMotionFX::Node::ENodeFlags::FLAG_INCLUDEINBOUNDSCALC;// first bit
}
else
{
nodeChunk.mNodeFlags &= ~EMotionFX::Node::ENodeFlags::FLAG_INCLUDEINBOUNDSCALC;
nodeChunk.m_nodeFlags &= ~EMotionFX::Node::ENodeFlags::FLAG_INCLUDEINBOUNDSCALC;
}
// Add an isCritical option in node flag so it won't be optimized out.
if (node->GetIsCritical())
{
nodeChunk.mNodeFlags |= EMotionFX::Node::ENodeFlags::FLAG_CRITICAL; // third bit
nodeChunk.m_nodeFlags |= EMotionFX::Node::ENodeFlags::FLAG_CRITICAL; // third bit
}
else
{
nodeChunk.mNodeFlags &= ~EMotionFX::Node::ENodeFlags::FLAG_CRITICAL;
nodeChunk.m_nodeFlags &= ~EMotionFX::Node::ENodeFlags::FLAG_CRITICAL;
}
// log the node chunk information
@@ -90,15 +90,15 @@ namespace ExporterLib
{
MCore::LogDetailedInfo(" + Parent: name='%s' index=%i", actor->GetSkeleton()->GetNode(parentIndex)->GetName(), parentIndex);
}
MCore::LogDetailedInfo(" + NumChilds: %i", nodeChunk.mNumChilds);
MCore::LogDetailedInfo(" + Position: x=%f y=%f z=%f", nodeChunk.mLocalPos.mX, nodeChunk.mLocalPos.mY, nodeChunk.mLocalPos.mZ);
MCore::LogDetailedInfo(" + Rotation: x=%f y=%f z=%f w=%f", nodeChunk.mLocalQuat.mX, nodeChunk.mLocalQuat.mY, nodeChunk.mLocalQuat.mZ, nodeChunk.mLocalQuat.mW);
MCore::LogDetailedInfo(" + NumChilds: %i", nodeChunk.m_numChilds);
MCore::LogDetailedInfo(" + Position: x=%f y=%f z=%f", nodeChunk.m_localPos.m_x, nodeChunk.m_localPos.m_y, nodeChunk.m_localPos.m_z);
MCore::LogDetailedInfo(" + Rotation: x=%f y=%f z=%f w=%f", nodeChunk.m_localQuat.m_x, nodeChunk.m_localQuat.m_y, nodeChunk.m_localQuat.m_z, nodeChunk.m_localQuat.m_w);
const AZ::Vector3 euler = MCore::AzQuaternionToEulerAngles(rotation);
MCore::LogDetailedInfo(" + Rotation Euler: x=%f y=%f z=%f",
float(euler.GetX()) * 180.0 / MCore::Math::pi,
float(euler.GetY()) * 180.0 / MCore::Math::pi,
float(euler.GetZ()) * 180.0 / MCore::Math::pi);
MCore::LogDetailedInfo(" + Scale: x=%f y=%f z=%f", nodeChunk.mLocalScale.mX, nodeChunk.mLocalScale.mY, nodeChunk.mLocalScale.mZ);
MCore::LogDetailedInfo(" + Scale: x=%f y=%f z=%f", nodeChunk.m_localScale.m_x, nodeChunk.m_localScale.m_y, nodeChunk.m_localScale.m_z);
MCore::LogDetailedInfo(" + IncludeInBoundsCalc: %d", node->GetIncludeInBoundsCalc());
// log skeletal lods
@@ -111,12 +111,12 @@ namespace ExporterLib
MCore::LogDetailedInfo(lodString.c_str());
// endian conversion
ConvertFileVector3(&nodeChunk.mLocalPos, targetEndianType);
ConvertFileQuaternion(&nodeChunk.mLocalQuat, targetEndianType);
ConvertFileVector3(&nodeChunk.mLocalScale, targetEndianType);
ConvertUnsignedInt(&nodeChunk.mParentIndex, targetEndianType);
ConvertUnsignedInt(&nodeChunk.mNumChilds, targetEndianType);
ConvertUnsignedInt(&nodeChunk.mSkeletalLODs, targetEndianType);
ConvertFileVector3(&nodeChunk.m_localPos, targetEndianType);
ConvertFileQuaternion(&nodeChunk.m_localQuat, targetEndianType);
ConvertFileVector3(&nodeChunk.m_localScale, targetEndianType);
ConvertUnsignedInt(&nodeChunk.m_parentIndex, targetEndianType);
ConvertUnsignedInt(&nodeChunk.m_numChilds, targetEndianType);
ConvertUnsignedInt(&nodeChunk.m_skeletalLoDs, targetEndianType);
// write it
file->Write(&nodeChunk, sizeof(EMotionFX::FileFormat::Actor_Node2));
@@ -136,14 +136,14 @@ namespace ExporterLib
// chunk information
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_NODES;
chunkHeader.mVersion = 2;
chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_NODES;
chunkHeader.m_version = 2;
// get the nodes chunk size
chunkHeader.mSizeInBytes = aznumeric_caster(sizeof(EMotionFX::FileFormat::Actor_Nodes2) + numNodes * sizeof(EMotionFX::FileFormat::Actor_Node2));
chunkHeader.m_sizeInBytes = aznumeric_caster(sizeof(EMotionFX::FileFormat::Actor_Nodes2) + numNodes * sizeof(EMotionFX::FileFormat::Actor_Node2));
for (size_t i = 0; i < numNodes; i++)
{
chunkHeader.mSizeInBytes += GetStringChunkSize(actor->GetSkeleton()->GetNode(i)->GetName());
chunkHeader.m_sizeInBytes += GetStringChunkSize(actor->GetSkeleton()->GetNode(i)->GetName());
}
// endian conversion and write it
@@ -152,12 +152,12 @@ namespace ExporterLib
// nodes chunk
EMotionFX::FileFormat::Actor_Nodes2 nodesChunk;
nodesChunk.mNumNodes = aznumeric_caster(numNodes);
nodesChunk.mNumRootNodes = aznumeric_caster(actor->GetSkeleton()->GetNumRootNodes());
nodesChunk.m_numNodes = aznumeric_caster(numNodes);
nodesChunk.m_numRootNodes = aznumeric_caster(actor->GetSkeleton()->GetNumRootNodes());
// endian conversion and write it
ConvertUnsignedInt(&nodesChunk.mNumNodes, targetEndianType);
ConvertUnsignedInt(&nodesChunk.mNumRootNodes, targetEndianType);
ConvertUnsignedInt(&nodesChunk.m_numNodes, targetEndianType);
ConvertUnsignedInt(&nodesChunk.m_numRootNodes, targetEndianType);
file->Write(&nodesChunk, sizeof(EMotionFX::FileFormat::Actor_Nodes2));
@@ -182,12 +182,12 @@ namespace ExporterLib
memset(&groupChunk, 0, sizeof(EMotionFX::FileFormat::Actor_NodeGroup));
// set the data
groupChunk.mNumNodes = static_cast<uint16>(numNodes);
groupChunk.mDisabledOnDefault = nodeGroup->GetIsEnabledOnDefault() ? false : true;
groupChunk.m_numNodes = static_cast<uint16>(numNodes);
groupChunk.m_disabledOnDefault = nodeGroup->GetIsEnabledOnDefault() ? false : true;
// logging
MCore::LogDetailedInfo("- Group: name='%s'", nodeGroup->GetName());
MCore::LogDetailedInfo(" + DisabledOnDefault: %i", groupChunk.mDisabledOnDefault);
MCore::LogDetailedInfo(" + DisabledOnDefault: %i", groupChunk.m_disabledOnDefault);
AZStd::string nodesString;
for (size_t i = 0; i < numNodes; ++i)
{
@@ -197,10 +197,10 @@ namespace ExporterLib
nodesString += ", ";
}
}
MCore::LogDetailedInfo(" + Nodes (%i): %s", groupChunk.mNumNodes, nodesString.c_str());
MCore::LogDetailedInfo(" + Nodes (%i): %s", groupChunk.m_numNodes, nodesString.c_str());
// endian conversion
ConvertUnsignedShort(&groupChunk.mNumNodes, targetEndianType);
ConvertUnsignedShort(&groupChunk.m_numNodes, targetEndianType);
// write it
file->Write(&groupChunk, sizeof(EMotionFX::FileFormat::Actor_NodeGroup));
@@ -240,16 +240,16 @@ namespace ExporterLib
// chunk information
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_NODEGROUPS;
chunkHeader.mVersion = 1;
chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_NODEGROUPS;
chunkHeader.m_version = 1;
// calculate the chunk size
chunkHeader.mSizeInBytes = sizeof(uint16);
chunkHeader.m_sizeInBytes = sizeof(uint16);
for (const EMotionFX::NodeGroup* nodeGroup : nodeGroups)
{
chunkHeader.mSizeInBytes += sizeof(EMotionFX::FileFormat::Actor_NodeGroup);
chunkHeader.mSizeInBytes += GetStringChunkSize(nodeGroup->GetNameString());
chunkHeader.mSizeInBytes += sizeof(uint16) * nodeGroup->GetNumNodes();
chunkHeader.m_sizeInBytes += sizeof(EMotionFX::FileFormat::Actor_NodeGroup);
chunkHeader.m_sizeInBytes += GetStringChunkSize(nodeGroup->GetNameString());
chunkHeader.m_sizeInBytes += sizeof(uint16) * nodeGroup->GetNumNodes();
}
// endian conversion
@@ -309,9 +309,9 @@ namespace ExporterLib
// chunk information
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_NODEMOTIONSOURCES;
chunkHeader.mSizeInBytes = aznumeric_caster(sizeof(EMotionFX::FileFormat::Actor_NodeMotionSources2) + (numNodes * sizeof(uint16)) + (numNodes * sizeof(uint8) * 2));
chunkHeader.mVersion = 1;
chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_NODEMOTIONSOURCES;
chunkHeader.m_sizeInBytes = aznumeric_caster(sizeof(EMotionFX::FileFormat::Actor_NodeMotionSources2) + (numNodes * sizeof(uint16)) + (numNodes * sizeof(uint8) * 2));
chunkHeader.m_version = 1;
// endian conversion and write it
ConvertFileChunk(&chunkHeader, targetEndianType);
@@ -320,10 +320,10 @@ namespace ExporterLib
// the node motion sources chunk data
EMotionFX::FileFormat::Actor_NodeMotionSources2 nodeMotionSourcesChunk;
nodeMotionSourcesChunk.mNumNodes = aznumeric_caster(numNodes);
nodeMotionSourcesChunk.m_numNodes = aznumeric_caster(numNodes);
// convert endian and save to the file
ConvertUnsignedInt(&nodeMotionSourcesChunk.mNumNodes, targetEndianType);
ConvertUnsignedInt(&nodeMotionSourcesChunk.m_numNodes, targetEndianType);
file->Write(&nodeMotionSourcesChunk, sizeof(EMotionFX::FileFormat::Actor_NodeMotionSources2));
@@ -336,7 +336,7 @@ namespace ExporterLib
for (const EMotionFX::Actor::NodeMirrorInfo& nodeMirrorInfo : *nodeMirrorInfos)
{
// get the motion node source
uint16 nodeMotionSource = nodeMirrorInfo.mSourceNode;
uint16 nodeMotionSource = nodeMirrorInfo.m_sourceNode;
// convert endian and save to the file
ConvertUnsignedShort(&nodeMotionSource, targetEndianType);
@@ -346,14 +346,14 @@ namespace ExporterLib
// write all axes
for (const EMotionFX::Actor::NodeMirrorInfo& nodeMirrorInfo : *nodeMirrorInfos)
{
uint8 axis = static_cast<uint8>(nodeMirrorInfo.mAxis);
uint8 axis = static_cast<uint8>(nodeMirrorInfo.m_axis);
file->Write(&axis, sizeof(uint8));
}
// write all flags
for (const EMotionFX::Actor::NodeMirrorInfo& nodeMirrorInfo : *nodeMirrorInfos)
{
uint8 flags = static_cast<uint8>(nodeMirrorInfo.mFlags);
uint8 flags = static_cast<uint8>(nodeMirrorInfo.m_flags);
file->Write(&flags, sizeof(uint8));
}
}
@@ -398,9 +398,9 @@ namespace ExporterLib
// chunk information
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_ATTACHMENTNODES;
chunkHeader.mSizeInBytes = aznumeric_caster(sizeof(EMotionFX::FileFormat::Actor_AttachmentNodes) + numAttachmentNodes * sizeof(uint16));
chunkHeader.mVersion = 1;
chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_ATTACHMENTNODES;
chunkHeader.m_sizeInBytes = aznumeric_caster(sizeof(EMotionFX::FileFormat::Actor_AttachmentNodes) + numAttachmentNodes * sizeof(uint16));
chunkHeader.m_version = 1;
// endian conversion and write it
ConvertFileChunk(&chunkHeader, targetEndianType);
@@ -409,10 +409,10 @@ namespace ExporterLib
// the attachment nodes chunk data
EMotionFX::FileFormat::Actor_AttachmentNodes attachmentNodesChunk;
attachmentNodesChunk.mNumNodes = aznumeric_caster(numAttachmentNodes);
attachmentNodesChunk.m_numNodes = aznumeric_caster(numAttachmentNodes);
// convert endian and save to the file
ConvertUnsignedInt(&attachmentNodesChunk.mNumNodes, targetEndianType);
ConvertUnsignedInt(&attachmentNodesChunk.m_numNodes, targetEndianType);
file->Write(&attachmentNodesChunk, sizeof(EMotionFX::FileFormat::Actor_AttachmentNodes));
// log details
@@ -26,9 +26,9 @@ namespace ExporterLib
EMotionFX::MotionData::SaveSettings saveSettings;
saveSettings.m_targetEndianType = targetEndianType;
EMotionFX::FileFormat::FileChunk chunkHeader;
chunkHeader.mChunkID = EMotionFX::FileFormat::MOTION_CHUNK_MOTIONDATA;
chunkHeader.mVersion = 1;
chunkHeader.mSizeInBytes = static_cast<AZ::u32>(
chunkHeader.m_chunkId = EMotionFX::FileFormat::MOTION_CHUNK_MOTIONDATA;
chunkHeader.m_version = 1;
chunkHeader.m_sizeInBytes = static_cast<AZ::u32>(
sizeof(EMotionFX::FileFormat::Motion_MotionData) +
ExporterLib::GetAzStringChunkSize(uuidString) +
ExporterLib::GetAzStringChunkSize(nameString) +
@@ -1,186 +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
*
*/
#include "Exporter.h"
#include <EMotionFX/Source/SkinningInfoVertexAttributeLayer.h>
#include <EMotionFX/Source/Actor.h>
#include <EMotionFX/Source/Mesh.h>
#include <EMotionFX/Source/Node.h>
#include <EMotionFX/Source/Importer/ActorFileFormat.h>
#include <MCore/Source/LogManager.h>
namespace ExporterLib
{
// save the given skin for the given LOD level
void SaveSkin(MCore::Stream* file, EMotionFX::Mesh* mesh, uint32 nodeIndex, bool isCollisionMesh, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType)
{
MCORE_ASSERT(mesh);
const uint32 numLayers = mesh->GetNumSharedVertexAttributeLayers();
for (uint32 layerNr = 0; layerNr < numLayers; ++layerNr)
{
EMotionFX::VertexAttributeLayer* vertexAttributeLayer = mesh->GetSharedVertexAttributeLayer(layerNr);
if (vertexAttributeLayer->GetType() != EMotionFX::SkinningInfoVertexAttributeLayer::TYPE_ID)
{
continue;
}
EMotionFX::SkinningInfoVertexAttributeLayer* skinLayer = static_cast<EMotionFX::SkinningInfoVertexAttributeLayer*>(vertexAttributeLayer);
// get the number of original vertices
const uint32 numOrgVerts = skinLayer->GetNumAttributes();
// get the number of total influences
uint32 numTotalInfluences = 0;
uint32 v;
for (v = 0; v < numOrgVerts; ++v)
{
numTotalInfluences += aznumeric_cast<uint32>(skinLayer->GetNumInfluences(v));
}
// skip meshes which don't contain any influences
if (numOrgVerts <= 0)
{
continue;
}
if (numOrgVerts != mesh->GetNumOrgVertices())
{
MCore::LogWarning("More/Less skinning influences (%i) found than the mesh actually has original vertices (%i).", numOrgVerts, mesh->GetNumOrgVertices());
}
// chunk header
EMotionFX::FileFormat::FileChunk chunkHeader;
// calculate the total size and write the chunk header
uint32 totalSize = sizeof(EMotionFX::FileFormat::Actor_SkinningInfo);
totalSize += numTotalInfluences * sizeof(EMotionFX::FileFormat::Actor_SkinInfluence);
totalSize += numOrgVerts * sizeof(EMotionFX::FileFormat::Actor_SkinningInfoTableEntry);
chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_SKINNINGINFO;
chunkHeader.mSizeInBytes = totalSize;
chunkHeader.mVersion = 1;
// endian conversion
ConvertFileChunk(&chunkHeader, targetEndianType);
// write header and influence
file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk));
if (nodeIndex == MCORE_INVALIDINDEX32)
{
MCore::LogError("Skin (Nr=%i) is not connected to a valid transform node.", nodeIndex);
}
MCore::LogDetailedInfo(" - Skinning Info (NodeNr=%i):", nodeIndex);
MCore::LogDetailedInfo(" + Total data size: %d kB", totalSize / 1024);
MCore::LogDetailedInfo(" + Num org vertices: %d", numOrgVerts);
MCore::LogDetailedInfo(" + Num total influences: %d", numTotalInfluences);
EMotionFX::FileFormat::Actor_SkinningInfo skinningInfoChunk;
memset(&skinningInfoChunk, 0, sizeof(EMotionFX::FileFormat::Actor_SkinningInfo));
skinningInfoChunk.mIsForCollisionMesh = isCollisionMesh ? 1 : 0;
skinningInfoChunk.mNodeIndex = nodeIndex;
skinningInfoChunk.mLOD = lodLevel;
skinningInfoChunk.mNumTotalInfluences = numTotalInfluences;
AZStd::set<AZ::u32> localJointIndices = skinLayer->CalcLocalJointIndices(numOrgVerts);
skinningInfoChunk.mNumLocalBones = static_cast<AZ::u32>(localJointIndices.size());
ConvertUnsignedInt(&skinningInfoChunk.mNodeIndex, targetEndianType);
ConvertUnsignedInt(&skinningInfoChunk.mLOD, targetEndianType);
ConvertUnsignedInt(&skinningInfoChunk.mNumTotalInfluences, targetEndianType);
ConvertUnsignedInt(&skinningInfoChunk.mNumLocalBones, targetEndianType);
file->Write(&skinningInfoChunk, sizeof(EMotionFX::FileFormat::Actor_SkinningInfo));
for (v = 0; v < numOrgVerts; ++v)
{
const uint32 weightCount = aznumeric_cast<uint32>(skinLayer->GetNumInfluences(v));
//LogDebug(" - Vertex#%i: NumWeights='%i'", v, weightCount);
for (uint32 w = 0; w < weightCount; ++w)
{
EMotionFX::FileFormat::Actor_SkinInfluence skinInfluence;
memset(&skinInfluence, 0, sizeof(EMotionFX::FileFormat::Actor_SkinInfluence));
skinInfluence.mNodeNr = skinLayer->GetInfluence(v, w)->GetNodeNr();
skinInfluence.mWeight = skinLayer->GetInfluence(v, w)->GetWeight();
//LogDebug(" + SkingInfluence#%i: NodeNr='%i', Weight='%f'", w, skinInfluence.mNodeNr, skinInfluence.mWeight);
ConvertUnsignedShort(&skinInfluence.mNodeNr, targetEndianType);
ConvertFloat(&skinInfluence.mWeight, targetEndianType);
file->Write(&skinInfluence, sizeof(EMotionFX::FileFormat::Actor_SkinInfluence));
}
}
uint32 currentInfluence = 0;
for (v = 0; v < numOrgVerts; ++v)
{
const uint32 weightCount = aznumeric_cast<uint32>(skinLayer->GetNumInfluences(v));
EMotionFX::FileFormat::Actor_SkinningInfoTableEntry skinningTableEntryChunk;
skinningTableEntryChunk.mNumElements = weightCount;
skinningTableEntryChunk.mStartIndex = currentInfluence;
ConvertUnsignedInt(&skinningTableEntryChunk.mNumElements, targetEndianType);
ConvertUnsignedInt(&skinningTableEntryChunk.mStartIndex, targetEndianType);
file->Write(&skinningTableEntryChunk, sizeof(EMotionFX::FileFormat::Actor_SkinningInfoTableEntry));
currentInfluence += weightCount;
}
}
}
// save skins for all nodes for the given LOD level
void SaveSkins(MCore::Stream* file, EMotionFX::Actor* actor, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType)
{
MCORE_ASSERT(file);
// get the number of nodes
const uint32 numNodes = actor->GetNumNodes();
MCore::LogDetailedInfo("============================================================");
MCore::LogInfo("Skins (LOD=%d", lodLevel);
MCore::LogDetailedInfo("============================================================");
// iterate through all nodes
for (uint32 i = 0; i < numNodes; i++)
{
// get the mesh and save it
EMotionFX::Mesh* mesh = actor->GetMesh(lodLevel, i);
if (mesh)
{
SaveSkin(file, mesh, i, false, lodLevel, targetEndianType);
}
// get the collision mesh and save it
//EMotionFX::Mesh* collisionMesh = actor->GetCollisionMesh(lodLevel, i);
//if (collisionMesh)
//SaveSkin( file, collisionMesh, i, true, lodLevel, targetEndianType );
}
}
// save all skins for all LOD levels
void SaveSkins(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType)
{
// get the number of LOD levels, iterate through them and save all skins
const uint32 numLODLevels = actor->GetNumLODLevels();
for (uint32 i = 0; i < numLODLevels; ++i)
{
SaveSkins(file, actor, i, targetEndianType);
}
}
} // namespace ExporterLib
@@ -17,10 +17,10 @@ namespace MCommon
Camera::Camera()
{
Reset();
mPosition = AZ::Vector3::CreateZero();
mScreenWidth = 0;
mScreenHeight = 0;
mProjectionMode = PROJMODE_PERSPECTIVE;
m_position = AZ::Vector3::CreateZero();
m_screenWidth = 0;
m_screenHeight = 0;
m_projectionMode = PROJMODE_PERSPECTIVE;
}
@@ -36,27 +36,27 @@ namespace MCommon
MCORE_UNUSED(timeDelta);
// setup projection matrix
switch (mProjectionMode)
switch (m_projectionMode)
{
// initialize for perspective projection
case PROJMODE_PERSPECTIVE:
{
MCore::PerspectiveRH(mProjectionMatrix, MCore::Math::DegreesToRadians(mFOV), mAspect, mNearClipDistance, mFarClipDistance);
MCore::PerspectiveRH(m_projectionMatrix, MCore::Math::DegreesToRadians(m_fov), m_aspect, m_nearClipDistance, m_farClipDistance);
break;
}
// initialize for orthographic projection
case PROJMODE_ORTHOGRAPHIC:
{
const float halfX = mOrthoClipDimensions.GetX() * 0.5f;
const float halfY = mOrthoClipDimensions.GetY() * 0.5f;
MCore::OrthoOffCenterRH(mProjectionMatrix, -halfX, halfX, halfY, -halfY, -mFarClipDistance, mFarClipDistance);
const float halfX = m_orthoClipDimensions.GetX() * 0.5f;
const float halfY = m_orthoClipDimensions.GetY() * 0.5f;
MCore::OrthoOffCenterRH(m_projectionMatrix, -halfX, halfX, halfY, -halfY, -m_farClipDistance, m_farClipDistance);
break;
}
}
// calculate the viewproj matrix
mViewProjMatrix = mProjectionMatrix * mViewMatrix;
m_viewProjMatrix = m_projectionMatrix * m_viewMatrix;
}
@@ -65,24 +65,24 @@ namespace MCommon
{
MCORE_UNUSED(flightTime);
mFOV = 55.0f;
mNearClipDistance = 0.1f;
mFarClipDistance = 200.0f;
mAspect = 16.0f / 9.0f;
mRotationSpeed = 0.5f;
mTranslationSpeed = 1.0f;
mViewMatrix = AZ::Matrix4x4::CreateIdentity();
m_fov = 55.0f;
m_nearClipDistance = 0.1f;
m_farClipDistance = 200.0f;
m_aspect = 16.0f / 9.0f;
m_rotationSpeed = 0.5f;
m_translationSpeed = 1.0f;
m_viewMatrix = AZ::Matrix4x4::CreateIdentity();
}
// unproject screen coordinates to a ray
MCore::Ray Camera::Unproject(int32 screenX, int32 screenY)
{
const AZ::Matrix4x4 invProj = MCore::InvertProjectionMatrix(mProjectionMatrix);
const AZ::Matrix4x4 invView = MCore::InvertProjectionMatrix(mViewMatrix);
const AZ::Matrix4x4 invProj = MCore::InvertProjectionMatrix(m_projectionMatrix);
const AZ::Matrix4x4 invView = MCore::InvertProjectionMatrix(m_viewMatrix);
const AZ::Vector3 start = MCore::Unproject(static_cast<float>(screenX), static_cast<float>(screenY), static_cast<float>(mScreenWidth), static_cast<float>(mScreenHeight), mNearClipDistance, invProj, invView);
const AZ::Vector3 end = MCore::Unproject(static_cast<float>(screenX), static_cast<float>(screenY), static_cast<float>(mScreenWidth), static_cast<float>(mScreenHeight), mFarClipDistance, invProj, invView);
const AZ::Vector3 start = MCore::Unproject(static_cast<float>(screenX), static_cast<float>(screenY), static_cast<float>(m_screenWidth), static_cast<float>(m_screenHeight), m_nearClipDistance, invProj, invView);
const AZ::Vector3 end = MCore::Unproject(static_cast<float>(screenX), static_cast<float>(screenY), static_cast<float>(m_screenWidth), static_cast<float>(m_screenHeight), m_farClipDistance, invProj, invView);
return MCore::Ray(start, end);
}
@@ -148,24 +148,24 @@ namespace MCommon
* The projection matrix will be calculated every Update().
* @return The projection matrix.
*/
MCORE_INLINE AZ::Matrix4x4& GetProjectionMatrix() { return mProjectionMatrix; }
MCORE_INLINE const AZ::Matrix4x4& GetProjectionMatrix() const { return mProjectionMatrix; }
MCORE_INLINE AZ::Matrix4x4& GetProjectionMatrix() { return m_projectionMatrix; }
MCORE_INLINE const AZ::Matrix4x4& GetProjectionMatrix() const { return m_projectionMatrix; }
/**
* Get the view matrix of the camera.
* The view matrix will be calculated every Update().
* @return The view matrix.
*/
MCORE_INLINE AZ::Matrix4x4& GetViewMatrix() { return mViewMatrix; }
MCORE_INLINE const AZ::Matrix4x4& GetViewMatrix() const { return mViewMatrix; }
MCORE_INLINE AZ::Matrix4x4& GetViewMatrix() { return m_viewMatrix; }
MCORE_INLINE const AZ::Matrix4x4& GetViewMatrix() const { return m_viewMatrix; }
/**
* Get the precalculated viewMatrix * projectionMatrix of the camera.
* The viewproj matrix will be calculated every Update().
* @return The precalculated matrix containing the result of viewMatrix * projectionMatrix.
*/
MCORE_INLINE AZ::Matrix4x4& GetViewProjMatrix() { return mViewProjMatrix; }
MCORE_INLINE const AZ::Matrix4x4& GetViewProjMatrix() const { return mViewProjMatrix; }
MCORE_INLINE AZ::Matrix4x4& GetViewProjMatrix() { return m_viewProjMatrix; }
MCORE_INLINE const AZ::Matrix4x4& GetViewProjMatrix() const { return m_viewProjMatrix; }
/**
* Get the translation speed.
@@ -261,20 +261,20 @@ namespace MCommon
virtual void AutoUpdateLimits() {}
protected:
AZ::Matrix4x4 mProjectionMatrix; /**< The projection matrix. */
AZ::Matrix4x4 mViewMatrix; /**< The view matrix. */
AZ::Matrix4x4 mViewProjMatrix; /**< ViewMatrix * projectionMatrix. Will be recalculated every update call. */
AZ::Vector3 mPosition; /**< The camera position. */
AZ::Vector2 mOrthoClipDimensions; /**< A two component vector which defines the distance to the left (x component) and to the top (y component) from the view origin. */
float mFOV; /**< The vertical field-of-view in degrees. */
float mNearClipDistance; /**< Distance to the near clipping plane. */
float mFarClipDistance; /**< Distance to the far clipping plane. */
float mAspect; /**< x/y viewport ratio. */
float mRotationSpeed; /**< The angle in degrees that will be applied to the current rotation when the mouse is moving one pixel. */
float mTranslationSpeed; /**< The value that will be applied to the current camera position when moving the mouse one pixel. */
ProjectionMode mProjectionMode; /**< The projection mode. The camera supports either perspective or orthographic projection. */
uint32 mScreenWidth; /**< The screen width in pixels where the camera is used. */
uint32 mScreenHeight; /**< The screen height in pixels where the camera is used. */
AZ::Matrix4x4 m_projectionMatrix; /**< The projection matrix. */
AZ::Matrix4x4 m_viewMatrix; /**< The view matrix. */
AZ::Matrix4x4 m_viewProjMatrix; /**< ViewMatrix * projectionMatrix. Will be recalculated every update call. */
AZ::Vector3 m_position; /**< The camera position. */
AZ::Vector2 m_orthoClipDimensions; /**< A two component vector which defines the distance to the left (x component) and to the top (y component) from the view origin. */
float m_fov; /**< The vertical field-of-view in degrees. */
float m_nearClipDistance; /**< Distance to the near clipping plane. */
float m_farClipDistance; /**< Distance to the far clipping plane. */
float m_aspect; /**< x/y viewport ratio. */
float m_rotationSpeed; /**< The angle in degrees that will be applied to the current rotation when the mouse is moving one pixel. */
float m_translationSpeed; /**< The value that will be applied to the current camera position when moving the mouse one pixel. */
ProjectionMode m_projectionMode; /**< The projection mode. The camera supports either perspective or orthographic projection. */
uint32 m_screenWidth; /**< The screen width in pixels where the camera is used. */
uint32 m_screenHeight; /**< The screen height in pixels where the camera is used. */
};
// include inline code
@@ -12,139 +12,139 @@
// set the camera position
MCORE_INLINE void Camera::SetPosition(const AZ::Vector3& position)
{
mPosition = position;
m_position = position;
}
// get the camera position
MCORE_INLINE const AZ::Vector3& Camera::GetPosition() const
{
return mPosition;
return m_position;
}
// set the projection type
MCORE_INLINE void Camera::SetProjectionMode(ProjectionMode projectionMode)
{
mProjectionMode = projectionMode;
m_projectionMode = projectionMode;
}
// get the projection type
MCORE_INLINE Camera::ProjectionMode Camera::GetProjectionMode() const
{
return mProjectionMode;
return m_projectionMode;
}
// set the clip dimensions for the orthographic projection mode
MCORE_INLINE void Camera::SetOrthoClipDimensions(const AZ::Vector2& clipDimensions)
{
mOrthoClipDimensions = clipDimensions;
m_orthoClipDimensions = clipDimensions;
}
// set the screen dimensions where this camera is used in
MCORE_INLINE void Camera::SetScreenDimensions(uint32 width, uint32 height)
{
mScreenWidth = width;
mScreenHeight = height;
m_screenWidth = width;
m_screenHeight = height;
}
// set the field of view in degrees
MCORE_INLINE void Camera::SetFOV(float fieldOfView)
{
mFOV = fieldOfView;
m_fov = fieldOfView;
}
// set near clip plane distance
MCORE_INLINE void Camera::SetNearClipDistance(float nearClipDistance)
{
mNearClipDistance = nearClipDistance;
m_nearClipDistance = nearClipDistance;
}
// set far clip plane distance
MCORE_INLINE void Camera::SetFarClipDistance(float farClipDistance)
{
mFarClipDistance = farClipDistance;
m_farClipDistance = farClipDistance;
}
// set the aspect ratio - the aspect ratio is calculated by width/height
MCORE_INLINE void Camera::SetAspectRatio(float aspect)
{
mAspect = aspect;
m_aspect = aspect;
}
// return the field of view in degrees
MCORE_INLINE float Camera::GetFOV() const
{
return mFOV;
return m_fov;
}
// return the near clip plane distance
MCORE_INLINE float Camera::GetNearClipDistance() const
{
return mNearClipDistance;
return m_nearClipDistance;
}
// return the far clip plane distance
MCORE_INLINE float Camera::GetFarClipDistance() const
{
return mFarClipDistance;
return m_farClipDistance;
}
// return the aspect ratio
MCORE_INLINE float Camera::GetAspectRatio() const
{
return mAspect;
return m_aspect;
}
// get the translation speed
MCORE_INLINE float Camera::GetTranslationSpeed() const
{
return mTranslationSpeed;
return m_translationSpeed;
}
// set the translation speed
MCORE_INLINE void Camera::SetTranslationSpeed(float translationSpeed)
{
mTranslationSpeed = translationSpeed;
m_translationSpeed = translationSpeed;
}
// get the rotation speed in degrees
MCORE_INLINE float Camera::GetRotationSpeed() const
{
return mRotationSpeed;
return m_rotationSpeed;
}
// set the rotation speed in degrees
MCORE_INLINE void Camera::SetRotationSpeed(float rotationSpeed)
{
mRotationSpeed = rotationSpeed;
m_rotationSpeed = rotationSpeed;
}
// Get the screen width.
MCORE_INLINE uint32 Camera::GetScreenWidth()
{
return mScreenWidth;
return m_screenWidth;
}
// Get the screen height
MCORE_INLINE uint32 Camera::GetScreenHeight()
{
return mScreenHeight;
return m_screenHeight;
}
@@ -32,20 +32,20 @@ namespace MCommon
MCORE_UNUSED(timeDelta);
// lock pitching to [-90.0°, 90.0°]
if (mPitch < -90.0f + 0.1f)
if (m_pitch < -90.0f + 0.1f)
{
mPitch = -90.0f + 0.1f;
m_pitch = -90.0f + 0.1f;
}
if (mPitch > 90.0f - 0.1f)
if (m_pitch > 90.0f - 0.1f)
{
mPitch = 90.0f - 0.1f;
m_pitch = 90.0f - 0.1f;
}
// calculate the camera direction vector based on the yaw and pitch
AZ::Vector3 direction = (AZ::Matrix4x4::CreateRotationX(MCore::Math::DegreesToRadians(mPitch)) * AZ::Matrix4x4::CreateRotationY(MCore::Math::DegreesToRadians(mYaw))) * (AZ::Vector3(0.0f, 0.0f, 1.0f)).GetNormalized();
AZ::Vector3 direction = (AZ::Matrix4x4::CreateRotationX(MCore::Math::DegreesToRadians(m_pitch)) * AZ::Matrix4x4::CreateRotationY(MCore::Math::DegreesToRadians(m_yaw))) * (AZ::Vector3(0.0f, 0.0f, 1.0f)).GetNormalized();
// look from the camera position into the newly calculated direction
MCore::LookAt(mViewMatrix, mPosition, mPosition + direction * 10.0f, AZ::Vector3(0.0f, 1.0f, 0.0f));
MCore::LookAt(m_viewMatrix, m_position, m_position + direction * 10.0f, AZ::Vector3(0.0f, 1.0f, 0.0f));
// update our base camera
Camera::Update();
@@ -62,7 +62,7 @@ namespace MCommon
EKeyboardButtonState buttonState = (EKeyboardButtonState)keyboardKeyFlags;
AZ::Matrix4x4 transposedViewMatrix(mViewMatrix);
AZ::Matrix4x4 transposedViewMatrix(m_viewMatrix);
transposedViewMatrix.Transpose();
// get the movement direction vector based on the keyboard input
@@ -95,14 +95,14 @@ namespace MCommon
// only move the camera when the delta movement is not the zero vector
if (MCore::SafeLength(deltaMovement) > MCore::Math::epsilon)
{
mPosition += deltaMovement.GetNormalized() * mTranslationSpeed;
m_position += deltaMovement.GetNormalized() * m_translationSpeed;
}
// rotate the camera
if (buttonState & ENABLE_MOUSELOOK)
{
mYaw += mouseMovementX * mRotationSpeed;
mPitch += mouseMovementY * mRotationSpeed;
m_yaw += mouseMovementX * m_rotationSpeed;
m_pitch += mouseMovementY * m_rotationSpeed;
}
}
@@ -115,8 +115,8 @@ namespace MCommon
// reset the base class attributes
Camera::Reset();
mPitch = 0.0f;
mYaw = 0.0f;
mRoll = 0.0f;
m_pitch = 0.0f;
m_yaw = 0.0f;
m_roll = 0.0f;
}
} // namespace MCommon
@@ -60,37 +60,37 @@ namespace MCommon
* Set the pitch angle in degrees. Looking up and down is limited to 90°. (0=Straight Ahead, +Up, -Down)
* @param The pitch angle in degrees, range[-90.0°, 90.0°].
*/
MCORE_INLINE void SetPitch(float pitch) { mPitch = pitch; }
MCORE_INLINE void SetPitch(float pitch) { m_pitch = pitch; }
/**
* Set the yaw angle in degrees. Vertical rotation. (0=East, +North, -South).
* @param yaw The yaw angle in degrees.
*/
MCORE_INLINE void SetYaw(float yaw) { mYaw = yaw; }
MCORE_INLINE void SetYaw(float yaw) { m_yaw = yaw; }
/**
* Set the roll angle in degrees. Rotation around the direction axis (0=Straight, +Clockwise, -CCW).
* @param roll The roll angle in degrees.
*/
MCORE_INLINE void SetRoll(float roll) { mRoll = roll; }
MCORE_INLINE void SetRoll(float roll) { m_roll = roll; }
/**
* Get the pitch angle in degrees. Looking up and down is limited to 90°. (0=Straight Ahead, +Up, -Down)
* @return The pitch angle in degrees, range[-90.0°, 90.0°].
*/
MCORE_INLINE float GetPitch() const { return mPitch; }
MCORE_INLINE float GetPitch() const { return m_pitch; }
/**
* Get the yaw angle in degrees. Vertical rotation. (0=East, +North, -South).
* @return The yaw angle in degrees.
*/
MCORE_INLINE float GetYaw() const { return mYaw; }
MCORE_INLINE float GetYaw() const { return m_yaw; }
/**
* Get the roll angle in degrees. Rotation around the direction axis (0=Straight, +Clockwise, -CCW).
* @return The roll angle in degrees.
*/
MCORE_INLINE float GetRoll() const { return mRoll; }
MCORE_INLINE float GetRoll() const { return m_roll; }
/**
* Update the camera transformation.
@@ -119,9 +119,9 @@ namespace MCommon
void Reset(float flightTime = 0.0f);
private:
float mPitch; /**< Up and down. (0=straight ahead, +up, -down) */
float mYaw; /**< Steering. (0=east, +north, -south) */
float mRoll; /**< Rotation around axis of screen. (0=straight, +clockwise, -CCW) */
float m_pitch; /**< Up and down. (0=straight ahead, +up, -down) */
float m_yaw; /**< Steering. (0=east, +north, -south) */
float m_roll; /**< Rotation around axis of screen. (0=straight, +clockwise, -CCW) */
};
} // namespace MCommon
@@ -29,8 +29,8 @@ namespace MCommon
// look at target
void LookAtCamera::LookAt(const AZ::Vector3& target, const AZ::Vector3& up)
{
mTarget = target;
mUp = up;
m_target = target;
m_up = up;
}
@@ -39,7 +39,7 @@ namespace MCommon
{
MCORE_UNUSED(timeDelta);
MCore::LookAtRH(mViewMatrix, mPosition, mTarget, mUp);
MCore::LookAtRH(m_viewMatrix, m_position, m_target, m_up);
// update our base camera at the very end
Camera::Update();
@@ -53,6 +53,6 @@ namespace MCommon
// reset the base class attributes
Camera::Reset();
mUp.Set(0.0f, 0.0f, 1.0f);
m_up.Set(0.0f, 0.0f, 1.0f);
}
} // namespace MCommon
@@ -66,29 +66,29 @@ namespace MCommon
* Set the target position. Note that the camera needs an update after setting a new target.
* @param[in] target The new camera target.
*/
MCORE_INLINE void SetTarget(const AZ::Vector3& target) { mTarget = target; }
MCORE_INLINE void SetTarget(const AZ::Vector3& target) { m_target = target; }
/**
* Get the target position.
* @return The current camera target.
*/
MCORE_INLINE AZ::Vector3 GetTarget() const { return mTarget; }
MCORE_INLINE AZ::Vector3 GetTarget() const { return m_target; }
/**
* Set the up vector for the camera. Note that the camera needs an update after setting a new up vector.
* @param[in] up The new camera up vector.
*/
MCORE_INLINE void SetUp(const AZ::Vector3& up) { mUp = up; }
MCORE_INLINE void SetUp(const AZ::Vector3& up) { m_up = up; }
/**
* Get the camera up vector.
* @return The current up vector.
*/
MCORE_INLINE AZ::Vector3 GetUp() const { return mUp; }
MCORE_INLINE AZ::Vector3 GetUp() const { return m_up; }
protected:
AZ::Vector3 mTarget; /**< The camera target. */
AZ::Vector3 mUp; /**< The up vector of the camera. */
AZ::Vector3 m_target; /**< The camera target. */
AZ::Vector3 m_up; /**< The up vector of the camera. */
};
} // namespace MCommon
@@ -33,32 +33,32 @@ namespace MCommon
// reset the parent class attributes
LookAtCamera::Reset();
mMinDistance = mNearClipDistance;
mMaxDistance = mFarClipDistance * 0.5f;
mPosition = AZ::Vector3::CreateZero();
mPositionDelta = AZ::Vector2(0.0f, 0.0f);
m_minDistance = m_nearClipDistance;
m_maxDistance = m_farClipDistance * 0.5f;
m_position = AZ::Vector3::CreateZero();
m_positionDelta = AZ::Vector2(0.0f, 0.0f);
if (flightTime < MCore::Math::epsilon)
{
mFlightActive = false;
mCurrentDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType());
mAlpha = GetDefaultAlpha();
mBeta = GetDefaultBeta();
mTarget = AZ::Vector3::CreateZero();
m_flightActive = false;
m_currentDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType());
m_alpha = GetDefaultAlpha();
m_beta = GetDefaultBeta();
m_target = AZ::Vector3::CreateZero();
}
else
{
mFlightActive = true;
mFlightMaxTime = flightTime;
mFlightCurrentTime = 0.0f;
mFlightSourceDistance = mCurrentDistance;
mFlightTargetDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType());
mFlightSourcePosition = mTarget;
mFlightTargetPosition = AZ::Vector3::CreateZero();
mFlightSourceAlpha = mAlpha;
mFlightTargetAlpha = GetDefaultAlpha();
mFlightSourceBeta = mBeta;
mFlightTargetBeta = GetDefaultBeta();
m_flightActive = true;
m_flightMaxTime = flightTime;
m_flightCurrentTime = 0.0f;
m_flightSourceDistance = m_currentDistance;
m_flightTargetDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType());
m_flightSourcePosition = m_target;
m_flightTargetPosition = AZ::Vector3::CreateZero();
m_flightSourceAlpha = m_alpha;
m_flightTargetAlpha = GetDefaultAlpha();
m_flightSourceBeta = m_beta;
m_flightTargetBeta = GetDefaultBeta();
}
}
@@ -66,53 +66,53 @@ namespace MCommon
// update limits
void OrbitCamera::AutoUpdateLimits()
{
mMinDistance = mNearClipDistance;
mMaxDistance = mFarClipDistance * 0.5f;
m_minDistance = m_nearClipDistance;
m_maxDistance = m_farClipDistance * 0.5f;
}
void OrbitCamera::StartFlight(float distance, const AZ::Vector3& position, float alpha, float beta, float flightTime)
{
mFlightActive = true;
mFlightMaxTime = flightTime;
mFlightCurrentTime = 0.0f;
mFlightSourceDistance = mCurrentDistance;
mFlightSourcePosition = mTarget;
mFlightTargetDistance = distance;
mFlightTargetPosition = position;
mFlightSourceAlpha = mAlpha;
mFlightTargetAlpha = alpha;
mFlightSourceBeta = mBeta;
mFlightTargetBeta = beta;
m_flightActive = true;
m_flightMaxTime = flightTime;
m_flightCurrentTime = 0.0f;
m_flightSourceDistance = m_currentDistance;
m_flightSourcePosition = m_target;
m_flightTargetDistance = distance;
m_flightTargetPosition = position;
m_flightSourceAlpha = m_alpha;
m_flightTargetAlpha = alpha;
m_flightSourceBeta = m_beta;
m_flightTargetBeta = beta;
}
// closeup view of the given bounding box
void OrbitCamera::ViewCloseup(const MCore::AABB& boundingBox, float flightTime)
{
mFlightActive = true;
mFlightMaxTime = flightTime;
mFlightCurrentTime = 0.0f;
mFlightSourceDistance = mCurrentDistance;
mFlightSourcePosition = mTarget;
const float distanceHorizontalFOV = boundingBox.CalcRadius() / MCore::Math::Tan(0.5f * MCore::Math::DegreesToRadians(mFOV));
const float distanceVerticalFOV = boundingBox.CalcRadius() / MCore::Math::Tan(0.5f * MCore::Math::DegreesToRadians(mFOV * mAspect));
mFlightTargetDistance = MCore::Max(distanceHorizontalFOV, distanceVerticalFOV) * 0.9f;
mFlightTargetPosition = boundingBox.CalcMiddle();
mFlightSourceAlpha = mAlpha;
mFlightSourceAlpha = mAlpha;
mFlightTargetAlpha = GetDefaultAlpha();
mFlightSourceBeta = mBeta;
mFlightTargetBeta = GetDefaultBeta();
m_flightActive = true;
m_flightMaxTime = flightTime;
m_flightCurrentTime = 0.0f;
m_flightSourceDistance = m_currentDistance;
m_flightSourcePosition = m_target;
const float distanceHorizontalFOV = boundingBox.CalcRadius() / MCore::Math::Tan(0.5f * MCore::Math::DegreesToRadians(m_fov));
const float distanceVerticalFOV = boundingBox.CalcRadius() / MCore::Math::Tan(0.5f * MCore::Math::DegreesToRadians(m_fov * m_aspect));
m_flightTargetDistance = MCore::Max(distanceHorizontalFOV, distanceVerticalFOV) * 0.9f;
m_flightTargetPosition = boundingBox.CalcMiddle();
m_flightSourceAlpha = m_alpha;
m_flightSourceAlpha = m_alpha;
m_flightTargetAlpha = GetDefaultAlpha();
m_flightSourceBeta = m_beta;
m_flightTargetBeta = GetDefaultBeta();
// make sure the target flight distance is in range
if (mFlightTargetDistance < mMinDistance)
if (m_flightTargetDistance < m_minDistance)
{
mFlightTargetDistance = mMinDistance;
m_flightTargetDistance = m_minDistance;
}
if (mFlightTargetDistance > mMaxDistance)
if (m_flightTargetDistance > m_maxDistance)
{
mFlightTargetDistance = mMaxDistance;
m_flightTargetDistance = m_maxDistance;
}
}
@@ -127,24 +127,24 @@ namespace MCommon
if (leftButtonPressed && rightButtonPressed == false && middleButtonPressed == false)
{
// rotate our camera
mAlpha += mRotationSpeed * (float)-mouseMovementX;
mBeta += mRotationSpeed * (float) mouseMovementY;
m_alpha += m_rotationSpeed * (float)-mouseMovementX;
m_beta += m_rotationSpeed * (float) mouseMovementY;
// prevent the camera from looking upside down
if (mBeta >= 90.0f - 0.01f)
if (m_beta >= 90.0f - 0.01f)
{
mBeta = 90.0f - 0.01f;
m_beta = 90.0f - 0.01f;
}
if (mBeta <= -90.0f + 0.01f)
if (m_beta <= -90.0f + 0.01f)
{
mBeta = -90.0f + 0.01f;
m_beta = -90.0f + 0.01f;
}
// reset the camera to no rotation if we made a whole circle
if (mAlpha >= 360.0f || mAlpha <= -360.0f)
if (m_alpha >= 360.0f || m_alpha <= -360.0f)
{
mAlpha = 0.0f;
m_alpha = 0.0f;
}
}
@@ -152,8 +152,8 @@ namespace MCommon
// zoom camera in or out
if (leftButtonPressed == false && rightButtonPressed && middleButtonPressed == false)
{
const float distanceScale = mCurrentDistance * 0.002f;
mCurrentDistance += (float)-mouseMovementY * distanceScale;
const float distanceScale = m_currentDistance * 0.002f;
m_currentDistance += (float)-mouseMovementY * distanceScale;
}
// is middle (or left+right) mouse button pressed?
@@ -161,13 +161,13 @@ namespace MCommon
if ((leftButtonPressed == false && rightButtonPressed == false && middleButtonPressed) ||
(leftButtonPressed && rightButtonPressed && middleButtonPressed == false))
{
const float distanceScale = mCurrentDistance * 0.002f;
const float distanceScale = m_currentDistance * 0.002f;
//if (MCore::GetCoordinateSystem().IsRightHanded())
//distanceScale *= -1.0f;
mPositionDelta.SetX((float)mouseMovementX * distanceScale);
mPositionDelta.SetY((float)mouseMovementY * distanceScale);
m_positionDelta.SetX((float)mouseMovementX * distanceScale);
m_positionDelta.SetY((float)mouseMovementY * distanceScale);
}
}
@@ -175,59 +175,59 @@ namespace MCommon
// update the camera
void OrbitCamera::Update(float timeDelta)
{
if (mFlightActive)
if (m_flightActive)
{
mFlightCurrentTime += timeDelta;
m_flightCurrentTime += timeDelta;
const float normalizedTime = mFlightCurrentTime / mFlightMaxTime;
const float normalizedTime = m_flightCurrentTime / m_flightMaxTime;
const float interpolatedTime = MCore::CosineInterpolate<float>(0.0f, 1.0f, normalizedTime);
mTarget = mFlightSourcePosition + (mFlightTargetPosition - mFlightSourcePosition) * interpolatedTime;
mCurrentDistance = mFlightSourceDistance + (mFlightTargetDistance - mFlightSourceDistance) * interpolatedTime;
mAlpha = mFlightSourceAlpha + (mFlightTargetAlpha - mFlightSourceAlpha) * interpolatedTime;
mBeta = mFlightSourceBeta + (mFlightTargetBeta - mFlightSourceBeta) * interpolatedTime;
m_target = m_flightSourcePosition + (m_flightTargetPosition - m_flightSourcePosition) * interpolatedTime;
m_currentDistance = m_flightSourceDistance + (m_flightTargetDistance - m_flightSourceDistance) * interpolatedTime;
m_alpha = m_flightSourceAlpha + (m_flightTargetAlpha - m_flightSourceAlpha) * interpolatedTime;
m_beta = m_flightSourceBeta + (m_flightTargetBeta - m_flightSourceBeta) * interpolatedTime;
if (mFlightCurrentTime >= mFlightMaxTime)
if (m_flightCurrentTime >= m_flightMaxTime)
{
mFlightActive = false;
mTarget = mFlightTargetPosition;
mCurrentDistance = mFlightTargetDistance;
mAlpha = mFlightTargetAlpha;
mBeta = mFlightTargetBeta;
m_flightActive = false;
m_target = m_flightTargetPosition;
m_currentDistance = m_flightTargetDistance;
m_alpha = m_flightTargetAlpha;
m_beta = m_flightTargetBeta;
}
}
// HACK TODO REMOVEME !!!
const float scale = 1.0f;
mCurrentDistance *= scale;
m_currentDistance *= scale;
if (mCurrentDistance <= mMinDistance * scale)
if (m_currentDistance <= m_minDistance * scale)
{
mCurrentDistance = mMinDistance * scale;
m_currentDistance = m_minDistance * scale;
}
if (mCurrentDistance >= mMaxDistance * scale)
if (m_currentDistance >= m_maxDistance * scale)
{
mCurrentDistance = mMaxDistance * scale;
m_currentDistance = m_maxDistance * scale;
}
// calculate unit direction vector based on our two angles
AZ::Vector3 unitSphereVector;
unitSphereVector.SetX(MCore::Math::Cos(MCore::Math::DegreesToRadians(mAlpha)) * MCore::Math::Cos(MCore::Math::DegreesToRadians(mBeta)));
unitSphereVector.SetY(MCore::Math::Sin(MCore::Math::DegreesToRadians(mAlpha)) * MCore::Math::Cos(MCore::Math::DegreesToRadians(mBeta)));
unitSphereVector.SetZ(MCore::Math::Sin(MCore::Math::DegreesToRadians(mBeta)));
unitSphereVector.SetX(MCore::Math::Cos(MCore::Math::DegreesToRadians(m_alpha)) * MCore::Math::Cos(MCore::Math::DegreesToRadians(m_beta)));
unitSphereVector.SetY(MCore::Math::Sin(MCore::Math::DegreesToRadians(m_alpha)) * MCore::Math::Cos(MCore::Math::DegreesToRadians(m_beta)));
unitSphereVector.SetZ(MCore::Math::Sin(MCore::Math::DegreesToRadians(m_beta)));
// calculate the right and the up vector based on the direction vector
AZ::Vector3 rightVec = unitSphereVector.Cross(AZ::Vector3(0.0f, 0.0f, 1.0f)).GetNormalized();
AZ::Vector3 upVec = rightVec.Cross(unitSphereVector).GetNormalized();
// calculate the lookat target and the camera position using our rotation sphere vectors
mTarget += (rightVec * mPositionDelta.GetX()) * mTranslationSpeed + (upVec * mPositionDelta.GetY()) * mTranslationSpeed;
mPosition = mTarget + (unitSphereVector * mCurrentDistance);
m_target += (rightVec * m_positionDelta.GetX()) * m_translationSpeed + (upVec * m_positionDelta.GetY()) * m_translationSpeed;
m_position = m_target + (unitSphereVector * m_currentDistance);
// reset the position delta
mPositionDelta = AZ::Vector2(0.0f, 0.0f);
m_positionDelta = AZ::Vector2(0.0f, 0.0f);
// update our lookat camera at the very end
LookAtCamera::Update();
@@ -76,27 +76,27 @@ namespace MCommon
void ViewCloseup(const MCore::AABB& boundingBox, float flightTime) override;
void StartFlight(float distance, const AZ::Vector3& position, float alpha, float beta, float flightTime);
bool GetIsFlightActive() const { return mFlightActive; }
void SetFlightTargetPosition(const AZ::Vector3& targetPos) { mFlightTargetPosition = targetPos; }
bool GetIsFlightActive() const { return m_flightActive; }
void SetFlightTargetPosition(const AZ::Vector3& targetPos) { m_flightTargetPosition = targetPos; }
float FlightTimeLeft() const
{
if (mFlightActive == false)
if (m_flightActive == false)
{
return 0.0f;
}
return mFlightMaxTime - mFlightCurrentTime;
return m_flightMaxTime - m_flightCurrentTime;
}
MCORE_INLINE float GetCurrentDistance() const { return mCurrentDistance; }
void SetCurrentDistance(float distance) { mCurrentDistance = distance; }
MCORE_INLINE float GetCurrentDistance() const { return m_currentDistance; }
void SetCurrentDistance(float distance) { m_currentDistance = distance; }
MCORE_INLINE float GetAlpha() const { return mAlpha; }
MCORE_INLINE float GetAlpha() const { return m_alpha; }
static float GetDefaultAlpha() { return 110.0f; }
void SetAlpha(float alpha) { mAlpha = alpha; }
void SetAlpha(float alpha) { m_alpha = alpha; }
MCORE_INLINE float GetBeta() const { return mBeta; }
MCORE_INLINE float GetBeta() const { return m_beta; }
static float GetDefaultBeta() { return 20.0f; }
void SetBeta(float beta) { mBeta = beta; }
void SetBeta(float beta) { m_beta = beta; }
// automatically updates the camera afterwards
void Set(float alpha, float beta, float currentDistance, const AZ::Vector3& target);
@@ -105,24 +105,24 @@ namespace MCommon
private:
AZ::Vector2 mPositionDelta; /**< The position delta which will be applied to the camera position when calling update. After adjusting the position it will be reset again. */
float mMinDistance; /**< The minimum distance from the orbit camera to its target in the orbit sphere. */
float mMaxDistance; /**< The maximum distance from the orbit camera to its target in the orbit sphere. */
float mCurrentDistance; /**< The current distance from the orbit camera to its target in the orbit sphere. */
float mAlpha; /**< The horizontal angle in our orbit sphere. */
float mBeta; /**< The vertical angle in our orbit sphere. */
AZ::Vector2 m_positionDelta; /**< The position delta which will be applied to the camera position when calling update. After adjusting the position it will be reset again. */
float m_minDistance; /**< The minimum distance from the orbit camera to its target in the orbit sphere. */
float m_maxDistance; /**< The maximum distance from the orbit camera to its target in the orbit sphere. */
float m_currentDistance; /**< The current distance from the orbit camera to its target in the orbit sphere. */
float m_alpha; /**< The horizontal angle in our orbit sphere. */
float m_beta; /**< The vertical angle in our orbit sphere. */
bool mFlightActive;
float mFlightMaxTime;
float mFlightCurrentTime;
float mFlightSourceDistance;
float mFlightTargetDistance;
AZ::Vector3 mFlightSourcePosition;
AZ::Vector3 mFlightTargetPosition;
float mFlightSourceAlpha;
float mFlightTargetAlpha;
float mFlightSourceBeta;
float mFlightTargetBeta;
bool m_flightActive;
float m_flightMaxTime;
float m_flightCurrentTime;
float m_flightSourceDistance;
float m_flightTargetDistance;
AZ::Vector3 m_flightSourcePosition;
AZ::Vector3 m_flightTargetPosition;
float m_flightSourceAlpha;
float m_flightTargetAlpha;
float m_flightSourceBeta;
float m_flightTargetBeta;
};
} // namespace MCommon
@@ -21,7 +21,7 @@ namespace MCommon
{
Reset();
SetMode(viewMode);
mProjectionMode = PROJMODE_ORTHOGRAPHIC;
m_projectionMode = PROJMODE_ORTHOGRAPHIC;
}
@@ -34,50 +34,50 @@ namespace MCommon
// update the camera position, orientation and it's matrices
void OrthographicCamera::Update(float timeDelta)
{
if (mFlightActive)
if (m_flightActive)
{
mFlightCurrentTime += timeDelta;
m_flightCurrentTime += timeDelta;
const float normalizedTime = mFlightCurrentTime / mFlightMaxTime;
const float normalizedTime = m_flightCurrentTime / m_flightMaxTime;
const float interpolatedTime = MCore::CosineInterpolate<float>(0.0f, 1.0f, normalizedTime);
mPosition = mFlightSourcePosition + (mFlightTargetPosition - mFlightSourcePosition) * interpolatedTime;
mCurrentDistance = mFlightSourceDistance + (mFlightTargetDistance - mFlightSourceDistance) * interpolatedTime;
m_position = m_flightSourcePosition + (m_flightTargetPosition - m_flightSourcePosition) * interpolatedTime;
m_currentDistance = m_flightSourceDistance + (m_flightTargetDistance - m_flightSourceDistance) * interpolatedTime;
if (mFlightCurrentTime >= mFlightMaxTime)
if (m_flightCurrentTime >= m_flightMaxTime)
{
mFlightActive = false;
mPosition = mFlightTargetPosition;
mCurrentDistance = mFlightTargetDistance;
m_flightActive = false;
m_position = m_flightTargetPosition;
m_currentDistance = m_flightTargetDistance;
}
}
// HACK TODO REMOVEME !!!
const float scale = 1.0f;
mCurrentDistance *= scale;
m_currentDistance *= scale;
if (mCurrentDistance <= mMinDistance * scale)
if (m_currentDistance <= m_minDistance * scale)
{
mCurrentDistance = mMinDistance * scale;
m_currentDistance = m_minDistance * scale;
}
if (mCurrentDistance >= mMaxDistance * scale)
if (m_currentDistance >= m_maxDistance * scale)
{
mCurrentDistance = mMaxDistance * scale;
m_currentDistance = m_maxDistance * scale;
}
// fake zoom the orthographic camera
const float orthoScale = scale * 0.001f;
const float deltaX = mCurrentDistance * mScreenWidth * orthoScale;
const float deltaY = mCurrentDistance * mScreenHeight * orthoScale;
const float deltaX = m_currentDistance * m_screenWidth * orthoScale;
const float deltaY = m_currentDistance * m_screenHeight * orthoScale;
SetOrthoClipDimensions(AZ::Vector2(deltaX, deltaY));
// adjust the mouse delta movement so that one pixel mouse movement is exactly one pixel on screen
mPositionDelta.SetX(mPositionDelta.GetX() * mCurrentDistance * orthoScale);
mPositionDelta.SetY(mPositionDelta.GetY() * mCurrentDistance * orthoScale);
m_positionDelta.SetX(m_positionDelta.GetX() * m_currentDistance * orthoScale);
m_positionDelta.SetY(m_positionDelta.GetY() * m_currentDistance * orthoScale);
AZ::Vector3 xAxis, yAxis, zAxis;
switch (mMode)
switch (m_mode)
{
case VIEWMODE_FRONT:
{
@@ -86,11 +86,11 @@ namespace MCommon
zAxis = AZ::Vector3(0.0f, 1.0f, 0.0f); // depth axis
// translate the camera
mPosition += xAxis * -mPositionDelta.GetX();
mPosition += yAxis * mPositionDelta.GetY();
m_position += xAxis * -m_positionDelta.GetX();
m_position += yAxis * m_positionDelta.GetY();
// setup the view matrix
MCore::LookAtRH(mViewMatrix, mPosition + zAxis * mCurrentDistance, mPosition, yAxis);
MCore::LookAtRH(m_viewMatrix, m_position + zAxis * m_currentDistance, m_position, yAxis);
break;
}
@@ -101,11 +101,11 @@ namespace MCommon
zAxis = AZ::Vector3(0.0f, -1.0f, 0.0f); // depth axis
// translate the camera
mPosition += xAxis * -mPositionDelta.GetX();
mPosition += yAxis * mPositionDelta.GetY();
m_position += xAxis * -m_positionDelta.GetX();
m_position += yAxis * m_positionDelta.GetY();
// setup the view matrix
MCore::LookAtRH(mViewMatrix, mPosition + zAxis * mCurrentDistance, mPosition, yAxis);
MCore::LookAtRH(m_viewMatrix, m_position + zAxis * m_currentDistance, m_position, yAxis);
break;
}
@@ -117,11 +117,11 @@ namespace MCommon
zAxis = AZ::Vector3(-1.0f, 0.0f, 0.0f); // depth axis
// translate the camera
mPosition += xAxis * mPositionDelta.GetX();
mPosition += yAxis * mPositionDelta.GetY();
m_position += xAxis * m_positionDelta.GetX();
m_position += yAxis * m_positionDelta.GetY();
// setup the view matrix
MCore::LookAtRH(mViewMatrix, mPosition + zAxis * mCurrentDistance, mPosition, yAxis);
MCore::LookAtRH(m_viewMatrix, m_position + zAxis * m_currentDistance, m_position, yAxis);
break;
}
@@ -132,11 +132,11 @@ namespace MCommon
zAxis = AZ::Vector3(1.0f, 0.0f, 0.0f); // depth axis
// translate the camera
mPosition += xAxis * mPositionDelta.GetX();
mPosition += yAxis * mPositionDelta.GetY();
m_position += xAxis * m_positionDelta.GetX();
m_position += yAxis * m_positionDelta.GetY();
// setup the view matrix
MCore::LookAtRH(mViewMatrix, mPosition + zAxis * mCurrentDistance, mPosition, yAxis);
MCore::LookAtRH(m_viewMatrix, m_position + zAxis * m_currentDistance, m_position, yAxis);
break;
}
@@ -147,11 +147,11 @@ namespace MCommon
zAxis = AZ::Vector3(0.0f, 0.0f, 1.0f); // depth axis
// translate the camera
mPosition += -xAxis* mPositionDelta.GetX();
mPosition += yAxis * mPositionDelta.GetY();
m_position += -xAxis* m_positionDelta.GetX();
m_position += yAxis * m_positionDelta.GetY();
// setup the view matrix
MCore::LookAtRH(mViewMatrix, mPosition + zAxis * mCurrentDistance, mPosition, yAxis);
MCore::LookAtRH(m_viewMatrix, m_position + zAxis * m_currentDistance, m_position, yAxis);
break;
}
@@ -162,18 +162,18 @@ namespace MCommon
zAxis = AZ::Vector3(0.0f, 0.0f, -1.0f); // depth axis
// translate the camera
mPosition += -xAxis* mPositionDelta.GetX();
mPosition += yAxis * mPositionDelta.GetY();
m_position += -xAxis* m_positionDelta.GetX();
m_position += yAxis * m_positionDelta.GetY();
// setup the view matrix
MCore::LookAtRH(mViewMatrix, mPosition + zAxis * mCurrentDistance, mPosition, yAxis);
MCore::LookAtRH(m_viewMatrix, m_position + zAxis * m_currentDistance, m_position, yAxis);
break;
}
}
;
// reset the position delta
mPositionDelta = AZ::Vector2(0.0f, 0.0f);
m_positionDelta = AZ::Vector2(0.0f, 0.0f);
// update our base camera
Camera::Update();
@@ -189,8 +189,8 @@ namespace MCommon
// zoom camera in or out
if (leftButtonPressed == false && rightButtonPressed && middleButtonPressed == false)
{
const float distanceScale = mCurrentDistance * 0.002f;
mCurrentDistance += (float)-mouseMovementY * distanceScale;
const float distanceScale = m_currentDistance * 0.002f;
m_currentDistance += (float)-mouseMovementY * distanceScale;
}
// is middle (or left+right) mouse button pressed?
@@ -198,8 +198,8 @@ namespace MCommon
if ((leftButtonPressed == false && rightButtonPressed == false && middleButtonPressed) ||
(leftButtonPressed && rightButtonPressed && middleButtonPressed == false))
{
mPositionDelta.SetX((float)mouseMovementX);
mPositionDelta.SetY((float)mouseMovementY);
m_positionDelta.SetX((float)mouseMovementX);
m_positionDelta.SetY((float)mouseMovementY);
}
}
@@ -207,41 +207,41 @@ namespace MCommon
// reset the camera attributes
void OrthographicCamera::Reset(float flightTime)
{
mPositionDelta = AZ::Vector2(0.0f, 0.0f);
mMinDistance = MCore::Math::epsilon;
mMaxDistance = mFarClipDistance * 0.5f;
m_positionDelta = AZ::Vector2(0.0f, 0.0f);
m_minDistance = MCore::Math::epsilon;
m_maxDistance = m_farClipDistance * 0.5f;
AZ::Vector3 resetPosition(0.0f, 0.0f, 0.0f);
switch (mMode)
switch (m_mode)
{
case VIEWMODE_FRONT:
{
resetPosition.SetY(mCurrentDistance);
resetPosition.SetY(m_currentDistance);
break;
}
case VIEWMODE_BACK:
{
resetPosition.SetY(-mCurrentDistance);
resetPosition.SetY(-m_currentDistance);
break;
}
case VIEWMODE_LEFT:
{
resetPosition.SetX(-mCurrentDistance);
resetPosition.SetX(-m_currentDistance);
break;
}
case VIEWMODE_RIGHT:
{
resetPosition.SetX(mCurrentDistance);
resetPosition.SetX(m_currentDistance);
break;
}
case VIEWMODE_TOP:
{
resetPosition.SetZ(mCurrentDistance);
resetPosition.SetZ(m_currentDistance);
break;
}
case VIEWMODE_BOTTOM:
{
resetPosition.SetZ(-mCurrentDistance);
resetPosition.SetZ(-m_currentDistance);
break;
}
}
@@ -249,19 +249,19 @@ namespace MCommon
if (flightTime < MCore::Math::epsilon)
{
mFlightActive = false;
mCurrentDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType());
mPosition = resetPosition;
m_flightActive = false;
m_currentDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType());
m_position = resetPosition;
}
else
{
mFlightActive = true;
mFlightMaxTime = flightTime;
mFlightCurrentTime = 0.0f;
mFlightSourceDistance = mCurrentDistance;
mFlightTargetDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType());
mFlightSourcePosition = mPosition;
mFlightTargetPosition = resetPosition;
m_flightActive = true;
m_flightMaxTime = flightTime;
m_flightCurrentTime = 0.0f;
m_flightSourceDistance = m_currentDistance;
m_flightTargetDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType());
m_flightSourcePosition = m_position;
m_flightTargetPosition = resetPosition;
}
// reset the base class attributes
@@ -271,22 +271,22 @@ namespace MCommon
void OrthographicCamera::StartFlight(float distance, const AZ::Vector3& position, float flightTime)
{
mFlightMaxTime = flightTime;
mFlightCurrentTime = 0.0f;
mFlightSourceDistance = mCurrentDistance;
mFlightSourcePosition = mPosition;
m_flightMaxTime = flightTime;
m_flightCurrentTime = 0.0f;
m_flightSourceDistance = m_currentDistance;
m_flightSourcePosition = m_position;
if (flightTime < MCore::Math::epsilon)
{
mFlightActive = false;
mCurrentDistance = distance;
mPosition = position;
m_flightActive = false;
m_currentDistance = distance;
m_position = position;
}
else
{
mFlightActive = true;
mFlightTargetDistance = distance;
mFlightTargetPosition = position;
m_flightActive = true;
m_flightTargetDistance = distance;
m_flightTargetPosition = position;
}
}
@@ -294,14 +294,14 @@ namespace MCommon
// closeup view of the given bounding box
void OrthographicCamera::ViewCloseup(const MCore::AABB& boundingBox, float flightTime)
{
mFlightMaxTime = flightTime;
mFlightCurrentTime = 0.0f;
mFlightSourceDistance = mCurrentDistance;
mFlightSourcePosition = mPosition;
m_flightMaxTime = flightTime;
m_flightCurrentTime = 0.0f;
m_flightSourceDistance = m_currentDistance;
m_flightSourcePosition = m_position;
float boxWidth = 0.0f;
float boxHeight = 0.0f;
switch (mMode)
switch (m_mode)
{
case VIEWMODE_FRONT:
{
@@ -343,32 +343,32 @@ namespace MCommon
;
const float orthoScale = 0.001f;
assert(mScreenWidth != 0 && mScreenHeight != 0);
const float distanceX = (boxWidth) / (mScreenWidth * orthoScale);
const float distanceY = (boxHeight) / (mScreenHeight * orthoScale);
assert(m_screenWidth != 0 && m_screenHeight != 0);
const float distanceX = (boxWidth) / (m_screenWidth * orthoScale);
const float distanceY = (boxHeight) / (m_screenHeight * orthoScale);
//LOG("box: x=%f y=%f, boxAspect=%f, orthoAspect=%f, distX=%f, distY=%f", boxWidth, boxHeight, boxAspect, orthoAspect, distanceX, distanceY);
if (flightTime < MCore::Math::epsilon)
{
mFlightActive = false;
mCurrentDistance = MCore::Max(distanceX, distanceY) * 1.1f;
mPosition = boundingBox.CalcMiddle();
m_flightActive = false;
m_currentDistance = MCore::Max(distanceX, distanceY) * 1.1f;
m_position = boundingBox.CalcMiddle();
}
else
{
mFlightActive = true;
mFlightTargetDistance = MCore::Max(distanceX, distanceY) * 1.1f;
mFlightTargetPosition = boundingBox.CalcMiddle();
m_flightActive = true;
m_flightTargetDistance = MCore::Max(distanceX, distanceY) * 1.1f;
m_flightTargetPosition = boundingBox.CalcMiddle();
}
// make sure the target flight distance is in range
if (mFlightTargetDistance < mMinDistance)
if (m_flightTargetDistance < m_minDistance)
{
mFlightTargetDistance = mMinDistance;
m_flightTargetDistance = m_minDistance;
}
if (mFlightTargetDistance > mMaxDistance)
if (m_flightTargetDistance > m_maxDistance)
{
mFlightTargetDistance = mMaxDistance;
m_flightTargetDistance = m_maxDistance;
}
}
@@ -376,7 +376,7 @@ namespace MCommon
// get the type identification string
const char* OrthographicCamera::GetTypeString() const
{
switch (mMode)
switch (m_mode)
{
case VIEWMODE_FRONT:
{
@@ -419,8 +419,8 @@ namespace MCommon
// unproject screen coordinates to a ray
MCore::Ray OrthographicCamera::Unproject(int32 screenX, int32 screenY)
{
AZ::Vector3 start = MCore::UnprojectOrtho(static_cast<float>(screenX), static_cast<float>(screenY), static_cast<float>(mScreenWidth), static_cast<float>(mScreenHeight), -1.0f, mProjectionMatrix, mViewMatrix);
AZ::Vector3 end = MCore::UnprojectOrtho(static_cast<float>(screenX), static_cast<float>(screenY), static_cast<float>(mScreenWidth), static_cast<float>(mScreenHeight), 1.0f, mProjectionMatrix, mViewMatrix);
AZ::Vector3 start = MCore::UnprojectOrtho(static_cast<float>(screenX), static_cast<float>(screenY), static_cast<float>(m_screenWidth), static_cast<float>(m_screenHeight), -1.0f, m_projectionMatrix, m_viewMatrix);
AZ::Vector3 end = MCore::UnprojectOrtho(static_cast<float>(screenX), static_cast<float>(screenY), static_cast<float>(m_screenWidth), static_cast<float>(m_screenHeight), 1.0f, m_projectionMatrix, m_viewMatrix);
return MCore::Ray(start, end);
}
@@ -429,7 +429,7 @@ namespace MCommon
// update limits
void OrthographicCamera::AutoUpdateLimits()
{
mMinDistance = mNearClipDistance;
mMaxDistance = mFarClipDistance * 0.5f;
m_minDistance = m_nearClipDistance;
m_maxDistance = m_farClipDistance * 0.5f;
}
} // namespace MCommon
@@ -60,8 +60,8 @@ namespace MCommon
*/
const char* GetTypeString() const override;
MCORE_INLINE void SetMode(ViewMode viewMode) { mMode = viewMode; }
MCORE_INLINE ViewMode GetMode() const { return mMode; }
MCORE_INLINE void SetMode(ViewMode viewMode) { m_mode = viewMode; }
MCORE_INLINE ViewMode GetMode() const { return m_mode; }
/**
* Update the camera transformation.
@@ -99,15 +99,15 @@ namespace MCommon
void AutoUpdateLimits() override;
void StartFlight(float distance, const AZ::Vector3& position, float flightTime);
bool GetIsFlightActive() const { return mFlightActive; }
void SetFlightTargetPosition(const AZ::Vector3& targetPos) { mFlightTargetPosition = targetPos; }
bool GetIsFlightActive() const { return m_flightActive; }
void SetFlightTargetPosition(const AZ::Vector3& targetPos) { m_flightTargetPosition = targetPos; }
float FlightTimeLeft() const
{
if (mFlightActive == false)
if (m_flightActive == false)
{
return 0.0f;
}
return mFlightMaxTime - mFlightCurrentTime;
return m_flightMaxTime - m_flightCurrentTime;
}
/**
@@ -118,22 +118,22 @@ namespace MCommon
*/
MCore::Ray Unproject(int32 screenX, int32 screenY) override;
MCORE_INLINE void SetCurrentDistance(float distance) { mCurrentDistance = distance; }
MCORE_INLINE float GetCurrentDistance() const { return mCurrentDistance; }
MCORE_INLINE void SetCurrentDistance(float distance) { m_currentDistance = distance; }
MCORE_INLINE float GetCurrentDistance() const { return m_currentDistance; }
private:
ViewMode mMode;
AZ::Vector2 mPositionDelta; /**< The position delta which will be applied to the camera position when calling update. After adjusting the position it will be reset again. */
float mMinDistance; /**< The minimum distance from the orbit camera to its target in the orbit sphere. */
float mMaxDistance; /**< The maximum distance from the orbit camera to its target in the orbit sphere. */
float mCurrentDistance; /**< The current distance from the orbit camera to its target in the orbit sphere. */
bool mFlightActive;
float mFlightMaxTime;
float mFlightCurrentTime;
float mFlightSourceDistance;
AZ::Vector3 mFlightSourcePosition;
float mFlightTargetDistance;
AZ::Vector3 mFlightTargetPosition;
ViewMode m_mode;
AZ::Vector2 m_positionDelta; /**< The position delta which will be applied to the camera position when calling update. After adjusting the position it will be reset again. */
float m_minDistance; /**< The minimum distance from the orbit camera to its target in the orbit sphere. */
float m_maxDistance; /**< The maximum distance from the orbit camera to its target in the orbit sphere. */
float m_currentDistance; /**< The current distance from the orbit camera to its target in the orbit sphere. */
bool m_flightActive;
float m_flightMaxTime;
float m_flightCurrentTime;
float m_flightSourceDistance;
AZ::Vector3 m_flightSourcePosition;
float m_flightTargetDistance;
AZ::Vector3 m_flightTargetPosition;
};
} // namespace MCommon
File diff suppressed because it is too large Load Diff
@@ -33,11 +33,11 @@ namespace MCommon
public:
// colors
static MCore::RGBAColor mSelectionColor;
static MCore::RGBAColor mSelectionColorDarker;
static MCore::RGBAColor mRed;
static MCore::RGBAColor mGreen;
static MCore::RGBAColor mBlue;
static MCore::RGBAColor s_selectionColor;
static MCore::RGBAColor s_selectionColorDarker;
static MCore::RGBAColor s_red;
static MCore::RGBAColor s_green;
static MCore::RGBAColor s_blue;
};
@@ -149,12 +149,12 @@ namespace MCommon
*/
AABBRenderSettings();
bool mNodeBasedAABB; /**< Enable in case you want to render the node based AABB (default=true). */
bool mMeshBasedAABB; /**< Enable in case you want to render the mesh based AABB (default=true). */
bool mStaticBasedAABB; /**< Enable in case you want to render the static based AABB (default=true). */
MCore::RGBAColor mNodeBasedColor; /**< The color of the node based AABB. */
MCore::RGBAColor mMeshBasedColor; /**< The color of the mesh based AABB. */
MCore::RGBAColor mStaticBasedColor; /**< The color of the static based AABB. */
bool m_nodeBasedAabb; /**< Enable in case you want to render the node based AABB (default=true). */
bool m_meshBasedAabb; /**< Enable in case you want to render the mesh based AABB (default=true). */
bool m_staticBasedAabb; /**< Enable in case you want to render the static based AABB (default=true). */
MCore::RGBAColor m_nodeBasedColor; /**< The color of the node based AABB. */
MCore::RGBAColor m_meshBasedColor; /**< The color of the mesh based AABB. */
MCore::RGBAColor m_staticBasedColor; /**< The color of the static based AABB. */
};
/**
@@ -239,7 +239,7 @@ namespace MCommon
* @param color The desired sphere color.
* @param worldTM The world space transformation matrix.
*/
MCORE_INLINE void RenderSphere(const MCore::RGBAColor& color, const AZ::Transform& worldTM) { RenderUtilMesh(mUnitSphereMesh, color, worldTM); }
MCORE_INLINE void RenderSphere(const MCore::RGBAColor& color, const AZ::Transform& worldTM) { RenderUtilMesh(m_unitSphereMesh, color, worldTM); }
/**
* Render a circle, consisting of lines.
@@ -255,7 +255,7 @@ namespace MCommon
* @param color The desired cube color.
* @param worldTM The world space transformation matrix.
*/
MCORE_INLINE void RenderCube(const MCore::RGBAColor& color, const AZ::Transform& worldTM) { RenderUtilMesh(mUnitCubeMesh, color, worldTM); }
MCORE_INLINE void RenderCube(const MCore::RGBAColor& color, const AZ::Transform& worldTM) { RenderUtilMesh(m_unitCubeMesh, color, worldTM); }
/**
* Render a cylinder.
@@ -265,7 +265,7 @@ namespace MCommon
* @param color The desired cylinder color.
* @param worldTM The world space transformation matrix.
*/
MCORE_INLINE void RenderCylinder(float baseRadius, float topRadius, float length, const MCore::RGBAColor& color, const AZ::Transform& worldTM) { FillCylinder(mCylinderMesh, baseRadius, topRadius, length); RenderUtilMesh(mCylinderMesh, color, worldTM); }
MCORE_INLINE void RenderCylinder(float baseRadius, float topRadius, float length, const MCore::RGBAColor& color, const AZ::Transform& worldTM) { FillCylinder(m_cylinderMesh, baseRadius, topRadius, length); RenderUtilMesh(m_cylinderMesh, color, worldTM); }
/**
* Render a cylinder.
@@ -302,7 +302,7 @@ namespace MCommon
* @param color The desired arrow head color.
* @param worldTM The world space transformation matrix.
*/
MCORE_INLINE void RenderArrowHead(float height, float radius, const MCore::RGBAColor& color, const AZ::Transform& worldTM) { FillArrowHead(mArrowHeadMesh, height, radius); RenderUtilMesh(mArrowHeadMesh, color, worldTM); }
MCORE_INLINE void RenderArrowHead(float height, float radius, const MCore::RGBAColor& color, const AZ::Transform& worldTM) { FillArrowHead(m_arrowHeadMesh, height, radius); RenderUtilMesh(m_arrowHeadMesh, color, worldTM); }
/**
* Render an arrow head.
@@ -336,17 +336,17 @@ namespace MCommon
*/
AxisRenderingSettings();
AZ::Transform mWorldTM; /**< The world space transformation matrix to visualize. */
AZ::Vector3 mCameraRight; /**< The inverse of the camera's right vector used for billboarding the axis names. */
AZ::Vector3 mCameraUp; /**< The inverse of the camera's up vector used for billboarding the axis names. */
float mSize; /**< The size value in units is used to control the scaling of the axis. */
bool mRenderXAxis; /**< Set to true if you want to render the x axis, false if the x axis should be skipped. */
bool mRenderYAxis; /**< Set to true if you want to render the y axis, false if the y axis should be skipped. */
bool mRenderZAxis; /**< Set to true if you want to render the z axis, false if the z axis should be skipped. */
bool mRenderXAxisName; /**< Set to true if you want to render the name of the x axis. The name will only be rendered if the axis itself will be rendered as well. */
bool mRenderYAxisName; /**< Set to true if you want to render the name of the y axis. The name will only be rendered if the axis itself will be rendered as well. */
bool mRenderZAxisName; /**< Set to true if you want to render the name of the z axis. The name will only be rendered if the axis itself will be rendered as well. */
bool mSelected; /**< Set to true if you want to render the axis using the selection color. */
AZ::Transform m_worldTm; /**< The world space transformation matrix to visualize. */
AZ::Vector3 m_cameraRight; /**< The inverse of the camera's right vector used for billboarding the axis names. */
AZ::Vector3 m_cameraUp; /**< The inverse of the camera's up vector used for billboarding the axis names. */
float m_size; /**< The size value in units is used to control the scaling of the axis. */
bool m_renderXAxis; /**< Set to true if you want to render the x axis, false if the x axis should be skipped. */
bool m_renderYAxis; /**< Set to true if you want to render the y axis, false if the y axis should be skipped. */
bool m_renderZAxis; /**< Set to true if you want to render the z axis, false if the z axis should be skipped. */
bool m_renderXAxisName; /**< Set to true if you want to render the name of the x axis. The name will only be rendered if the axis itself will be rendered as well. */
bool m_renderYAxisName; /**< Set to true if you want to render the name of the y axis. The name will only be rendered if the axis itself will be rendered as well. */
bool m_renderZAxisName; /**< Set to true if you want to render the name of the z axis. The name will only be rendered if the axis itself will be rendered as well. */
bool m_selected; /**< Set to true if you want to render the axis using the selection color. */
};
/**
@@ -372,8 +372,8 @@ namespace MCommon
struct MCOMMON_API LineVertex
{
MCORE_MEMORYOBJECTCATEGORY(RenderUtil::LineVertex, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MCOMMON);
AZ::Vector3 mPosition; /**< The position of the vertex. */
MCore::RGBAColor mColor; /**< The vertex color. */
AZ::Vector3 m_position; /**< The position of the vertex. */
MCore::RGBAColor m_color; /**< The vertex color. */
};
/**
@@ -384,12 +384,12 @@ namespace MCommon
*/
MCORE_INLINE void RenderLine(const AZ::Vector3& v1, const AZ::Vector3& v2, const MCore::RGBAColor& color)
{
mVertexBuffer[mNumVertices].mPosition = v1;
mVertexBuffer[mNumVertices + 1].mPosition = v2;
mVertexBuffer[mNumVertices].mColor = color;
mVertexBuffer[mNumVertices + 1].mColor = color;
mNumVertices += 2;
if (mNumVertices >= mNumMaxLineVertices)
m_vertexBuffer[m_numVertices].m_position = v1;
m_vertexBuffer[m_numVertices + 1].m_position = v2;
m_vertexBuffer[m_numVertices].m_color = color;
m_vertexBuffer[m_numVertices + 1].m_color = color;
m_numVertices += 2;
if (m_numVertices >= s_numMaxLineVertices)
{
RenderLines();
}
@@ -416,11 +416,11 @@ namespace MCommon
struct MCOMMON_API Line2D
{
MCORE_MEMORYOBJECTCATEGORY(RenderUtil::Line2D, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MCOMMON);
float mX1; /**< The x position of the first vertex. */
float mY1; /**< The y position of the first vertex. */
float mX2; /**< The x position of the second vertex. */
float mY2; /**< The y position of the second vertex. */
MCore::RGBAColor mColor; /**< The line color. */
float m_x1; /**< The x position of the first vertex. */
float m_y1; /**< The y position of the first vertex. */
float m_x2; /**< The x position of the second vertex. */
float m_y2; /**< The y position of the second vertex. */
MCore::RGBAColor m_color; /**< The line color. */
};
/**
@@ -433,13 +433,13 @@ namespace MCommon
*/
MCORE_INLINE void Render2DLine(float x1, float y1, float x2, float y2, const MCore::RGBAColor& color)
{
m2DLines[mNum2DLines].mX1 = x1;
m2DLines[mNum2DLines].mY1 = y1;
m2DLines[mNum2DLines].mX2 = x2;
m2DLines[mNum2DLines].mY2 = y2;
m2DLines[mNum2DLines].mColor = color;
mNum2DLines++;
if (mNum2DLines >= mNumMax2DLines)
m_m2DLines[m_num2DLines].m_x1 = x1;
m_m2DLines[m_num2DLines].m_y1 = y1;
m_m2DLines[m_num2DLines].m_x2 = x2;
m_m2DLines[m_num2DLines].m_y2 = y2;
m_m2DLines[m_num2DLines].m_color = color;
m_num2DLines++;
if (m_num2DLines >= s_numMax2DLines)
{
Render2DLines();
}
@@ -489,9 +489,9 @@ namespace MCommon
*/
void Allocate(uint32 numVertices, uint32 numIndices, bool hasNormals);
AZStd::vector<AZ::Vector3> mPositions; /**< The vertex buffer. */
AZStd::vector<uint32> mIndices; /**< The index buffer. */
AZStd::vector<AZ::Vector3> mNormals; /**< The normal buffer. */
AZStd::vector<AZ::Vector3> m_positions; /**< The vertex buffer. */
AZStd::vector<uint32> m_indices; /**< The index buffer. */
AZStd::vector<AZ::Vector3> m_normals; /**< The normal buffer. */
};
/**
@@ -500,12 +500,12 @@ namespace MCommon
struct UtilMeshVertex
{
MCORE_MEMORYOBJECTCATEGORY(RenderUtil::UtilMeshVertex, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MCOMMON);
AZ::Vector3 mPosition; /**< The position of the vertex. */
AZ::Vector3 mNormal; /**< The vertex normal. */
AZ::Vector3 m_position; /**< The position of the vertex. */
AZ::Vector3 m_normal; /**< The vertex normal. */
UtilMeshVertex(const AZ::Vector3& pos, const AZ::Vector3& normal)
: mPosition(pos)
, mNormal(normal) {}
: m_position(pos)
, m_normal(normal) {}
};
/**
@@ -530,51 +530,33 @@ namespace MCommon
* To avoid recalculating them several times we do this at a central place. This function needs to be called before switching to a new mesh inside
* the render loop as well as before an animation update, so before calling any of the render normals, face normals, tangents and bitangents functions.
*/
MCORE_INLINE void ResetCurrentMesh() { mCurrentMesh = NULL; }
MCORE_INLINE void ResetCurrentMesh() { m_currentMesh = NULL; }
//---------------------------------------------------------------------------------------------
/*struct MCOMMON_API Triangle
{
MCORE_MEMORYOBJECTCATEGORY( RenderUtil::Triangle, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MCOMMON );
AZ::Vector3 mPosA;
AZ::Vector3 mPosB;
AZ::Vector3 mPosC;
AZ::Vector3 mNormalA;
AZ::Vector3 mNormalB;
AZ::Vector3 mNormalC;
uint32 mColor;
Triangle() {}
Triangle(const AZ::Vector3& posA, const AZ::Vector3& posB, const AZ::Vector3& posC, const AZ::Vector3& normalA, const AZ::Vector3& normalB, const AZ::Vector3& normalC, uint32 color) : mPosA(posA), mPosB(posB), mPosC(posC), mNormalA(normalA), mNormalB(normalB), mNormalC(normalC), mColor(color) {}
};*/
/**
* The vertex structure to be used for rendering util meshes.
*/
struct TriangleVertex
{
MCORE_MEMORYOBJECTCATEGORY(RenderUtil::TriangleVertex, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MCOMMON);
AZ::Vector3 mPosition; /**< The position of the vertex. */
AZ::Vector3 mNormal; /**< The vertex normal. */
uint32 mColor;
AZ::Vector3 m_position; /**< The position of the vertex. */
AZ::Vector3 m_normal; /**< The vertex normal. */
uint32 m_color;
MCORE_INLINE TriangleVertex(const AZ::Vector3& pos, const AZ::Vector3& normal, uint32 color)
: mPosition(pos)
, mNormal(normal)
, mColor(color) {}
: m_position(pos)
, m_normal(normal)
, m_color(color) {}
};
MCORE_INLINE void AddTriangle(const AZ::Vector3& posA, const AZ::Vector3& posB, const AZ::Vector3& posC, const AZ::Vector3& normalA, const AZ::Vector3& normalB, const AZ::Vector3& normalC, uint32 color)
{
mTriangleVertices.emplace_back(TriangleVertex(posA, normalA, color));
mTriangleVertices.emplace_back(TriangleVertex(posB, normalB, color));
mTriangleVertices.emplace_back(TriangleVertex(posC, normalC, color));
m_triangleVertices.emplace_back(TriangleVertex(posA, normalA, color));
m_triangleVertices.emplace_back(TriangleVertex(posB, normalB, color));
m_triangleVertices.emplace_back(TriangleVertex(posC, normalC, color));
if (mTriangleVertices.size() + 2 >= mNumMaxTriangleVertices)
if (m_triangleVertices.size() + 2 >= s_numMaxTriangleVertices)
{
RenderTriangles();
}
@@ -604,20 +586,20 @@ namespace MCommon
struct TrajectoryPathParticle
{
EMotionFX::Transform mWorldTM;
EMotionFX::Transform m_worldTm;
};
struct TrajectoryTracePath
{
AZStd::vector<TrajectoryPathParticle> mTraceParticles;
EMotionFX::ActorInstance* mActorInstance;
float mTimePassed;
AZStd::vector<TrajectoryPathParticle> m_traceParticles;
EMotionFX::ActorInstance* m_actorInstance;
float m_timePassed;
TrajectoryTracePath()
{
mTraceParticles.reserve(250);
mTimePassed = 0.0f;
mActorInstance = NULL;
m_traceParticles.reserve(250);
m_timePassed = 0.0f;
m_actorInstance = NULL;
}
};
@@ -637,7 +619,7 @@ namespace MCommon
/**
* Render text to screen. This will only work in case the Render2DLines() function has been implemented.
*/
MCORE_INLINE void RenderText(float x, float y, const char* text, const MCore::RGBAColor& color = MCore::RGBAColor(1.0f, 1.0f, 1.0f), float fontSize = 11.0f, bool centered = false) { mFont->Render(x * m_devicePixelRatio, (y * m_devicePixelRatio) + fontSize - 1, fontSize, centered, text, color); }
MCORE_INLINE void RenderText(float x, float y, const char* text, const MCore::RGBAColor& color = MCore::RGBAColor(1.0f, 1.0f, 1.0f), float fontSize = 11.0f, bool centered = false) { m_font->Render(x * m_devicePixelRatio, (y * m_devicePixelRatio) + fontSize - 1, fontSize, centered, text, color); }
/**
* Render text to screen. This will only work in case the Render2DLines() function has been implemented.
@@ -750,19 +732,19 @@ namespace MCommon
MCORE_INLINE float GetWidth() const
{
float ret = 0.1f;
if (mIndexCount > 0)
if (m_indexCount > 0)
{
ret = (mX2 - mX1) + 0.05f;
ret = (m_x2 - m_x1) + 0.05f;
}
return ret;
}
float mX1;
float mX2;
float mY1;
float mY2;
unsigned short mIndexCount;
const unsigned short* mIndices;
float m_x1;
float m_x2;
float m_y1;
float m_y2;
unsigned short m_indexCount;
const unsigned short* m_indices;
};
class MCOMMON_API VectorFont
@@ -780,39 +762,39 @@ namespace MCommon
float CalculateTextWidth(const char* text);
private:
uint32 mVersion;
uint32 mVcount;
uint32 mCount;
float* mVertices;
uint32 mIcount;
FontChar mCharacters[256];
RenderUtil* mRenderUtil;
uint32 m_version;
uint32 m_vcount;
uint32 m_count;
float* m_vertices;
uint32 m_icount;
FontChar m_characters[256];
RenderUtil* m_renderUtil;
};
EMotionFX::Mesh* mCurrentMesh; /**< A pointer to the mesh whose world space positions are in the pre-calculated positions buffer. NULL in case we haven't pre-calculated any positions yet. */
AZStd::vector<AZ::Vector3> mWorldSpacePositions; /**< The buffer used to store world space positions for rendering normals, tangents and the wireframe. */
EMotionFX::Mesh* m_currentMesh; /**< A pointer to the mesh whose world space positions are in the pre-calculated positions buffer. NULL in case we haven't pre-calculated any positions yet. */
AZStd::vector<AZ::Vector3> m_worldSpacePositions; /**< The buffer used to store world space positions for rendering normals, tangents and the wireframe. */
LineVertex* mVertexBuffer; /**< Array of line vertices. */
uint32 mNumVertices; /**< The current number of vertices in the array. */
static uint32 mNumMaxLineVertices; /**< The maximum capacity of the line vertex buffer. */
LineVertex* m_vertexBuffer; /**< Array of line vertices. */
uint32 m_numVertices; /**< The current number of vertices in the array. */
static uint32 s_numMaxLineVertices; /**< The maximum capacity of the line vertex buffer. */
Line2D* m2DLines; /**< Array of 2D lines. */
uint32 mNum2DLines; /**< The current number of 2D lines in the array. */
static uint32 mNumMax2DLines; /**< The maximum capacity of the 2D line buffer. */
static float m_wireframeSphereSegmentCount;
Line2D* m_m2DLines; /**< Array of 2D lines. */
uint32 m_num2DLines; /**< The current number of 2D lines in the array. */
static uint32 s_numMax2DLines; /**< The maximum capacity of the 2D line buffer. */
static float s_wireframeSphereSegmentCount;
float m_devicePixelRatio;
VectorFont* mFont; /**< The vector font used to render text. */
VectorFont* m_font; /**< The vector font used to render text. */
UtilMesh* mUnitSphereMesh; /**< The preallocated and preconstructed sphere mesh used for rendering. */
UtilMesh* mCylinderMesh; /**< The preallocated and preconstructed cylinder mesh used for rendering. */
UtilMesh* mUnitCubeMesh; /**< The preallocated and preconstructed cube mesh used for rendering. */
UtilMesh* mArrowHeadMesh; /**< The preallocated and preconstructed arrow head mesh used for rendering. */
static uint32 mNumMaxMeshVertices; /**< The maximum capacity of the util mesh vertex buffer. */
static uint32 mNumMaxMeshIndices; /**< The maximum capacity of the util mesh index buffer */
UtilMesh* m_unitSphereMesh; /**< The preallocated and preconstructed sphere mesh used for rendering. */
UtilMesh* m_cylinderMesh; /**< The preallocated and preconstructed cylinder mesh used for rendering. */
UtilMesh* m_unitCubeMesh; /**< The preallocated and preconstructed cube mesh used for rendering. */
UtilMesh* m_arrowHeadMesh; /**< The preallocated and preconstructed arrow head mesh used for rendering. */
static uint32 s_numMaxMeshVertices; /**< The maximum capacity of the util mesh vertex buffer. */
static uint32 s_numMaxMeshIndices; /**< The maximum capacity of the util mesh index buffer */
// helper variables for rendering triangles
AZStd::vector<TriangleVertex> mTriangleVertices;
static uint32 mNumMaxTriangleVertices; /**< The maximum capacity of the triangle vertex buffer */
AZStd::vector<TriangleVertex> m_triangleVertices;
static uint32 s_numMaxTriangleVertices; /**< The maximum capacity of the triangle vertex buffer */
};
} // namespace MCommon
@@ -16,10 +16,10 @@ namespace MCommon
RotateManipulator::RotateManipulator(float scalingFactor, bool isVisible)
: TransformationManipulator(scalingFactor, isVisible)
{
mMode = ROTATE_NONE;
mRotation = AZ::Vector3::CreateZero();
mRotationQuat = AZ::Quaternion::CreateIdentity();
mClickPosition = AZ::Vector3::CreateZero();
m_mode = ROTATE_NONE;
m_rotation = AZ::Vector3::CreateZero();
m_rotationQuat = AZ::Quaternion::CreateIdentity();
m_clickPosition = AZ::Vector3::CreateZero();
}
@@ -34,35 +34,35 @@ namespace MCommon
{
MCORE_UNUSED(camera);
// adjust the mSize when in ortho mode
mSize = mScalingFactor;
mInnerRadius = 0.15f * mSize;
mOuterRadius = 0.2f * mSize;
mArrowBaseRadius = mInnerRadius / 70.0f;
mAABBWidth = mInnerRadius / 30.0f;// previous 70.0f
mAxisSize = mSize * 0.05f;
mTextDistance = mSize * 0.05f;
mInnerQuadSize = 0.45f * MCore::Math::Sqrt(2) * mInnerRadius;
// adjust the m_size when in ortho mode
m_size = m_scalingFactor;
m_innerRadius = 0.15f * m_size;
m_outerRadius = 0.2f * m_size;
m_arrowBaseRadius = m_innerRadius / 70.0f;
m_aabbWidth = m_innerRadius / 30.0f;// previous 70.0f
m_axisSize = m_size * 0.05f;
m_textDistance = m_size * 0.05f;
m_innerQuadSize = 0.45f * MCore::Math::Sqrt(2) * m_innerRadius;
// set the bounding volumes of the axes selection
mXAxisAABB.SetMax(mPosition + AZ::Vector3(mAABBWidth, mInnerRadius, mInnerRadius));
mXAxisAABB.SetMin(mPosition - AZ::Vector3(mAABBWidth, mInnerRadius, mInnerRadius));
mYAxisAABB.SetMax(mPosition + AZ::Vector3(mInnerRadius, mAABBWidth, mInnerRadius));
mYAxisAABB.SetMin(mPosition - AZ::Vector3(mInnerRadius, mAABBWidth, mInnerRadius));
mZAxisAABB.SetMax(mPosition + AZ::Vector3(mInnerRadius, mInnerRadius, mAABBWidth));
mZAxisAABB.SetMin(mPosition - AZ::Vector3(mInnerRadius, mInnerRadius, mAABBWidth));
mXAxisInnerAABB.SetMax(mPosition + AZ::Vector3(mAABBWidth, mInnerQuadSize, mInnerQuadSize));
mXAxisInnerAABB.SetMin(mPosition - AZ::Vector3(mAABBWidth, mInnerQuadSize, mInnerQuadSize));
mYAxisInnerAABB.SetMax(mPosition + AZ::Vector3(mInnerQuadSize, mAABBWidth, mInnerQuadSize));
mYAxisInnerAABB.SetMin(mPosition - AZ::Vector3(mInnerQuadSize, mAABBWidth, mInnerQuadSize));
mZAxisInnerAABB.SetMax(mPosition + AZ::Vector3(mInnerQuadSize, mInnerQuadSize, mAABBWidth));
mZAxisInnerAABB.SetMin(mPosition - AZ::Vector3(mInnerQuadSize, mInnerQuadSize, mAABBWidth));
m_xAxisAabb.SetMax(m_position + AZ::Vector3(m_aabbWidth, m_innerRadius, m_innerRadius));
m_xAxisAabb.SetMin(m_position - AZ::Vector3(m_aabbWidth, m_innerRadius, m_innerRadius));
m_yAxisAabb.SetMax(m_position + AZ::Vector3(m_innerRadius, m_aabbWidth, m_innerRadius));
m_yAxisAabb.SetMin(m_position - AZ::Vector3(m_innerRadius, m_aabbWidth, m_innerRadius));
m_zAxisAabb.SetMax(m_position + AZ::Vector3(m_innerRadius, m_innerRadius, m_aabbWidth));
m_zAxisAabb.SetMin(m_position - AZ::Vector3(m_innerRadius, m_innerRadius, m_aabbWidth));
m_xAxisInnerAabb.SetMax(m_position + AZ::Vector3(m_aabbWidth, m_innerQuadSize, m_innerQuadSize));
m_xAxisInnerAabb.SetMin(m_position - AZ::Vector3(m_aabbWidth, m_innerQuadSize, m_innerQuadSize));
m_yAxisInnerAabb.SetMax(m_position + AZ::Vector3(m_innerQuadSize, m_aabbWidth, m_innerQuadSize));
m_yAxisInnerAabb.SetMin(m_position - AZ::Vector3(m_innerQuadSize, m_aabbWidth, m_innerQuadSize));
m_zAxisInnerAabb.SetMax(m_position + AZ::Vector3(m_innerQuadSize, m_innerQuadSize, m_aabbWidth));
m_zAxisInnerAabb.SetMin(m_position - AZ::Vector3(m_innerQuadSize, m_innerQuadSize, m_aabbWidth));
// set the bounding spheres for inner and outer circle modifiers
mInnerBoundingSphere.SetCenter(mPosition);
mInnerBoundingSphere.SetRadius(mInnerRadius);
mOuterBoundingSphere.SetCenter(mPosition);
mOuterBoundingSphere.SetRadius(mOuterRadius);
m_innerBoundingSphere.SetCenter(m_position);
m_innerBoundingSphere.SetRadius(m_innerRadius);
m_outerBoundingSphere.SetCenter(m_position);
m_outerBoundingSphere.SetRadius(m_outerRadius);
}
@@ -82,7 +82,7 @@ namespace MCommon
MCore::Ray mousePosRay = camera->Unproject(mousePosX, mousePosY);
// check if mouse ray hits the outer sphere of the manipulator
if (mousePosRay.Intersects(mOuterBoundingSphere))
if (mousePosRay.Intersects(m_outerBoundingSphere))
{
return true;
}
@@ -109,14 +109,14 @@ namespace MCommon
MCore::Ray camRay = camera->Unproject(screenWidth / 2, screenHeight / 2);
AZ::Vector3 camDir = camRay.GetDirection();
mSignX = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) >= MCore::Math::halfPi) ? 1.0f : -1.0f;
mSignY = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) >= MCore::Math::halfPi) ? 1.0f : -1.0f;
mSignZ = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) >= MCore::Math::halfPi) ? 1.0f : -1.0f;
m_signX = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) >= MCore::Math::halfPi) ? 1.0f : -1.0f;
m_signY = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) >= MCore::Math::halfPi) ? 1.0f : -1.0f;
m_signZ = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) >= MCore::Math::halfPi) ? 1.0f : -1.0f;
// determine the axis visibility, to disable movement for invisible axes
mXAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false);
mYAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false);
mZAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false);
m_xAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false);
m_yAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false);
m_zAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false);
// update the bounding volumes
UpdateBoundingVolumes();
@@ -127,12 +127,12 @@ namespace MCommon
void RotateManipulator::Render(MCommon::Camera* camera, RenderUtil* renderUtil)
{
// return if no render util is set
if (renderUtil == nullptr || camera == nullptr || mIsVisible == false)
if (renderUtil == nullptr || camera == nullptr || m_isVisible == false)
{
return;
}
// set mSize variables for the gizmo
// set m_size variables for the gizmo
const uint32 screenWidth = camera->GetScreenWidth();
const uint32 screenHeight = camera->GetScreenHeight();
@@ -143,14 +143,13 @@ namespace MCommon
MCore::RGBAColor blueTransparent = MCore::RGBAColor(0.0, 0.0, 0.762f, 0.2f);
MCore::RGBAColor greyTransparent = MCore::RGBAColor(0.5f, 0.5f, 0.5f, 0.3f);
MCore::RGBAColor xAxisColor = (mMode == ROTATE_X) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mRed;
MCore::RGBAColor yAxisColor = (mMode == ROTATE_Y) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mGreen;
MCore::RGBAColor zAxisColor = (mMode == ROTATE_Z) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mBlue;
MCore::RGBAColor camRollAxisColor = (mMode == ROTATE_CAMROLL) ? ManipulatorColors::mSelectionColor : grey;
//MCore::RGBAColor camPitchYawColor = (mMode == ROTATE_CAMPITCHYAW) ? ManipulatorColors::mSelectionColor : grey;
MCore::RGBAColor xAxisColor = (m_mode == ROTATE_X) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_red;
MCore::RGBAColor yAxisColor = (m_mode == ROTATE_Y) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_green;
MCore::RGBAColor zAxisColor = (m_mode == ROTATE_Z) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_blue;
MCore::RGBAColor camRollAxisColor = (m_mode == ROTATE_CAMROLL) ? ManipulatorColors::s_selectionColor : grey;
// render axis in the center of the rotation gizmo
renderUtil->RenderAxis(mAxisSize, mPosition, AZ::Vector3(1.0f, 0.0f, 0.0f), AZ::Vector3(0.0f, 1.0f, 0.0f), AZ::Vector3(0.0f, 0.0f, 1.0f));
renderUtil->RenderAxis(m_axisSize, m_position, AZ::Vector3(1.0f, 0.0f, 0.0f), AZ::Vector3(0.0f, 1.0f, 0.0f), AZ::Vector3(0.0f, 0.0f, 1.0f));
// shoot rays to the plane, to get upwards pointing vector on the plane
// used for the text positioning and the angle visualization for the view rotation axis
@@ -159,7 +158,7 @@ namespace MCommon
AZ::Vector3 camRollAxis = originRay.GetDirection();
// calculate the plane perpendicular to the view rotation axis
MCore::PlaneEq rotationPlane(originRay.GetDirection(), mPosition);
MCore::PlaneEq rotationPlane(originRay.GetDirection(), m_position);
// get the intersection points of the rays and the plane
AZ::Vector3 originRayIntersect, upVecRayIntersect;
@@ -177,66 +176,43 @@ namespace MCommon
camViewMat.InvertFull();
// set the translation part of the matrix
camViewMat.SetTranslation(mPosition);
camViewMat.SetTranslation(m_position);
// render the view axis rotation manipulator
const AZ::Transform camViewTransform = AZ::Transform::CreateFromMatrix3x3AndTranslation(
AZ::Matrix3x3::CreateFromMatrix4x4(camViewMat), camViewMat.GetTranslation());
renderUtil->RenderCircle(camViewTransform, mOuterRadius, 64, camRollAxisColor);
renderUtil->RenderCircle(camViewTransform, mInnerRadius, 64, grey);
renderUtil->RenderCircle(camViewTransform, m_outerRadius, 64, camRollAxisColor);
renderUtil->RenderCircle(camViewTransform, m_innerRadius, 64, grey);
if (mMode == ROTATE_CAMPITCHYAW)
if (m_mode == ROTATE_CAMPITCHYAW)
{
renderUtil->RenderCircle(camViewTransform, mInnerRadius, 64, grey, 0.0f, MCore::Math::twoPi, true, greyTransparent);
renderUtil->RenderCircle(camViewTransform, m_innerRadius, 64, grey, 0.0f, MCore::Math::twoPi, true, greyTransparent);
}
// handle the rotation around the camera roll axis
/*
if (mMode == ROTATE_CAMROLL)
{
// calculate angle of the click position to the reference directions
const float angleUp = Math::ACos( mClickPosition.Dot(upVector) );
const float angleLeft = Math::ACos( mClickPosition.Dot(leftVector) );
// rotate the whole circle around pi, if rotation is in the negative direction
if (mRotation.Dot(mRotationAxis) < 0)
camViewMat = camViewMat * camViewMat.RotationMatrixAxisAngle( upVector, Math::pi );
// handle different dot product results (necessary because dot product only handles a range of [0, pi])
if (angleLeft > Math::halfPi)
camViewMat = camViewMat * camViewMat.RotationMatrixAxisAngle( mRotationAxis, -angleUp );
else
camViewMat = camViewMat * camViewMat.RotationMatrixAxisAngle( mRotationAxis, angleUp );
// render the rotated circle segment to represent the current rotation angle around the view axis
renderUtil->RenderCircle( camViewMat, mOuterRadius, 64, ManipulatorColors::mSelectionColor, 0.0f, mRotation.Length(), true, greyTransparent );
}
*/
// calculate the signs of the rotation and the angle between the axes and the click position
const float signX = (mRotation.GetX() >= 0) ? 1.0f : -1.0f;
const float signY = (mRotation.GetY() >= 0) ? 1.0f : -1.0f;
const float signZ = (mRotation.GetZ() >= 0) ? 1.0f : -1.0f;
const float angleX = MCore::Math::ACos(mClickPosition.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f)));
const float angleY = MCore::Math::ACos(mClickPosition.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f)));
const float angleZ = MCore::Math::ACos(mClickPosition.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f)));
const float signX = (m_rotation.GetX() >= 0) ? 1.0f : -1.0f;
const float signY = (m_rotation.GetY() >= 0) ? 1.0f : -1.0f;
const float signZ = (m_rotation.GetZ() >= 0) ? 1.0f : -1.0f;
const float angleX = MCore::Math::ACos(m_clickPosition.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f)));
const float angleY = MCore::Math::ACos(m_clickPosition.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f)));
const float angleZ = MCore::Math::ACos(m_clickPosition.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f)));
// transformation matrix for the circle for rotation around the x axis
AZ::Transform rotMatrixX = MCore::GetRotationMatrixAxisAngle(AZ::Vector3(0.0f, 1.0f, 0.0f), signX * MCore::Math::halfPi);
// set the translation part of the matrix
rotMatrixX.SetTranslation(mPosition);
rotMatrixX.SetTranslation(m_position);
// render the circle for the rotation around the x axis
if (mMode == ROTATE_X)
if (m_mode == ROTATE_X)
{
renderUtil->RenderCircle(rotMatrixX, mInnerRadius, 64, grey);
renderUtil->RenderCircle(rotMatrixX, m_innerRadius, 64, grey);
}
renderUtil->RenderCircle(rotMatrixX, mInnerRadius, 64, xAxisColor, 0.0f, MCore::Math::twoPi, false, MCore::RGBAColor(), true, camRollAxis);
renderUtil->RenderCircle(rotMatrixX, m_innerRadius, 64, xAxisColor, 0.0f, MCore::Math::twoPi, false, MCore::RGBAColor(), true, camRollAxis);
// draw current angle if in x rotation mode
if (mMode == ROTATE_X)
if (m_mode == ROTATE_X)
{
// handle different dot product results (necessary because dot product only handles a range of [0, pi])
if (angleZ > MCore::Math::halfPi)
@@ -249,28 +225,28 @@ namespace MCommon
}
// set the translation part of the matrix
rotMatrixX.SetTranslation(mPosition);
rotMatrixX.SetTranslation(m_position);
// render the rotated circle segment to represent the current rotation angle around the x axis
renderUtil->RenderCircle(rotMatrixX, mInnerRadius, 64, ManipulatorColors::mSelectionColor, 0.0f, MCore::Math::Abs(mRotation.GetX()), true, redTransparent, true, camRollAxis);
renderUtil->RenderCircle(rotMatrixX, m_innerRadius, 64, ManipulatorColors::s_selectionColor, 0.0f, MCore::Math::Abs(m_rotation.GetX()), true, redTransparent, true, camRollAxis);
}
// rotation matrix for rotation around the y axis
AZ::Transform rotMatrixY = MCore::GetRotationMatrixAxisAngle(AZ::Vector3(1.0f, 0.0f, 0.0f), MCore::Math::halfPi);
// set the translation part of the matrix
rotMatrixY.SetTranslation(mPosition);
rotMatrixY.SetTranslation(m_position);
// render the circle for rotation around the y axis
if (mMode == ROTATE_Y)
if (m_mode == ROTATE_Y)
{
renderUtil->RenderCircle(rotMatrixY, mInnerRadius, 64, grey);
renderUtil->RenderCircle(rotMatrixY, m_innerRadius, 64, grey);
}
renderUtil->RenderCircle(rotMatrixY, mInnerRadius, 64, yAxisColor, 0.0f, MCore::Math::twoPi, false, MCore::RGBAColor(), true, camRollAxis);
renderUtil->RenderCircle(rotMatrixY, m_innerRadius, 64, yAxisColor, 0.0f, MCore::Math::twoPi, false, MCore::RGBAColor(), true, camRollAxis);
// draw current angle if in y rotation mode
if (mMode == ROTATE_Y)
if (m_mode == ROTATE_Y)
{
// render current rotation angle depending on the dot product results calculated above
if (signY > 0)
@@ -293,28 +269,28 @@ namespace MCommon
}
// set the translation part of the matrix
rotMatrixY.SetTranslation(mPosition);
rotMatrixY.SetTranslation(m_position);
// render the rotated circle segment to represent the current rotation angle around the y axis
renderUtil->RenderCircle(rotMatrixY, mInnerRadius, 64, ManipulatorColors::mSelectionColor, 0.0f, MCore::Math::Abs(mRotation.GetY()), true, greenTransparent, true, camRollAxis);
renderUtil->RenderCircle(rotMatrixY, m_innerRadius, 64, ManipulatorColors::s_selectionColor, 0.0f, MCore::Math::Abs(m_rotation.GetY()), true, greenTransparent, true, camRollAxis);
}
// the circle for rotation around the z axis
AZ::Transform rotMatrixZ = AZ::Transform::CreateIdentity();
// set the translation part of the matrix
rotMatrixZ.SetTranslation(mPosition);
rotMatrixZ.SetTranslation(m_position);
// render the circle for rotation around the z axis
if (mMode == ROTATE_Z)
if (m_mode == ROTATE_Z)
{
renderUtil->RenderCircle(rotMatrixZ, mInnerRadius, 64, grey);
renderUtil->RenderCircle(rotMatrixZ, m_innerRadius, 64, grey);
}
renderUtil->RenderCircle(rotMatrixZ, mInnerRadius, 64, zAxisColor, 0.0f, MCore::Math::twoPi, false, MCore::RGBAColor(), true, camRollAxis);
renderUtil->RenderCircle(rotMatrixZ, m_innerRadius, 64, zAxisColor, 0.0f, MCore::Math::twoPi, false, MCore::RGBAColor(), true, camRollAxis);
// draw current angle if in z rotation mode
if (mMode == ROTATE_Z)
if (m_mode == ROTATE_Z)
{
// render current rotation angle depending on the dot product results calculated above
if (signZ < 0.0f)
@@ -337,56 +313,56 @@ namespace MCommon
}
// set the translation part of the matrix
rotMatrixZ.SetTranslation(mPosition);
rotMatrixZ.SetTranslation(m_position);
// render the rotated circle segment to represent the current rotation angle around the z axis
renderUtil->RenderCircle(rotMatrixZ, mInnerRadius, 64, ManipulatorColors::mSelectionColor, 0.0f, MCore::Math::Abs(mRotation.GetZ()), true, blueTransparent, true, camRollAxis);
renderUtil->RenderCircle(rotMatrixZ, m_innerRadius, 64, ManipulatorColors::s_selectionColor, 0.0f, MCore::Math::Abs(m_rotation.GetZ()), true, blueTransparent, true, camRollAxis);
}
// break if in different projection mode and camera roll rotation mode
if (mCurrentProjectionMode != camera->GetProjectionMode() && mMode == ROTATE_CAMROLL)
if (m_currentProjectionMode != camera->GetProjectionMode() && m_mode == ROTATE_CAMROLL)
{
return;
}
// render the absolute rotation if gizmo is hit
if (mMode != ROTATE_NONE)
if (m_mode != ROTATE_NONE)
{
const AZ::Vector3 currRot = MCore::AzQuaternionToEulerAngles(mCallback->GetCurrValueQuat());
mTempString = AZStd::string::format("Abs. Rotation X: %.3f, Y: %.3f, Z: %.3f", MCore::Math::RadiansToDegrees(currRot.GetX() + MCore::Math::epsilon), MCore::Math::RadiansToDegrees(currRot.GetY() + MCore::Math::epsilon), MCore::Math::RadiansToDegrees(currRot.GetZ() + MCore::Math::epsilon));
renderUtil->RenderText(10, 10, mTempString.c_str(), ManipulatorColors::mSelectionColor, 9.0f);
const AZ::Vector3 currRot = MCore::AzQuaternionToEulerAngles(m_callback->GetCurrValueQuat());
m_tempString = AZStd::string::format("Abs. Rotation X: %.3f, Y: %.3f, Z: %.3f", MCore::Math::RadiansToDegrees(currRot.GetX() + MCore::Math::epsilon), MCore::Math::RadiansToDegrees(currRot.GetY() + MCore::Math::epsilon), MCore::Math::RadiansToDegrees(currRot.GetZ() + MCore::Math::epsilon));
renderUtil->RenderText(10, 10, m_tempString.c_str(), ManipulatorColors::s_selectionColor, 9.0f);
}
// if the rotation has been changed draw the current direction of the rotation
if (mRotation.GetLength() > 0.0f)
if (m_rotation.GetLength() > 0.0f)
{
// render text with the rotation values of the axes
float radius = (mMode == ROTATE_CAMROLL) ? mOuterRadius : mInnerRadius;
mTempString = AZStd::string::format("[%.2f, %.2f, %.2f]", MCore::Math::RadiansToDegrees(mRotation.GetX()), MCore::Math::RadiansToDegrees(mRotation.GetY()), MCore::Math::RadiansToDegrees(mRotation.GetZ()));
float radius = (m_mode == ROTATE_CAMROLL) ? m_outerRadius : m_innerRadius;
m_tempString = AZStd::string::format("[%.2f, %.2f, %.2f]", MCore::Math::RadiansToDegrees(m_rotation.GetX()), MCore::Math::RadiansToDegrees(m_rotation.GetY()), MCore::Math::RadiansToDegrees(m_rotation.GetZ()));
//String rotationValues = String() = AZStd::string::format("[%.2f, %.2f, %.2f]", camera->GetPosition().x, camera->GetPosition().y, camera->GetPosition().z);
AZ::Vector3 textPosition = MCore::Project(mPosition + (upVector * (mOuterRadius + mTextDistance)), camera->GetViewProjMatrix(), screenWidth, screenHeight);
renderUtil->RenderText(textPosition.GetX() - 2.9f * mTempString.size(), textPosition.GetY(), mTempString.c_str(), ManipulatorColors::mSelectionColor);
AZ::Vector3 textPosition = MCore::Project(m_position + (upVector * (m_outerRadius + m_textDistance)), camera->GetViewProjMatrix(), screenWidth, screenHeight);
renderUtil->RenderText(textPosition.GetX() - 2.9f * m_tempString.size(), textPosition.GetY(), m_tempString.c_str(), ManipulatorColors::s_selectionColor);
// mark the click position with a small cube
AZ::Vector3 clickPosition = mPosition + mClickPosition * radius;
AZ::Vector3 clickPosition = m_position + m_clickPosition * radius;
// calculate the tangent at the click position
MCore::RGBAColor rotDirColorNegative = (mRotation.Dot(mRotationAxis) > 0.0f) ? ManipulatorColors::mSelectionColor : grey;
MCore::RGBAColor rotDirColorPositive = (mRotation.Dot(mRotationAxis) < 0.0f) ? ManipulatorColors::mSelectionColor : grey;
MCore::RGBAColor rotDirColorNegative = (m_rotation.Dot(m_rotationAxis) > 0.0f) ? ManipulatorColors::s_selectionColor : grey;
MCore::RGBAColor rotDirColorPositive = (m_rotation.Dot(m_rotationAxis) < 0.0f) ? ManipulatorColors::s_selectionColor : grey;
// render the tangent directions at the click positions
AZ::Vector3 tangent = mRotationAxis.Cross(mClickPosition).GetNormalized();
renderUtil->RenderLine(clickPosition, clickPosition + 1.5f * mAxisSize * tangent, rotDirColorPositive);
renderUtil->RenderLine(clickPosition, clickPosition - 1.5f * mAxisSize * tangent, rotDirColorNegative);
renderUtil->RenderCylinder(2.0f * mArrowBaseRadius, 0.0f, 0.5f * mAxisSize, clickPosition + 1.5f * mAxisSize * tangent, tangent, rotDirColorPositive);
renderUtil->RenderCylinder(2.0f * mArrowBaseRadius, 0.0f, 0.5f * mAxisSize, clickPosition - 1.5f * mAxisSize * tangent, -tangent, rotDirColorNegative);
AZ::Vector3 tangent = m_rotationAxis.Cross(m_clickPosition).GetNormalized();
renderUtil->RenderLine(clickPosition, clickPosition + 1.5f * m_axisSize * tangent, rotDirColorPositive);
renderUtil->RenderLine(clickPosition, clickPosition - 1.5f * m_axisSize * tangent, rotDirColorNegative);
renderUtil->RenderCylinder(2.0f * m_arrowBaseRadius, 0.0f, 0.5f * m_axisSize, clickPosition + 1.5f * m_axisSize * tangent, tangent, rotDirColorPositive);
renderUtil->RenderCylinder(2.0f * m_arrowBaseRadius, 0.0f, 0.5f * m_axisSize, clickPosition - 1.5f * m_axisSize * tangent, -tangent, rotDirColorNegative);
}
else
{
if (mName.size() > 0)
if (m_name.size() > 0)
{
AZ::Vector3 textPosition = MCore::Project(mPosition + (upVector * (mOuterRadius + mTextDistance)), camera->GetViewProjMatrix(), screenWidth, screenHeight);
renderUtil->RenderText(textPosition.GetX(), textPosition.GetY(), mName.c_str(), ManipulatorColors::mSelectionColor, 11.0f, true);
AZ::Vector3 textPosition = MCore::Project(m_position + (upVector * (m_outerRadius + m_textDistance)), camera->GetViewProjMatrix(), screenWidth, screenHeight);
renderUtil->RenderText(textPosition.GetX(), textPosition.GetY(), m_name.c_str(), ManipulatorColors::s_selectionColor, 11.0f, true);
}
}
}
@@ -399,7 +375,7 @@ namespace MCommon
MCORE_UNUSED(middleButtonPressed);
// check if camera has been set
if (camera == nullptr || mIsVisible == false || (leftButtonPressed && rightButtonPressed))
if (camera == nullptr || m_isVisible == false || (leftButtonPressed && rightButtonPressed))
{
return;
}
@@ -407,7 +383,7 @@ namespace MCommon
// update the axis visibility flags
UpdateAxisDirections(camera);
// get screen mSize
// get screen m_size
uint32 screenWidth = camera->GetScreenWidth();
uint32 screenHeight = camera->GetScreenHeight();
@@ -416,15 +392,15 @@ namespace MCommon
//MCore::Ray mousePrevPosRay = camera->Unproject( mousePosX-mouseMovementX, mousePosY-mouseMovementY );
MCore::Ray camRollRay = camera->Unproject(screenWidth / 2, screenHeight / 2);
AZ::Vector3 camRollAxis = camRollRay.GetDirection();
mRotationQuat = AZ::Quaternion::CreateIdentity();
m_rotationQuat = AZ::Quaternion::CreateIdentity();
// check for the selected axis/plane
if (mSelectionLocked == false || mMode == ROTATE_NONE)
if (m_selectionLocked == false || m_mode == ROTATE_NONE)
{
// update old rotation of the callback
if (mCallback)
if (m_callback)
{
mCallback->UpdateOldValues();
m_callback->UpdateOldValues();
}
// the intersection variables
@@ -432,88 +408,88 @@ namespace MCommon
// set rotation mode to rotation around the x axis, if the following intersection conditions are fulfilled
// innerAABB not hit, outerAABB hit, innerBoundingSphere hit and angle between cameraRollAxis and clickPosition > pi/2
if ((mousePosRay.Intersects(mXAxisInnerAABB) == false ||
(camera->GetProjectionMode() == MCommon::Camera::PROJMODE_ORTHOGRAPHIC && mXAxisVisible)) &&
mousePosRay.Intersects(mXAxisAABB, &intersectA, &intersectB) &&
mousePosRay.Intersects(mInnerBoundingSphere) &&
MCore::Math::ACos(camRollAxis.Dot((intersectA - mPosition).GetNormalized())) > MCore::Math::halfPi)
if ((mousePosRay.Intersects(m_xAxisInnerAabb) == false ||
(camera->GetProjectionMode() == MCommon::Camera::PROJMODE_ORTHOGRAPHIC && m_xAxisVisible)) &&
mousePosRay.Intersects(m_xAxisAabb, &intersectA, &intersectB) &&
mousePosRay.Intersects(m_innerBoundingSphere) &&
MCore::Math::ACos(camRollAxis.Dot((intersectA - m_position).GetNormalized())) > MCore::Math::halfPi)
{
mMode = ROTATE_X;
mRotationAxis = AZ::Vector3(1.0f, 0.0f, 0.0f);
mClickPosition = (intersectA - mPosition).GetNormalized();
mClickPosition.SetX(0.0f);
m_mode = ROTATE_X;
m_rotationAxis = AZ::Vector3(1.0f, 0.0f, 0.0f);
m_clickPosition = (intersectA - m_position).GetNormalized();
m_clickPosition.SetX(0.0f);
}
// set rotation mode to rotation around the y axis, if the following intersection conditions are fulfilled
// innerAABB not hit, outerAABB hit, innerBoundingSphere hit and angle between cameraRollAxis and clickPosition > pi/2
else if ((mousePosRay.Intersects(mYAxisInnerAABB) == false ||
(camera->GetProjectionMode() == MCommon::Camera::PROJMODE_ORTHOGRAPHIC && mYAxisVisible)) &&
mousePosRay.Intersects(mYAxisAABB, &intersectA, &intersectB) && mousePosRay.Intersects(mInnerBoundingSphere) &&
MCore::Math::ACos(camRollAxis.Dot((intersectA - mPosition).GetNormalized())) > MCore::Math::halfPi)
else if ((mousePosRay.Intersects(m_yAxisInnerAabb) == false ||
(camera->GetProjectionMode() == MCommon::Camera::PROJMODE_ORTHOGRAPHIC && m_yAxisVisible)) &&
mousePosRay.Intersects(m_yAxisAabb, &intersectA, &intersectB) && mousePosRay.Intersects(m_innerBoundingSphere) &&
MCore::Math::ACos(camRollAxis.Dot((intersectA - m_position).GetNormalized())) > MCore::Math::halfPi)
{
mMode = ROTATE_Y;
mRotationAxis = AZ::Vector3(0.0f, 1.0f, 0.0f);
mClickPosition = (intersectA - mPosition).GetNormalized();
mClickPosition.SetY(0.0f);
m_mode = ROTATE_Y;
m_rotationAxis = AZ::Vector3(0.0f, 1.0f, 0.0f);
m_clickPosition = (intersectA - m_position).GetNormalized();
m_clickPosition.SetY(0.0f);
}
// set rotation mode to rotation around the z axis, if the following intersection conditions are fulfilled
// innerAABB not hit, outerAABB hit, innerBoundingSphere hit and angle between cameraRollAxis and clickPosition > pi/2
else if ((mousePosRay.Intersects(mZAxisInnerAABB) == false ||
(camera->GetProjectionMode() == MCommon::Camera::PROJMODE_ORTHOGRAPHIC && mZAxisVisible)) &&
mousePosRay.Intersects(mZAxisAABB, &intersectA, &intersectB) && mousePosRay.Intersects(mInnerBoundingSphere) &&
MCore::Math::ACos(camRollAxis.Dot((intersectA - mPosition).GetNormalized())) > MCore::Math::halfPi)
else if ((mousePosRay.Intersects(m_zAxisInnerAabb) == false ||
(camera->GetProjectionMode() == MCommon::Camera::PROJMODE_ORTHOGRAPHIC && m_zAxisVisible)) &&
mousePosRay.Intersects(m_zAxisAabb, &intersectA, &intersectB) && mousePosRay.Intersects(m_innerBoundingSphere) &&
MCore::Math::ACos(camRollAxis.Dot((intersectA - m_position).GetNormalized())) > MCore::Math::halfPi)
{
mMode = ROTATE_Z;
mRotationAxis = AZ::Vector3(0.0f, 0.0f, 1.0f);
mClickPosition = (intersectA - mPosition).GetNormalized();
mClickPosition.SetZ(0.0f);
m_mode = ROTATE_Z;
m_rotationAxis = AZ::Vector3(0.0f, 0.0f, 1.0f);
m_clickPosition = (intersectA - m_position).GetNormalized();
m_clickPosition.SetZ(0.0f);
}
// set rotation mode to rotation around the pitch and yaw axis of the camera,
// if the inner sphere is hit and none of the previous conditions was fulfilled
else if (mousePosRay.Intersects(mInnerBoundingSphere, &intersectA, &intersectB))
else if (mousePosRay.Intersects(m_innerBoundingSphere, &intersectA, &intersectB))
{
mMode = ROTATE_CAMPITCHYAW;
m_mode = ROTATE_CAMPITCHYAW;
// set the rotation axis to zero, because no single axis exists in this mode
mRotationAxis = AZ::Vector3::CreateZero();
m_rotationAxis = AZ::Vector3::CreateZero();
// project the click position onto the plane which is perpendicular to the rotation direction
MCore::PlaneEq rotationPlane(camRollAxis, mPosition);
mClickPosition = (rotationPlane.Project(intersectA - mPosition)).GetNormalized();
MCore::PlaneEq rotationPlane(camRollAxis, m_position);
m_clickPosition = (rotationPlane.Project(intersectA - m_position)).GetNormalized();
}
// set rotation mode to rotation around the roll axis of the camera,
// if the outer sphere is hit and none of the previous conditions was fulfilled
else if (mousePosRay.Intersects(mOuterBoundingSphere, &intersectA, &intersectB))
else if (mousePosRay.Intersects(m_outerBoundingSphere, &intersectA, &intersectB))
{
// set rotation mode to rotate around the view axis
mMode = ROTATE_CAMROLL;
m_mode = ROTATE_CAMROLL;
// set the rotation axis to the look at ray direction
mRotationAxis = camRollRay.GetDirection();
m_rotationAxis = camRollRay.GetDirection();
// project the click position onto the plane which is perpendicular to the rotation direction
MCore::PlaneEq rotationPlane(mRotationAxis, AZ::Vector3::CreateZero());
mClickPosition = (rotationPlane.Project(intersectA - mPosition)).GetNormalized();
MCore::PlaneEq rotationPlane(m_rotationAxis, AZ::Vector3::CreateZero());
m_clickPosition = (rotationPlane.Project(intersectA - m_position)).GetNormalized();
}
// no bounding volume is currently hit, therefore do not rotate
else
{
mMode = ROTATE_NONE;
m_mode = ROTATE_NONE;
}
}
// set selection lock and current projection mode
mSelectionLocked = leftButtonPressed;
mCurrentProjectionMode = camera->GetProjectionMode();
m_selectionLocked = leftButtonPressed;
m_currentProjectionMode = camera->GetProjectionMode();
// reset the gizmo if no rotation mode is selected
if (mSelectionLocked == false || mMode == ROTATE_NONE)
if (m_selectionLocked == false || m_mode == ROTATE_NONE)
{
mRotation = AZ::Vector3::CreateZero();
m_rotation = AZ::Vector3::CreateZero();
return;
}
@@ -527,13 +503,13 @@ namespace MCommon
}
// set the rotation depending on the rotation mode
if (mMode == ROTATE_CAMPITCHYAW)
if (m_mode == ROTATE_CAMPITCHYAW)
{
// the yaw axis of the camera view
MCore::Ray camYawRay = camera->Unproject(screenWidth / 2, screenHeight / 2 - 10);
// calculate the plane perpendicular to the view rotation axis
MCore::PlaneEq rotationPlane(camRollAxis, mPosition);
MCore::PlaneEq rotationPlane(camRollAxis, m_position);
// get the intersection points of the rays and the plane
AZ::Vector3 originRayIntersect, upVecRayIntersect;
@@ -548,69 +524,46 @@ namespace MCommon
// calculate the projected axes, used to determine the angle between click position
// and the axes. This allows weighting the angles by the movement direction.
AZ::Vector3 projectedCenter = MCore::Project(mPosition, camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 projectedClickPosYaw = MCore::Project(mPosition - leftVector, camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 projectedClickPosPitch = MCore::Project(mPosition - upVector, camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 projectedCenter = MCore::Project(m_position, camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 projectedClickPosYaw = MCore::Project(m_position - leftVector, camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 projectedClickPosPitch = MCore::Project(m_position - upVector, camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 projDirClickPosYaw = (projectedClickPosYaw - projectedCenter).GetNormalized();
AZ::Vector3 projDirClickPosPitch = (projectedClickPosPitch - projectedCenter).GetNormalized();
// calculate the angle between mouse movement and projected rotation axis
float angleYaw = projDirClickPosYaw.Dot(mouseMovementV3) * mScalingFactor * movementLength * 0.00005f;
float anglePitch = projDirClickPosPitch.Dot(mouseMovementV3) * mScalingFactor * movementLength * 0.00005f;
float angleYaw = projDirClickPosYaw.Dot(mouseMovementV3) * m_scalingFactor * movementLength * 0.00005f;
float anglePitch = projDirClickPosPitch.Dot(mouseMovementV3) * m_scalingFactor * movementLength * 0.00005f;
// perform rotation arround the cam yaw and pitch axis
AZ::Quaternion rotation = MCore::CreateFromAxisAndAngle(upVector, -angleYaw);
rotation = rotation * MCore::CreateFromAxisAndAngle(leftVector, anglePitch);
// set euler angles of the rotation variable
mRotation += MCore::AzQuaternionToEulerAngles(rotation);
mRotationQuat = rotation;
m_rotation += MCore::AzQuaternionToEulerAngles(rotation);
m_rotationQuat = rotation;
}
else
{
/*
// HINT: uncommented stuff is the exact rotation, used in maya
// generate current translation plane and calculate mouse intersections
MCore::PlaneEq movementPlane( mRotationAxis, mPosition );
Vector3 mousePosIntersect, mousePrevPosIntersect;
mousePosRay.Intersects( movementPlane, &mousePosIntersect );
mousePrevPosRay.Intersects( movementPlane, &mousePrevPosIntersect );
// normalize the intersection points, as only the angle between them is needed
mousePosIntersect = (mousePosIntersect - mPosition).Normalize();
mousePrevPosIntersect = (mousePrevPosIntersect - mPosition).Normalize();
// distance of the mouse intersections is the actual movement on the plane
float angleSign = MCore::Sgn((mRotationAxis.Cross(mousePosIntersect-mousePrevPosIntersect)).Dot(mousePosIntersect));
float angle = MCore::Math::ACos( (mousePrevPosIntersect).Dot((mousePosIntersect)) ) * angleSign;
mRotation += mRotationAxis * angle;
mRotation = Vector3( MCore::Clamp(mRotation.x, -Math::twoPi, Math::twoPi), MCore::Clamp(mRotation.y, -Math::twoPi, Math::twoPi), MCore::Clamp(mRotation.z, -Math::twoPi, Math::twoPi) );
mRotationQuat = Quaternion( mRotationAxis, MCore::Clamp(-angle, -Math::twoPi, Math::twoPi) );
*/
// calculate the projected center and click position to determine the rotation angle
AZ::Vector3 tangent = (mRotationAxis.Cross(mClickPosition)).GetNormalized();
AZ::Vector3 projectedCenter = MCore::Project(mPosition, camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 projectedClickPos = MCore::Project(mPosition - tangent, camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 tangent = (m_rotationAxis.Cross(m_clickPosition)).GetNormalized();
AZ::Vector3 projectedCenter = MCore::Project(m_position, camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 projectedClickPos = MCore::Project(m_position - tangent, camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 projDirClickPos = (projectedClickPos - projectedCenter);
// calculate the angle between mouse movement and projected rotation axis
//float angle = Math::DegreesToRadians(Math::Floor(Math::RadiansToDegrees((projDirClickPos.Dot( mouseMovementV3 ) * mScalingFactor * 0.00002f) * movementLength)));
float angle = MCore::Math::DegreesToRadians(MCore::Sgn<float>(projDirClickPos.Dot(mouseMovementV3)) * 0.2f * MCore::Math::Floor(movementLength + 0.5f));
// adjust rotation
mRotation += mRotationAxis * angle;
//mRotation = Vector3( MCore::Clamp(mRotation.x, -Math::twoPi, Math::twoPi), MCore::Clamp(mRotation.y, -Math::twoPi, Math::twoPi), MCore::Clamp(mRotation.z, -Math::twoPi, Math::twoPi) );
mRotationQuat = AZ::Quaternion::CreateFromAxisAngle(mRotationAxis, MCore::Math::FMod(-angle, MCore::Math::twoPi));
mRotationQuat.Normalize();
m_rotation += m_rotationAxis * angle;
m_rotationQuat = AZ::Quaternion::CreateFromAxisAngle(m_rotationAxis, MCore::Math::FMod(-angle, MCore::Math::twoPi));
m_rotationQuat.Normalize();
}
// update the callback
if (mCallback)
if (m_callback)
{
const AZ::Quaternion curRot = mCallback->GetCurrValueQuat();
const AZ::Quaternion newRot = (curRot * mRotationQuat).GetNormalized();
mCallback->Update(newRot);
const AZ::Quaternion curRot = m_callback->GetCurrValueQuat();
const AZ::Quaternion newRot = (curRot * m_rotationQuat).GetNormalized();
m_callback->Update(newRot);
}
}
} // namespace MCommon
@@ -88,40 +88,40 @@ namespace MCommon
void ProcessMouseInput(MCommon::Camera* camera, int32 mousePosX, int32 mousePosY, int32 mouseMovementX, int32 mouseMovementY, bool leftButtonPressed, bool middleButtonPressed, bool rightButtonPressed, uint32 keyboardKeyFlags = 0);
protected:
AZ::Vector3 mRotation;
AZ::Quaternion mRotationQuat;
AZ::Vector3 mRotationAxis;
AZ::Vector3 mClickPosition;
AZ::Vector3 m_rotation;
AZ::Quaternion m_rotationQuat;
AZ::Vector3 m_rotationAxis;
AZ::Vector3 m_clickPosition;
// bounding volumes for the axes
MCore::BoundingSphere mInnerBoundingSphere;
MCore::BoundingSphere mOuterBoundingSphere;
MCore::AABB mXAxisAABB;
MCore::AABB mYAxisAABB;
MCore::AABB mZAxisAABB;
MCore::AABB mXAxisInnerAABB;
MCore::AABB mYAxisInnerAABB;
MCore::AABB mZAxisInnerAABB;
MCore::BoundingSphere m_innerBoundingSphere;
MCore::BoundingSphere m_outerBoundingSphere;
MCore::AABB m_xAxisAabb;
MCore::AABB m_yAxisAabb;
MCore::AABB m_zAxisAabb;
MCore::AABB m_xAxisInnerAabb;
MCore::AABB m_yAxisInnerAabb;
MCore::AABB m_zAxisInnerAabb;
// the proportions of the rotation manipulator
float mSize;
float mInnerRadius;
float mOuterRadius;
float mArrowBaseRadius;
float mAABBWidth;
float mAxisSize;
float mTextDistance;
float mInnerQuadSize;
float m_size;
float m_innerRadius;
float m_outerRadius;
float m_arrowBaseRadius;
float m_aabbWidth;
float m_axisSize;
float m_textDistance;
float m_innerQuadSize;
// orientation information
float mSignX;
float mSignY;
float mSignZ;
bool mXAxisVisible;
bool mYAxisVisible;
bool mZAxisVisible;
float m_signX;
float m_signY;
float m_signZ;
bool m_xAxisVisible;
bool m_yAxisVisible;
bool m_zAxisVisible;
// store the projection mode of the current render widget
MCommon::Camera::ProjectionMode mCurrentProjectionMode;
MCommon::Camera::ProjectionMode m_currentProjectionMode;
};
} // namespace MCommon
@@ -16,12 +16,12 @@ namespace MCommon
: TransformationManipulator(scalingFactor, isVisible)
{
// set the initial values
mMode = SCALE_NONE;
mSelectionLocked = false;
mCallback = nullptr;
mPosition = AZ::Vector3::CreateZero();
mScaleDirection = AZ::Vector3::CreateZero();
mScale = AZ::Vector3::CreateZero();
m_mode = SCALE_NONE;
m_selectionLocked = false;
m_callback = nullptr;
m_position = AZ::Vector3::CreateZero();
m_scaleDirection = AZ::Vector3::CreateZero();
m_scale = AZ::Vector3::CreateZero();
}
@@ -40,35 +40,35 @@ namespace MCommon
UpdateAxisDirections(camera);
}
mSize = mScalingFactor;
mScaledSize = AZ::Vector3(mSize, mSize, mSize) + AZ::Vector3(MCore::Max(float(mScale.GetX()), -mSize), MCore::Max(float(mScale.GetY()), -mSize), MCore::Max(float(mScale.GetZ()), -mSize));
mDiagScale = 0.5f;
mArrowLength = mSize / 10.0f;
mBaseRadius = mSize / 15.0f;
m_size = m_scalingFactor;
m_scaledSize = AZ::Vector3(m_size, m_size, m_size) + AZ::Vector3(MCore::Max(float(m_scale.GetX()), -m_size), MCore::Max(float(m_scale.GetY()), -m_size), MCore::Max(float(m_scale.GetZ()), -m_size));
m_diagScale = 0.5f;
m_arrowLength = m_size / 10.0f;
m_baseRadius = m_size / 15.0f;
// positions for the plane selectors
mFirstPlaneSelectorPos = mScaledSize * 0.3f;
mSecPlaneSelectorPos = mScaledSize * 0.6f;
m_firstPlaneSelectorPos = m_scaledSize * 0.3f;
m_secPlaneSelectorPos = m_scaledSize * 0.6f;
// set the bounding volumes of the axes selection
mXAxisAABB.SetMax(mPosition + mSignX * AZ::Vector3(mScaledSize.GetX() + mArrowLength, mBaseRadius, mBaseRadius));
mXAxisAABB.SetMin(mPosition - mSignX * AZ::Vector3(mBaseRadius, mBaseRadius, mBaseRadius));
mYAxisAABB.SetMax(mPosition + mSignY * AZ::Vector3(mBaseRadius, mScaledSize.GetY() + mArrowLength, mBaseRadius));
mYAxisAABB.SetMin(mPosition - mSignY * AZ::Vector3(mBaseRadius, mBaseRadius, mBaseRadius));
mZAxisAABB.SetMax(mPosition + mSignZ * AZ::Vector3(mBaseRadius, mBaseRadius, mScaledSize.GetZ() + mArrowLength));
mZAxisAABB.SetMin(mPosition - mSignZ * AZ::Vector3(mBaseRadius, mBaseRadius, mBaseRadius));
m_xAxisAabb.SetMax(m_position + m_signX * AZ::Vector3(m_scaledSize.GetX() + m_arrowLength, m_baseRadius, m_baseRadius));
m_xAxisAabb.SetMin(m_position - m_signX * AZ::Vector3(m_baseRadius, m_baseRadius, m_baseRadius));
m_yAxisAabb.SetMax(m_position + m_signY * AZ::Vector3(m_baseRadius, m_scaledSize.GetY() + m_arrowLength, m_baseRadius));
m_yAxisAabb.SetMin(m_position - m_signY * AZ::Vector3(m_baseRadius, m_baseRadius, m_baseRadius));
m_zAxisAabb.SetMax(m_position + m_signZ * AZ::Vector3(m_baseRadius, m_baseRadius, m_scaledSize.GetZ() + m_arrowLength));
m_zAxisAabb.SetMin(m_position - m_signZ * AZ::Vector3(m_baseRadius, m_baseRadius, m_baseRadius));
// set bounding volumes for the plane selectors
mXYPlaneAABB.SetMax(mPosition + AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, mSecPlaneSelectorPos.GetY() * mSignY, mBaseRadius * mSignZ));
mXYPlaneAABB.SetMin(mPosition + 0.3f * AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, mSecPlaneSelectorPos.GetY() * mSignY, 0) - AZ::Vector3(mBaseRadius * mSignX, mBaseRadius * mSignY, mBaseRadius * mSignZ));
mXZPlaneAABB.SetMax(mPosition + AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, mBaseRadius * mSignY, mSecPlaneSelectorPos.GetZ() * mSignZ));
mXZPlaneAABB.SetMin(mPosition + 0.3f * AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, 0, mSecPlaneSelectorPos.GetZ() * mSignZ) - AZ::Vector3(mBaseRadius * mSignX, mBaseRadius * mSignY, mBaseRadius * mSignZ));
mYZPlaneAABB.SetMax(mPosition + AZ::Vector3(mBaseRadius * mSignX, mSecPlaneSelectorPos.GetY() * mSignY, mSecPlaneSelectorPos.GetZ() * mSignZ));
mYZPlaneAABB.SetMin(mPosition + 0.3f * AZ::Vector3(0, mSecPlaneSelectorPos.GetY() * mSignY, mSecPlaneSelectorPos.GetZ() * mSignZ) - AZ::Vector3(mBaseRadius * mSignX, mBaseRadius * mSignY, mBaseRadius * mSignZ));
m_xyPlaneAabb.SetMax(m_position + AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, m_secPlaneSelectorPos.GetY() * m_signY, m_baseRadius * m_signZ));
m_xyPlaneAabb.SetMin(m_position + 0.3f * AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, m_secPlaneSelectorPos.GetY() * m_signY, 0) - AZ::Vector3(m_baseRadius * m_signX, m_baseRadius * m_signY, m_baseRadius * m_signZ));
m_xzPlaneAabb.SetMax(m_position + AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, m_baseRadius * m_signY, m_secPlaneSelectorPos.GetZ() * m_signZ));
m_xzPlaneAabb.SetMin(m_position + 0.3f * AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, 0, m_secPlaneSelectorPos.GetZ() * m_signZ) - AZ::Vector3(m_baseRadius * m_signX, m_baseRadius * m_signY, m_baseRadius * m_signZ));
m_yzPlaneAabb.SetMax(m_position + AZ::Vector3(m_baseRadius * m_signX, m_secPlaneSelectorPos.GetY() * m_signY, m_secPlaneSelectorPos.GetZ() * m_signZ));
m_yzPlaneAabb.SetMin(m_position + 0.3f * AZ::Vector3(0, m_secPlaneSelectorPos.GetY() * m_signY, m_secPlaneSelectorPos.GetZ() * m_signZ) - AZ::Vector3(m_baseRadius * m_signX, m_baseRadius * m_signY, m_baseRadius * m_signZ));
// set bounding volume for the box selector
mXYZBoxAABB.SetMin(mPosition - AZ::Vector3(mBaseRadius * mSignX, mBaseRadius * mSignY, mBaseRadius * mSignZ));
mXYZBoxAABB.SetMax(mPosition + mDiagScale * AZ::Vector3(mFirstPlaneSelectorPos.GetX() * mSignX, mFirstPlaneSelectorPos.GetY() * mSignY, mFirstPlaneSelectorPos.GetZ() * mSignZ));
m_xyzBoxAabb.SetMin(m_position - AZ::Vector3(m_baseRadius * m_signX, m_baseRadius * m_signY, m_baseRadius * m_signZ));
m_xyzBoxAabb.SetMax(m_position + m_diagScale * AZ::Vector3(m_firstPlaneSelectorPos.GetX() * m_signX, m_firstPlaneSelectorPos.GetY() * m_signY, m_firstPlaneSelectorPos.GetZ() * m_signZ));
}
@@ -89,14 +89,14 @@ namespace MCommon
MCore::Ray camRay = camera->Unproject(screenWidth / 2, screenHeight / 2);
AZ::Vector3 camDir = camRay.GetDirection();
mSignX = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) >= MCore::Math::halfPi - MCore::Math::epsilon) ? 1.0f : -1.0f;
mSignY = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) >= MCore::Math::halfPi - MCore::Math::epsilon) ? 1.0f : -1.0f;
mSignZ = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) >= MCore::Math::halfPi - MCore::Math::epsilon) ? 1.0f : -1.0f;
m_signX = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) >= MCore::Math::halfPi - MCore::Math::epsilon) ? 1.0f : -1.0f;
m_signY = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) >= MCore::Math::halfPi - MCore::Math::epsilon) ? 1.0f : -1.0f;
m_signZ = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) >= MCore::Math::halfPi - MCore::Math::epsilon) ? 1.0f : -1.0f;
// determine the axis visibility, to disable movement for invisible axes
mXAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false);
mYAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false);
mZAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false);
m_xAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false);
m_yAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false);
m_zAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false);
}
@@ -116,13 +116,13 @@ namespace MCommon
MCore::Ray mouseRay = camera->Unproject(mousePosX, mousePosY);
// check if one of the AABBs is hit
if (mouseRay.Intersects(mXAxisAABB) ||
mouseRay.Intersects(mYAxisAABB) ||
mouseRay.Intersects(mZAxisAABB) ||
mouseRay.Intersects(mXYPlaneAABB) ||
mouseRay.Intersects(mXZPlaneAABB) ||
mouseRay.Intersects(mYZPlaneAABB) ||
mouseRay.Intersects(mXYZBoxAABB))
if (mouseRay.Intersects(m_xAxisAabb) ||
mouseRay.Intersects(m_yAxisAabb) ||
mouseRay.Intersects(m_zAxisAabb) ||
mouseRay.Intersects(m_xyPlaneAabb) ||
mouseRay.Intersects(m_xzPlaneAabb) ||
mouseRay.Intersects(m_yzPlaneAabb) ||
mouseRay.Intersects(m_xyzBoxAabb))
{
return true;
}
@@ -136,12 +136,12 @@ namespace MCommon
void ScaleManipulator::Render(MCommon::Camera* camera, RenderUtil* renderUtil)
{
// return if no render util is set
if (renderUtil == nullptr || camera == nullptr || mIsVisible == false)
if (renderUtil == nullptr || camera == nullptr || m_isVisible == false)
{
return;
}
// set mSize variables for the gizmo
// set m_size variables for the gizmo
const uint32 screenWidth = camera->GetScreenWidth();
const uint32 screenHeight = camera->GetScreenHeight();
@@ -149,131 +149,131 @@ namespace MCommon
UpdateAxisDirections(camera);
// set color for the axes, depending on the selection (TODO: maybe put these into the constructor.)
MCore::RGBAColor xAxisColor = (mMode == SCALE_XYZ || mMode == SCALE_X || mMode == SCALE_XY || mMode == SCALE_XZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mRed;
MCore::RGBAColor yAxisColor = (mMode == SCALE_XYZ || mMode == SCALE_Y || mMode == SCALE_XY || mMode == SCALE_YZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mGreen;
MCore::RGBAColor zAxisColor = (mMode == SCALE_XYZ || mMode == SCALE_Z || mMode == SCALE_XZ || mMode == SCALE_YZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mBlue;
MCore::RGBAColor xyPlaneColorX = (mMode == SCALE_XYZ || mMode == SCALE_XY) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mRed;
MCore::RGBAColor xyPlaneColorY = (mMode == SCALE_XYZ || mMode == SCALE_XY) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mGreen;
MCore::RGBAColor xzPlaneColorX = (mMode == SCALE_XYZ || mMode == SCALE_XZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mRed;
MCore::RGBAColor xzPlaneColorZ = (mMode == SCALE_XYZ || mMode == SCALE_XZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mBlue;
MCore::RGBAColor yzPlaneColorY = (mMode == SCALE_XYZ || mMode == SCALE_YZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mGreen;
MCore::RGBAColor yzPlaneColorZ = (mMode == SCALE_XYZ || mMode == SCALE_YZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mBlue;
MCore::RGBAColor xAxisColor = (m_mode == SCALE_XYZ || m_mode == SCALE_X || m_mode == SCALE_XY || m_mode == SCALE_XZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_red;
MCore::RGBAColor yAxisColor = (m_mode == SCALE_XYZ || m_mode == SCALE_Y || m_mode == SCALE_XY || m_mode == SCALE_YZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_green;
MCore::RGBAColor zAxisColor = (m_mode == SCALE_XYZ || m_mode == SCALE_Z || m_mode == SCALE_XZ || m_mode == SCALE_YZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_blue;
MCore::RGBAColor xyPlaneColorX = (m_mode == SCALE_XYZ || m_mode == SCALE_XY) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_red;
MCore::RGBAColor xyPlaneColorY = (m_mode == SCALE_XYZ || m_mode == SCALE_XY) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_green;
MCore::RGBAColor xzPlaneColorX = (m_mode == SCALE_XYZ || m_mode == SCALE_XZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_red;
MCore::RGBAColor xzPlaneColorZ = (m_mode == SCALE_XYZ || m_mode == SCALE_XZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_blue;
MCore::RGBAColor yzPlaneColorY = (m_mode == SCALE_XYZ || m_mode == SCALE_YZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_green;
MCore::RGBAColor yzPlaneColorZ = (m_mode == SCALE_XYZ || m_mode == SCALE_YZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_blue;
// the x axis with cube at the line end
AZ::Vector3 firstPlanePosX = mPosition + mSignX * AZ::Vector3(mFirstPlaneSelectorPos.GetX(), 0.0f, 0.0f);
AZ::Vector3 secPlanePosX = mPosition + mSignX * AZ::Vector3(mSecPlaneSelectorPos.GetX(), 0.0f, 0.0f);
if (mXAxisVisible)
AZ::Vector3 firstPlanePosX = m_position + m_signX * AZ::Vector3(m_firstPlaneSelectorPos.GetX(), 0.0f, 0.0f);
AZ::Vector3 secPlanePosX = m_position + m_signX * AZ::Vector3(m_secPlaneSelectorPos.GetX(), 0.0f, 0.0f);
if (m_xAxisVisible)
{
renderUtil->RenderLine(mPosition, mPosition + mSignX * AZ::Vector3(mScaledSize.GetX() + 0.5f * mBaseRadius, 0.0f, 0.0f), xAxisColor);
AZ::Vector3 quadPos = MCore::Project(mPosition + mSignX * AZ::Vector3(mScaledSize.GetX() + mBaseRadius, 0, 0), camera->GetViewProjMatrix(), screenWidth, screenHeight);
renderUtil->RenderBorderedRect(static_cast<int32>(quadPos.GetX() - 2.0f), static_cast<int32>(quadPos.GetX() + 3.0f), static_cast<int32>(quadPos.GetY() - 2.0f), static_cast<int32>(quadPos.GetY() + 3.0f), ManipulatorColors::mRed, ManipulatorColors::mRed);
renderUtil->RenderLine(m_position, m_position + m_signX * AZ::Vector3(m_scaledSize.GetX() + 0.5f * m_baseRadius, 0.0f, 0.0f), xAxisColor);
AZ::Vector3 quadPos = MCore::Project(m_position + m_signX * AZ::Vector3(m_scaledSize.GetX() + m_baseRadius, 0, 0), camera->GetViewProjMatrix(), screenWidth, screenHeight);
renderUtil->RenderBorderedRect(static_cast<int32>(quadPos.GetX() - 2.0f), static_cast<int32>(quadPos.GetX() + 3.0f), static_cast<int32>(quadPos.GetY() - 2.0f), static_cast<int32>(quadPos.GetY() + 3.0f), ManipulatorColors::s_red, ManipulatorColors::s_red);
// render the plane selector lines
renderUtil->RenderLine(firstPlanePosX, firstPlanePosX + mDiagScale * (AZ::Vector3(0, mFirstPlaneSelectorPos.GetY() * mSignY, 0) - AZ::Vector3(mFirstPlaneSelectorPos.GetX() * mSignX, 0, 0)), xyPlaneColorX);
renderUtil->RenderLine(firstPlanePosX, firstPlanePosX + mDiagScale * (AZ::Vector3(0, 0, mFirstPlaneSelectorPos.GetZ() * mSignZ) - AZ::Vector3(mFirstPlaneSelectorPos.GetX() * mSignX, 0, 0)), xzPlaneColorX);
renderUtil->RenderLine(secPlanePosX, secPlanePosX + mDiagScale * (AZ::Vector3(0, mSecPlaneSelectorPos.GetY() * mSignY, 0) - AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, 0, 0)), xyPlaneColorX);
renderUtil->RenderLine(secPlanePosX, secPlanePosX + mDiagScale * (AZ::Vector3(0, 0, mSecPlaneSelectorPos.GetZ() * mSignZ) - AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, 0, 0)), xzPlaneColorX);
renderUtil->RenderLine(firstPlanePosX, firstPlanePosX + m_diagScale * (AZ::Vector3(0, m_firstPlaneSelectorPos.GetY() * m_signY, 0) - AZ::Vector3(m_firstPlaneSelectorPos.GetX() * m_signX, 0, 0)), xyPlaneColorX);
renderUtil->RenderLine(firstPlanePosX, firstPlanePosX + m_diagScale * (AZ::Vector3(0, 0, m_firstPlaneSelectorPos.GetZ() * m_signZ) - AZ::Vector3(m_firstPlaneSelectorPos.GetX() * m_signX, 0, 0)), xzPlaneColorX);
renderUtil->RenderLine(secPlanePosX, secPlanePosX + m_diagScale * (AZ::Vector3(0, m_secPlaneSelectorPos.GetY() * m_signY, 0) - AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, 0, 0)), xyPlaneColorX);
renderUtil->RenderLine(secPlanePosX, secPlanePosX + m_diagScale * (AZ::Vector3(0, 0, m_secPlaneSelectorPos.GetZ() * m_signZ) - AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, 0, 0)), xzPlaneColorX);
}
// the y axis with cube at the line end
AZ::Vector3 firstPlanePosY = mPosition + mSignY * AZ::Vector3(0.0f, mFirstPlaneSelectorPos.GetY(), 0.0f);
AZ::Vector3 secPlanePosY = mPosition + mSignY * AZ::Vector3(0.0f, mSecPlaneSelectorPos.GetY(), 0.0f);
if (mYAxisVisible)
AZ::Vector3 firstPlanePosY = m_position + m_signY * AZ::Vector3(0.0f, m_firstPlaneSelectorPos.GetY(), 0.0f);
AZ::Vector3 secPlanePosY = m_position + m_signY * AZ::Vector3(0.0f, m_secPlaneSelectorPos.GetY(), 0.0f);
if (m_yAxisVisible)
{
renderUtil->RenderLine(mPosition, mPosition + mSignY * AZ::Vector3(0.0f, mScaledSize.GetY(), 0.0f), yAxisColor);
AZ::Vector3 quadPos = MCore::Project(mPosition + mSignY * AZ::Vector3(0, mScaledSize.GetY() + 0.5f * mBaseRadius, 0), camera->GetViewProjMatrix(), screenWidth, screenHeight);
renderUtil->RenderBorderedRect(static_cast<int32>(quadPos.GetX() - 2.0f), static_cast<int32>(quadPos.GetX() + 3.0f), static_cast<int32>(quadPos.GetY() - 2.0f), static_cast<int32>(quadPos.GetY() + 3.0f), ManipulatorColors::mGreen, ManipulatorColors::mGreen);
renderUtil->RenderLine(m_position, m_position + m_signY * AZ::Vector3(0.0f, m_scaledSize.GetY(), 0.0f), yAxisColor);
AZ::Vector3 quadPos = MCore::Project(m_position + m_signY * AZ::Vector3(0, m_scaledSize.GetY() + 0.5f * m_baseRadius, 0), camera->GetViewProjMatrix(), screenWidth, screenHeight);
renderUtil->RenderBorderedRect(static_cast<int32>(quadPos.GetX() - 2.0f), static_cast<int32>(quadPos.GetX() + 3.0f), static_cast<int32>(quadPos.GetY() - 2.0f), static_cast<int32>(quadPos.GetY() + 3.0f), ManipulatorColors::s_green, ManipulatorColors::s_green);
// render the plane selector lines
renderUtil->RenderLine(firstPlanePosY, firstPlanePosY + mDiagScale * (AZ::Vector3(mFirstPlaneSelectorPos.GetX() * mSignX, 0, 0) - AZ::Vector3(0, mFirstPlaneSelectorPos.GetY() * mSignY, 0)), xyPlaneColorY);
renderUtil->RenderLine(firstPlanePosY, firstPlanePosY + mDiagScale * (AZ::Vector3(0, 0, mFirstPlaneSelectorPos.GetZ() * mSignZ) - AZ::Vector3(0, mFirstPlaneSelectorPos.GetY() * mSignY, 0)), yzPlaneColorY);
renderUtil->RenderLine(secPlanePosY, secPlanePosY + mDiagScale * (AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, 0, 0) - AZ::Vector3(0, mSecPlaneSelectorPos.GetY() * mSignY, 0)), xyPlaneColorY);
renderUtil->RenderLine(secPlanePosY, secPlanePosY + mDiagScale * (AZ::Vector3(0, 0, mSecPlaneSelectorPos.GetZ() * mSignZ) - AZ::Vector3(0, mSecPlaneSelectorPos.GetY() * mSignY, 0)), yzPlaneColorY);
renderUtil->RenderLine(firstPlanePosY, firstPlanePosY + m_diagScale * (AZ::Vector3(m_firstPlaneSelectorPos.GetX() * m_signX, 0, 0) - AZ::Vector3(0, m_firstPlaneSelectorPos.GetY() * m_signY, 0)), xyPlaneColorY);
renderUtil->RenderLine(firstPlanePosY, firstPlanePosY + m_diagScale * (AZ::Vector3(0, 0, m_firstPlaneSelectorPos.GetZ() * m_signZ) - AZ::Vector3(0, m_firstPlaneSelectorPos.GetY() * m_signY, 0)), yzPlaneColorY);
renderUtil->RenderLine(secPlanePosY, secPlanePosY + m_diagScale * (AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, 0, 0) - AZ::Vector3(0, m_secPlaneSelectorPos.GetY() * m_signY, 0)), xyPlaneColorY);
renderUtil->RenderLine(secPlanePosY, secPlanePosY + m_diagScale * (AZ::Vector3(0, 0, m_secPlaneSelectorPos.GetZ() * m_signZ) - AZ::Vector3(0, m_secPlaneSelectorPos.GetY() * m_signY, 0)), yzPlaneColorY);
}
// the z axis with cube at the line end
AZ::Vector3 firstPlanePosZ = mPosition + mSignZ * AZ::Vector3(0.0f, 0.0f, mFirstPlaneSelectorPos.GetZ());
AZ::Vector3 secPlanePosZ = mPosition + mSignZ * AZ::Vector3(0.0f, 0.0f, mSecPlaneSelectorPos.GetZ());
if (mZAxisVisible)
AZ::Vector3 firstPlanePosZ = m_position + m_signZ * AZ::Vector3(0.0f, 0.0f, m_firstPlaneSelectorPos.GetZ());
AZ::Vector3 secPlanePosZ = m_position + m_signZ * AZ::Vector3(0.0f, 0.0f, m_secPlaneSelectorPos.GetZ());
if (m_zAxisVisible)
{
renderUtil->RenderLine(mPosition, mPosition + mSignZ * AZ::Vector3(0.0f, 0.0f, mScaledSize.GetZ()), zAxisColor);
AZ::Vector3 quadPos = MCore::Project(mPosition + mSignZ * AZ::Vector3(0, 0, mScaledSize.GetZ() + 0.5f * mBaseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight);
renderUtil->RenderBorderedRect(static_cast<int32>(quadPos.GetX() - 2.0f), static_cast<int32>(quadPos.GetX() + 3.0f), static_cast<int32>(quadPos.GetY() - 2.0f), static_cast<int32>(quadPos.GetY() + 3.0f), ManipulatorColors::mBlue, ManipulatorColors::mBlue);
renderUtil->RenderLine(m_position, m_position + m_signZ * AZ::Vector3(0.0f, 0.0f, m_scaledSize.GetZ()), zAxisColor);
AZ::Vector3 quadPos = MCore::Project(m_position + m_signZ * AZ::Vector3(0, 0, m_scaledSize.GetZ() + 0.5f * m_baseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight);
renderUtil->RenderBorderedRect(static_cast<int32>(quadPos.GetX() - 2.0f), static_cast<int32>(quadPos.GetX() + 3.0f), static_cast<int32>(quadPos.GetY() - 2.0f), static_cast<int32>(quadPos.GetY() + 3.0f), ManipulatorColors::s_blue, ManipulatorColors::s_blue);
// render the plane selector lines
renderUtil->RenderLine(firstPlanePosZ, firstPlanePosZ + mDiagScale * (AZ::Vector3(mFirstPlaneSelectorPos.GetX() * mSignX, 0, 0) - AZ::Vector3(0, 0, mFirstPlaneSelectorPos.GetZ() * mSignZ)), xzPlaneColorZ);
renderUtil->RenderLine(firstPlanePosZ, firstPlanePosZ + mDiagScale * (AZ::Vector3(0, mFirstPlaneSelectorPos.GetY() * mSignY, 0) - AZ::Vector3(0, 0, mFirstPlaneSelectorPos.GetZ() * mSignZ)), yzPlaneColorZ);
renderUtil->RenderLine(secPlanePosZ, secPlanePosZ + mDiagScale * (AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, 0, 0) - AZ::Vector3(0, 0, mSecPlaneSelectorPos.GetZ() * mSignZ)), xzPlaneColorZ);
renderUtil->RenderLine(secPlanePosZ, secPlanePosZ + mDiagScale * (AZ::Vector3(0, mSecPlaneSelectorPos.GetY() * mSignY, 0) - AZ::Vector3(0, 0, mSecPlaneSelectorPos.GetZ() * mSignZ)), yzPlaneColorZ);
renderUtil->RenderLine(firstPlanePosZ, firstPlanePosZ + m_diagScale * (AZ::Vector3(m_firstPlaneSelectorPos.GetX() * m_signX, 0, 0) - AZ::Vector3(0, 0, m_firstPlaneSelectorPos.GetZ() * m_signZ)), xzPlaneColorZ);
renderUtil->RenderLine(firstPlanePosZ, firstPlanePosZ + m_diagScale * (AZ::Vector3(0, m_firstPlaneSelectorPos.GetY() * m_signY, 0) - AZ::Vector3(0, 0, m_firstPlaneSelectorPos.GetZ() * m_signZ)), yzPlaneColorZ);
renderUtil->RenderLine(secPlanePosZ, secPlanePosZ + m_diagScale * (AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, 0, 0) - AZ::Vector3(0, 0, m_secPlaneSelectorPos.GetZ() * m_signZ)), xzPlaneColorZ);
renderUtil->RenderLine(secPlanePosZ, secPlanePosZ + m_diagScale * (AZ::Vector3(0, m_secPlaneSelectorPos.GetY() * m_signY, 0) - AZ::Vector3(0, 0, m_secPlaneSelectorPos.GetZ() * m_signZ)), yzPlaneColorZ);
}
// calculate projected positions for the axis labels and render the text
AZ::Vector3 textPosY = MCore::Project(mPosition + mSignY * AZ::Vector3(0.0, mScaledSize.GetY() + mArrowLength + mBaseRadius, -mBaseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 textPosX = MCore::Project(mPosition + mSignX * AZ::Vector3(mScaledSize.GetX() + mArrowLength + mBaseRadius, -mBaseRadius, 0.0), camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 textPosZ = MCore::Project(mPosition + mSignZ * AZ::Vector3(0.0, mBaseRadius, mScaledSize.GetZ() + mArrowLength + mBaseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 textPosY = MCore::Project(m_position + m_signY * AZ::Vector3(0.0, m_scaledSize.GetY() + m_arrowLength + m_baseRadius, -m_baseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 textPosX = MCore::Project(m_position + m_signX * AZ::Vector3(m_scaledSize.GetX() + m_arrowLength + m_baseRadius, -m_baseRadius, 0.0), camera->GetViewProjMatrix(), screenWidth, screenHeight);
AZ::Vector3 textPosZ = MCore::Project(m_position + m_signZ * AZ::Vector3(0.0, m_baseRadius, m_scaledSize.GetZ() + m_arrowLength + m_baseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight);
renderUtil->RenderText(textPosX.GetX(), textPosX.GetY(), "X", xAxisColor);
renderUtil->RenderText(textPosY.GetX(), textPosY.GetY(), "Y", yAxisColor);
renderUtil->RenderText(textPosZ.GetX(), textPosZ.GetY(), "Z", zAxisColor);
// Render the triangles for plane selection
if (mMode == SCALE_XY && mXAxisVisible && mYAxisVisible)
if (m_mode == SCALE_XY && m_xAxisVisible && m_yAxisVisible)
{
renderUtil->RenderTriangle(firstPlanePosX, secPlanePosX, secPlanePosY, ManipulatorColors::mSelectionColorDarker);
renderUtil->RenderTriangle(firstPlanePosX, secPlanePosY, firstPlanePosY, ManipulatorColors::mSelectionColorDarker);
renderUtil->RenderTriangle(firstPlanePosX, secPlanePosX, secPlanePosY, ManipulatorColors::s_selectionColorDarker);
renderUtil->RenderTriangle(firstPlanePosX, secPlanePosY, firstPlanePosY, ManipulatorColors::s_selectionColorDarker);
}
else if (mMode == SCALE_XZ && mXAxisVisible && mZAxisVisible)
else if (m_mode == SCALE_XZ && m_xAxisVisible && m_zAxisVisible)
{
renderUtil->RenderTriangle(firstPlanePosX, secPlanePosX, secPlanePosZ, ManipulatorColors::mSelectionColorDarker);
renderUtil->RenderTriangle(firstPlanePosX, secPlanePosZ, firstPlanePosZ, ManipulatorColors::mSelectionColorDarker);
renderUtil->RenderTriangle(firstPlanePosX, secPlanePosX, secPlanePosZ, ManipulatorColors::s_selectionColorDarker);
renderUtil->RenderTriangle(firstPlanePosX, secPlanePosZ, firstPlanePosZ, ManipulatorColors::s_selectionColorDarker);
}
else if (mMode == SCALE_YZ && mYAxisVisible && mZAxisVisible)
else if (m_mode == SCALE_YZ && m_yAxisVisible && m_zAxisVisible)
{
renderUtil->RenderTriangle(firstPlanePosZ, secPlanePosZ, secPlanePosY, ManipulatorColors::mSelectionColorDarker);
renderUtil->RenderTriangle(firstPlanePosZ, secPlanePosY, firstPlanePosY, ManipulatorColors::mSelectionColorDarker);
renderUtil->RenderTriangle(firstPlanePosZ, secPlanePosZ, secPlanePosY, ManipulatorColors::s_selectionColorDarker);
renderUtil->RenderTriangle(firstPlanePosZ, secPlanePosY, firstPlanePosY, ManipulatorColors::s_selectionColorDarker);
}
else if (mMode == SCALE_XYZ)
else if (m_mode == SCALE_XYZ)
{
renderUtil->RenderTriangle(firstPlanePosX, firstPlanePosY, firstPlanePosZ, ManipulatorColors::mSelectionColorDarker);
renderUtil->RenderTriangle(mPosition, firstPlanePosX, firstPlanePosZ, ManipulatorColors::mSelectionColorDarker);
renderUtil->RenderTriangle(mPosition, firstPlanePosX, firstPlanePosY, ManipulatorColors::mSelectionColorDarker);
renderUtil->RenderTriangle(mPosition, firstPlanePosY, firstPlanePosZ, ManipulatorColors::mSelectionColorDarker);
renderUtil->RenderTriangle(firstPlanePosX, firstPlanePosY, firstPlanePosZ, ManipulatorColors::s_selectionColorDarker);
renderUtil->RenderTriangle(m_position, firstPlanePosX, firstPlanePosZ, ManipulatorColors::s_selectionColorDarker);
renderUtil->RenderTriangle(m_position, firstPlanePosX, firstPlanePosY, ManipulatorColors::s_selectionColorDarker);
renderUtil->RenderTriangle(m_position, firstPlanePosY, firstPlanePosZ, ManipulatorColors::s_selectionColorDarker);
}
// check if callback exists
if (mCallback == nullptr)
if (m_callback == nullptr)
{
return;
}
// render the current scale factor in percent if gizmo is hit
if (mMode != SCALE_NONE)
if (m_mode != SCALE_NONE)
{
const AZ::Vector3& currScale = mCallback->GetCurrValueVec();
mTempString = AZStd::string::format("Abs. Scale X: %.3f, Y: %.3f, Z: %.3f", MCore::Max(float(currScale.GetX()), 0.0f), MCore::Max(float(currScale.GetY()), 0.0f), MCore::Max(float(currScale.GetZ()), 0.0f));
renderUtil->RenderText(10, 10, mTempString.c_str(), ManipulatorColors::mSelectionColor, 9.0f);
const AZ::Vector3& currScale = m_callback->GetCurrValueVec();
m_tempString = AZStd::string::format("Abs. Scale X: %.3f, Y: %.3f, Z: %.3f", MCore::Max(float(currScale.GetX()), 0.0f), MCore::Max(float(currScale.GetY()), 0.0f), MCore::Max(float(currScale.GetZ()), 0.0f));
renderUtil->RenderText(10, 10, m_tempString.c_str(), ManipulatorColors::s_selectionColor, 9.0f);
}
// calculate the position offset of the relative text
float yOffset = (camera->GetProjectionMode() == MCommon::Camera::PROJMODE_PERSPECTIVE) ? 80.0f : 50.0f;
// text position relative scaling or name displayed below the gizmo
AZ::Vector3 textPos = MCore::Project(mPosition + (mSize * AZ::Vector3(mSignX, mSignY, mSignZ) / 3.0f), camera->GetViewProjMatrix(), camera->GetScreenWidth(), camera->GetScreenHeight());
AZ::Vector3 textPos = MCore::Project(m_position + (m_size * AZ::Vector3(m_signX, m_signY, m_signZ) / 3.0f), camera->GetViewProjMatrix(), camera->GetScreenWidth(), camera->GetScreenHeight());
// render the relative scale when moving
if (mSelectionLocked && mMode != SCALE_NONE)
if (m_selectionLocked && m_mode != SCALE_NONE)
{
// calculate the scale factor
AZ::Vector3 scaleFactor = ((AZ::Vector3(mSize, mSize, mSize) + mScale) / (float)mSize);
AZ::Vector3 scaleFactor = ((AZ::Vector3(m_size, m_size, m_size) + m_scale) / (float)m_size);
// render the scaling value below the gizmo
mTempString = AZStd::string::format("X: %.3f, Y: %.3f, Z: %.3f", MCore::Max(float(scaleFactor.GetX()), 0.0f), MCore::Max(float(scaleFactor.GetY()), 0.0f), MCore::Max(float(scaleFactor.GetZ()), 0.0f));
renderUtil->RenderText(textPos.GetX(), textPos.GetY() + yOffset, mTempString.c_str(), ManipulatorColors::mSelectionColor, 9.0f, true);
m_tempString = AZStd::string::format("X: %.3f, Y: %.3f, Z: %.3f", MCore::Max(float(scaleFactor.GetX()), 0.0f), MCore::Max(float(scaleFactor.GetY()), 0.0f), MCore::Max(float(scaleFactor.GetZ()), 0.0f));
renderUtil->RenderText(textPos.GetX(), textPos.GetY() + yOffset, m_tempString.c_str(), ManipulatorColors::s_selectionColor, 9.0f, true);
}
else
{
if (mName.size() > 0)
if (m_name.size() > 0)
{
renderUtil->RenderText(textPos.GetX(), textPos.GetY() + yOffset, mName.c_str(), ManipulatorColors::mSelectionColor, 9.0f, true);
renderUtil->RenderText(textPos.GetX(), textPos.GetY() + yOffset, m_name.c_str(), ManipulatorColors::s_selectionColor, 9.0f, true);
}
}
}
@@ -286,12 +286,12 @@ namespace MCommon
MCORE_UNUSED(middleButtonPressed);
// check if camera has been set
if (camera == nullptr || mIsVisible == false || (leftButtonPressed && rightButtonPressed))
if (camera == nullptr || m_isVisible == false || (leftButtonPressed && rightButtonPressed))
{
return;
}
// get screen mSize
// get screen m_size
const uint32 screenWidth = camera->GetScreenWidth();
const uint32 screenHeight = camera->GetScreenHeight();
@@ -303,63 +303,63 @@ namespace MCommon
MCore::Ray mousePrevPosRay = camera->Unproject(mousePosX - mouseMovementX, mousePosY - mouseMovementY);
// check for the selected axis/plane
if (mSelectionLocked == false || mMode == SCALE_NONE)
if (m_selectionLocked == false || m_mode == SCALE_NONE)
{
// update old rotation of the callback
if (mCallback)
if (m_callback)
{
mCallback->UpdateOldValues();
m_callback->UpdateOldValues();
}
// handle different scale cases depending on the bounding volumes
if (mousePosRay.Intersects(mXYZBoxAABB))
if (mousePosRay.Intersects(m_xyzBoxAabb))
{
mMode = SCALE_XYZ;
mScaleDirection = AZ::Vector3(mSignX, mSignY, mSignZ);
m_mode = SCALE_XYZ;
m_scaleDirection = AZ::Vector3(m_signX, m_signY, m_signZ);
}
else if (mousePosRay.Intersects(mXYPlaneAABB) && mXAxisVisible && mYAxisVisible)
else if (mousePosRay.Intersects(m_xyPlaneAabb) && m_xAxisVisible && m_yAxisVisible)
{
mMode = SCALE_XY;
mScaleDirection = AZ::Vector3(mSignX, mSignY, 0.0f);
m_mode = SCALE_XY;
m_scaleDirection = AZ::Vector3(m_signX, m_signY, 0.0f);
}
else if (mousePosRay.Intersects(mXZPlaneAABB) && mXAxisVisible && mZAxisVisible)
else if (mousePosRay.Intersects(m_xzPlaneAabb) && m_xAxisVisible && m_zAxisVisible)
{
mMode = SCALE_XZ;
mScaleDirection = AZ::Vector3(mSignX, 0.0f, mSignZ);
m_mode = SCALE_XZ;
m_scaleDirection = AZ::Vector3(m_signX, 0.0f, m_signZ);
}
else if (mousePosRay.Intersects(mYZPlaneAABB) && mYAxisVisible && mZAxisVisible)
else if (mousePosRay.Intersects(m_yzPlaneAabb) && m_yAxisVisible && m_zAxisVisible)
{
mMode = SCALE_YZ;
mScaleDirection = AZ::Vector3(0.0f, mSignY, mSignZ);
m_mode = SCALE_YZ;
m_scaleDirection = AZ::Vector3(0.0f, m_signY, m_signZ);
}
else if (mousePosRay.Intersects(mXAxisAABB) && mXAxisVisible)
else if (mousePosRay.Intersects(m_xAxisAabb) && m_xAxisVisible)
{
mMode = SCALE_X;
mScaleDirection = AZ::Vector3(mSignX, 0.0f, 0.0f);
m_mode = SCALE_X;
m_scaleDirection = AZ::Vector3(m_signX, 0.0f, 0.0f);
}
else if (mousePosRay.Intersects(mYAxisAABB) && mYAxisVisible)
else if (mousePosRay.Intersects(m_yAxisAabb) && m_yAxisVisible)
{
mMode = SCALE_Y;
mScaleDirection = AZ::Vector3(0.0f, mSignY, 0.0f);
m_mode = SCALE_Y;
m_scaleDirection = AZ::Vector3(0.0f, m_signY, 0.0f);
}
else if (mousePosRay.Intersects(mZAxisAABB) && mZAxisVisible)
else if (mousePosRay.Intersects(m_zAxisAabb) && m_zAxisVisible)
{
mMode = SCALE_Z;
mScaleDirection = AZ::Vector3(0.0f, 0.0f, mSignZ);
m_mode = SCALE_Z;
m_scaleDirection = AZ::Vector3(0.0f, 0.0f, m_signZ);
}
else
{
mMode = SCALE_NONE;
m_mode = SCALE_NONE;
}
}
// set selection lock
mSelectionLocked = leftButtonPressed;
m_selectionLocked = leftButtonPressed;
// move the gizmo
if (mSelectionLocked == false || mMode == SCALE_NONE)
if (m_selectionLocked == false || m_mode == SCALE_NONE)
{
mScale = AZ::Vector3::CreateZero();
m_scale = AZ::Vector3::CreateZero();
return;
}
@@ -369,7 +369,7 @@ namespace MCommon
// calculate the movement of the mouse on a plane located at the gizmo position
// and perpendicular to the camera direction
MCore::Ray camRay = camera->Unproject(screenWidth / 2, screenHeight / 2);
MCore::PlaneEq movementPlane(camRay.GetDirection(), mPosition);
MCore::PlaneEq movementPlane(camRay.GetDirection(), m_position);
// calculate the intersection points of the mouse positions with the previously calculated plane
AZ::Vector3 mousePosIntersect, mousePrevPosIntersect;
@@ -377,17 +377,17 @@ namespace MCommon
mousePrevPosRay.Intersects(movementPlane, &mousePrevPosIntersect);
// project the mouse movement onto the scale axis
scaleChange = (mScaleDirection * mScaleDirection.Dot(mousePosIntersect) - mScaleDirection * mScaleDirection.Dot(mousePrevPosIntersect));
scaleChange = (m_scaleDirection * m_scaleDirection.Dot(mousePosIntersect) - m_scaleDirection * m_scaleDirection.Dot(mousePrevPosIntersect));
// update the scale of the gizmo
scaleChange = AZ::Vector3(scaleChange.GetX() * mSignX, scaleChange.GetY() * mSignY, scaleChange.GetZ() * mSignZ);
mScale += scaleChange;
scaleChange = AZ::Vector3(scaleChange.GetX() * m_signX, scaleChange.GetY() * m_signY, scaleChange.GetZ() * m_signZ);
m_scale += scaleChange;
// update the callback actor instance
if (mCallback)
if (m_callback)
{
AZ::Vector3 updateScale = (AZ::Vector3(mSize, mSize, mSize) + mScale) / (float)mSize;
mCallback->Update(updateScale);
AZ::Vector3 updateScale = (AZ::Vector3(m_size, m_size, m_size) + m_scale) / (float)m_size;
m_callback->Update(updateScale);
}
}
} // namespace MCommon
@@ -90,31 +90,31 @@ namespace MCommon
protected:
// scale vectors
AZ::Vector3 mScaleDirection;
AZ::Vector3 mScale;
AZ::Vector3 m_scaleDirection;
AZ::Vector3 m_scale;
// bounding volumes for the axes
MCore::AABB mXAxisAABB;
MCore::AABB mYAxisAABB;
MCore::AABB mZAxisAABB;
MCore::AABB mXYPlaneAABB;
MCore::AABB mXZPlaneAABB;
MCore::AABB mYZPlaneAABB;
MCore::AABB mXYZBoxAABB;
MCore::AABB m_xAxisAabb;
MCore::AABB m_yAxisAabb;
MCore::AABB m_zAxisAabb;
MCore::AABB m_xyPlaneAabb;
MCore::AABB m_xzPlaneAabb;
MCore::AABB m_yzPlaneAabb;
MCore::AABB m_xyzBoxAabb;
// size properties of the scale manipulator
float mSize;
AZ::Vector3 mScaledSize;
float mDiagScale;
float mArrowLength;
float mBaseRadius;
AZ::Vector3 mFirstPlaneSelectorPos;
AZ::Vector3 mSecPlaneSelectorPos;
float mSignX;
float mSignY;
float mSignZ;
bool mXAxisVisible;
bool mYAxisVisible;
bool mZAxisVisible;
float m_size;
AZ::Vector3 m_scaledSize;
float m_diagScale;
float m_arrowLength;
float m_baseRadius;
AZ::Vector3 m_firstPlaneSelectorPos;
AZ::Vector3 m_secPlaneSelectorPos;
float m_signX;
float m_signY;
float m_signZ;
bool m_xAxisVisible;
bool m_yAxisVisible;
bool m_zAxisVisible;
};
} // namespace MCommon

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