Merged from main

This commit is contained in:
pereslav
2021-05-18 13:10:44 +01:00
1102 changed files with 6650 additions and 72333 deletions
@@ -236,8 +236,6 @@ namespace AzFramework
// Archive classes relies on the FileIOBase DirectInstance to close
// files properly
m_directFileIO.reset();
// The AZ::Console skips destruction and always leaks to allow it to be used in static memory
}
void Application::Start(const Descriptor& descriptor, const StartupParameters& startupParameters)
@@ -24,7 +24,7 @@ namespace AZ::IO
ePakPriorityPakOnly = 2
};
// variables that control behavior of Archive/StreamEngine subsystems
// variables that control behavior of the Archive subsystem
struct ArchiveVars
{
#if defined(_RELEASE)
@@ -881,7 +881,7 @@ namespace AzFramework
serializeContext->ClassDeprecate("NetBindable", "{80206665-D429-4703-B42E-94434F82F381}");
serializeContext->Class<TransformComponent, AZ::Component>()
->Version(4, &TransformComponentVersionConverter)
->Version(5, &TransformComponentVersionConverter)
->Field("Parent", &TransformComponent::m_parentId)
->Field("Transform", &TransformComponent::m_worldTM)
->Field("LocalTransform", &TransformComponent::m_localTM)
@@ -40,17 +40,18 @@ namespace AzFramework
//! Standard parameters for drawing text on screen
struct TextDrawParameters
{
ViewportId m_drawViewportId = InvalidViewportId; //! Viewport to draw into
AZ::Vector3 m_position; //! world space position for 3d draws, screen space x,y,depth for 2d.
AZ::Color m_color = AZ::Colors::White; //! Color to draw the text
AZ::Vector2 m_scale = AZ::Vector2(1.0f); //! font scale
TextHorizontalAlignment m_hAlign = TextHorizontalAlignment::Left; //! Horizontal text alignment
TextVerticalAlignment m_vAlign = TextVerticalAlignment::Top; //! Vertical text alignment
bool m_monospace = false; //! disable character proportional spacing
bool m_depthTest = false; //! Test character against the depth buffer
bool m_virtual800x600ScreenSize = true; //! Text placement and size are scaled relative to a virtual 800x600 resolution
bool m_scaleWithWindow = false; //! Font gets bigger as the window gets bigger
bool m_multiline = true; //! text respects ascii newline characters
ViewportId m_drawViewportId = InvalidViewportId; //!< Viewport to draw into
AZ::Vector3 m_position; //!< world space position for 3d draws, screen space x,y,depth for 2d.
AZ::Color m_color = AZ::Colors::White; //!< Color to draw the text
AZ::Vector2 m_scale = AZ::Vector2(1.0f); //!< font scale
float m_lineSpacing; //!< Spacing between new lines, as a percentage of m_scale.
TextHorizontalAlignment m_hAlign = TextHorizontalAlignment::Left; //!< Horizontal text alignment
TextVerticalAlignment m_vAlign = TextVerticalAlignment::Top; //!< Vertical text alignment
bool m_monospace = false; //!< disable character proportional spacing
bool m_depthTest = false; //!< Test character against the depth buffer
bool m_virtual800x600ScreenSize = true; //!< Text placement and size are scaled relative to a virtual 800x600 resolution
bool m_scaleWithWindow = false; //!< Font gets bigger as the window gets bigger
bool m_multiline = true; //!< text respects ascii newline characters
};
class FontDrawInterface
@@ -63,10 +64,13 @@ namespace AzFramework
virtual void DrawScreenAlignedText2d(
const TextDrawParameters& params,
const AZStd::string_view& string) = 0;
AZStd::string_view text) = 0;
virtual void DrawScreenAlignedText3d(
const TextDrawParameters& params,
const AZStd::string_view& string) = 0;
AZStd::string_view text) = 0;
virtual AZ::Vector2 GetTextSize(
const TextDrawParameters& params,
AZStd::string_view text) = 0;
};
class FontQueryInterface
@@ -18,6 +18,7 @@
#include <AzFramework/Physics/Collision/CollisionGroups.h>
#include <AzFramework/Physics/Collision/CollisionLayers.h>
#include <AzFramework/Physics/Common/PhysicsTypes.h>
#include <AzFramework/Physics/Common/PhysicsSimulatedBody.h>
#include <AzFramework/Physics/Configuration/SimulatedBodyConfiguration.h>
@@ -36,7 +37,7 @@ namespace Physics
static void Reflect(AZ::ReflectContext* context);
AZStd::string m_name;
ShapeConfigurationList m_shapes;
AzPhysics::ShapeColliderPairList m_shapes;
};
class CharacterColliderConfiguration
@@ -57,7 +57,7 @@ namespace Physics
classElement.RemoveElement(shapesIndex);
// add a new vector in the new format
const int newShapesIndex = classElement.AddElement<ShapeConfigurationList>(context, "shapes");
const int newShapesIndex = classElement.AddElement<AzPhysics::ShapeColliderPairList>(context, "shapes");
if (newShapesIndex != -1)
{
AZ::SerializeContext::DataElementNode& newShapesElement = classElement.GetSubElement(newShapesIndex);
@@ -65,7 +65,9 @@ namespace Physics
// convert the old shapes into the new format and add to the vector
for (AZ::SerializeContext::DataElementNode shape : shapesCopy)
{
const int pairIndex = newShapesElement.AddElementWithData<ShapeConfigurationPair>(context, "element", ShapeConfigurationPair());
const int pairIndex = newShapesElement.AddElementWithData<AzPhysics::ShapeColliderPair>(
context, "element", AzPhysics::ShapeColliderPair());
AZ::SerializeContext::DataElementNode& pairElement = newShapesElement.GetSubElement(pairIndex);
ColliderConfiguration colliderConfig;
@@ -131,8 +133,8 @@ namespace Physics
AZ::SerializeContext::DataElementNode* baseBaseClass1 = baseClass1->FindSubElement(AZ_CRC("BaseClass1", 0xd4925735));
if (baseBaseClass1 && baseBaseClass1->FindSubElementAndGetData<AZStd::string>(AZ_CRC("name", 0x5e237e06), name))
{
ShapeConfigurationList shapes;
if (nodeElement.FindSubElementAndGetData<ShapeConfigurationList>(AZ_CRC("shapes", 0x93dba512), shapes))
AzPhysics::ShapeColliderPairList shapes;
if (nodeElement.FindSubElementAndGetData<AzPhysics::ShapeColliderPairList>(AZ_CRC("shapes", 0x93dba512), shapes))
{
CharacterColliderNodeConfiguration newColliderNodeConfig;
newColliderNodeConfig.m_name = name;
@@ -70,7 +70,10 @@ namespace AzPhysics
using SimulatedBodyHandleList = AZStd::vector<SimulatedBodyHandle>;
//! Helper used for pairing the ShapeConfiguration and ColliderConfiguration together which is used when creating a Simulated Body.
using ShapeColliderPair = AZStd::pair<Physics::ColliderConfiguration*, Physics::ShapeConfiguration*>;
using ShapeColliderPair = AZStd::pair<
AZStd::shared_ptr<Physics::ColliderConfiguration>,
AZStd::shared_ptr<Physics::ShapeConfiguration>>;
using ShapeColliderPairList = AZStd::vector<ShapeColliderPair>;
//! Flags used to specifying which properties of a body to compute.
enum class MassComputeFlags : AZ::u8
@@ -80,9 +80,6 @@ namespace Physics
void OnContactOffsetChanged();
};
using ShapeConfigurationPair = AZStd::pair<AZStd::shared_ptr<ColliderConfiguration>, AZStd::shared_ptr<ShapeConfiguration>>;
using ShapeConfigurationList = AZStd::vector<ShapeConfigurationPair>;
struct RayCastRequest;
class Shape
@@ -979,7 +979,7 @@ namespace AzFramework
};
serializeContext->Class<ScriptComponent, AZ::Component>()
->Version(3, converter)
->Version(4, converter)
->Field("ContextID", &ScriptComponent::m_contextId)
->Field("Properties", &ScriptComponent::m_properties)
->Field("Script", &ScriptComponent::m_script)
@@ -0,0 +1,54 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Description : Ebus for querying thermal information of the device.
#pragma once
#include <AzCore/EBus/EBus.h>
// The different types of temperature sensor that could be available on the device.
enum class ThermalSensorType : int
{
CPU = 0,
GPU,
Battery,
Count
};
// Handles requests for thermal information
class ThermalInfoHandler : public AZ::EBusTraits
{
public:
static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single;
static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single;
virtual ~ThermalInfoHandler() = default;
/**
* Returns the current temperature of a specific sensor in Celcius degrees.
* If the type of sensor is not available on the device it returns 0.
*
* \param sensor The sensor type.
*/
virtual float GetSensorTemp(ThermalSensorType sensor) = 0;
/**
* Returns the temperature that is considered as overheating for a specific sensor.
* The value returned is in Celcius degrees.
*
* \param sensor The sensor type.
*/
virtual float GetSensorOverheatingTemp(ThermalSensorType sensor) = 0;
};
using ThermalInfoRequestsBus = AZ::EBus<ThermalInfoHandler>;
@@ -74,7 +74,6 @@ namespace AzFramework
void SetCameraClippingVolumeFromPerspectiveFovMatrixRH(CameraState& cameraState, const AZ::Matrix4x4& clipFromView)
{
const float m11 = clipFromView(1, 1);
const float m22 = clipFromView(2, 2);
const float m23 = clipFromView(2, 3);
cameraState.m_nearClip = m23 / m22;
@@ -84,7 +83,12 @@ namespace AzFramework
{
AZStd::swap(cameraState.m_nearClip, cameraState.m_farClip);
}
cameraState.m_fovOrZoom = 2 * (AZ::Constants::HalfPi - atanf(m11));
cameraState.m_fovOrZoom = RetrieveFov(clipFromView);
}
float RetrieveFov(const AZ::Matrix4x4& clipFromView)
{
return 2.0f * (AZ::Constants::HalfPi - AZStd::atan(clipFromView(1, 1)));
}
void CameraState::Reflect(AZ::SerializeContext& serializeContext)
@@ -17,54 +17,57 @@
namespace AzFramework
{
/// Represents the camera state populated by the viewport camera.
//! Represents the camera state populated by the viewport camera.
struct CameraState
{
/// @cond
//! @cond
AZ_TYPE_INFO(CameraState, "{D309D934-044C-4BA8-91F1-EA3A45177A52}")
CameraState() = default;
/// @endcond
//! @endcond
static void Reflect(AZ::SerializeContext& context);
/// Return the vertical fov of the camera when the view is in perspective.
//! Return the vertical fov of the camera when the view is in perspective.
float VerticalFovRadian() const { return m_fovOrZoom; }
/// Return the zoom amount of the camera when the view is in orthographic.
//! Return the zoom amount of the camera when the view is in orthographic.
float Zoom() const { return m_fovOrZoom; }
AZ::Vector3 m_position = AZ::Vector3::CreateZero(); ///< World position of the camera.
AZ::Vector3 m_forward = AZ::Vector3::CreateAxisY(); ///< Forward look direction of the camera (world space).
AZ::Vector3 m_side = AZ::Vector3::CreateAxisX(); ///< Side vector of camera (orthogonal to forward and up).
AZ::Vector3 m_up = AZ::Vector3::CreateAxisZ(); ///< Up vector of the camera (cameras frame - world space).
AZ::Vector2 m_viewportSize = AZ::Vector2::CreateZero(); ///< Dimensions of the viewport.
float m_nearClip = 0.01f; ///< Near clip plane of the camera.
float m_farClip = 100.0f; ///< Far clip plane of the camera.
float m_fovOrZoom = 0.0f; ///< Fov or zoom of camera depending on if it is using orthographic projection or not.
bool m_orthographic = false; ///< Is the camera using orthographic projection or not.
AZ::Vector3 m_position = AZ::Vector3::CreateZero(); //!< World position of the camera.
AZ::Vector3 m_forward = AZ::Vector3::CreateAxisY(); //!< Forward look direction of the camera (world space).
AZ::Vector3 m_side = AZ::Vector3::CreateAxisX(); //!< Side vector of camera (orthogonal to forward and up).
AZ::Vector3 m_up = AZ::Vector3::CreateAxisZ(); //!< Up vector of the camera (cameras frame - world space).
AZ::Vector2 m_viewportSize = AZ::Vector2::CreateZero(); //!< Dimensions of the viewport.
float m_nearClip = 0.01f; //!< Near clip plane of the camera.
float m_farClip = 100.0f; //!< Far clip plane of the camera.
float m_fovOrZoom = 0.0f; //!< Fov or zoom of camera depending on if it is using orthographic projection or not.
bool m_orthographic = false; //!< Is the camera using orthographic projection or not.
};
/// Create a camera at the given transform with a specific viewport size.
/// @note The near/far clip planes and fov are sensible default values - please
/// use SetCameraClippingVolume to override them.
//! Create a camera at the given transform with a specific viewport size.
//! @note The near/far clip planes and fov are sensible default values - please
//! use SetCameraClippingVolume to override them.
CameraState CreateDefaultCamera(const AZ::Transform& transform, const AZ::Vector2& viewportSize);
/// Create a camera at the given position (no orientation) with a specific viewport size.
/// @note The near/far clip planes and fov are sensible default values - please
/// use SetCameraClippingVolume to override them.
//! Create a camera at the given position (no orientation) with a specific viewport size.
//! @note The near/far clip planes and fov are sensible default values - please
//! use SetCameraClippingVolume to override them.
CameraState CreateIdentityDefaultCamera(const AZ::Vector3& position, const AZ::Vector2& viewportSize);
/// Create a camera transformed by the given view to world matrix with a specific viewport size.
/// @note The near/far clip planes and fov are sensible default values - please
/// use SetCameraClippingVolume to override them.
//! Create a camera transformed by the given view to world matrix with a specific viewport size.
//! @note The near/far clip planes and fov are sensible default values - please
//! use SetCameraClippingVolume to override them.
CameraState CreateCameraFromWorldFromViewMatrix(const AZ::Matrix4x4& worldFromView, const AZ::Vector2& viewportSize);
/// Override the default near/far clipping planes and fov of the camera.
//! Override the default near/far clipping planes and fov of the camera.
void SetCameraClippingVolume(CameraState& cameraState, float nearPlane, float farPlane, float fovRad);
/// Override the default near/far clipping planes and fov of the camera by inferring them the specified right handed transform into clip space.
//! Override the default near/far clipping planes and fov of the camera by inferring them the specified right handed transform into clip space.
void SetCameraClippingVolumeFromPerspectiveFovMatrixRH(CameraState& cameraState, const AZ::Matrix4x4& clipFromView);
/// Set the transform for an existing camera.
//! Retrieve the field of view (Fov) from the perspective projection matrix (view space to clip space).
float RetrieveFov(const AZ::Matrix4x4& clipFromView);
//! Set the transform for an existing camera.
void SetCameraTransform(CameraState& cameraState, const AZ::Transform& transform);
} // namespace AzFramework
@@ -1,68 +1,68 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzFramework/Viewport/ClickDetector.h>
#include <AzFramework/Viewport/ScreenGeometry.h>
namespace AzFramework
{
ClickDetector::ClickOutcome ClickDetector::DetectClick(const ClickEvent clickEvent, const ScreenVector& cursorDelta)
{
if (clickEvent == ClickEvent::Down)
{
const auto now = std::chrono::steady_clock::now();
if (m_tryBeginTime)
{
const std::chrono::duration<float> diff = now - m_tryBeginTime.value();
if (diff.count() < m_doubleClickInterval)
{
return ClickOutcome::Nil;
}
}
m_detectionState = DetectionState::WaitingForMove;
m_moveAccumulator = 0.0f;
m_tryBeginTime = now;
}
else if (clickEvent == ClickEvent::Up)
{
const auto clickOutcome = [detectionState = m_detectionState] {
if (detectionState == DetectionState::WaitingForMove)
{
return ClickOutcome::Click;
}
if (detectionState == DetectionState::Moved)
{
return ClickOutcome::Release;
}
return ClickOutcome::Nil;
}();
m_detectionState = DetectionState::Nil;
return clickOutcome;
}
if (m_detectionState == DetectionState::WaitingForMove)
{
// only allow the action to begin if the mouse has been moved a small amount
m_moveAccumulator += ScreenVectorLength(cursorDelta);
if (m_moveAccumulator > m_deadZone)
{
m_detectionState = DetectionState::Moved;
return ClickOutcome::Move;
}
}
return ClickOutcome::Nil;
}
} // namespace AzFramework
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzFramework/Viewport/ClickDetector.h>
#include <AzFramework/Viewport/ScreenGeometry.h>
namespace AzFramework
{
ClickDetector::ClickOutcome ClickDetector::DetectClick(const ClickEvent clickEvent, const ScreenVector& cursorDelta)
{
if (clickEvent == ClickEvent::Down)
{
const auto now = std::chrono::steady_clock::now();
if (m_tryBeginTime)
{
const std::chrono::duration<float> diff = now - m_tryBeginTime.value();
if (diff.count() < m_doubleClickInterval)
{
return ClickOutcome::Nil;
}
}
m_detectionState = DetectionState::WaitingForMove;
m_moveAccumulator = 0.0f;
m_tryBeginTime = now;
}
else if (clickEvent == ClickEvent::Up)
{
const auto clickOutcome = [detectionState = m_detectionState] {
if (detectionState == DetectionState::WaitingForMove)
{
return ClickOutcome::Click;
}
if (detectionState == DetectionState::Moved)
{
return ClickOutcome::Release;
}
return ClickOutcome::Nil;
}();
m_detectionState = DetectionState::Nil;
return clickOutcome;
}
if (m_detectionState == DetectionState::WaitingForMove)
{
// only allow the action to begin if the mouse has been moved a small amount
m_moveAccumulator += ScreenVectorLength(cursorDelta);
if (m_moveAccumulator > m_deadZone)
{
m_detectionState = DetectionState::Moved;
return ClickOutcome::Move;
}
}
return ClickOutcome::Nil;
}
} // namespace AzFramework
@@ -1,56 +1,56 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzFramework/Viewport/ScreenGeometry.h>
#include <AzCore/std/optional.h>
namespace AzFramework
{
//! Utility type to wrap a current and last cursor position.
struct CursorState
{
//! Returns the delta between the current and last cursor position.
[[nodiscard]] ScreenVector CursorDelta() const;
//! Call this in a 'handle event' call to update the most recent cursor position.
void SetCurrentPosition(const ScreenPoint& currentPosition);
//! Call this in an 'update' call to copy the current cursor position to the last
//! cursor position.
void Update();
private:
AZStd::optional<ScreenPoint> m_lastCursorPosition;
AZStd::optional<ScreenPoint> m_currentCursorPosition;
};
inline void CursorState::SetCurrentPosition(const ScreenPoint& currentPosition)
{
m_currentCursorPosition = currentPosition;
}
inline ScreenVector CursorState::CursorDelta() const
{
return m_currentCursorPosition.has_value() && m_lastCursorPosition.has_value()
? m_currentCursorPosition.value() - m_lastCursorPosition.value()
: ScreenVector(0, 0);
}
inline void CursorState::Update()
{
if (m_currentCursorPosition.has_value())
{
m_lastCursorPosition = m_currentCursorPosition;
}
}
} // namespace AzFramework
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzFramework/Viewport/ScreenGeometry.h>
#include <AzCore/std/optional.h>
namespace AzFramework
{
//! Utility type to wrap a current and last cursor position.
struct CursorState
{
//! Returns the delta between the current and last cursor position.
[[nodiscard]] ScreenVector CursorDelta() const;
//! Call this in a 'handle event' call to update the most recent cursor position.
void SetCurrentPosition(const ScreenPoint& currentPosition);
//! Call this in an 'update' call to copy the current cursor position to the last
//! cursor position.
void Update();
private:
AZStd::optional<ScreenPoint> m_lastCursorPosition;
AZStd::optional<ScreenPoint> m_currentCursorPosition;
};
inline void CursorState::SetCurrentPosition(const ScreenPoint& currentPosition)
{
m_currentCursorPosition = currentPosition;
}
inline ScreenVector CursorState::CursorDelta() const
{
return m_currentCursorPosition.has_value() && m_lastCursorPosition.has_value()
? m_currentCursorPosition.value() - m_lastCursorPosition.value()
: ScreenVector(0, 0);
}
inline void CursorState::Update()
{
if (m_currentCursorPosition.has_value())
{
m_lastCursorPosition = m_currentCursorPosition;
}
}
} // namespace AzFramework
@@ -296,6 +296,7 @@ set(FILES
Spawnable/SpawnableSystemComponent.cpp
Terrain/TerrainDataRequestBus.h
Terrain/TerrainDataRequestBus.cpp
Thermal/ThermalInfo.h
Platform/PlatformDefaults.h
Windowing/WindowBus.h
Windowing/NativeWindow.cpp
@@ -13,6 +13,7 @@
#include <AzFramework/API/ApplicationAPI_Platform.h>
#include <AzFramework/Application/Application.h>
#include <AzFramework/Input/Buses/Notifications/RawInputNotificationBus_Platform.h>
#include <AzFramework/Thermal/ThermalInfo_Android.h>
#include <AzCore/Android/AndroidEnv.h>
#include <AzCore/Android/JNI/Object.h>
@@ -95,6 +96,7 @@ namespace AzFramework
private:
AndroidEventDispatcher* m_eventDispatcher;
ApplicationLifecycleEvents::Event m_lastEvent;
AZStd::unique_ptr<ThermalInfoHandler> m_thermalInfoHandler;
AZStd::atomic<bool> m_requestResponseReceived;
AZStd::unique_ptr<AZ::Android::JNI::Object> m_lumberyardActivity;
@@ -125,6 +127,10 @@ namespace AzFramework
AndroidLifecycleEvents::Bus::Handler::BusConnect();
AndroidAppRequests::Bus::Handler::BusConnect();
PermissionRequestResultNotification::Bus::Handler::BusConnect();
#if !defined(AZ_RELEASE_BUILD)
m_thermalInfoHandler = AZStd::make_unique<ThermalInfoAndroidHandler>();
#endif
}
////////////////////////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,124 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#if !defined(AZ_RELEASE_BUILD)
#include "ThermalInfo_Android.h"
#include <AzCore/std/string/string.h>
#include <AzFramework/StringFunc/StringFunc.h>
#include <cstdio>
#include <sys/types.h>
#include <dirent.h>
ThermalInfoAndroidHandler::ThermalInfoAndroidHandler()
{
static_assert(AZ_ARRAY_SIZE(m_temperatureFiles) == static_cast<int>(ThermalSensorType::Count), "Thermal count does not match temperature array size");
ThermalInfoRequestsBus::Handler::BusConnect();
memset(m_temperatureFiles, 0, sizeof(m_temperatureFiles));
const int sensorCount = static_cast<int>(ThermalSensorType::Count);
const char* sensorTypes[sensorCount] = { "cpu", "gpu", "battery" };
const int maxStringLen = 128;
char tempString[maxStringLen];
const char* thermalPath = "/sys/class/thermal";
// List the elements from the thermal folder to get the thermal_zones available on the device
DIR* directory = opendir(thermalPath);
if (directory)
{
struct dirent* item;
const char* thermalPrefix = "thermal_zone";
// List all items of the directory and find the one that start with thermal_zone (thermal_zone0, thermal_zone1, etc)
while ((item = readdir(directory)) != nullptr)
{
if (strncmp(item->d_name, thermalPrefix, strlen(thermalPrefix)) == 0)
{
// Try to deduce the type of sensor. For this we read the "type" file of the thermal zone.
// This "type" is a string set by the manufacturer, so it can be anything.
AZStd::string path = AZStd::string::format("%s/%s/type", thermalPath, item->d_name);
FILE* sensorTypeFile = fopen(path.c_str(), "r");
if (sensorTypeFile)
{
if (fscanf(sensorTypeFile, "%s", tempString))
{
for (int i = 0; i < sensorCount; ++i)
{
if (m_temperatureFiles[i])
{
continue;
}
size_t foundPos = AzFramework::StringFunc::Find(tempString, sensorTypes[i]);
if (foundPos != AZStd::string::npos)
{
path = AZStd::string::format("%s/%s/temp", thermalPath, item->d_name);
m_temperatureFiles[i] = fopen(path.c_str(), "r");
break;
}
}
}
fclose(sensorTypeFile);
}
}
}
closedir(directory);
}
int cpuSensorIndex = static_cast<int>(ThermalSensorType::CPU);
if (!m_temperatureFiles[cpuSensorIndex])
{
// If we didn't find the CPU sensor just assume it's the first one.
AZStd::string path = AZStd::string::format("%s/thermal_zone0/temp", thermalPath);
m_temperatureFiles[cpuSensorIndex] = fopen(path.c_str(), "r");
}
}
ThermalInfoAndroidHandler::~ThermalInfoAndroidHandler()
{
ThermalInfoRequestsBus::Handler::BusDisconnect();
for (int i = 0; i < static_cast<int>(ThermalSensorType::Count); ++i)
{
if (m_temperatureFiles[i])
{
fclose(m_temperatureFiles[i]);
}
}
}
float ThermalInfoAndroidHandler::GetSensorTemp(ThermalSensorType sensor)
{
FILE* tempFile = m_temperatureFiles[static_cast<int>(sensor)];
if (!tempFile)
{
return 0.f;
}
fseek(tempFile, 0, SEEK_SET);
float temperature = 0.f;
fscanf(tempFile, "%f", &temperature);
temperature /= 1000.0f;
return temperature;
}
float ThermalInfoAndroidHandler::GetSensorOverheatingTemp(ThermalSensorType sensor)
{
const int overheatingTemperatures[static_cast<int>(ThermalSensorType::Count)] =
{
70, // CPU
70, // GPU
40 // Battery
};
return overheatingTemperatures[static_cast<int>(sensor)];
}
#endif // !defined(AZ_RELEASE_BUILD)
@@ -0,0 +1,30 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#if !defined(AZ_RELEASE_BUILD)
#include <AzFramework/Thermal/ThermalInfo.h>
class ThermalInfoAndroidHandler : public ThermalInfoRequestsBus::Handler
{
public:
ThermalInfoAndroidHandler();
~ThermalInfoAndroidHandler() override;
float GetSensorTemp(ThermalSensorType sensor) override;
float GetSensorOverheatingTemp(ThermalSensorType sensor) override;
private:
FILE* m_temperatureFiles[static_cast<int>(ThermalSensorType::Count)];
};
#endif // !defined(AZ_RELEASE_BUILD)
@@ -36,4 +36,6 @@ set(FILES
AzFramework/Process/ProcessCommon.h
AzFramework/Process/ProcessWatcher_Android.cpp
AzFramework/Process/ProcessCommunicator_Android.cpp
AzFramework/Thermal/ThermalInfo_Android.cpp
AzFramework/Thermal/ThermalInfo_Android.h
)