Compare commits

...

69 Commits

Author SHA1 Message Date
a81d12d480 fixed version 2025-05-13 09:48:46 +03:00
17eb0cd0dc improved naming 2025-05-13 09:47:08 +03:00
52024285d2 added noexcept 2025-05-13 09:34:39 +03:00
f179aea4d7 removed even float type from vector classes 2025-05-13 09:22:23 +03:00
1196bb86b4 Merge pull request #44 from orange-cpp/feature/noexcept
Feature/noexcept
2025-05-05 02:34:43 +03:00
5489c296e9 added more noexcept 2025-05-05 02:24:23 +03:00
50ddf2d31e added more noexcept 2025-05-05 01:46:50 +03:00
a6e4c0461d added noexcept 2025-05-05 01:16:12 +03:00
6749f9f759 added noexcept for color and angles 2025-05-04 19:16:49 +03:00
9a38d47b0d added noexcept for vector types 2025-05-04 19:13:26 +03:00
f6f8bba032 changed license to zlib 2025-05-04 19:05:10 +03:00
ce08fcdd29 removed useless source files 2025-05-04 19:03:18 +03:00
49ea113348 fixed style 2025-05-04 18:54:33 +03:00
af21f9a946 removed pow 2025-05-04 18:07:35 +03:00
f096f7179f fixed clang format 2025-05-04 17:42:32 +03:00
e025e99d18 Update README.md 2025-05-04 00:55:35 +03:00
30eef59360 Update cmake-multi-platform.yml
switched to clang

Update cmake-multi-platform.yml
Update cmake-multi-platform.yml
Update cmake-multi-platform.yml
Update cmake-multi-platform.yml
Update cmake-multi-platform.yml
Update cmake-multi-platform.yml
Update cmake-multi-platform.yml
Update cmake-multi-platform.yml
added runtime dir

fix
2025-05-03 22:51:46 +03:00
c2a6cf5c47 Merge pull request #43 from orange-cpp/orange-cpp-ci
Create cmake-multi-platform.yml
2025-05-03 22:04:37 +03:00
7f55383bc1 Create cmake-multi-platform.yml 2025-05-03 22:04:10 +03:00
449c60133c bugfix 2025-05-03 21:36:16 +03:00
31d3359507 Merge pull request #42 from orange-cpp/feature/new-codestyle
Feature/new codestyle
2025-05-03 20:59:06 +03:00
dd738f365d fix 2025-05-03 20:51:50 +03:00
b5e788385d fixed style 2025-05-03 20:38:58 +03:00
df6d75e554 changed code style 2025-05-03 20:31:59 +03:00
be3fae63b8 patched clang format 2025-05-03 16:50:29 +03:00
dd731b60c3 updated clang format 2025-05-03 16:39:38 +03:00
b06fd00673 Merge pull request #41 from orange-cpp/u/improved-cmake
improved cmake, removed useless cmake files
2025-04-30 21:31:34 +03:00
998c8f3a43 improved cmake, removed useless cmake files 2025-04-30 21:26:25 +03:00
faeef594b9 moved installation stuff to INSTALL.md 2025-04-30 18:15:46 +03:00
40a301186e Merge pull request #40 from orange-cpp/u/orange/inverted-matrix
U/orange/inverted matrix
2025-04-29 20:53:02 +03:00
a41526c494 style fix 2025-04-29 20:52:41 +03:00
a0d1dc4313 added test case 2025-04-29 20:49:59 +03:00
1c5c9360c8 added inverse method 2025-04-29 20:33:39 +03:00
4615769682 added additional methods 2025-04-29 20:10:17 +03:00
4ef674f7b4 fixed infinite recursion in compile time 2025-04-29 20:08:27 +03:00
69b9049fb0 fixed gimba lock for unity 2025-04-26 00:52:46 +03:00
2734b58bdd fixed gimba lock for opengl camera 2025-04-26 00:32:53 +03:00
d7f1f49165 resetting state 2025-04-25 23:52:10 +03:00
94b1453cae removed .idea folder 2025-04-23 02:48:45 +03:00
3e67d8a99c added credits 2025-04-23 02:46:08 +03:00
8c00ab3d9d Merge pull request #38 from orange-cpp/u/orange-cpp/3d-primitives
U/orange cpp/3d primitives
2025-04-18 17:00:38 +03:00
d14cb1e93e reset to default 2025-04-18 16:55:07 +03:00
c692cf39e1 updated readme 2025-04-18 16:53:53 +03:00
9c934c5d9c improved tests 2025-04-18 16:36:22 +03:00
Vladislav Alpatov
f8202b116d improved line tracer 2025-04-18 16:00:23 +03:00
8bf0bb8e0d improved line trace and box primitive 2025-04-18 13:56:08 +03:00
a340766348 switched to polygons 2025-04-18 12:34:24 +03:00
254674a62e fixed code style 2025-04-18 12:11:43 +03:00
97c2da893b added ratio param 2025-04-18 01:33:47 +03:00
0ce30a7038 added new build option 2025-04-18 00:51:07 +03:00
492ddfd566 added box 2025-04-18 00:43:46 +03:00
baf7ee8f88 fixed include 2025-04-16 20:35:17 +03:00
9fde11733f Merge pull request #37 from orange-cpp/u/engine_rotation_mats
U/engine rotation mats
2025-04-16 23:21:58 +03:00
0069b8bd96 improved openg gl rotation matrix, added tests 2025-04-16 19:11:02 +03:00
127bae0b78 added tests for source 2025-04-16 18:53:31 +03:00
bed204a663 added unit tests 2025-04-16 18:35:50 +03:00
3f6ea010dc fixed formating 2025-04-16 17:52:57 +03:00
592a98f38c removed method from Mat added method for unity 2025-04-16 17:52:19 +03:00
7873047550 added func
added rotation matrix for opengl

updated unit tests
2025-04-16 17:40:00 +03:00
1601f3cbc8 added func
added rotation matrix for opengl
2025-04-16 17:40:00 +03:00
2180f8ab97 removed whitespaces 2025-04-16 12:21:10 +03:00
b613ff9ef1 added missing header 2025-04-13 23:15:27 +03:00
145eadfffa Merge pull request #36 from orange-cpp/u/orange-cpp/small-refactoring
U/orange cpp/small refactoring
2025-04-12 13:34:28 +03:00
14acebad5f fixed tests 2025-04-12 00:04:07 +03:00
4a7a631932 added const method to mat 2025-04-11 23:57:56 +03:00
e08c22f604 added new build option 2025-04-11 23:54:56 +03:00
1b47f45af9 improved naming 2025-04-11 23:30:07 +03:00
466d8f7bec improvement 2025-04-11 23:20:16 +03:00
3631c5d698 replaced with STL relization 2025-04-11 23:10:02 +03:00
92 changed files with 2006 additions and 1678 deletions

View File

@@ -1,62 +1,64 @@
# Generated from CLion C/C++ Code Style settings # Generated by CLion for Stroustrup
--- # The Stroustrup style, named after Bjarne Stroustrup, the creator of C++, is similar to the K&R style but differs
Language: Cpp # in its treatment of the class definitions and the placement of braces in certain contexts. The opening brace is
# placed on the same line as the control statement, and the closing brace is on its own line.
BasedOnStyle: LLVM BasedOnStyle: LLVM
AccessModifierOffset: -4 AccessModifierOffset: -4
AlignConsecutiveAssignments: false AlignConsecutiveAssignments: None
AlignConsecutiveDeclarations: false AlignConsecutiveBitFields: None
AlignOperands: true AlignConsecutiveDeclarations: None
AlignConsecutiveMacros: AcrossEmptyLinesAndComments
AlignTrailingComments: false AlignTrailingComments: false
AllowShortBlocksOnASingleLine: false AllowShortBlocksOnASingleLine: Never
AllowShortFunctionsOnASingleLine: None AllowShortFunctionsOnASingleLine: None
AlwaysBreakTemplateDeclarations: Yes AllowShortIfStatementsOnASingleLine: false
BraceWrapping: AllowShortLoopsOnASingleLine: false
BreakTemplateDeclarations: Leave
BreakBeforeBraces: Custom
BraceWrapping:
AfterCaseLabel: true AfterCaseLabel: true
AfterClass: true AfterClass: true
AfterControlStatement: true
AfterEnum: true
AfterFunction: true AfterFunction: true
AfterControlStatement: true
SplitEmptyFunction: true
AfterEnum: true
AfterNamespace: true AfterNamespace: true
AfterStruct: true AfterStruct: true
AfterUnion: true AfterUnion: true
AfterExternBlock: true AfterExternBlock: true
BeforeCatch: false BeforeCatch: true
BeforeElse: false BeforeElse: true
BeforeLambdaBody: true BeforeLambdaBody: true
BeforeWhile: false BeforeWhile: true
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true SplitEmptyRecord: true
SplitEmptyNamespace: true SplitEmptyNamespace: true
BreakBeforeBraces: Custom BreakBeforeBinaryOperators: NonAssignment
BreakConstructorInitializers: AfterColon BreakBeforeConceptDeclarations: false
BreakConstructorInitializersBeforeComma: false
ColumnLimit: 120 ColumnLimit: 120
ConstructorInitializerAllOnOneLineOrOnePerLine: false IncludeBlocks: Merge
ContinuationIndentWidth: 8 IndentExternBlock: Indent
IncludeCategories: IndentRequiresClause: false
- Regex: '^<.*'
Priority: 1
- Regex: '^".*'
Priority: 2
- Regex: '.*'
Priority: 3
IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseLabels: true
IndentWidth: 4 IndentWidth: 4
InsertNewlineAtEOF: true ContinuationIndentWidth: 8
MacroBlockBegin: '' KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 2
NamespaceIndentation: All NamespaceIndentation: All
PointerAlignment: Left PointerAlignment: Left
SpaceAfterCStyleCast: true SortUsingDeclarations: true
SpaceAfterTemplateKeyword: false SpaceAfterTemplateKeyword: false
SpaceBeforeCtorInitializerColon: false
SpaceBeforeParens: Custom
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterFunctionDeclarationName: false
AfterFunctionDefinitionName: false
AfterForeachMacros: true
AfterIfMacros: true
AfterOverloadedOperator: false
BeforeNonEmptyParentheses: false
SpaceBeforeRangeBasedForLoopColon: false SpaceBeforeRangeBasedForLoopColon: false
SpaceInEmptyParentheses: false SpaceInEmptyParentheses: false
SpacesInAngles: false
SpacesInConditionalStatement: false
SpacesInCStyleCastParentheses: false SpacesInCStyleCastParentheses: false
SpacesInParentheses: false SpacesInConditionalStatement: false
TabWidth: 4 SpacesInContainerLiterals: false
... SpacesInParentheses: false

View File

@@ -0,0 +1,79 @@
name: Omath CI (Arch Linux / Windows)
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
##############################################################################
# 1) ARCH LINUX Clang / Ninja
##############################################################################
jobs:
arch-build-and-test:
name: Arch Linux (Clang)
runs-on: ubuntu-latest
container: archlinux:latest
steps:
- name: Install basic tool-chain with pacman
shell: bash
run: |
pacman -Sy --noconfirm archlinux-keyring
pacman -Syu --noconfirm --needed \
git base-devel clang cmake ninja
- name: Checkout repository (with sub-modules)
uses: actions/checkout@v4
with:
submodules: recursive
- name: Configure (cmake --preset)
shell: bash
run: cmake --preset linux-release -DOMATH_BUILD_TESTS=ON
- name: Build
shell: bash
run: cmake --build cmake-build/build/linux-release --target all
- name: Run unit_tests
shell: bash
run: ./out/Release/unit_tests
##############################################################################
# 2) Windows MSVC / Ninja
##############################################################################
windows-build-and-test:
name: Windows (MSVC)
runs-on: windows-latest
steps:
- name: Checkout repository (with sub-modules)
uses: actions/checkout@v4
with:
submodules: recursive
- name: Install Ninja
uses: seanmiddleditch/gha-setup-ninja@v4
- name: Set up MSVC developer command-prompt
uses: ilammy/msvc-dev-cmd@v1
- name: Configure (cmake --preset)
shell: bash
run: cmake --preset windows-release -DOMATH_BUILD_TESTS=ON
- name: Build
shell: bash
run: cmake --build cmake-build/build/windows-release --target all
- name: Run unit_tests.exe
shell: bash
run: ./out/Release/unit_tests.exe

8
.idea/modules.xml generated
View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/uml.iml" filepath="$PROJECT_DIR$/.idea/uml.iml" />
</modules>
</component>
</project>

2
.idea/uml.iml generated
View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module classpath="CMake" type="CPP_MODULE" version="4" />

7
.idea/vcs.xml generated
View File

@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
<mapping directory="$PROJECT_DIR$/extlibs/googletest" vcs="Git" />
</component>
</project>

View File

@@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 3.26) cmake_minimum_required(VERSION 3.26)
project(omath VERSION 1.0.1 LANGUAGES CXX) project(omath VERSION 3.0.2 LANGUAGES CXX)
include(CMakePackageConfigHelpers) include(CMakePackageConfigHelpers)
@@ -11,14 +11,20 @@ option(OMATH_BUILD_AS_SHARED_LIBRARY "Build Omath as .so or .dll" OFF)
option(OMATH_USE_AVX2 "Omath will use AVX2 to boost performance" ON) option(OMATH_USE_AVX2 "Omath will use AVX2 to boost performance" ON)
option(OMATH_IMGUI_INTEGRATION "Omath will define method to convert omath types to imgui types" OFF) option(OMATH_IMGUI_INTEGRATION "Omath will define method to convert omath types to imgui types" OFF)
option(OMATH_BUILD_EXAMPLES "Build example projects with you can learn & play" OFF) option(OMATH_BUILD_EXAMPLES "Build example projects with you can learn & play" OFF)
option(OMATH_STATIC_MSVC_RUNTIME_LIBRARY "Force Omath to link static runtime" OFF) option(OMATH_STATIC_MSVC_RUNTIME_LIBRARY "Force Omath to link static runtime" OFF)
option(OMATH_SUPRESS_SAFETY_CHECKS "Supress some safety checks in release build to improve general performance" ON)
option(OMATH_USE_UNITY_BUILD "Will enable unity build to speed up compilation" ON)
file(GLOB_RECURSE OMATH_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/source/*.cpp")
file(GLOB_RECURSE OMATH_HEADERS CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/include/*.hpp")
if (OMATH_BUILD_AS_SHARED_LIBRARY) if (OMATH_BUILD_AS_SHARED_LIBRARY)
add_library(omath SHARED source/matrix.cpp) add_library(omath SHARED ${OMATH_SOURCES} ${OMATH_HEADERS})
else() else ()
add_library(omath STATIC source/matrix.cpp add_library(omath STATIC ${OMATH_SOURCES} ${OMATH_HEADERS})
source/matrix.cpp) endif ()
endif()
message(STATUS "Building on ${CMAKE_HOST_SYSTEM_NAME}") message(STATUS "Building on ${CMAKE_HOST_SYSTEM_NAME}")
add_library(omath::omath ALIAS omath) add_library(omath::omath ALIAS omath)
@@ -26,62 +32,68 @@ if (OMATH_IMGUI_INTEGRATION)
target_compile_definitions(omath PUBLIC OMATH_IMGUI_INTEGRATION) target_compile_definitions(omath PUBLIC OMATH_IMGUI_INTEGRATION)
# IMGUI is being linked as submodule # IMGUI is being linked as submodule
if(TARGET imgui) if (TARGET imgui)
target_link_libraries(omath PUBLIC imgui) target_link_libraries(omath PUBLIC imgui)
install(TARGETS imgui install(TARGETS imgui
EXPORT omathTargets EXPORT omathTargets
ARCHIVE DESTINATION lib ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib LIBRARY DESTINATION lib
RUNTIME DESTINATION bin) RUNTIME DESTINATION bin)
else() else ()
# Assume that IMGUI linked via VCPKG. # Assume that IMGUI linked via VCPKG.
find_package(imgui CONFIG REQUIRED) find_package(imgui CONFIG REQUIRED)
target_link_libraries(omath PUBLIC imgui::imgui) target_link_libraries(omath PUBLIC imgui::imgui)
endif() endif ()
endif() endif ()
if (OMATH_USE_AVX2) if (OMATH_USE_AVX2)
target_compile_definitions(omath PUBLIC OMATH_USE_AVX2) target_compile_definitions(omath PUBLIC OMATH_USE_AVX2)
endif() endif ()
if (OMATH_SUPRESS_SAFETY_CHECKS)
target_compile_definitions(omath PUBLIC OMATH_SUPRESS_SAFETY_CHECKS)
endif ()
set_target_properties(omath PROPERTIES set_target_properties(omath PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}" ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}" LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}"
UNITY_BUILD ON
UNITY_BUILD_BATCH_SIZE 20
CXX_STANDARD 23 CXX_STANDARD 23
CXX_STANDARD_REQUIRED ON) CXX_STANDARD_REQUIRED ON)
if (OMATH_USE_UNITY_BUILD)
set_target_properties(omath PROPERTIES
UNITY_BUILD ON
UNITY_BUILD_BATCH_SIZE 20)
endif ()
if (OMATH_STATIC_MSVC_RUNTIME_LIBRARY) if (OMATH_STATIC_MSVC_RUNTIME_LIBRARY)
set_target_properties(omath PROPERTIES set_target_properties(omath PROPERTIES
MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>" MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>"
) )
endif() endif ()
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
target_compile_options(omath PRIVATE -mavx2 -mfma) target_compile_options(omath PRIVATE -mavx2 -mfma)
endif() endif ()
target_compile_features(omath PUBLIC cxx_std_23) target_compile_features(omath PUBLIC cxx_std_23)
add_subdirectory(source) if (OMATH_BUILD_TESTS)
if(OMATH_BUILD_TESTS)
add_subdirectory(extlibs) add_subdirectory(extlibs)
add_subdirectory(tests) add_subdirectory(tests)
endif() endif ()
if (OMATH_BUILD_EXAMPLES) if (OMATH_BUILD_EXAMPLES)
add_subdirectory(examples) add_subdirectory(examples)
endif() endif ()
if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC" AND OMATH_THREAT_WARNING_AS_ERROR) if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC" AND OMATH_THREAT_WARNING_AS_ERROR)
target_compile_options(omath PRIVATE /W4 /WX) target_compile_options(omath PRIVATE /W4 /WX)
elseif(OMATH_THREAT_WARNING_AS_ERROR) elseif (OMATH_THREAT_WARNING_AS_ERROR)
target_compile_options(omath PRIVATE -Wall -Wextra -Wpedantic -Werror) target_compile_options(omath PRIVATE -Wall -Wextra -Wpedantic -Werror)
endif() endif ()
target_include_directories(omath target_include_directories(omath
PUBLIC PUBLIC

View File

@@ -40,8 +40,8 @@
"binaryDir": "${sourceDir}/cmake-build/build/${presetName}", "binaryDir": "${sourceDir}/cmake-build/build/${presetName}",
"installDir": "${sourceDir}/cmake-build/install/${presetName}", "installDir": "${sourceDir}/cmake-build/install/${presetName}",
"cacheVariables": { "cacheVariables": {
"CMAKE_C_COMPILER": "gcc", "CMAKE_C_COMPILER": "clang",
"CMAKE_CXX_COMPILER": "g++" "CMAKE_CXX_COMPILER": "clang++"
}, },
"condition": { "condition": {
"type": "equals", "type": "equals",

11
CREDITS.md Normal file
View File

@@ -0,0 +1,11 @@
# OMATH CREDITS
Thanks to everyone who made this possible, including:
- Saikari aka luadebug for VCPKG port.
And a big hand to everyone else who has contributed over the past!
THANKS! <3
-- Orange++ <orange-cpp@yandex.ru>

54
INSTALL.md Normal file
View File

@@ -0,0 +1,54 @@
# 📥Installation Guide
## <img width="28px" src="https://vcpkg.io/assets/mark/mark.svg" /> Using vcpkg
**Note**: Support vcpkg for package management
1. Install [vcpkg](https://github.com/microsoft/vcpkg)
2. Run the following command to install the orange-math package:
```
vcpkg install orange-math
```
CMakeLists.txt
```cmake
find_package(omath CONFIG REQUIRED)
target_link_libraries(main PRIVATE omath::omath)
```
For detailed commands on installing different versions and more information, please refer to Microsoft's [official instructions](https://learn.microsoft.com/en-us/vcpkg/get_started/overview).
## <img width="28px" src="https://upload.wikimedia.org/wikipedia/commons/e/ef/CMake_logo.svg?" /> Build from source using CMake
1. **Preparation**
Install needed tools: cmake, clang, git, msvc (windows only).
1. **Linux:**
```bash
sudo pacman -Sy cmake ninja clang git
```
2. **MacOS:**
```bash
brew install llvm git cmake ninja
```
3. **Windows:**
Install Visual Studio from [here](https://visualstudio.microsoft.com/downloads/) and Git from [here](https://git-scm.com/downloads).
Use x64 Native Tools shell to execute needed commands down below.
2. **Clone the repository:**
```bash
git clone https://github.com/orange-cpp/omath.git
```
3. **Navigate to the project directory:**
```bash
cd omath
```
4. **Build the project using CMake:**
```bash
cmake --preset windows-release -S .
cmake --build cmake-build/build/windows-release --target omath -j 6
```
Use **\<platform\>-\<build configuration\>** preset to build siutable version for yourself. Like **windows-release** or **linux-release**.
| Platform Name | Build Config |
|---------------|---------------|
| windows | release/debug |
| linux | release/debug |
| darwin | release/debug |

20
LICENSE
View File

@@ -1,9 +1,17 @@
The MIT License (MIT) Copyright (C) 2024-2025 Orange++ <orange-cpp@yandex.ru>
Copyright (c) 2024 Orange++ This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.

View File

@@ -6,6 +6,7 @@
![GitHub contributors](https://img.shields.io/github/contributors/orange-cpp/omath) ![GitHub contributors](https://img.shields.io/github/contributors/orange-cpp/omath)
![GitHub top language](https://img.shields.io/github/languages/top/orange-cpp/omath) ![GitHub top language](https://img.shields.io/github/languages/top/orange-cpp/omath)
[![CodeFactor](https://www.codefactor.io/repository/github/orange-cpp/omath/badge)](https://www.codefactor.io/repository/github/orange-cpp/omath) [![CodeFactor](https://www.codefactor.io/repository/github/orange-cpp/omath/badge)](https://www.codefactor.io/repository/github/orange-cpp/omath)
![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/orange-cpp/omath/cmake-multi-platform.yml)
![GitHub forks](https://img.shields.io/github/forks/orange-cpp/omath) ![GitHub forks](https://img.shields.io/github/forks/orange-cpp/omath)
</div> </div>
@@ -37,40 +38,9 @@ Oranges's Math Library (omath) is a comprehensive, open-source library aimed at
| Linux | ✅YES | | Linux | ✅YES |
| Darwin (MacOS) | ✅YES | | Darwin (MacOS) | ✅YES |
## ⏬ Getting Started ## ⏬ Installation
### Prerequisites Please read our [installation guide](https://github.com/orange-cpp/omath/blob/main/INSTALL.md). If this link doesn't work check out INSTALL.md file.
- C++ Compiler
- CMake (for building the project)
### Installation
### vcpkg
**Note**: Support vcpkg for package management
1. Install vcpkg (https://github.com/microsoft/vcpkg)
2. Run the following command to install the orange-math package:
```
vcpkg install orange-math
```
CMakeLists.txt
```cmake
find_package(omath CONFIG REQUIRED)
target_link_libraries(main PRIVATE omath::omath)
```
For detailed commands on installing different versions and more information, please refer to Microsoft's official instructions (https://learn.microsoft.com/en-us/vcpkg/get_started/overview)
### Build from source
1. Clone the repository:
```
git clone https://github.com/orange-cpp/omath.git
```
2. Navigate to the project directory:
```
cd omath
```
3. Build the project using CMake:
```
cmake --preset windows-release -S .
cmake --build cmake-build/build/windows-release --target omath -j 6
```
Use **\<platform\>-\<build configuration\>** preset to build siutable version for yourself. Like **windows-release** or **linux-release**.
## ❔ Usage ## ❔ Usage
Simple world to screen function Simple world to screen function
```c++ ```c++
@@ -82,16 +52,17 @@ TEST(UnitTestProjection, IsPointOnScreen)
EXPECT_TRUE(proj.has_value()); EXPECT_TRUE(proj.has_value());
} }
``` ```
## Showcase
<details> <details>
<summary>OMATH for making cheats</summary> <summary>OMATH for making cheats (click to open)</summary>
With `omath/projection` module you can achieve simple ESP hack for powered by Source/Unreal/Unity engine games, like [Apex Legends](https://store.steampowered.com/app/1172470/Apex_Legends/). With `omath/projection` module you can achieve simple ESP hack for powered by Source/Unreal/Unity engine games, like [Apex Legends](https://store.steampowered.com/app/1172470/Apex_Legends/).
![banner](https://i.imgur.com/lcJrfcZ.png) ![banner](https://i.imgur.com/lcJrfcZ.png)
Or for InfinityWard Engine based games. Like Call of Duty Black Ops 2! Or for InfinityWard Engine based games. Like Call of Duty Black Ops 2!
![banner](https://i.imgur.com/F8dmdoo.png) ![banner](https://i.imgur.com/F8dmdoo.png)
Or create simple trigger bot with embeded traceline from omath::collision::LineTrace
![banner](https://i.imgur.com/fxMjRKo.jpeg)
Or even advanced projectile aimbot Or even advanced projectile aimbot
[Watch Video](https://youtu.be/lM_NJ1yCunw?si=5E87OrQMeypxSJ3E) [Watch Video](https://youtu.be/lM_NJ1yCunw?si=5E87OrQMeypxSJ3E)
</details> </details>

View File

@@ -0,0 +1,17 @@
//
// Created by Vlad on 4/18/2025.
//
#pragma once
#include <array>
#include "omath/triangle.hpp"
#include "omath/vector3.hpp"
namespace omath::primitives
{
[[nodiscard]]
std::array<Triangle<Vector3<float>>, 12> create_box(const Vector3<float>& top, const Vector3<float>& bottom,
const Vector3<float>& dir_forward, const Vector3<float>& dir_right,
float ratio = 4.f) noexcept;
}

View File

@@ -7,7 +7,6 @@
#include <algorithm> #include <algorithm>
#include <utility> #include <utility>
namespace omath namespace omath
{ {
enum class AngleFlags enum class AngleFlags
@@ -21,10 +20,10 @@ namespace omath
class Angle class Angle
{ {
Type m_angle; Type m_angle;
constexpr explicit Angle(const Type& degrees) constexpr explicit Angle(const Type& degrees) noexcept
{ {
if constexpr (flags == AngleFlags::Normalized) if constexpr (flags == AngleFlags::Normalized)
m_angle = angles::WrapAngle(degrees, min, max); m_angle = angles::wrap_angle(degrees, min, max);
else if constexpr (flags == AngleFlags::Clamped) else if constexpr (flags == AngleFlags::Clamped)
m_angle = std::clamp(degrees, min, max); m_angle = std::clamp(degrees, min, max);
@@ -34,74 +33,74 @@ namespace omath
std::unreachable(); std::unreachable();
} }
} }
public: public:
[[nodiscard]] [[nodiscard]]
constexpr static Angle FromDegrees(const Type& degrees) constexpr static Angle from_degrees(const Type& degrees) noexcept
{ {
return Angle{degrees}; return Angle{degrees};
} }
constexpr Angle() : m_angle(0) constexpr Angle() noexcept: m_angle(0)
{ {
} }
[[nodiscard]] [[nodiscard]]
constexpr static Angle FromRadians(const Type& degrees) constexpr static Angle from_radians(const Type& degrees) noexcept
{ {
return Angle{angles::RadiansToDegrees<Type>(degrees)}; return Angle{angles::radians_to_degrees<Type>(degrees)};
} }
[[nodiscard]] [[nodiscard]]
constexpr const Type& operator*() const constexpr const Type& operator*() const noexcept
{ {
return m_angle; return m_angle;
} }
[[nodiscard]] [[nodiscard]]
constexpr Type AsDegrees() const constexpr Type as_degrees() const noexcept
{ {
return m_angle; return m_angle;
} }
[[nodiscard]] [[nodiscard]]
constexpr Type AsRadians() const constexpr Type as_radians() const noexcept
{ {
return angles::DegreesToRadians(m_angle); return angles::degrees_to_radians(m_angle);
} }
[[nodiscard]] [[nodiscard]]
Type Sin() const Type sin() const noexcept
{ {
return std::sin(AsRadians()); return std::sin(as_radians());
} }
[[nodiscard]] [[nodiscard]]
Type Cos() const Type cos() const noexcept
{ {
return std::cos(AsRadians()); return std::cos(as_radians());
} }
[[nodiscard]] [[nodiscard]]
Type Tan() const Type tan() const noexcept
{ {
return std::tan(AsRadians()); return std::tan(as_radians());
} }
[[nodiscard]] [[nodiscard]]
Type Atan() const Type atan() const noexcept
{ {
return std::atan(AsRadians()); return std::atan(as_radians());
} }
[[nodiscard]] [[nodiscard]]
Type Cot() const Type cot() const noexcept
{ {
return Cos() / Sin(); return cos() / sin();
} }
constexpr Angle& operator+=(const Angle& other) constexpr Angle& operator+=(const Angle& other) noexcept
{ {
if constexpr (flags == AngleFlags::Normalized) if constexpr (flags == AngleFlags::Normalized)
m_angle = angles::WrapAngle(m_angle + other.m_angle, min, max); m_angle = angles::wrap_angle(m_angle + other.m_angle, min, max);
else if constexpr (flags == AngleFlags::Clamped) else if constexpr (flags == AngleFlags::Clamped)
m_angle = std::clamp(m_angle + other.m_angle, min, max); m_angle = std::clamp(m_angle + other.m_angle, min, max);
@@ -115,18 +114,18 @@ namespace omath
} }
[[nodiscard]] [[nodiscard]]
constexpr std::partial_ordering operator<=>(const Angle& other) const = default; constexpr std::partial_ordering operator<=>(const Angle& other) const noexcept = default;
constexpr Angle& operator-=(const Angle& other) constexpr Angle& operator-=(const Angle& other) noexcept
{ {
return operator+=(-other); return operator+=(-other);
} }
[[nodiscard]] [[nodiscard]]
constexpr Angle& operator+(const Angle& other) constexpr Angle& operator+(const Angle& other) noexcept
{ {
if constexpr (flags == AngleFlags::Normalized) if constexpr (flags == AngleFlags::Normalized)
return {angles::WrapAngle(m_angle + other.m_angle, min, max)}; return {angles::wrap_angle(m_angle + other.m_angle, min, max)};
else if constexpr (flags == AngleFlags::Clamped) else if constexpr (flags == AngleFlags::Clamped)
return {std::clamp(m_angle + other.m_angle, min, max)}; return {std::clamp(m_angle + other.m_angle, min, max)};
@@ -138,15 +137,15 @@ namespace omath
} }
[[nodiscard]] [[nodiscard]]
constexpr Angle& operator-(const Angle& other) constexpr Angle& operator-(const Angle& other) noexcept
{ {
return operator+(-other); return operator+(-other);
} }
[[nodiscard]] [[nodiscard]]
constexpr Angle operator-() const constexpr Angle operator-() const noexcept
{ {
return Angle{-m_angle}; return Angle{-m_angle};
} }
}; };
} } // namespace omath

View File

@@ -10,54 +10,55 @@ namespace omath::angles
{ {
template<class Type> template<class Type>
requires std::is_floating_point_v<Type> requires std::is_floating_point_v<Type>
[[nodiscard]] constexpr Type RadiansToDegrees(const Type& radians) [[nodiscard]] constexpr Type radians_to_degrees(const Type& radians) noexcept
{ {
return radians * (Type(180) / std::numbers::pi_v<Type>); return radians * (static_cast<Type>(180) / std::numbers::pi_v<Type>);
} }
template<class Type> template<class Type>
requires std::is_floating_point_v<Type> requires std::is_floating_point_v<Type>
[[nodiscard]] constexpr Type DegreesToRadians(const Type& degrees) [[nodiscard]] constexpr Type degrees_to_radians(const Type& degrees) noexcept
{ {
return degrees * (std::numbers::pi_v<Type> / Type(180)); return degrees * (std::numbers::pi_v<Type> / static_cast<Type>(180));
}
template<class type>
requires std::is_floating_point_v<type>
[[nodiscard]] type HorizontalFovToVertical(const type& horFov, const type& aspect)
{
const auto fovRad = DegreesToRadians(horFov);
const auto vertFov = type(2) * std::atan(std::tan(fovRad / type(2)) / aspect);
return RadiansToDegrees(vertFov);
} }
template<class Type> template<class Type>
requires std::is_floating_point_v<Type> requires std::is_floating_point_v<Type>
[[nodiscard]] Type VerticalFovToHorizontal(const Type& vertFov, const Type& aspect) [[nodiscard]] Type horizontal_fov_to_vertical(const Type& horizontal_fov, const Type& aspect) noexcept
{ {
const auto fovRad = DegreesToRadians(vertFov); const auto fov_rad = degrees_to_radians(horizontal_fov);
const auto horFov = Type(2) * std::atan(std::tan(fovRad / Type(2)) * aspect); const auto vert_fov = static_cast<Type>(2) * std::atan(std::tan(fov_rad / static_cast<Type>(2)) / aspect);
return RadiansToDegrees(horFov); return radians_to_degrees(vert_fov);
}
template<class Type>
requires std::is_floating_point_v<Type>
[[nodiscard]] Type vertical_fov_to_horizontal(const Type& vertical_fov, const Type& aspect) noexcept
{
const auto fov_as_radians = degrees_to_radians(vertical_fov);
const auto horizontal_fov =
static_cast<Type>(2) * std::atan(std::tan(fov_as_radians / static_cast<Type>(2)) * aspect);
return radians_to_degrees(horizontal_fov);
} }
template<class Type> template<class Type>
requires std::is_arithmetic_v<Type> requires std::is_arithmetic_v<Type>
[[nodiscard]] Type WrapAngle(const Type& angle, const Type& min, const Type& max) [[nodiscard]] Type wrap_angle(const Type& angle, const Type& min, const Type& max) noexcept
{ {
if (angle <= max && angle >= min) if (angle <= max && angle >= min)
return angle; return angle;
const Type range = max - min; const Type range = max - min;
Type wrappedAngle = std::fmod(angle - min, range); Type wrapped_angle = std::fmod(angle - min, range);
if (wrappedAngle < 0) if (wrapped_angle < 0)
wrappedAngle += range; wrapped_angle += range;
return wrappedAngle + min; return wrapped_angle + min;
} }
} } // namespace omath::angles

View File

@@ -13,26 +13,25 @@ namespace omath::collision
public: public:
Vector3<float> start; Vector3<float> start;
Vector3<float> end; Vector3<float> end;
bool infinite_length = false;
[[nodiscard]] [[nodiscard]]
Vector3<float> DirectionVector() const; Vector3<float> direction_vector() const noexcept;
[[nodiscard]] [[nodiscard]]
Vector3<float> DirectionVectorNormalized() const; Vector3<float> direction_vector_normalized() const noexcept;
}; };
class LineTracer class LineTracer
{ {
public: public:
LineTracer() = delete; LineTracer() = delete;
[[nodiscard]] [[nodiscard]]
static bool CanTraceLine(const Ray& ray, const Triangle<Vector3<float>>& triangle); static bool can_trace_line(const Ray& ray, const Triangle<Vector3<float>>& triangle) noexcept;
// Realization of MöllerTrumbore intersection algorithm // Realization of MöllerTrumbore intersection algorithm
// https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm // https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm
[[nodiscard]] [[nodiscard]]
static Vector3<float> GetRayHitPoint(const Ray& ray, const Triangle<Vector3<float>>& triangle); static Vector3<float> get_ray_hit_point(const Ray& ray, const Triangle<Vector3<float>>& triangle) noexcept;
}; };
} } // namespace omath::collision

View File

@@ -4,95 +4,93 @@
#pragma once #pragma once
#include <cstdint>
#include "omath/vector3.hpp" #include "omath/vector3.hpp"
#include "omath/vector4.hpp" #include "omath/vector4.hpp"
#include <cstdint>
#ifdef max #ifdef max
#undef max #undef max
#endif #endif
#ifdef min #ifdef min
#undef min #undef min
#endif #endif
namespace omath namespace omath
{ {
struct HSV struct Hsv
{ {
float hue{}; float hue{};
float saturation{}; float saturation{};
float value{}; float value{};
}; };
class Color final : public Vector4<float> class Color final : public Vector4<float>
{ {
public: public:
constexpr Color(const float r, const float g, const float b, const float a) : Vector4(r, g, b, a) constexpr Color(const float r, const float g, const float b, const float a) noexcept: Vector4(r, g, b, a)
{ {
Clamp(0.f, 1.f); clamp(0.f, 1.f);
} }
constexpr explicit Color() = default; constexpr explicit Color() noexcept = default;
[[nodiscard]] [[nodiscard]]
constexpr static Color FromRGBA(const uint8_t r, const uint8_t g, const uint8_t b, const uint8_t a) constexpr static Color from_rgba(const uint8_t r, const uint8_t g, const uint8_t b, const uint8_t a) noexcept
{ {
return Color{Vector4(r, g, b, a) / 255.f}; return Color{Vector4(r, g, b, a) / 255.f};
} }
[[nodiscard]] [[nodiscard]]
constexpr static Color FromHSV(float hue, const float saturation, const float value) constexpr static Color from_hsv(float hue, const float saturation, const float value) noexcept
{ {
float r{}, g{}, b{}; float r{}, g{}, b{};
hue = std::clamp(hue, 0.f, 1.f); hue = std::clamp(hue, 0.f, 1.f);
const int i = static_cast<int>(hue * 6.f); const int i = static_cast<int>(hue * 6.f);
const float f = hue * 6 - i; const float f = hue * 6.f - static_cast<float>(i);
const float p = value * (1 - saturation); const float p = value * (1 - saturation);
const float q = value * (1 - f * saturation); const float q = value * (1 - f * saturation);
const float t = value * (1 - (1 - f) * saturation); const float t = value * (1 - (1 - f) * saturation);
switch (i % 6) switch (i % 6)
{ {
case 0: case 0:
r = value, g = t, b = p; r = value, g = t, b = p;
break; break;
case 1: case 1:
r = q, g = value, b = p; r = q, g = value, b = p;
break; break;
case 2: case 2:
r = p, g = value, b = t; r = p, g = value, b = t;
break; break;
case 3: case 3:
r = p, g = q, b = value; r = p, g = q, b = value;
break; break;
case 4: case 4:
r = t, g = p, b = value; r = t, g = p, b = value;
break; break;
case 5: case 5:
r = value, g = p, b = q; r = value, g = p, b = q;
break; break;
default: default:
return {0.f, 0.f, 0.f, 0.f}; return {0.f, 0.f, 0.f, 0.f};
} }
return {r, g, b, 1.f}; return {r, g, b, 1.f};
} }
[[nodiscard]] [[nodiscard]]
constexpr static Color FromHSV(const HSV& hsv) constexpr static Color from_hsv(const Hsv& hsv) noexcept
{ {
return FromHSV(hsv.hue, hsv.saturation, hsv.value); return from_hsv(hsv.hue, hsv.saturation, hsv.value);
} }
[[nodiscard]] [[nodiscard]]
constexpr HSV ToHSV() const constexpr Hsv to_hsv() const noexcept
{ {
HSV hsvData; Hsv hsv_data;
const float& red = x; const float& red = x;
const float& green = y; const float& green = y;
@@ -102,70 +100,69 @@ namespace omath
const float min = std::min({red, green, blue}); const float min = std::min({red, green, blue});
const float delta = max - min; const float delta = max - min;
if (delta == 0.f) if (delta == 0.f)
hsvData.hue = 0.f; hsv_data.hue = 0.f;
else if (max == red) else if (max == red)
hsvData.hue = 60.f * (std::fmodf(((green - blue) / delta), 6.f)); hsv_data.hue = 60.f * (std::fmodf(((green - blue) / delta), 6.f));
else if (max == green) else if (max == green)
hsvData.hue = 60.f * (((blue - red) / delta) + 2.f); hsv_data.hue = 60.f * (((blue - red) / delta) + 2.f);
else if (max == blue) else if (max == blue)
hsvData.hue = 60.f * (((red - green) / delta) + 4.f); hsv_data.hue = 60.f * (((red - green) / delta) + 4.f);
if (hsvData.hue < 0.f) if (hsv_data.hue < 0.f)
hsvData.hue += 360.f; hsv_data.hue += 360.f;
hsvData.hue /= 360.f; hsv_data.hue /= 360.f;
hsvData.saturation = max == 0.f ? 0.f : delta / max; hsv_data.saturation = max == 0.f ? 0.f : delta / max;
hsvData.value = max; hsv_data.value = max;
return hsvData; return hsv_data;
} }
constexpr explicit Color(const Vector4& vec) : Vector4(vec) constexpr explicit Color(const Vector4& vec) noexcept: Vector4(vec)
{ {
Clamp(0.f, 1.f); clamp(0.f, 1.f);
} }
constexpr void SetHue(const float hue) constexpr void set_hue(const float hue) noexcept
{ {
auto hsv = ToHSV(); auto hsv = to_hsv();
hsv.hue = hue; hsv.hue = hue;
*this = FromHSV(hsv); *this = from_hsv(hsv);
} }
constexpr void SetSaturation(const float saturation) constexpr void set_saturation(const float saturation) noexcept
{ {
auto hsv = ToHSV(); auto hsv = to_hsv();
hsv.saturation = saturation; hsv.saturation = saturation;
*this = FromHSV(hsv); *this = from_hsv(hsv);
} }
constexpr void SetValue(const float value) constexpr void set_value(const float value) noexcept
{ {
auto hsv = ToHSV(); auto hsv = to_hsv();
hsv.value = value; hsv.value = value;
*this = FromHSV(hsv); *this = from_hsv(hsv);
} }
[[nodiscard]] [[nodiscard]]
constexpr Color Blend(const Color& other, float ratio) const constexpr Color blend(const Color& other, float ratio) const noexcept
{ {
ratio = std::clamp(ratio, 0.f, 1.f); ratio = std::clamp(ratio, 0.f, 1.f);
return Color(*this * (1.f - ratio) + other * ratio); return Color(*this * (1.f - ratio) + other * ratio);
} }
[[nodiscard]] static constexpr Color Red() [[nodiscard]] static constexpr Color red()
{ {
return {1.f, 0.f, 0.f, 1.f}; return {1.f, 0.f, 0.f, 1.f};
} }
[[nodiscard]] static constexpr Color Green() [[nodiscard]] static constexpr Color green()
{ {
return {0.f, 1.f, 0.f, 1.f}; return {0.f, 1.f, 0.f, 1.f};
} }
[[nodiscard]] static constexpr Color Blue() [[nodiscard]] static constexpr Color blue()
{ {
return {0.f, 0.f, 1.f, 1.f}; return {0.f, 0.f, 1.f, 1.f};
} }

View File

@@ -8,14 +8,15 @@
namespace omath::iw_engine namespace omath::iw_engine
{ {
class Camera final : public projection::Camera<Mat4x4, ViewAngles> class Camera final : public projection::Camera<Mat4X4, ViewAngles>
{ {
public: public:
Camera(const Vector3<float>& position, const ViewAngles& viewAngles, const projection::ViewPort& viewPort, Camera(const Vector3<float>& position, const ViewAngles& view_angles, const projection::ViewPort& view_port,
const Angle<float, 0.f, 180.f, AngleFlags::Clamped>& fov, float near, float far); const Angle<float, 0.f, 180.f, AngleFlags::Clamped>& fov, float near, float far);
void LookAt(const Vector3<float>& target) override; void look_at(const Vector3<float>& target) override;
protected: protected:
[[nodiscard]] Mat4x4 CalcViewMatrix() const override; [[nodiscard]] Mat4X4 calc_view_matrix() const noexcept override;
[[nodiscard]] Mat4x4 CalcProjectionMatrix() const override; [[nodiscard]] Mat4X4 calc_projection_matrix() const noexcept override;
}; };
} } // namespace omath::iw_engine

View File

@@ -3,23 +3,23 @@
// //
#pragma once #pragma once
#include <omath/vector3.hpp>
#include <omath/mat.hpp>
#include <omath/angle.hpp> #include <omath/angle.hpp>
#include <omath/mat.hpp>
#include <omath/vector3.hpp>
#include <omath/view_angles.hpp> #include <omath/view_angles.hpp>
namespace omath::iw_engine namespace omath::iw_engine
{ {
constexpr Vector3<float> kAbsUp = {0, 0, 1}; constexpr Vector3<float> k_abs_up = {0, 0, 1};
constexpr Vector3<float> kAbsRight = {0, -1, 0}; constexpr Vector3<float> k_abs_right = {0, -1, 0};
constexpr Vector3<float> kAbsForward = {1, 0, 0}; constexpr Vector3<float> k_abs_forward = {1, 0, 0};
using Mat4x4 = Mat<4, 4, float, MatStoreType::ROW_MAJOR>; using Mat4X4 = Mat<4, 4, float, MatStoreType::ROW_MAJOR>;
using Mat3x3 = Mat<4, 4, float, MatStoreType::ROW_MAJOR>; using Mat3X3 = Mat<4, 4, float, MatStoreType::ROW_MAJOR>;
using Mat1x3 = Mat<1, 3, float, MatStoreType::ROW_MAJOR>; using Mat1X3 = Mat<1, 3, float, MatStoreType::ROW_MAJOR>;
using PitchAngle = Angle<float, -89.f, 89.f, AngleFlags::Clamped>; using PitchAngle = Angle<float, -89.f, 89.f, AngleFlags::Clamped>;
using YawAngle = Angle<float, -180.f, 180.f, AngleFlags::Normalized>; using YawAngle = Angle<float, -180.f, 180.f, AngleFlags::Normalized>;
using RollAngle = Angle<float, -180.f, 180.f, AngleFlags::Normalized>; using RollAngle = Angle<float, -180.f, 180.f, AngleFlags::Normalized>;
using ViewAngles = omath::ViewAngles<PitchAngle, YawAngle, RollAngle>; using ViewAngles = omath::ViewAngles<PitchAngle, YawAngle, RollAngle>;
} } // namespace omath::iw_engine

View File

@@ -8,17 +8,19 @@
namespace omath::iw_engine namespace omath::iw_engine
{ {
[[nodiscard]] [[nodiscard]]
Vector3<float> ForwardVector(const ViewAngles& angles); Vector3<float> forward_vector(const ViewAngles& angles) noexcept;
[[nodiscard]] [[nodiscard]]
Vector3<float> RightVector(const ViewAngles& angles); Vector3<float> right_vector(const ViewAngles& angles) noexcept;
[[nodiscard]] [[nodiscard]]
Vector3<float> UpVector(const ViewAngles& angles); Vector3<float> up_vector(const ViewAngles& angles) noexcept;
[[nodiscard]] Mat4x4 CalcViewMatrix(const ViewAngles& angles, const Vector3<float>& cam_origin);
[[nodiscard]] [[nodiscard]]
Mat4x4 CalcPerspectiveProjectionMatrix(float fieldOfView, float aspectRatio, float near, float far); Mat4X4 rotation_matrix(const ViewAngles& angles) noexcept;
[[nodiscard]] Mat4X4 calc_view_matrix(const ViewAngles& angles, const Vector3<float>& cam_origin) noexcept;
[[nodiscard]]
Mat4X4 calc_perspective_projection_matrix(float field_of_view, float aspect_ratio, float near, float far) noexcept;
} // namespace omath::iw_engine } // namespace omath::iw_engine

View File

@@ -7,13 +7,13 @@
namespace omath::opengl_engine namespace omath::opengl_engine
{ {
class Camera final : public projection::Camera<Mat4x4, ViewAngles> class Camera final : public projection::Camera<Mat4X4, ViewAngles>
{ {
public: public:
Camera(const Vector3<float>& position, const ViewAngles& viewAngles, const projection::ViewPort& viewPort, Camera(const Vector3<float>& position, const ViewAngles& view_angles, const projection::ViewPort& view_port,
const Angle<float, 0.f, 180.f, AngleFlags::Clamped>& fov, float near, float far); const Angle<float, 0.f, 180.f, AngleFlags::Clamped>& fov, float near, float far);
void LookAt(const Vector3<float>& target) override; void look_at(const Vector3<float>& target) override;
[[nodiscard]] Mat4x4 CalcViewMatrix() const override; [[nodiscard]] Mat4X4 calc_view_matrix() const noexcept override;
[[nodiscard]] Mat4x4 CalcProjectionMatrix() const override; [[nodiscard]] Mat4X4 calc_projection_matrix() const noexcept override;
}; };
} } // namespace omath::opengl_engine

View File

@@ -10,16 +10,16 @@
namespace omath::opengl_engine namespace omath::opengl_engine
{ {
constexpr Vector3<float> kAbsUp = {0, 1, 0}; constexpr Vector3<float> k_abs_up = {0, 1, 0};
constexpr Vector3<float> kAbsRight = {1, 0, 0}; constexpr Vector3<float> k_abs_right = {1, 0, 0};
constexpr Vector3<float> kAbsForward = {0, 0, -1}; constexpr Vector3<float> k_abs_forward = {0, 0, -1};
using Mat4x4 = Mat<4, 4, float, MatStoreType::COLUMN_MAJOR>; using Mat4X4 = Mat<4, 4, float, MatStoreType::COLUMN_MAJOR>;
using Mat3x3 = Mat<4, 4, float, MatStoreType::COLUMN_MAJOR>; using Mat3X3 = Mat<4, 4, float, MatStoreType::COLUMN_MAJOR>;
using Mat1x3 = Mat<1, 3, float, MatStoreType::COLUMN_MAJOR>; using Mat1X3 = Mat<1, 3, float, MatStoreType::COLUMN_MAJOR>;
using PitchAngle = Angle<float, 0.f, 180.f, AngleFlags::Clamped>; using PitchAngle = Angle<float, -90.f, 90.f, AngleFlags::Clamped>;
using YawAngle = Angle<float, 0.f, 360.f, AngleFlags::Normalized>; using YawAngle = Angle<float, -180.f, 180.f, AngleFlags::Normalized>;
using RollAngle = Angle<float, 0.f, 360.f, AngleFlags::Normalized>; using RollAngle = Angle<float, -180.f, 180.f, AngleFlags::Normalized>;
using ViewAngles = omath::ViewAngles<PitchAngle, YawAngle, RollAngle>; using ViewAngles = omath::ViewAngles<PitchAngle, YawAngle, RollAngle>;
} } // namespace omath::opengl_engine

View File

@@ -8,17 +8,19 @@
namespace omath::opengl_engine namespace omath::opengl_engine
{ {
[[nodiscard]] [[nodiscard]]
Vector3<float> ForwardVector(const ViewAngles& angles); Vector3<float> forward_vector(const ViewAngles& angles) noexcept;
[[nodiscard]] [[nodiscard]]
Vector3<float> RightVector(const ViewAngles& angles); Vector3<float> right_vector(const ViewAngles& angles) noexcept;
[[nodiscard]] [[nodiscard]]
Vector3<float> UpVector(const ViewAngles& angles); Vector3<float> up_vector(const ViewAngles& angles) noexcept;
[[nodiscard]] Mat4x4 CalcViewMatrix(const ViewAngles& angles, const Vector3<float>& cam_origin);
[[nodiscard]] Mat4X4 calc_view_matrix(const ViewAngles& angles, const Vector3<float>& cam_origin) noexcept;
[[nodiscard]] [[nodiscard]]
Mat4x4 CalcPerspectiveProjectionMatrix(float fieldOfView, float aspectRatio, float near, float far); Mat4X4 rotation_matrix(const ViewAngles& angles) noexcept;
[[nodiscard]]
Mat4X4 calc_perspective_projection_matrix(float field_of_view, float aspect_ratio, float near, float far) noexcept;
} // namespace omath::opengl_engine } // namespace omath::opengl_engine

View File

@@ -7,14 +7,15 @@
namespace omath::source_engine namespace omath::source_engine
{ {
class Camera final : public projection::Camera<Mat4x4, ViewAngles> class Camera final : public projection::Camera<Mat4X4, ViewAngles>
{ {
public: public:
Camera(const Vector3<float>& position, const ViewAngles& viewAngles, const projection::ViewPort& viewPort, Camera(const Vector3<float>& position, const ViewAngles& view_angles, const projection::ViewPort& view_port,
const Angle<float, 0.f, 180.f, AngleFlags::Clamped>& fov, float near, float far); const Angle<float, 0.f, 180.f, AngleFlags::Clamped>& fov, float near, float far);
void LookAt(const Vector3<float>& target) override; void look_at(const Vector3<float>& target) override;
protected: protected:
[[nodiscard]] Mat4x4 CalcViewMatrix() const override; [[nodiscard]] Mat4X4 calc_view_matrix() const noexcept override;
[[nodiscard]] Mat4x4 CalcProjectionMatrix() const override; [[nodiscard]] Mat4X4 calc_projection_matrix() const noexcept override;
}; };
} } // namespace omath::source_engine

View File

@@ -3,23 +3,23 @@
// //
#pragma once #pragma once
#include <omath/vector3.hpp>
#include <omath/mat.hpp>
#include <omath/angle.hpp> #include <omath/angle.hpp>
#include <omath/mat.hpp>
#include <omath/vector3.hpp>
#include <omath/view_angles.hpp> #include <omath/view_angles.hpp>
namespace omath::source_engine namespace omath::source_engine
{ {
constexpr Vector3<float> kAbsUp = {0, 0, 1}; constexpr Vector3<float> k_abs_up = {0, 0, 1};
constexpr Vector3<float> kAbsRight = {0, -1, 0}; constexpr Vector3<float> k_abs_right = {0, -1, 0};
constexpr Vector3<float> kAbsForward = {1, 0, 0}; constexpr Vector3<float> k_abs_forward = {1, 0, 0};
using Mat4x4 = Mat<4, 4, float, MatStoreType::ROW_MAJOR>; using Mat4X4 = Mat<4, 4, float, MatStoreType::ROW_MAJOR>;
using Mat3x3 = Mat<4, 4, float, MatStoreType::ROW_MAJOR>; using Mat3X3 = Mat<4, 4, float, MatStoreType::ROW_MAJOR>;
using Mat1x3 = Mat<1, 3, float, MatStoreType::ROW_MAJOR>; using Mat1X3 = Mat<1, 3, float, MatStoreType::ROW_MAJOR>;
using PitchAngle = Angle<float, -89.f, 89.f, AngleFlags::Clamped>; using PitchAngle = Angle<float, -89.f, 89.f, AngleFlags::Clamped>;
using YawAngle = Angle<float, -180.f, 180.f, AngleFlags::Normalized>; using YawAngle = Angle<float, -180.f, 180.f, AngleFlags::Normalized>;
using RollAngle = Angle<float, -180.f, 180.f, AngleFlags::Normalized>; using RollAngle = Angle<float, -180.f, 180.f, AngleFlags::Normalized>;
using ViewAngles = omath::ViewAngles<PitchAngle, YawAngle, RollAngle>; using ViewAngles = omath::ViewAngles<PitchAngle, YawAngle, RollAngle>;
} // namespace omath::source } // namespace omath::source_engine

View File

@@ -7,17 +7,19 @@
namespace omath::source_engine namespace omath::source_engine
{ {
[[nodiscard]] [[nodiscard]]
Vector3<float> ForwardVector(const ViewAngles& angles); Vector3<float> forward_vector(const ViewAngles& angles) noexcept;
[[nodiscard]] [[nodiscard]]
Vector3<float> RightVector(const ViewAngles& angles); Mat4X4 rotation_matrix(const ViewAngles& angles) noexcept;
[[nodiscard]] [[nodiscard]]
Vector3<float> UpVector(const ViewAngles& angles); Vector3<float> right_vector(const ViewAngles& angles) noexcept;
[[nodiscard]] Mat4x4 CalcViewMatrix(const ViewAngles& angles, const Vector3<float>& cam_origin);
[[nodiscard]] [[nodiscard]]
Mat4x4 CalcPerspectiveProjectionMatrix(float fieldOfView, float aspectRatio, float near, float far); Vector3<float> up_vector(const ViewAngles& angles) noexcept;
} // namespace omath::source
[[nodiscard]] Mat4X4 calc_view_matrix(const ViewAngles& angles, const Vector3<float>& cam_origin) noexcept;
[[nodiscard]]
Mat4X4 calc_perspective_projection_matrix(float field_of_view, float aspect_ratio, float near, float far) noexcept;
} // namespace omath::source_engine

View File

@@ -8,14 +8,15 @@
namespace omath::unity_engine namespace omath::unity_engine
{ {
class Camera final : public projection::Camera<Mat4x4, ViewAngles> class Camera final : public projection::Camera<Mat4X4, ViewAngles>
{ {
public: public:
Camera(const Vector3<float>& position, const ViewAngles& viewAngles, const projection::ViewPort& viewPort, Camera(const Vector3<float>& position, const ViewAngles& view_angles, const projection::ViewPort& view_port,
const Angle<float, 0.f, 180.f, AngleFlags::Clamped>& fov, float near, float far); const Angle<float, 0.f, 180.f, AngleFlags::Clamped>& fov, float near, float far);
void LookAt(const Vector3<float>& target) override; void look_at(const Vector3<float>& target) override;
protected: protected:
[[nodiscard]] Mat4x4 CalcViewMatrix() const override; [[nodiscard]] Mat4X4 calc_view_matrix() const noexcept override;
[[nodiscard]] Mat4x4 CalcProjectionMatrix() const override; [[nodiscard]] Mat4X4 calc_projection_matrix() const noexcept override;
}; };
} } // namespace omath::unity_engine

View File

@@ -4,23 +4,23 @@
#pragma once #pragma once
#include <omath/vector3.hpp>
#include <omath/mat.hpp>
#include <omath/angle.hpp> #include <omath/angle.hpp>
#include <omath/mat.hpp>
#include <omath/vector3.hpp>
#include <omath/view_angles.hpp> #include <omath/view_angles.hpp>
namespace omath::unity_engine namespace omath::unity_engine
{ {
constexpr Vector3<float> kAbsUp = {0, 1, 0}; constexpr Vector3<float> k_abs_up = {0, 1, 0};
constexpr Vector3<float> kAbsRight = {1, 0, 0}; constexpr Vector3<float> k_abs_right = {1, 0, 0};
constexpr Vector3<float> kAbsForward = {0, 0, 1}; constexpr Vector3<float> k_abs_forward = {0, 0, 1};
using Mat4x4 = Mat<4, 4, float, MatStoreType::ROW_MAJOR>; using Mat4X4 = Mat<4, 4, float, MatStoreType::ROW_MAJOR>;
using Mat3x3 = Mat<4, 4, float, MatStoreType::ROW_MAJOR>; using Mat3X3 = Mat<4, 4, float, MatStoreType::ROW_MAJOR>;
using Mat1x3 = Mat<1, 3, float, MatStoreType::ROW_MAJOR>; using Mat1X3 = Mat<1, 3, float, MatStoreType::ROW_MAJOR>;
using PitchAngle = Angle<float, -89.f, 89.f, AngleFlags::Clamped>; using PitchAngle = Angle<float, -90.f, 90.f, AngleFlags::Clamped>;
using YawAngle = Angle<float, -180.f, 180.f, AngleFlags::Normalized>; using YawAngle = Angle<float, -180.f, 180.f, AngleFlags::Normalized>;
using RollAngle = Angle<float, -180.f, 180.f, AngleFlags::Normalized>; using RollAngle = Angle<float, -180.f, 180.f, AngleFlags::Normalized>;
using ViewAngles = omath::ViewAngles<PitchAngle, YawAngle, RollAngle>; using ViewAngles = omath::ViewAngles<PitchAngle, YawAngle, RollAngle>;
} // namespace omath::source } // namespace omath::unity_engine

View File

@@ -8,17 +8,19 @@
namespace omath::unity_engine namespace omath::unity_engine
{ {
[[nodiscard]] [[nodiscard]]
Vector3<float> ForwardVector(const ViewAngles& angles); Vector3<float> forward_vector(const ViewAngles& angles) noexcept;
[[nodiscard]] [[nodiscard]]
Vector3<float> RightVector(const ViewAngles& angles); Vector3<float> right_vector(const ViewAngles& angles) noexcept;
[[nodiscard]] [[nodiscard]]
Vector3<float> UpVector(const ViewAngles& angles); Vector3<float> up_vector(const ViewAngles& angles) noexcept;
[[nodiscard]] Mat4x4 CalcViewMatrix(const ViewAngles& angles, const Vector3<float>& cam_origin);
[[nodiscard]] Mat4X4 calc_view_matrix(const ViewAngles& angles, const Vector3<float>& cam_origin) noexcept;
[[nodiscard]] [[nodiscard]]
Mat4x4 CalcPerspectiveProjectionMatrix(float fieldOfView, float aspectRatio, float near, float far); Mat4X4 rotation_matrix(const ViewAngles& angles) noexcept;
} // namespace omath::source
[[nodiscard]]
Mat4X4 calc_perspective_projection_matrix(float field_of_view, float aspect_ratio, float near, float far) noexcept;
} // namespace omath::unity_engine

View File

@@ -2,20 +2,19 @@
// Created by vlad on 9/29/2024. // Created by vlad on 9/29/2024.
// //
#pragma once #pragma once
#include "omath/vector3.hpp"
#include <algorithm> #include <algorithm>
#include <array> #include <array>
#include <iomanip> #include <iomanip>
#include <numeric>
#include <sstream> #include <sstream>
#include <stdexcept> #include <stdexcept>
#include <utility> #include <utility>
#include "omath/vector3.hpp"
#ifdef near #ifdef near
#undef near #undef near
#endif #endif
#ifdef far #ifdef far
#undef far #undef far
#endif #endif
@@ -33,25 +32,22 @@ namespace omath
COLUMN_MAJOR COLUMN_MAJOR
}; };
template<typename M1, typename M2> concept MatTemplateEqual
template<typename M1, typename M2> = (M1::rows == M2::rows) && (M1::columns == M2::columns)
concept MatTemplateEqual = && std::is_same_v<typename M1::value_type, typename M2::value_type> && (M1::store_type == M2::store_type);
(M1::rows == M2::rows) && (M1::columns == M2::columns) &&
std::is_same_v<typename M1::value_type, typename M2::value_type> &&
(M1::store_type == M2::store_type);
template<size_t Rows = 0, size_t Columns = 0, class Type = float, MatStoreType StoreType = MatStoreType::ROW_MAJOR> template<size_t Rows = 0, size_t Columns = 0, class Type = float, MatStoreType StoreType = MatStoreType::ROW_MAJOR>
requires std::is_arithmetic_v<Type> requires std::is_arithmetic_v<Type>
class Mat final class Mat final
{ {
public: public:
constexpr Mat() noexcept constexpr Mat() noexcept
{ {
Clear(); clear();
} }
[[nodiscard]] [[nodiscard]]
constexpr static MatStoreType GetStoreOrdering() noexcept constexpr static MatStoreType get_store_ordering() noexcept
{ {
return StoreType; return StoreType;
} }
@@ -60,24 +56,24 @@ namespace omath
if (rows.size() != Rows) if (rows.size() != Rows)
throw std::invalid_argument("Initializer list rows size does not match template parameter Rows"); throw std::invalid_argument("Initializer list rows size does not match template parameter Rows");
auto rowIt = rows.begin(); auto row_it = rows.begin();
for (size_t i = 0; i < Rows; ++i, ++rowIt) for (size_t i = 0; i < Rows; ++i, ++row_it)
{ {
if (rowIt->size() != Columns) if (row_it->size() != Columns)
throw std::invalid_argument( throw std::invalid_argument(
"All rows must have the same number of columns as template parameter Columns"); "All rows must have the same number of columns as template parameter Columns");
auto colIt = rowIt->begin(); auto col_it = row_it->begin();
for (size_t j = 0; j < Columns; ++j, ++colIt) for (size_t j = 0; j < Columns; ++j, ++col_it)
{ {
At(i, j) = std::move(*colIt); at(i, j) = std::move(*col_it);
} }
} }
} }
constexpr explicit Mat(const Type* rawData) constexpr explicit Mat(const Type* raw_data)
{ {
std::copy_n(rawData, Rows * Columns, m_data.begin()); std::copy_n(raw_data, Rows * Columns, m_data.begin());
} }
constexpr Mat(const Mat& other) noexcept constexpr Mat(const Mat& other) noexcept
@@ -88,7 +84,13 @@ namespace omath
[[nodiscard]] [[nodiscard]]
constexpr Type& operator[](const size_t row, const size_t col) constexpr Type& operator[](const size_t row, const size_t col)
{ {
return At(row, col); return at(row, col);
}
[[nodiscard]]
constexpr Type& operator[](const size_t row, const size_t col) const
{
return at(row, col);
} }
constexpr Mat(Mat&& other) noexcept constexpr Mat(Mat&& other) noexcept
@@ -97,34 +99,35 @@ namespace omath
} }
[[nodiscard]] [[nodiscard]]
static constexpr size_t RowCount() noexcept static constexpr size_t row_count() noexcept
{ {
return Rows; return Rows;
} }
[[nodiscard]] [[nodiscard]]
static constexpr size_t ColumnsCount() noexcept static constexpr size_t columns_count() noexcept
{ {
return Columns; return Columns;
} }
[[nodiscard]] [[nodiscard]]
static consteval MatSize Size() noexcept static consteval MatSize size() noexcept
{ {
return {Rows, Columns}; return {Rows, Columns};
} }
[[nodiscard]] [[nodiscard]]
constexpr const Type& At(const size_t rowIndex, const size_t columnIndex) const constexpr const Type& at(const size_t row_index, const size_t column_index) const
{ {
if (rowIndex >= Rows || columnIndex >= Columns) #if !defined(NDEBUG) && defined(OMATH_SUPRESS_SAFETY_CHECKS)
if (row_index >= Rows || column_index >= Columns)
throw std::out_of_range("Index out of range"); throw std::out_of_range("Index out of range");
#endif
if constexpr (StoreType == MatStoreType::ROW_MAJOR) if constexpr (StoreType == MatStoreType::ROW_MAJOR)
return m_data[rowIndex * Columns + columnIndex]; return m_data[row_index * Columns + column_index];
else if constexpr (StoreType == MatStoreType::COLUMN_MAJOR) else if constexpr (StoreType == MatStoreType::COLUMN_MAJOR)
return m_data[rowIndex + columnIndex * Rows]; return m_data[row_index + column_index * Rows];
else else
{ {
@@ -133,34 +136,29 @@ namespace omath
} }
} }
[[nodiscard]] constexpr Type& At(const size_t rowIndex, const size_t columnIndex) [[nodiscard]] constexpr Type& at(const size_t row_index, const size_t column_index)
{ {
return const_cast<Type&>(std::as_const(*this).At(rowIndex, columnIndex)); return const_cast<Type&>(std::as_const(*this).at(row_index, column_index));
} }
[[nodiscard]] [[nodiscard]]
constexpr Type Sum() const noexcept constexpr Type sum() const noexcept
{ {
Type sum = 0; return std::accumulate(m_data.begin(), m_data.end(), static_cast<Type>(0));
for (size_t i = 0; i < Rows; ++i)
for (size_t j = 0; j < Columns; ++j)
sum += At(i, j);
return sum;
} }
constexpr void Clear() noexcept constexpr void clear() noexcept
{ {
Set(0); set(static_cast<Type>(0));
} }
constexpr void Set(const Type& value) noexcept constexpr void set(const Type& value) noexcept
{ {
std::ranges::fill(m_data, value); std::ranges::fill(m_data, value);
} }
// Operator overloading for multiplication with another Mat // Operator overloading for multiplication with another Mat
template<size_t OtherColumns> template<size_t OtherColumns> [[nodiscard]]
constexpr Mat<Rows, OtherColumns, Type, StoreType> constexpr Mat<Rows, OtherColumns, Type, StoreType>
operator*(const Mat<Columns, OtherColumns, Type, StoreType>& other) const operator*(const Mat<Columns, OtherColumns, Type, StoreType>& other) const
{ {
@@ -171,109 +169,101 @@ namespace omath
{ {
Type sum = 0; Type sum = 0;
for (size_t k = 0; k < Columns; ++k) for (size_t k = 0; k < Columns; ++k)
sum += At(i, k) * other.At(k, j); sum += at(i, k) * other.at(k, j);
result.At(i, j) = sum; result.at(i, j) = sum;
} }
return result; return result;
} }
constexpr Mat& operator*=(const Type& f) noexcept constexpr Mat& operator*=(const Type& f) noexcept
{ {
for (size_t i = 0; i < Rows; ++i) std::ranges::for_each(m_data, [&f](auto& val) { val *= f; });
for (size_t j = 0; j < Columns; ++j)
At(i, j) *= f;
return *this; return *this;
} }
template<size_t OtherColumns> template<size_t OtherColumns> constexpr Mat<Rows, OtherColumns, Type, StoreType>
constexpr Mat<Rows, OtherColumns, Type, StoreType>
operator*=(const Mat<Columns, OtherColumns, Type, StoreType>& other) operator*=(const Mat<Columns, OtherColumns, Type, StoreType>& other)
{ {
return *this = *this * other; return *this = *this * other;
} }
[[nodiscard]] [[nodiscard]]
constexpr Mat operator*(const Type& f) const noexcept constexpr Mat operator*(const Type& value) const noexcept
{ {
Mat result(*this); Mat result(*this);
result *= f; result *= value;
return result; return result;
} }
constexpr Mat& operator/=(const Type& f) noexcept constexpr Mat& operator/=(const Type& value) noexcept
{ {
for (size_t i = 0; i < Rows; ++i) std::ranges::for_each(m_data, [&value](auto& val) { val /= value; });
for (size_t j = 0; j < Columns; ++j)
At(i, j) /= f;
return *this; return *this;
} }
[[nodiscard]] [[nodiscard]]
constexpr Mat operator/(const Type& f) const noexcept constexpr Mat operator/(const Type& value) const noexcept
{ {
Mat result(*this); Mat result(*this);
result /= f; result /= value;
return result; return result;
} }
constexpr Mat& operator=(const Mat& other) noexcept constexpr Mat& operator=(const Mat& other) noexcept
{ {
if (this == &other) if (this != &other)
return *this; m_data = other.m_data;
for (size_t i = 0; i < Rows; ++i)
for (size_t j = 0; j < Columns; ++j)
At(i, j) = other.At(i, j);
return *this; return *this;
} }
constexpr Mat& operator=(Mat&& other) noexcept constexpr Mat& operator=(Mat&& other) noexcept
{ {
if (this == &other) if (this != &other)
return *this; m_data = std::move(other.m_data);
for (size_t i = 0; i < Rows; ++i)
for (size_t j = 0; j < Columns; ++j)
At(i, j) = other.At(i, j);
return *this; return *this;
} }
[[nodiscard]] [[nodiscard]]
constexpr Mat<Columns, Rows, Type, StoreType> Transposed() const noexcept constexpr Mat<Columns, Rows, Type, StoreType> transposed() const noexcept
{ {
Mat<Columns, Rows, Type, StoreType> transposed; Mat<Columns, Rows, Type, StoreType> transposed;
for (size_t i = 0; i < Rows; ++i) for (size_t i = 0; i < Rows; ++i)
for (size_t j = 0; j < Columns; ++j) for (size_t j = 0; j < Columns; ++j)
transposed.At(j, i) = At(i, j); transposed.at(j, i) = at(i, j);
return transposed; return transposed;
} }
[[nodiscard]] [[nodiscard]]
constexpr Type Determinant() const constexpr Type determinant() const
{ {
static_assert(Rows == Columns, "Determinant is only defined for square matrices."); static_assert(Rows == Columns, "Determinant is only defined for square matrices.");
if constexpr (Rows == 1) if constexpr (Rows == 1)
return At(0, 0); return at(0, 0);
else if constexpr (Rows == 2) if constexpr (Rows == 2)
return At(0, 0) * At(1, 1) - At(0, 1) * At(1, 0); return at(0, 0) * at(1, 1) - at(0, 1) * at(1, 0);
else
if constexpr (Rows > 2)
{ {
Type det = 0; Type det = 0;
for (size_t i = 0; i < Columns; ++i) for (size_t column = 0; column < Columns; ++column)
{ {
const Type cofactor = (i % 2 == 0 ? 1 : -1) * At(0, i) * Minor(0, i).Determinant(); const Type cofactor = at(0, column) * alg_complement(0, column);
det += cofactor; det += cofactor;
} }
return det; return det;
} }
std::unreachable();
} }
[[nodiscard]] [[nodiscard]]
constexpr Mat<Rows - 1, Columns - 1, Type, StoreType> Minor(const size_t row, const size_t column) const constexpr Mat<Rows - 1, Columns - 1, Type, StoreType> strip(const size_t row, const size_t column) const
{ {
static_assert(Rows - 1 > 0 && Columns - 1 > 0);
Mat<Rows - 1, Columns - 1, Type, StoreType> result; Mat<Rows - 1, Columns - 1, Type, StoreType> result;
for (size_t i = 0, m = 0; i < Rows; ++i) for (size_t i = 0, m = 0; i < Rows; ++i)
{ {
@@ -283,7 +273,7 @@ namespace omath
{ {
if (j == column) if (j == column)
continue; continue;
result.At(m, n) = At(i, j); result.at(m, n) = at(i, j);
++n; ++n;
} }
++m; ++m;
@@ -292,19 +282,32 @@ namespace omath
} }
[[nodiscard]] [[nodiscard]]
constexpr const std::array<Type, Rows * Columns>& RawArray() const constexpr Type minor(const size_t row, const size_t column) const
{
return strip(row, column).determinant();
}
[[nodiscard]]
constexpr Type alg_complement(const size_t row, const size_t column) const
{
const auto minor_value = minor(row, column);
return (row + column + 2) % 2 == 0 ? minor_value : -minor_value;
}
[[nodiscard]]
constexpr const std::array<Type, Rows * Columns>& raw_array() const
{ {
return m_data; return m_data;
} }
[[nodiscard]] [[nodiscard]]
constexpr std::array<Type, Rows * Columns>& RawArray() constexpr std::array<Type, Rows * Columns>& raw_array()
{ {
return const_cast<std::array<Type, Rows * Columns>>(std::as_const(*this).RawArray()); return m_data;
} }
[[nodiscard]] [[nodiscard]]
std::string ToString() const noexcept std::string to_string() const noexcept
{ {
std::ostringstream oss; std::ostringstream oss;
oss << "[["; oss << "[[";
@@ -316,7 +319,7 @@ namespace omath
for (size_t j = 0; j < Columns; ++j) for (size_t j = 0; j < Columns; ++j)
{ {
oss << std::setw(9) << std::fixed << std::setprecision(3) << At(i, j); oss << std::setw(9) << std::fixed << std::setprecision(3) << at(i, j);
if (j != Columns - 1) if (j != Columns - 1)
oss << ", "; oss << ", ";
} }
@@ -339,37 +342,55 @@ namespace omath
// Static methods that return fixed-size matrices // Static methods that return fixed-size matrices
[[nodiscard]] [[nodiscard]]
constexpr static Mat<4, 4> ToScreenMat(const Type& screenWidth, const Type& screenHeight) noexcept constexpr static Mat<4, 4> to_screen_mat(const Type& screen_width, const Type& screen_height) noexcept
{ {
return { return {
{screenWidth / 2, 0, 0, 0}, {screen_width / 2, 0, 0, 0},
{0, -screenHeight / 2, 0, 0}, {0, -screen_height / 2, 0, 0},
{0, 0, 1, 0}, {0, 0, 1, 0},
{screenWidth / 2, screenHeight / 2, 0, 1}, {screen_width / 2, screen_height / 2, 0, 1},
}; };
} }
[[nodiscard]]
constexpr std::optional<Mat> inverted() const
{
const auto det = determinant();
if (det == 0)
return std::nullopt;
const auto transposed_mat = transposed();
Mat result;
for (std::size_t row = 0; row < Rows; row++)
for (std::size_t column = 0; column < Rows; column++)
result.at(row, column) = transposed_mat.alg_complement(row, column);
result /= det;
return {result};
}
private: private:
std::array<Type, Rows * Columns> m_data; std::array<Type, Rows * Columns> m_data;
}; };
template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR> template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR> [[nodiscard]]
[[nodiscard]] constexpr static Mat<1, 4, Type, St> mat_row_from_vector(const Vector3<Type>& vector) noexcept
constexpr static Mat<1, 4, Type, St> MatRowFromVector(const Vector3<Type>& vector) noexcept
{ {
return {{vector.x, vector.y, vector.z, 1}}; return {{vector.x, vector.y, vector.z, 1}};
} }
template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR> template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR> [[nodiscard]]
[[nodiscard]] constexpr static Mat<4, 1, Type, St> mat_column_from_vector(const Vector3<Type>& vector) noexcept
constexpr static Mat<4, 1, Type, St> MatColumnFromVector(const Vector3<Type>& vector) noexcept
{ {
return {{vector.x}, {vector.y}, {vector.z}, {1}}; return {{vector.x}, {vector.y}, {vector.z}, {1}};
} }
template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR> template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR>
[[nodiscard]] [[nodiscard]]
constexpr Mat<4, 4, Type, St> MatTranslation(const Vector3<Type>& diff) noexcept constexpr Mat<4, 4, Type, St> mat_translation(const Vector3<Type>& diff) noexcept
{ {
return return
{ {
@@ -382,38 +403,38 @@ namespace omath
template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR, class Angle> template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR, class Angle>
[[nodiscard]] [[nodiscard]]
Mat<4, 4, Type, St> MatRotationAxisX(const Angle& angle) noexcept Mat<4, 4, Type, St> mat_rotation_axis_x(const Angle& angle) noexcept
{ {
return return
{ {
{1, 0, 0, 0}, {1, 0, 0, 0},
{0, angle.Cos(), -angle.Sin(), 0}, {0, angle.cos(), -angle.sin(), 0},
{0, angle.Sin(), angle.Cos(), 0}, {0, angle.sin(), angle.cos(), 0},
{0, 0, 0, 1} {0, 0, 0, 1}
}; };
} }
template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR, class Angle> template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR, class Angle>
[[nodiscard]] [[nodiscard]]
Mat<4, 4, Type, St> MatRotationAxisY(const Angle& angle) noexcept Mat<4, 4, Type, St> mat_rotation_axis_y(const Angle& angle) noexcept
{ {
return return
{ {
{angle.Cos(), 0, angle.Sin(), 0}, {angle.cos(), 0, angle.sin(), 0},
{0 , 1, 0, 0}, {0 , 1, 0, 0},
{-angle.Sin(), 0, angle.Cos(), 0}, {-angle.sin(), 0, angle.cos(), 0},
{0 , 0, 0, 1} {0 , 0, 0, 1}
}; };
} }
template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR, class Angle> template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR, class Angle>
[[nodiscard]] [[nodiscard]]
Mat<4, 4, Type, St> MatRotationAxisZ(const Angle& angle) noexcept Mat<4, 4, Type, St> mat_rotation_axis_z(const Angle& angle) noexcept
{ {
return return
{ {
{angle.Cos(), -angle.Sin(), 0, 0}, {angle.cos(), -angle.sin(), 0, 0},
{angle.Sin(), angle.Cos(), 0, 0}, {angle.sin(), angle.cos(), 0, 0},
{ 0, 0, 1, 0}, { 0, 0, 1, 0},
{ 0, 0, 0, 1}, { 0, 0, 0, 1},
}; };
@@ -421,8 +442,8 @@ namespace omath
template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR> template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR>
[[nodiscard]] [[nodiscard]]
static Mat<4, 4, Type, St> MatCameraView(const Vector3<Type>& forward, const Vector3<Type>& right, static Mat<4, 4, Type, St> mat_camera_view(const Vector3<Type>& forward, const Vector3<Type>& right,
const Vector3<Type>& up, const Vector3<Type>& cameraOrigin) noexcept const Vector3<Type>& up, const Vector3<Type>& camera_origin) noexcept
{ {
return Mat<4, 4, Type, St> return Mat<4, 4, Type, St>
{ {
@@ -430,39 +451,31 @@ namespace omath
{up.x, up.y, up.z, 0}, {up.x, up.y, up.z, 0},
{forward.x, forward.y, forward.z, 0}, {forward.x, forward.y, forward.z, 0},
{0, 0, 0, 1}, {0, 0, 0, 1},
} * mat_translation<Type, St>(-camera_origin);
} * MatTranslation<Type, St>(-cameraOrigin);
}
template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR, class ViewAngles>
[[nodiscard]]
Mat<4, 4, Type, St> MatRotation(const ViewAngles& angles) noexcept
{
return MatRotationAxisZ(angles.yaw) * MatRotationAxisY(angles.pitch) * MatRotationAxisX(angles.roll);
} }
template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR> template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR>
[[nodiscard]] [[nodiscard]]
Mat<4, 4, Type, St> MatPerspectiveLeftHanded(const float fieldOfView, const float aspectRatio, const float near, Mat<4, 4, Type, St> mat_perspective_left_handed(const float field_of_view, const float aspect_ratio,
const float far) noexcept const float near, const float far) noexcept
{ {
const float fovHalfTan = std::tan(angles::DegreesToRadians(fieldOfView) / 2.f); const float fov_half_tan = std::tan(angles::degrees_to_radians(field_of_view) / 2.f);
return {{1.f / (aspectRatio * fovHalfTan), 0.f, 0.f, 0.f}, return {{1.f / (aspect_ratio * fov_half_tan), 0.f, 0.f, 0.f},
{0.f, 1.f / fovHalfTan, 0.f, 0.f}, {0.f, 1.f / fov_half_tan, 0.f, 0.f},
{0.f, 0.f, (far + near) / (far - near), -(2.f * near * far) / (far - near)}, {0.f, 0.f, (far + near) / (far - near), -(2.f * near * far) / (far - near)},
{0.f, 0.f, 1.f, 0.f}}; {0.f, 0.f, 1.f, 0.f}};
} }
template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR> template<class Type = float, MatStoreType St = MatStoreType::ROW_MAJOR>
[[nodiscard]] [[nodiscard]]
Mat<4, 4, Type, St> MatPerspectiveRightHanded(const float fieldOfView, const float aspectRatio, const float near, Mat<4, 4, Type, St> mat_perspective_right_handed(const float field_of_view, const float aspect_ratio,
const float far) noexcept const float near, const float far) noexcept
{ {
const float fovHalfTan = std::tan(angles::DegreesToRadians(fieldOfView) / 2.f); const float fov_half_tan = std::tan(angles::degrees_to_radians(field_of_view) / 2.f);
return {{1.f / (aspectRatio * fovHalfTan), 0.f, 0.f, 0.f}, return {{1.f / (aspect_ratio * fov_half_tan), 0.f, 0.f, 0.f},
{0.f, 1.f / fovHalfTan, 0.f, 0.f}, {0.f, 1.f / fov_half_tan, 0.f, 0.f},
{0.f, 0.f, -(far + near) / (far - near), -(2.f * near * far) / (far - near)}, {0.f, 0.f, -(far + near) / (far - near), -(2.f * near * far) / (far - near)},
{0.f, 0.f, -1.f, 0.f}}; {0.f, 0.f, -1.f, 0.f}};
} }

View File

@@ -1,8 +1,8 @@
#pragma once #pragma once
#include "omath/vector3.hpp"
#include <initializer_list> #include <initializer_list>
#include <memory> #include <memory>
#include <string> #include <string>
#include "omath/vector3.hpp"
namespace omath namespace omath
{ {
@@ -16,51 +16,51 @@ namespace omath
Matrix(const std::initializer_list<std::initializer_list<float>>& rows); Matrix(const std::initializer_list<std::initializer_list<float>>& rows);
[[nodiscard]] [[nodiscard]]
static Matrix ToScreenMatrix(float screenWidth, float screenHeight); static Matrix to_screen_matrix(float screen_width, float screen_height);
[[nodiscard]] [[nodiscard]]
static Matrix TranslationMatrix(const Vector3<float>& diff); static Matrix translation_matrix(const Vector3<float>& diff);
[[nodiscard]] [[nodiscard]]
static Matrix OrientationMatrix(const Vector3<float>& forward, const Vector3<float>& right, const Vector3<float>& up); static Matrix orientation_matrix(const Vector3<float>& forward, const Vector3<float>& right,
const Vector3<float>& up);
[[nodiscard]] [[nodiscard]]
static Matrix ProjectionMatrix(float fieldOfView, float aspectRatio, float near, float far); static Matrix projection_matrix(float field_of_view, float aspect_ratio, float near, float far);
Matrix(const Matrix& other); Matrix(const Matrix& other);
Matrix(size_t rows, size_t columns, const float* pRaw); Matrix(size_t rows, size_t columns, const float* raw_data);
Matrix(Matrix&& other) noexcept; Matrix(Matrix&& other) noexcept;
[[nodiscard]] [[nodiscard]]
size_t RowCount() const noexcept; size_t row_count() const noexcept;
[[nodiscard]] [[nodiscard]]
float& operator[](size_t row, size_t column); float& operator[](size_t row, size_t column);
[[nodiscard]] [[nodiscard]]
size_t ColumnsCount() const noexcept; size_t columns_count() const noexcept;
[[nodiscard]] [[nodiscard]]
std::pair<size_t, size_t> Size() const noexcept; std::pair<size_t, size_t> size() const noexcept;
[[nodiscard]] [[nodiscard]]
float& At(size_t iRow, size_t iCol); float& at(size_t row, size_t col);
[[nodiscard]] [[nodiscard]]
float Sum(); float sum();
void SetDataFromRaw(const float* pRawMatrix); void set_data_from_raw(const float* raw_matrix);
[[nodiscard]] [[nodiscard]]
Matrix Transpose() const; Matrix transpose() const;
void Set(float val); void set(float val);
[[nodiscard]] [[nodiscard]]
const float& At(size_t iRow, size_t iCol) const; const float& at(size_t row, size_t col) const;
Matrix operator*(const Matrix& other) const; Matrix operator*(const Matrix& other) const;
@@ -72,22 +72,22 @@ namespace omath
Matrix& operator/=(float f); Matrix& operator/=(float f);
void Clear(); void clear();
[[nodiscard]] [[nodiscard]]
Matrix Strip(size_t row, size_t column) const; Matrix strip(size_t row, size_t column) const;
[[nodiscard]] [[nodiscard]]
float Minor(size_t i, size_t j) const; float minor(size_t i, size_t j) const;
[[nodiscard]] [[nodiscard]]
float AlgComplement(size_t i, size_t j) const; float alg_complement(size_t i, size_t j) const;
[[nodiscard]] [[nodiscard]]
float Determinant() const; float determinant() const;
[[nodiscard]] [[nodiscard]]
const float* Raw() const; const float* raw() const;
Matrix& operator=(const Matrix& other); Matrix& operator=(const Matrix& other);
@@ -96,7 +96,7 @@ namespace omath
Matrix operator/(float f) const; Matrix operator/(float f) const;
[[nodiscard]] [[nodiscard]]
std::string ToString() const; std::string to_string() const;
~Matrix(); ~Matrix();

View File

@@ -3,9 +3,9 @@
// //
#pragma once #pragma once
#include <vector>
#include "omath/pathfinding/navigation_mesh.hpp" #include "omath/pathfinding/navigation_mesh.hpp"
#include "omath/vector3.hpp" #include "omath/vector3.hpp"
#include <vector>
namespace omath::pathfinding namespace omath::pathfinding
{ {
@@ -14,17 +14,17 @@ namespace omath::pathfinding
{ {
public: public:
[[nodiscard]] [[nodiscard]]
static std::vector<Vector3<float>> FindPath(const Vector3<float>& start, const Vector3<float>& end, static std::vector<Vector3<float>> find_path(const Vector3<float>& start, const Vector3<float>& end,
const NavigationMesh& navMesh); const NavigationMesh& nav_mesh) noexcept;
private: private:
[[nodiscard]] [[nodiscard]]
static std::vector<Vector3<float>> static std::vector<Vector3<float>>
ReconstructFinalPath(const std::unordered_map<Vector3<float>, PathNode>& closedList, reconstruct_final_path(const std::unordered_map<Vector3<float>, PathNode>& closed_list,
const Vector3<float>& current); const Vector3<float>& current) noexcept;
[[nodiscard]] [[nodiscard]]
static auto GetPerfectNode(const std::unordered_map<Vector3<float>, PathNode>& openList, static auto get_perfect_node(const std::unordered_map<Vector3<float>, PathNode>& open_list,
const Vector3<float>& endVertex); const Vector3<float>& end_vertex) noexcept;
}; };
} // namespace omath::pathfinding } // namespace omath::pathfinding

View File

@@ -4,35 +4,34 @@
#pragma once #pragma once
#include "omath/vector3.hpp"
#include <expected> #include <expected>
#include <string> #include <string>
#include <vector> #include <vector>
#include "omath/vector3.hpp"
namespace omath::pathfinding namespace omath::pathfinding
{ {
enum Error enum Error
{ {
}; };
class NavigationMesh final class NavigationMesh final
{ {
public: public:
[[nodiscard]] [[nodiscard]]
std::expected<Vector3<float>, std::string> GetClosestVertex(const Vector3<float>& point) const; std::expected<Vector3<float>, std::string> get_closest_vertex(const Vector3<float>& point) const noexcept;
[[nodiscard]] [[nodiscard]]
const std::vector<Vector3<float>>& GetNeighbors(const Vector3<float>& vertex) const; const std::vector<Vector3<float>>& get_neighbors(const Vector3<float>& vertex) const noexcept;
[[nodiscard]] [[nodiscard]]
bool Empty() const; bool empty() const;
[[nodiscard]] std::vector<uint8_t> Serialize() const; [[nodiscard]] std::vector<uint8_t> serialize() const noexcept;
void Deserialize(const std::vector<uint8_t>& raw); void deserialize(const std::vector<uint8_t>& raw) noexcept;
std::unordered_map<Vector3<float>, std::vector<Vector3<float>>> m_verTextMap; std::unordered_map<Vector3<float>, std::vector<Vector3<float>>> m_vertex_map;
}; };
} // namespace omath::pathfinding } // namespace omath::pathfinding

View File

@@ -6,15 +6,14 @@
#include "omath/projectile_prediction/target.hpp" #include "omath/projectile_prediction/target.hpp"
#include "omath/vector3.hpp" #include "omath/vector3.hpp"
namespace omath::projectile_prediction namespace omath::projectile_prediction
{ {
class ProjPredEngine class ProjPredEngine
{ {
public: public:
[[nodiscard]] [[nodiscard]]
virtual std::optional<Vector3<float>> MaybeCalculateAimPoint(const Projectile& projectile, virtual std::optional<Vector3<float>> maybe_calculate_aim_point(const Projectile& projectile,
const Target& target) const = 0; const Target& target) const = 0;
virtual ~ProjPredEngine() = default; virtual ~ProjPredEngine() = default;
}; };
} // namespace omath::projectile_prediction } // namespace omath::projectile_prediction

View File

@@ -6,21 +6,23 @@
namespace omath::projectile_prediction namespace omath::projectile_prediction
{ {
class ProjPredEngineAVX2 final : public ProjPredEngine class ProjPredEngineAvx2 final : public ProjPredEngine
{ {
public: public:
[[nodiscard]] std::optional<Vector3<float>> MaybeCalculateAimPoint(const Projectile& projectile, [[nodiscard]] std::optional<Vector3<float>>
const Target& target) const override; maybe_calculate_aim_point(const Projectile& projectile, const Target& target) const override;
ProjPredEngineAvx2(float gravity_constant, float simulation_time_step, float maximum_simulation_time);
ProjPredEngineAVX2(float gravityConstant, float simulationTimeStep, float maximumSimulationTime); ~ProjPredEngineAvx2() override = default;
~ProjPredEngineAVX2() override = default;
private: private:
[[nodiscard]] static std::optional<float> CalculatePitch(const Vector3<float>& projOrigin, const Vector3<float>& targetPos, [[nodiscard]] static std::optional<float> calculate_pitch(const Vector3<float>& proj_origin,
float bulletGravity, float v0, float time); const Vector3<float>& target_pos,
const float m_gravityConstant; float bullet_gravity, float v0, float time) ;
const float m_simulationTimeStep;
const float m_maximumSimulationTime; // We use [[maybe_unused]] here since AVX2 is not available for ARM and ARM64 CPU
[[maybe_unused]] const float m_gravity_constant;
[[maybe_unused]] const float m_simulation_time_step;
[[maybe_unused]] const float m_maximum_simulation_time;
}; };
} // namespace omath::projectile_prediction } // namespace omath::projectile_prediction

View File

@@ -4,38 +4,37 @@
#pragma once #pragma once
#include <optional>
#include "omath/projectile_prediction/proj_pred_engine.hpp" #include "omath/projectile_prediction/proj_pred_engine.hpp"
#include "omath/projectile_prediction/projectile.hpp" #include "omath/projectile_prediction/projectile.hpp"
#include "omath/projectile_prediction/target.hpp" #include "omath/projectile_prediction/target.hpp"
#include "omath/vector3.hpp" #include "omath/vector3.hpp"
#include <optional>
namespace omath::projectile_prediction namespace omath::projectile_prediction
{ {
class ProjPredEngineLegacy final : public ProjPredEngine class ProjPredEngineLegacy final : public ProjPredEngine
{ {
public: public:
explicit ProjPredEngineLegacy(float gravityConstant, float simulationTimeStep, float maximumSimulationTime, explicit ProjPredEngineLegacy(float gravity_constant, float simulation_time_step, float maximum_simulation_time,
float distanceTolerance); float distance_tolerance);
[[nodiscard]] [[nodiscard]]
std::optional<Vector3<float>> MaybeCalculateAimPoint(const Projectile& projectile, std::optional<Vector3<float>> maybe_calculate_aim_point(const Projectile& projectile,
const Target& target) const override; const Target& target) const override;
private: private:
const float m_gravityConstant; const float m_gravity_constant;
const float m_simulationTimeStep; const float m_simulation_time_step;
const float m_maximumSimulationTime; const float m_maximum_simulation_time;
const float m_distanceTolerance; const float m_distance_tolerance;
[[nodiscard]] [[nodiscard]]
std::optional<float> MaybeCalculateProjectileLaunchPitchAngle(const Projectile& projectile, std::optional<float>
const Vector3<float>& targetPosition) const; maybe_calculate_projectile_launch_pitch_angle(const Projectile& projectile,
const Vector3<float>& target_position) const noexcept;
[[nodiscard]] [[nodiscard]]
bool IsProjectileReachedTarget(const Vector3<float>& targetPosition, const Projectile& projectile, float pitch, bool is_projectile_reached_target(const Vector3<float>& target_position, const Projectile& projectile,
float time) const; float pitch, float time) const noexcept;
}; };
} // namespace omath::projectile_prediction } // namespace omath::projectile_prediction

View File

@@ -10,12 +10,11 @@ namespace omath::projectile_prediction
class Projectile final class Projectile final
{ {
public: public:
[[nodiscard]] [[nodiscard]]
Vector3<float> PredictPosition(float pitch, float yaw, float time, float gravity) const; Vector3<float> predict_position(float pitch, float yaw, float time, float gravity) const noexcept;
Vector3<float> m_origin; Vector3<float> m_origin;
float m_launchSpeed{}; float m_launch_speed{};
float m_gravityScale{}; float m_gravity_scale{};
}; };
} } // namespace omath::projectile_prediction

View File

@@ -10,20 +10,19 @@ namespace omath::projectile_prediction
class Target final class Target final
{ {
public: public:
[[nodiscard]] [[nodiscard]]
constexpr Vector3<float> PredictPosition(const float time, const float gravity) const constexpr Vector3<float> predict_position(const float time, const float gravity) const noexcept
{ {
auto predicted = m_origin + m_velocity * time; auto predicted = m_origin + m_velocity * time;
if (m_isAirborne) if (m_is_airborne)
predicted.z -= gravity * std::pow(time, 2.f) * 0.5f; predicted.z -= gravity * (time*time) * 0.5f;
return predicted; return predicted;
} }
Vector3<float> m_origin; Vector3<float> m_origin;
Vector3<float> m_velocity; Vector3<float> m_velocity;
bool m_isAirborne{}; bool m_is_airborne{};
}; };
} } // namespace omath::projectile_prediction

View File

@@ -4,12 +4,12 @@
#pragma once #pragma once
#include "omath/projection/error_codes.hpp"
#include <expected> #include <expected>
#include <omath/angle.hpp> #include <omath/angle.hpp>
#include <omath/mat.hpp> #include <omath/mat.hpp>
#include <omath/vector3.hpp> #include <omath/vector3.hpp>
#include <type_traits> #include <type_traits>
#include "omath/projection/error_codes.hpp"
namespace omath::projection namespace omath::projection
{ {
@@ -19,157 +19,157 @@ namespace omath::projection
float m_width; float m_width;
float m_height; float m_height;
[[nodiscard]] constexpr float AspectRatio() const [[nodiscard]] constexpr float aspect_ratio() const
{ {
return m_width / m_height; return m_width / m_height;
} }
}; };
using FieldOfView = Angle<float, 0.f, 180.f, AngleFlags::Clamped>; using FieldOfView = Angle<float, 0.f, 180.f, AngleFlags::Clamped>;
template<class Mat4x4Type, class ViewAnglesType> template<class Mat4X4Type, class ViewAnglesType>
class Camera class Camera
{ {
public: public:
virtual ~Camera() = default; virtual ~Camera() = default;
Camera(const Vector3<float>& position, const ViewAnglesType& viewAngles, const ViewPort& viewPort, Camera(const Vector3<float>& position, const ViewAnglesType& view_angles, const ViewPort& view_port,
const FieldOfView& fov, const float near, const float far) : const FieldOfView& fov, const float near, const float far) noexcept
m_viewPort(viewPort), m_fieldOfView(fov), m_farPlaneDistance(far), m_nearPlaneDistance(near), : m_view_port(view_port), m_field_of_view(fov), m_far_plane_distance(far), m_near_plane_distance(near),
m_viewAngles(viewAngles), m_origin(position) m_view_angles(view_angles), m_origin(position)
{ {
} }
protected: protected:
virtual void LookAt(const Vector3<float>& target) = 0; virtual void look_at(const Vector3<float>& target) = 0;
[[nodiscard]] virtual Mat4x4Type CalcViewMatrix() const = 0; [[nodiscard]] virtual Mat4X4Type calc_view_matrix() const noexcept = 0;
[[nodiscard]] virtual Mat4x4Type CalcProjectionMatrix() const = 0; [[nodiscard]] virtual Mat4X4Type calc_projection_matrix() const noexcept = 0;
[[nodiscard]] Mat4x4Type CalcViewProjectionMatrix() const [[nodiscard]] Mat4X4Type calc_view_projection_matrix() const noexcept
{ {
return CalcProjectionMatrix() * CalcViewMatrix(); return calc_projection_matrix() * calc_view_matrix();
} }
public: public:
[[nodiscard]] const Mat4x4Type& GetViewProjectionMatrix() const [[nodiscard]] const Mat4X4Type& get_view_projection_matrix() const noexcept
{ {
if (!m_viewProjectionMatrix.has_value()) if (!m_view_projection_matrix.has_value())
m_viewProjectionMatrix = CalcViewProjectionMatrix(); m_view_projection_matrix = calc_view_projection_matrix();
return m_viewProjectionMatrix.value(); return m_view_projection_matrix.value();
} }
void SetFieldOfView(const FieldOfView& fov) void set_field_of_view(const FieldOfView& fov) noexcept
{ {
m_fieldOfView = fov; m_field_of_view = fov;
m_view_projection_matrix = std::nullopt;
} }
void SetNearPlane(const float near) void set_near_plane(const float near) noexcept
{ {
m_nearPlaneDistance = near; m_near_plane_distance = near;
m_view_projection_matrix = std::nullopt;
} }
void SetFarPlane(const float far) void set_far_plane(const float far) noexcept
{ {
m_farPlaneDistance = far; m_far_plane_distance = far;
m_view_projection_matrix = std::nullopt;
} }
void SetViewAngles(const ViewAnglesType& viewAngles) void set_view_angles(const ViewAnglesType& view_angles) noexcept
{ {
m_viewAngles = viewAngles; m_view_angles = view_angles;
m_view_projection_matrix = std::nullopt;
} }
void SetOrigin(const Vector3<float>& origin) void set_origin(const Vector3<float>& origin) noexcept
{ {
m_origin = origin; m_origin = origin;
m_view_projection_matrix = std::nullopt;
} }
void SetViewPort(const ViewPort& viewPort) void set_view_port(const ViewPort& view_port) noexcept
{ {
m_viewPort = viewPort; m_view_port = view_port;
m_view_projection_matrix = std::nullopt;
} }
[[nodiscard]] const FieldOfView& GetFieldOfView() const [[nodiscard]] const FieldOfView& get_field_of_view() const noexcept
{ {
return m_fieldOfView; return m_field_of_view;
} }
[[nodiscard]] const float& GetNearPlane() const [[nodiscard]] const float& get_near_plane() const noexcept
{ {
return m_nearPlaneDistance; return m_near_plane_distance;
} }
[[nodiscard]] const float& GetFarPlane() const [[nodiscard]] const float& get_far_plane() const noexcept
{ {
return m_farPlaneDistance; return m_far_plane_distance;
} }
[[nodiscard]] const ViewAnglesType& GetViewAngles() const [[nodiscard]] const ViewAnglesType& get_view_angles() const noexcept
{ {
return m_viewAngles; return m_view_angles;
} }
[[nodiscard]] const Vector3<float>& GetOrigin() const [[nodiscard]] const Vector3<float>& get_origin() const noexcept
{ {
return m_origin; return m_origin;
} }
[[nodiscard]] std::expected<Vector3<float>, Error> WorldToScreen(const Vector3<float>& worldPosition) const [[nodiscard]] std::expected<Vector3<float>, Error>
world_to_screen(const Vector3<float>& world_position) const noexcept
{ {
auto normalizedCords = WorldToViewPort(worldPosition); auto normalized_cords = world_to_view_port(world_position);
if (!normalizedCords.has_value()) if (!normalized_cords.has_value())
return std::unexpected{normalizedCords.error()}; return std::unexpected{normalized_cords.error()};
return ndc_to_screen_position(*normalized_cords);
return NdcToScreenPosition(*normalizedCords);
} }
[[nodiscard]] std::expected<Vector3<float>, Error> WorldToViewPort(const Vector3<float>& worldPosition) const [[nodiscard]] std::expected<Vector3<float>, Error>
world_to_view_port(const Vector3<float>& world_position) const noexcept
{ {
auto projected = GetViewProjectionMatrix() * auto projected = get_view_projection_matrix()
MatColumnFromVector<float, Mat4x4Type::GetStoreOrdering()>(worldPosition); * mat_column_from_vector<float, Mat4X4Type::get_store_ordering()>(world_position);
if (projected.At(3, 0) == 0.0f) if (projected.at(3, 0) == 0.0f)
return std::unexpected(Error::WORLD_POSITION_IS_OUT_OF_SCREEN_BOUNDS); return std::unexpected(Error::WORLD_POSITION_IS_OUT_OF_SCREEN_BOUNDS);
projected /= projected.At(3, 0); projected /= projected.at(3, 0);
if (IsNdcOutOfBounds(projected)) if (is_ndc_out_of_bounds(projected))
return std::unexpected(Error::WORLD_POSITION_IS_OUT_OF_SCREEN_BOUNDS); return std::unexpected(Error::WORLD_POSITION_IS_OUT_OF_SCREEN_BOUNDS);
return Vector3<float>{projected.At(0, 0), projected.At(1, 0), projected.At(2, 0)}; return Vector3<float>{projected.at(0, 0), projected.at(1, 0), projected.at(2, 0)};
} }
protected: protected:
ViewPort m_viewPort{}; ViewPort m_view_port{};
Angle<float, 0.f, 180.f, AngleFlags::Clamped> m_fieldOfView; Angle<float, 0.f, 180.f, AngleFlags::Clamped> m_field_of_view;
mutable std::optional<Mat4x4Type> m_viewProjectionMatrix; mutable std::optional<Mat4X4Type> m_view_projection_matrix;
float m_farPlaneDistance; float m_far_plane_distance;
float m_nearPlaneDistance; float m_near_plane_distance;
ViewAnglesType m_view_angles;
ViewAnglesType m_viewAngles;
Vector3<float> m_origin; Vector3<float> m_origin;
private: private:
template<class Type> template<class Type>
[[nodiscard]] [[nodiscard]] constexpr static bool is_ndc_out_of_bounds(const Type& ndc) noexcept
constexpr static bool IsNdcOutOfBounds(const Type& ndc)
{ {
return std::ranges::any_of(ndc.RawArray(), [](const auto& val) { return val < -1 || val > 1; }); return std::ranges::any_of(ndc.raw_array(), [](const auto& val) { return val < -1 || val > 1; });
} }
[[nodiscard]] Vector3<float> NdcToScreenPosition(const Vector3<float>& ndc) const [[nodiscard]] Vector3<float> ndc_to_screen_position(const Vector3<float>& ndc) const noexcept
{ {
return return {(ndc.x + 1.f) / 2.f * m_view_port.m_width, (1.f - ndc.y) / 2.f * m_view_port.m_height, ndc.z};
{
(ndc.x + 1.f) / 2.f * m_viewPort.m_width,
(1.f - ndc.y) / 2.f * m_viewPort.m_height,
ndc.z
};
} }
}; };
} // namespace omath::projection } // namespace omath::projection

View File

@@ -5,7 +5,6 @@
#pragma once #pragma once
#include <cstdint> #include <cstdint>
namespace omath::projection namespace omath::projection
{ {
enum class Error : uint16_t enum class Error : uint16_t

View File

@@ -6,15 +6,14 @@
namespace omath namespace omath
{ {
/* /*
|\ |\
| \ | \
a | \ hypot a | \ hypot
| \ | \
----- -----
b b
*/ */
template<class Vector> template<class Vector>
class Triangle final class Triangle final
@@ -31,52 +30,53 @@ namespace omath
Vector3<float> m_vertex3; Vector3<float> m_vertex3;
[[nodiscard]] [[nodiscard]]
constexpr Vector3<float> CalculateNormal() const constexpr Vector3<float> calculate_normal() const
{ {
const auto b = SideBVector(); const auto b = side_b_vector();
const auto a = SideAVector(); const auto a = side_a_vector();
return b.Cross(a).Normalized();
return b.cross(a).normalized();
} }
[[nodiscard]] [[nodiscard]]
float SideALength() const float side_a_length() const
{ {
return m_vertex1.DistTo(m_vertex2); return m_vertex1.distance_to(m_vertex2);
} }
[[nodiscard]] [[nodiscard]]
float SideBLength() const float side_b_length() const
{ {
return m_vertex3.DistTo(m_vertex2); return m_vertex3.distance_to(m_vertex2);
} }
[[nodiscard]] [[nodiscard]]
constexpr Vector3<float> SideAVector() const constexpr Vector3<float> side_a_vector() const
{ {
return m_vertex1 - m_vertex2; return m_vertex1 - m_vertex2;
} }
[[nodiscard]] [[nodiscard]]
constexpr float Hypot() const constexpr float hypot() const
{ {
return m_vertex1.DistTo(m_vertex3); return m_vertex1.distance_to(m_vertex3);
} }
[[nodiscard]] [[nodiscard]]
constexpr bool IsRectangular() const constexpr bool is_rectangular() const
{ {
const auto sideA = SideALength(); const auto side_a = side_a_length();
const auto sideB = SideBLength(); const auto side_b = side_b_length();
const auto hypot = Hypot(); const auto hypot_value = hypot();
return std::abs(sideA*sideA + sideB*sideB - hypot*hypot) <= 0.0001f; return std::abs(side_a * side_a + side_b * side_b - hypot_value * hypot_value) <= 0.0001f;
} }
[[nodiscard]] [[nodiscard]]
constexpr Vector3<float> SideBVector() const constexpr Vector3<float> side_b_vector() const
{ {
return m_vertex3 - m_vertex2; return m_vertex3 - m_vertex2;
} }
[[nodiscard]] [[nodiscard]]
constexpr Vector3<float> MidPoint() const constexpr Vector3<float> mid_point() const
{ {
return (m_vertex1 + m_vertex2 + m_vertex3) / 3; return (m_vertex1 + m_vertex2 + m_vertex3) / 3;
} }

View File

@@ -10,12 +10,11 @@
#include <imgui.h> #include <imgui.h>
#endif #endif
namespace omath namespace omath
{ {
template<class Type> template<class Type>
requires std::is_arithmetic_v<Type> requires std::is_arithmetic_v<Type>
class Vector2 class Vector2
{ {
public: public:
@@ -25,133 +24,133 @@ namespace omath
// Constructors // Constructors
constexpr Vector2() = default; constexpr Vector2() = default;
constexpr Vector2(const Type& x, const Type& y) : x(x), y(y) constexpr Vector2(const Type& x, const Type& y) noexcept: x(x), y(y)
{ {
} }
// Equality operators // Equality operators
[[nodiscard]] [[nodiscard]]
constexpr bool operator==(const Vector2& src) const constexpr bool operator==(const Vector2& other) const noexcept
{ {
return x == src.x && y == src.y; return x == other.x && y == other.y;
} }
[[nodiscard]] [[nodiscard]]
constexpr bool operator!=(const Vector2& src) const constexpr bool operator!=(const Vector2& other) const noexcept
{ {
return !(*this == src); return !(*this == other);
} }
// Compound assignment operators // Compound assignment operators
constexpr Vector2& operator+=(const Vector2& v) constexpr Vector2& operator+=(const Vector2& other) noexcept
{ {
x += v.x; x += other.x;
y += v.y; y += other.y;
return *this; return *this;
} }
constexpr Vector2& operator-=(const Vector2& v) constexpr Vector2& operator-=(const Vector2& other) noexcept
{ {
x -= v.x; x -= other.x;
y -= v.y; y -= other.y;
return *this; return *this;
} }
constexpr Vector2& operator*=(const Vector2& v) constexpr Vector2& operator*=(const Vector2& other) noexcept
{ {
x *= v.x; x *= other.x;
y *= v.y; y *= other.y;
return *this; return *this;
} }
constexpr Vector2& operator/=(const Vector2& v) constexpr Vector2& operator/=(const Vector2& other) noexcept
{ {
x /= v.x; x /= other.x;
y /= v.y; y /= other.y;
return *this; return *this;
} }
constexpr Vector2& operator*=(const Type& fl) constexpr Vector2& operator*=(const Type& value) noexcept
{ {
x *= fl; x *= value;
y *= fl; y *= value;
return *this; return *this;
} }
constexpr Vector2& operator/=(const Type& fl) constexpr Vector2& operator/=(const Type& value) noexcept
{ {
x /= fl; x /= value;
y /= fl; y /= value;
return *this; return *this;
} }
constexpr Vector2& operator+=(const Type& fl) constexpr Vector2& operator+=(const Type& value) noexcept
{ {
x += fl; x += value;
y += fl; y += value;
return *this; return *this;
} }
constexpr Vector2& operator-=(const Type& fl) constexpr Vector2& operator-=(const Type& value) noexcept
{ {
x -= fl; x -= value;
y -= fl; y -= value;
return *this; return *this;
} }
// Basic vector operations // Basic vector operations
[[nodiscard]] Type DistTo(const Vector2& vOther) const [[nodiscard]] Type distance_to(const Vector2& other) const noexcept
{ {
return std::sqrt(DistToSqr(vOther)); return std::sqrt(distance_to_sqr(other));
} }
[[nodiscard]] constexpr Type DistToSqr(const Vector2& vOther) const [[nodiscard]] constexpr Type distance_to_sqr(const Vector2& other) const noexcept
{ {
return (x - vOther.x) * (x - vOther.x) + (y - vOther.y) * (y - vOther.y); return (x - other.x) * (x - other.x) + (y - other.y) * (y - other.y);
} }
[[nodiscard]] constexpr Type Dot(const Vector2& vOther) const [[nodiscard]] constexpr Type dot(const Vector2& other) const noexcept
{ {
return x * vOther.x + y * vOther.y; return x * other.x + y * other.y;
} }
#ifndef _MSC_VER #ifndef _MSC_VER
[[nodiscard]] constexpr Type Length() const [[nodiscard]] constexpr Type length() const noexcept
{ {
return std::hypot(this->x, this->y); return std::hypot(this->x, this->y);
} }
[[nodiscard]] constexpr Vector2 Normalized() const [[nodiscard]] constexpr Vector2 normalized() const noexcept
{ {
const Type len = Length(); const Type len = length();
return len > 0.f ? *this / len : *this; return len > 0.f ? *this / len : *this;
} }
#else #else
[[nodiscard]] Type Length() const [[nodiscard]] Type length() const noexcept
{ {
return std::hypot(x, y); return std::hypot(x, y);
} }
[[nodiscard]] Vector2 Normalized() const [[nodiscard]] Vector2 normalized() const noexcept
{ {
const Type len = Length(); const Type len = length();
return len > 0.f ? *this / len : *this; return len > 0.f ? *this / len : *this;
} }
#endif #endif
[[nodiscard]] constexpr Type LengthSqr() const [[nodiscard]] constexpr Type length_sqr() const noexcept
{ {
return x * x + y * y; return x * x + y * y;
} }
constexpr Vector2& Abs() constexpr Vector2& abs() noexcept
{ {
// FIXME: Replace with std::abs, if it will become constexprable // FIXME: Replace with std::abs, if it will become constexprable
x = x < 0 ? -x : x; x = x < 0 ? -x : x;
@@ -159,47 +158,47 @@ namespace omath
return *this; return *this;
} }
[[nodiscard]] constexpr Vector2 operator-() const [[nodiscard]] constexpr Vector2 operator-() const noexcept
{ {
return {-x, -y}; return {-x, -y};
} }
// Binary arithmetic operators // Binary arithmetic operators
[[nodiscard]] constexpr Vector2 operator+(const Vector2& v) const [[nodiscard]] constexpr Vector2 operator+(const Vector2& other) const noexcept
{ {
return {x + v.x, y + v.y}; return {x + other.x, y + other.y};
} }
[[nodiscard]] constexpr Vector2 operator-(const Vector2& v) const [[nodiscard]] constexpr Vector2 operator-(const Vector2& other) const noexcept
{ {
return {x - v.x, y - v.y}; return {x - other.x, y - other.y};
} }
[[nodiscard]] constexpr Vector2 operator*(const float fl) const [[nodiscard]] constexpr Vector2 operator*(const Type& value) const noexcept
{ {
return {x * fl, y * fl}; return {x * value, y * value};
} }
[[nodiscard]] constexpr Vector2 operator/(const float fl) const [[nodiscard]] constexpr Vector2 operator/(const Type& value) const noexcept
{ {
return {x / fl, y / fl}; return {x / value, y / value};
} }
// Sum of elements // Sum of elements
[[nodiscard]] constexpr Type Sum() const [[nodiscard]] constexpr Type sum() const noexcept
{ {
return x + y; return x + y;
} }
[[nodiscard]] [[nodiscard]]
constexpr std::tuple<Type, Type> AsTuple() const constexpr std::tuple<Type, Type> as_tuple() const noexcept
{ {
return std::make_tuple(x, y); return std::make_tuple(x, y);
} }
#ifdef OMATH_IMGUI_INTEGRATION #ifdef OMATH_IMGUI_INTEGRATION
[[nodiscard]] [[nodiscard]]
ImVec2 ToImVec2() const ImVec2 to_im_vec2() const noexcept
{ {
return {static_cast<float>(this->x), static_cast<float>(this->y)}; return {static_cast<float>(this->x), static_cast<float>(this->y)};
} }

View File

@@ -4,11 +4,11 @@
#pragma once #pragma once
#include "omath/angle.hpp"
#include "omath/vector2.hpp"
#include <cstdint> #include <cstdint>
#include <expected> #include <expected>
#include <functional> #include <functional>
#include "omath/angle.hpp"
#include "omath/vector2.hpp"
namespace omath namespace omath
{ {
@@ -18,264 +18,258 @@ namespace omath
IMPOSSIBLE_BETWEEN_ANGLE, IMPOSSIBLE_BETWEEN_ANGLE,
}; };
template<class Type> requires std::is_arithmetic_v<Type> template<class Type>
requires std::is_arithmetic_v<Type>
class Vector3 : public Vector2<Type> class Vector3 : public Vector2<Type>
{ {
public: public:
Type z = static_cast<Type>(0); Type z = static_cast<Type>(0);
constexpr Vector3(const Type& x, const Type& y, const Type& z) : Vector2<Type>(x, y), z(z) { } constexpr Vector3(const Type& x, const Type& y, const Type& z) noexcept: Vector2<Type>(x, y), z(z)
constexpr Vector3() : Vector2<Type>() {};
[[nodiscard]] constexpr bool operator==(const Vector3& src) const
{ {
return Vector2<Type>::operator==(src) && (src.z == z); }
constexpr Vector3() noexcept: Vector2<Type>() {};
[[nodiscard]] constexpr bool operator==(const Vector3& other) const noexcept
{
return Vector2<Type>::operator==(other) && (other.z == z);
} }
[[nodiscard]] constexpr bool operator!=(const Vector3& src) const [[nodiscard]] constexpr bool operator!=(const Vector3& other) const noexcept
{ {
return !(*this == src); return !(*this == other);
} }
constexpr Vector3& operator+=(const Vector3& v) constexpr Vector3& operator+=(const Vector3& other) noexcept
{ {
Vector2<Type>::operator+=(v); Vector2<Type>::operator+=(other);
z += v.z; z += other.z;
return *this; return *this;
} }
constexpr Vector3& operator-=(const Vector3& v) constexpr Vector3& operator-=(const Vector3& other) noexcept
{ {
Vector2<Type>::operator-=(v); Vector2<Type>::operator-=(other);
z -= v.z; z -= other.z;
return *this; return *this;
} }
constexpr Vector3& operator*=(const float fl) constexpr Vector3& operator*=(const Type& value) noexcept
{ {
Vector2<Type>::operator*=(fl); Vector2<Type>::operator*=(value);
z *= fl; z *= value;
return *this; return *this;
} }
constexpr Vector3& operator*=(const Vector3& v) constexpr Vector3& operator*=(const Vector3& other) noexcept
{ {
Vector2<Type>::operator*=(v); Vector2<Type>::operator*=(other);
z *= v.z; z *= other.z;
return *this; return *this;
} }
constexpr Vector3& operator/=(const Vector3& v) constexpr Vector3& operator/=(const Vector3& other) noexcept
{ {
Vector2<Type>::operator/=(v); Vector2<Type>::operator/=(other);
z /= v.z; z /= other.z;
return *this; return *this;
} }
constexpr Vector3& operator+=(const float fl) constexpr Vector3& operator+=(const Type& value) noexcept
{ {
Vector2<Type>::operator+=(fl); Vector2<Type>::operator+=(value);
z += fl; z += value;
return *this; return *this;
} }
constexpr Vector3& operator/=(const float fl) constexpr Vector3& operator/=(const Type& value) noexcept
{ {
Vector2<Type>::operator/=(fl); Vector2<Type>::operator/=(value);
z /= fl; z /= value;
return *this; return *this;
} }
constexpr Vector3& operator-=(const float fl) constexpr Vector3& operator-=(const Type& value) noexcept
{ {
Vector2<Type>::operator-=(fl); Vector2<Type>::operator-=(value);
z -= fl; z -= value;
return *this; return *this;
} }
constexpr Vector3& Abs() constexpr Vector3& abs() noexcept
{ {
Vector2<Type>::Abs(); Vector2<Type>::abs();
z = z < 0.f ? -z : z; z = z < 0.f ? -z : z;
return *this; return *this;
} }
[[nodiscard]] constexpr Type DistToSqr(const Vector3& vOther) const [[nodiscard]] constexpr Type distance_to_sqr(const Vector3& other) const noexcept
{ {
return (*this - vOther).LengthSqr(); return (*this - other).length_sqr();
} }
[[nodiscard]] constexpr Type Dot(const Vector3& vOther) const [[nodiscard]] constexpr Type dot(const Vector3& other) const noexcept
{ {
return Vector2<Type>::Dot(vOther) + z * vOther.z; return Vector2<Type>::dot(other) + z * other.z;
} }
#ifndef _MSC_VER #ifndef _MSC_VER
[[nodiscard]] constexpr Type Length() const [[nodiscard]] constexpr Type length() const
{ {
return std::hypot(this->x, this->y, z); return std::hypot(this->x, this->y, z);
} }
[[nodiscard]] constexpr Type Length2D() const [[nodiscard]] constexpr Type length_2d() const
{ {
return Vector2<Type>::Length(); return Vector2<Type>::length();
} }
[[nodiscard]] Type DistTo(const Vector3& vOther) const [[nodiscard]] Type distance_to(const Vector3& other) const
{ {
return (*this - vOther).Length(); return (*this - other).length();
} }
[[nodiscard]] constexpr Vector3 Normalized() const [[nodiscard]] constexpr Vector3 normalized() const
{ {
const Type length = this->Length(); const Type length_value = this->length();
return length != 0 ? *this / length : *this; return length_value != 0 ? *this / length_value : *this;
} }
#else #else
[[nodiscard]] Type Length() const [[nodiscard]] Type length() const noexcept
{ {
return std::hypot(this->x, this->y, z); return std::hypot(this->x, this->y, z);
} }
[[nodiscard]] Vector3 Normalized() const [[nodiscard]] Vector3 normalized() const noexcept
{ {
const Type length = this->Length(); const Type len = this->length();
return length != 0 ? *this / length : *this; return len != 0 ? *this / len : *this;
} }
[[nodiscard]] Type Length2D() const [[nodiscard]] Type length_2d() const noexcept
{ {
return Vector2<Type>::Length(); return Vector2<Type>::length();
} }
[[nodiscard]] Type DistTo(const Vector3& vOther) const [[nodiscard]] Type distance_to(const Vector3& vOther) const noexcept
{ {
return (*this - vOther).Length(); return (*this - vOther).length();
} }
#endif #endif
[[nodiscard]] constexpr Type length_sqr() const noexcept
[[nodiscard]] constexpr Type LengthSqr() const
{ {
return Vector2<Type>::LengthSqr() + z * z; return Vector2<Type>::length_sqr() + z * z;
} }
[[nodiscard]] constexpr Vector3 operator-() const [[nodiscard]] constexpr Vector3 operator-() const noexcept
{ {
return {-this->x, -this->y, -z}; return {-this->x, -this->y, -z};
} }
[[nodiscard]] constexpr Vector3 operator+(const Vector3& v) const [[nodiscard]] constexpr Vector3 operator+(const Vector3& other) const noexcept
{ {
return {this->x + v.x, this->y + v.y, z + v.z}; return {this->x + other.x, this->y + other.y, z + other.z};
} }
[[nodiscard]] constexpr Vector3 operator-(const Vector3& v) const [[nodiscard]] constexpr Vector3 operator-(const Vector3& other) const noexcept
{ {
return {this->x - v.x, this->y - v.y, z - v.z}; return {this->x - other.x, this->y - other.y, z - other.z};
} }
[[nodiscard]] constexpr Vector3 operator*(const float fl) const [[nodiscard]] constexpr Vector3 operator*(const Type& value) const noexcept
{ {
return {this->x * fl, this->y * fl, z * fl}; return {this->x * value, this->y * value, z * value};
} }
[[nodiscard]] constexpr Vector3 operator*(const Vector3& v) const [[nodiscard]] constexpr Vector3 operator*(const Vector3& other) const noexcept
{ {
return {this->x * v.x, this->y * v.y, z * v.z}; return {this->x * other.x, this->y * other.y, z * other.z};
} }
[[nodiscard]] constexpr Vector3 operator/(const float fl) const [[nodiscard]] constexpr Vector3 operator/(const Type& value) const noexcept
{ {
return {this->x / fl, this->y / fl, z / fl}; return {this->x / value, this->y / value, z / value};
} }
[[nodiscard]] constexpr Vector3 operator/(const Vector3& v) const [[nodiscard]] constexpr Vector3 operator/(const Vector3& other) const noexcept
{ {
return {this->x / v.x, this->y / v.y, z / v.z}; return {this->x / other.x, this->y / other.y, z / other.z};
} }
[[nodiscard]] constexpr Vector3 Cross(const Vector3 &v) const [[nodiscard]] constexpr Vector3 cross(const Vector3& other) const noexcept
{ {
return return {this->y * other.z - z * other.y, z * other.x - this->x * other.z,
{ this->x * other.y - this->y * other.x};
this->y * v.z - z * v.y,
z * v.x - this->x * v.z,
this->x * v.y - this->y * v.x
};
} }
[[nodiscard]] constexpr Type Sum() const
[[nodiscard]] constexpr Type sum() const noexcept
{ {
return Sum2D() + z; return sum_2d() + z;
} }
[[nodiscard]] std::expected<Angle<float, 0.f, 180.f, AngleFlags::Clamped>, Vector3Error> [[nodiscard]] std::expected<Angle<float, 0.f, 180.f, AngleFlags::Clamped>, Vector3Error>
AngleBetween(const Vector3& other) const angle_between(const Vector3& other) const noexcept
{ {
const auto bottom = Length() * other.Length(); const auto bottom = length() * other.length();
if (bottom == 0.f) if (bottom == 0.f)
return std::unexpected(Vector3Error::IMPOSSIBLE_BETWEEN_ANGLE); return std::unexpected(Vector3Error::IMPOSSIBLE_BETWEEN_ANGLE);
return Angle<float, 0.f, 180.f, AngleFlags::Clamped>::FromRadians(std::acos(Dot(other) / bottom)); return Angle<float, 0.f, 180.f, AngleFlags::Clamped>::from_radians(std::acos(dot(other) / bottom));
} }
[[nodiscard]] bool IsPerpendicular(const Vector3& other) const [[nodiscard]] bool is_perpendicular(const Vector3& other) const noexcept
{ {
if (const auto angle = AngleBetween(other)) if (const auto angle = angle_between(other))
return angle->AsDegrees() == 90.f; return angle->as_degrees() == 90.f;
return false; return false;
} }
[[nodiscard]] constexpr Type Sum2D() const [[nodiscard]] constexpr Type sum_2d() const noexcept
{ {
return Vector2<Type>::Sum(); return Vector2<Type>::sum();
} }
[[nodiscard]] constexpr std::tuple<Type, Type, Type> AsTuple() const [[nodiscard]] constexpr std::tuple<Type, Type, Type> as_tuple() const noexcept
{ {
return std::make_tuple(this->x, this->y, z); return std::make_tuple(this->x, this->y, z);
} }
[[nodiscard]] Vector3 ViewAngleTo(const Vector3 &other) const [[nodiscard]] Vector3 view_angle_to(const Vector3& other) const noexcept
{ {
const float distance = DistTo(other); const auto distance = distance_to(other);
const auto delta = other - *this; const auto delta = other - *this;
return return {angles::radians_to_degrees(std::asin(delta.z / distance)),
{ angles::radians_to_degrees(std::atan2(delta.y, delta.x)), 0};
angles::RadiansToDegrees(std::asin(delta.z / distance)),
angles::RadiansToDegrees(std::atan2(delta.y, delta.x)),
0
};
} }
}; };
} } // namespace omath
// ReSharper disable once CppRedundantNamespaceDefinition // ReSharper disable once CppRedundantNamespaceDefinition
namespace std namespace std
{ {
template<> template<> struct hash<omath::Vector3<float>>
struct hash<omath::Vector3<float>>
{ {
std::size_t operator()(const omath::Vector3<float>& vec) const noexcept std::size_t operator()(const omath::Vector3<float>& vec) const noexcept
{ {
std::size_t hash = 0; std::size_t hash = 0;
constexpr std::hash<float> hasher; constexpr std::hash<float> hasher;
hash ^= hasher(vec.x) + 0x9e3779b9 + (hash<<6) + (hash>>2); hash ^= hasher(vec.x) + 0x9e3779b9 + (hash << 6) + (hash >> 2);
hash ^= hasher(vec.y) + 0x9e3779b9 + (hash<<6) + (hash>>2); hash ^= hasher(vec.y) + 0x9e3779b9 + (hash << 6) + (hash >> 2);
hash ^= hasher(vec.z) + 0x9e3779b9 + (hash<<6) + (hash>>2); hash ^= hasher(vec.z) + 0x9e3779b9 + (hash << 6) + (hash >> 2);
return hash; return hash;
} }
}; };
} } // namespace std

View File

@@ -6,100 +6,102 @@
#include <algorithm> #include <algorithm>
#include <omath/vector3.hpp> #include <omath/vector3.hpp>
namespace omath namespace omath
{ {
template <class Type> template<class Type>
requires std::is_arithmetic_v<Type>
class Vector4 : public Vector3<Type> class Vector4 : public Vector3<Type>
{ {
public: public:
Type w; Type w;
constexpr Vector4(const Type& x, const Type& y, const Type& z, const Type& w) : Vector3<Type>(x, y, z), w(w) {} constexpr Vector4(const Type& x, const Type& y, const Type& z, const Type& w): Vector3<Type>(x, y, z), w(w)
constexpr Vector4() : Vector3<Type>(), w(0) {}; {
}
constexpr Vector4() noexcept : Vector3<Type>(), w(0) {};
[[nodiscard]] [[nodiscard]]
constexpr bool operator==(const Vector4& src) const constexpr bool operator==(const Vector4& other) const noexcept
{ {
return Vector3<Type>::operator==(src) && w == src.w; return Vector3<Type>::operator==(other) && w == other.w;
} }
[[nodiscard]] [[nodiscard]]
constexpr bool operator!=(const Vector4& src) const constexpr bool operator!=(const Vector4& other) const noexcept
{ {
return !(*this == src); return !(*this == other);
} }
constexpr Vector4& operator+=(const Vector4& v) constexpr Vector4& operator+=(const Vector4& other) noexcept
{ {
Vector3<Type>::operator+=(v); Vector3<Type>::operator+=(other);
w += v.w; w += other.w;
return *this; return *this;
} }
constexpr Vector4& operator-=(const Vector4& v) constexpr Vector4& operator-=(const Vector4& other) noexcept
{ {
Vector3<Type>::operator-=(v); Vector3<Type>::operator-=(other);
w -= v.w; w -= other.w;
return *this; return *this;
} }
constexpr Vector4& operator*=(const float scalar) constexpr Vector4& operator*=(const Type& value) noexcept
{ {
Vector3<Type>::operator*=(scalar); Vector3<Type>::operator*=(value);
w *= scalar; w *= value;
return *this; return *this;
} }
constexpr Vector4& operator*=(const Vector4& v) constexpr Vector4& operator*=(const Vector4& other) noexcept
{ {
Vector3<Type>::operator*=(v); Vector3<Type>::operator*=(other);
w *= v.w; w *= other.w;
return *this; return *this;
} }
constexpr Vector4& operator/=(const float scalar) constexpr Vector4& operator/=(const Type& value) noexcept
{ {
Vector3<Type>::operator/=(scalar); Vector3<Type>::operator/=(value);
w /= scalar; w /= value;
return *this; return *this;
} }
constexpr Vector4& operator/=(const Vector4& v) constexpr Vector4& operator/=(const Vector4& other) noexcept
{ {
Vector3<Type>::operator/=(v); Vector3<Type>::operator/=(other);
w /= v.w; w /= other.w;
return *this; return *this;
} }
[[nodiscard]] constexpr Type LengthSqr() const [[nodiscard]] constexpr Type length_sqr() const noexcept
{ {
return Vector3<Type>::LengthSqr() + w * w; return Vector3<Type>::length_sqr() + w * w;
} }
[[nodiscard]] constexpr Type Dot(const Vector4& vOther) const [[nodiscard]] constexpr Type dot(const Vector4& other) const noexcept
{ {
return Vector3<Type>::Dot(vOther) + w * vOther.w; return Vector3<Type>::dot(other) + w * other.w;
} }
[[nodiscard]] Vector3<Type> Length() const [[nodiscard]] Vector3<Type> length() const noexcept
{ {
return std::sqrt(LengthSqr()); return std::sqrt(length_sqr());
} }
constexpr Vector4& Abs() constexpr Vector4& abs() noexcept
{ {
Vector3<Type>::Abs(); Vector3<Type>::abs();
w = w < 0.f ? -w : w; w = w < 0.f ? -w : w;
return *this; return *this;
} }
constexpr Vector4& Clamp(const Type& min, const Type& max) constexpr Vector4& clamp(const Type& min, const Type& max) noexcept
{ {
this->x = std::clamp(this->x, min, max); this->x = std::clamp(this->x, min, max);
this->y = std::clamp(this->y, min, max); this->y = std::clamp(this->y, min, max);
@@ -109,65 +111,64 @@ namespace omath
} }
[[nodiscard]] [[nodiscard]]
constexpr Vector4 operator-() const constexpr Vector4 operator-() const noexcept
{ {
return {-this->x, -this->y, -this->z, -w}; return {-this->x, -this->y, -this->z, -w};
} }
[[nodiscard]] [[nodiscard]]
constexpr Vector4 operator+(const Vector4& v) const constexpr Vector4 operator+(const Vector4& other) const noexcept
{ {
return {this->x + v.x, this->y + v.y, this->z + v.z, w + v.w}; return {this->x + other.x, this->y + other.y, this->z + other.z, w + other.w};
} }
[[nodiscard]] [[nodiscard]]
constexpr Vector4 operator-(const Vector4& v) const constexpr Vector4 operator-(const Vector4& other) const noexcept
{ {
return {this->x - v.x, this->y - v.y, this->z - v.z, w - v.w}; return {this->x - other.x, this->y - other.y, this->z - other.z, w - other.w};
} }
[[nodiscard]] [[nodiscard]]
constexpr Vector4 operator*(const Type& scalar) const constexpr Vector4 operator*(const Type& value) const noexcept
{ {
return {this->x * scalar, this->y * scalar, this->z * scalar, w * scalar}; return {this->x * value, this->y * value, this->z * value, w * value};
} }
[[nodiscard]] [[nodiscard]]
constexpr Vector4 operator*(const Vector4& v) const constexpr Vector4 operator*(const Vector4& other) const noexcept
{ {
return {this->x * v.x, this->y * v.y, this->z * v.z, w * v.w}; return {this->x * other.x, this->y * other.y, this->z * other.z, w * other.w};
} }
[[nodiscard]] [[nodiscard]]
constexpr Vector4 operator/(const Type& scalar) const constexpr Vector4 operator/(const Type& value) const noexcept
{ {
return {this->x / scalar, this->y / scalar, this->z / scalar, w / scalar}; return {this->x / value, this->y / value, this->z / value, w / value};
} }
[[nodiscard]] [[nodiscard]]
constexpr Vector4 operator/(const Vector4& v) const constexpr Vector4 operator/(const Vector4& other) const noexcept
{ {
return {this->x / v.x, this->y / v.y, this->z / v.z, w / v.w}; return {this->x / other.x, this->y / other.y, this->z / other.z, w / other.w};
} }
[[nodiscard]] [[nodiscard]]
constexpr Type Sum() const constexpr Type sum() const noexcept
{ {
return Vector3<Type>::Sum() + w; return Vector3<Type>::sum() + w;
} }
#ifdef OMATH_IMGUI_INTEGRATION #ifdef OMATH_IMGUI_INTEGRATION
[[nodiscard]] [[nodiscard]]
ImVec4 ToImVec4() const ImVec4 to_im_vec4() const noexcept
{ {
return return {
{ static_cast<float>(this->x),
static_cast<float>(this->x), static_cast<float>(this->y),
static_cast<float>(this->y), static_cast<float>(this->z),
static_cast<float>(this->z), static_cast<float>(w),
static_cast<float>(w),
}; };
} }
#endif #endif
}; };
} } // namespace omath

View File

@@ -12,4 +12,4 @@ namespace omath
YawType yaw; YawType yaw;
RollType roll; RollType roll;
}; };
} } // namespace omath

View File

@@ -0,0 +1,54 @@
//
// Created by Vlad on 4/18/2025.
//
#include "omath/3d_primitives/box.hpp"
namespace omath::primitives
{
std::array<Triangle<Vector3<float>>, 12> create_box(const Vector3<float>& top, const Vector3<float>& bottom,
const Vector3<float>& dir_forward,
const Vector3<float>& dir_right, const float ratio) noexcept
{
const auto height = top.distance_to(bottom);
const auto side_size = height / ratio;
// corner layout (03 bottom, 47 top)
std::array<Vector3<float>, 8> p;
p[0] = bottom + (dir_forward + dir_right) * side_size; // frontrightbottom
p[1] = bottom + (dir_forward - dir_right) * side_size; // frontleftbottom
p[2] = bottom + (-dir_forward + dir_right) * side_size; // backrightbottom
p[3] = bottom + (-dir_forward - dir_right) * side_size; // backleftbottom
p[4] = top + (dir_forward + dir_right) * side_size; // frontrighttop
p[5] = top + (dir_forward - dir_right) * side_size; // frontlefttop
p[6] = top + (-dir_forward + dir_right) * side_size; // backrighttop
p[7] = top + (-dir_forward - dir_right) * side_size; // backlefttop
std::array<Triangle<Vector3<float>>, 12> poly;
// bottom face (+Y up ⇒ wind CW when viewed from above)
poly[0] = {p[0], p[2], p[3]};
poly[1] = {p[0], p[3], p[1]};
// top face
poly[2] = {p[4], p[7], p[6]};
poly[3] = {p[4], p[5], p[7]};
// front face
poly[4] = {p[0], p[5], p[1]};
poly[5] = {p[0], p[4], p[5]};
// right face
poly[6] = {p[0], p[6], p[2]};
poly[7] = {p[0], p[4], p[6]};
// back face
poly[8] = {p[2], p[7], p[3]};
poly[9] = {p[2], p[6], p[7]};
// left face
poly[10] = {p[1], p[7], p[5]};
poly[11] = {p[1], p[3], p[7]};
return poly;
}
} // namespace omath::primitives

View File

@@ -1,10 +0,0 @@
target_sources(omath PRIVATE
matrix.cpp
color.cpp
)
add_subdirectory(projectile_prediction)
add_subdirectory(pathfinding)
add_subdirectory(projection)
add_subdirectory(collision)
add_subdirectory(engines)

View File

@@ -1,3 +0,0 @@
target_sources(omath PRIVATE
line_tracer.cpp
)

View File

@@ -5,58 +5,59 @@
namespace omath::collision namespace omath::collision
{ {
bool LineTracer::CanTraceLine(const Ray& ray, const Triangle<Vector3<float>>& triangle) bool LineTracer::can_trace_line(const Ray& ray, const Triangle<Vector3<float>>& triangle) noexcept
{ {
return GetRayHitPoint(ray, triangle) == ray.end; return get_ray_hit_point(ray, triangle) == ray.end;
} }
Vector3<float> Ray::DirectionVector() const Vector3<float> Ray::direction_vector() const noexcept
{ {
return end - start; return end - start;
} }
Vector3<float> Ray::DirectionVectorNormalized() const Vector3<float> Ray::direction_vector_normalized() const noexcept
{ {
return DirectionVector().Normalized(); return direction_vector().normalized();
} }
Vector3<float> LineTracer::GetRayHitPoint(const Ray& ray, const Triangle<Vector3<float>>& triangle) Vector3<float> LineTracer::get_ray_hit_point(const Ray& ray, const Triangle<Vector3<float>>& triangle) noexcept
{ {
constexpr float kEpsilon = std::numeric_limits<float>::epsilon(); constexpr float k_epsilon = std::numeric_limits<float>::epsilon();
const auto sideA = triangle.SideAVector(); const auto side_a = triangle.side_a_vector();
const auto sideB = triangle.SideBVector(); const auto side_b = triangle.side_b_vector();
const auto ray_dir = ray.direction_vector();
const auto rayDir = ray.DirectionVector(); const auto p = ray_dir.cross(side_b);
const auto det = side_a.dot(p);
const auto p = rayDir.Cross(sideB); if (std::abs(det) < k_epsilon)
const auto det = sideA.Dot(p);
if (std::abs(det) < kEpsilon)
return ray.end; return ray.end;
const auto invDet = 1.0f / det; const auto inv_det = 1.0f / det;
const auto t = ray.start - triangle.m_vertex2; const auto t = ray.start - triangle.m_vertex2;
const auto u = t.Dot(p) * invDet; const auto u = t.dot(p) * inv_det;
if ((u < 0 && std::abs(u) > k_epsilon) || (u > 1 && std::abs(u - 1) > k_epsilon))
if ((u < 0 && std::abs(u) > kEpsilon) || (u > 1 && std::abs(u - 1) > kEpsilon))
return ray.end; return ray.end;
const auto q = t.Cross(sideA); const auto q = t.cross(side_a);
const auto v = rayDir.Dot(q) * invDet; // ReSharper disable once CppTooWideScopeInitStatement
const auto v = ray_dir.dot(q) * inv_det;
if ((v < 0 && std::abs(v) > k_epsilon) || (u + v > 1 && std::abs(u + v - 1) > k_epsilon))
if ((v < 0 && std::abs(v) > kEpsilon) || (u + v > 1 && std::abs(u + v - 1) > kEpsilon))
return ray.end; return ray.end;
const auto tHit = sideB.Dot(q) * invDet; const auto t_hit = side_b.dot(q) * inv_det;
if (ray.infinite_length)
if (tHit <= kEpsilon) {
if (t_hit <= k_epsilon)
return ray.end;
}
else if (t_hit <= k_epsilon || t_hit > 1.0f - k_epsilon)
return ray.end; return ray.end;
return ray.start + rayDir * tHit; return ray.start + ray_dir * t_hit;
} }
} // namespace omath::collision } // namespace omath::collision

View File

@@ -1,13 +0,0 @@
//
// Created by vlad on 2/4/24.
//
#include "omath/color.hpp"
#include <algorithm>
#include <cmath>
namespace omath
{
}

View File

@@ -1,4 +0,0 @@
add_subdirectory(source_engine)
add_subdirectory(opengl_engine)
add_subdirectory(iw_engine)
add_subdirectory(unity_engine)

View File

@@ -1 +0,0 @@
target_sources(omath PRIVATE camera.cpp formulas.cpp)

View File

@@ -7,28 +7,27 @@
namespace omath::iw_engine namespace omath::iw_engine
{ {
Camera::Camera(const Vector3<float>& position, const ViewAngles& viewAngles, const projection::ViewPort& viewPort, Camera::Camera(const Vector3<float>& position, const ViewAngles& view_angles, const projection::ViewPort& view_port,
const Angle<float, 0.f, 180.f, AngleFlags::Clamped>& fov, const float near, const float far) : const Angle<float, 0.f, 180.f, AngleFlags::Clamped>& fov, const float near, const float far)
projection::Camera<Mat4x4, ViewAngles>(position, viewAngles, viewPort, fov, near, far) : projection::Camera<Mat4X4, ViewAngles>(position, view_angles, view_port, fov, near, far)
{ {
} }
void Camera::LookAt([[maybe_unused]] const Vector3<float>& target) void Camera::look_at([[maybe_unused]] const Vector3<float>& target)
{ {
const float distance = m_origin.DistTo(target); const float distance = m_origin.distance_to(target);
const auto delta = target - m_origin; const auto delta = target - m_origin;
m_view_angles.pitch = PitchAngle::from_radians(std::asin(delta.z / distance));
m_viewAngles.pitch = PitchAngle::FromRadians(std::asin(delta.z / distance)); m_view_angles.yaw = -YawAngle::from_radians(std::atan2(delta.y, delta.x));
m_viewAngles.yaw = -YawAngle::FromRadians(std::atan2(delta.y, delta.x)); m_view_angles.roll = RollAngle::from_radians(0.f);
m_viewAngles.roll = RollAngle::FromRadians(0.f);
} }
Mat4x4 Camera::CalcViewMatrix() const Mat4X4 Camera::calc_view_matrix() const noexcept
{ {
return iw_engine::CalcViewMatrix(m_viewAngles, m_origin); return iw_engine::calc_view_matrix(m_view_angles, m_origin);
} }
Mat4x4 Camera::CalcProjectionMatrix() const Mat4X4 Camera::calc_projection_matrix() const noexcept
{ {
return CalcPerspectiveProjectionMatrix(m_fieldOfView.AsDegrees(), m_viewPort.AspectRatio(), m_nearPlaneDistance, return calc_perspective_projection_matrix(m_field_of_view.as_degrees(), m_view_port.aspect_ratio(),
m_farPlaneDistance); m_near_plane_distance, m_far_plane_distance);
} }
} // namespace omath::openg } // namespace omath::iw_engine

View File

@@ -3,46 +3,49 @@
// //
#include "omath/engines/iw_engine/formulas.hpp" #include "omath/engines/iw_engine/formulas.hpp"
namespace omath::iw_engine namespace omath::iw_engine
{ {
Vector3<float> ForwardVector(const ViewAngles& angles) Vector3<float> forward_vector(const ViewAngles& angles) noexcept
{ {
const auto vec = MatRotation(angles) * MatColumnFromVector(kAbsForward); const auto vec = rotation_matrix(angles) * mat_column_from_vector(k_abs_forward);
return {vec.At(0, 0), vec.At(1, 0), vec.At(2, 0)}; return {vec.at(0, 0), vec.at(1, 0), vec.at(2, 0)};
} }
Vector3<float> RightVector(const ViewAngles& angles) Vector3<float> right_vector(const ViewAngles& angles) noexcept
{ {
const auto vec = MatRotation(angles) * MatColumnFromVector(kAbsRight); const auto vec = rotation_matrix(angles) * mat_column_from_vector(k_abs_right);
return {vec.At(0, 0), vec.At(1, 0), vec.At(2, 0)}; return {vec.at(0, 0), vec.at(1, 0), vec.at(2, 0)};
} }
Vector3<float> UpVector(const ViewAngles& angles) Vector3<float> up_vector(const ViewAngles& angles) noexcept
{ {
const auto vec = MatRotation(angles) * MatColumnFromVector(kAbsUp); const auto vec = rotation_matrix(angles) * mat_column_from_vector(k_abs_up);
return {vec.At(0, 0), vec.At(1, 0), vec.At(2, 0)}; return {vec.at(0, 0), vec.at(1, 0), vec.at(2, 0)};
}
Mat4X4 rotation_matrix(const ViewAngles& angles) noexcept
{
return mat_rotation_axis_z(angles.yaw) * mat_rotation_axis_y(angles.pitch) * mat_rotation_axis_x(angles.roll);
} }
Mat4x4 CalcViewMatrix(const ViewAngles& angles, const Vector3<float>& cam_origin) Mat4X4 calc_view_matrix(const ViewAngles& angles, const Vector3<float>& cam_origin) noexcept
{ {
return MatCameraView(ForwardVector(angles), RightVector(angles), UpVector(angles), cam_origin); return mat_camera_view(forward_vector(angles), right_vector(angles), up_vector(angles), cam_origin);
} }
Mat4x4 CalcPerspectiveProjectionMatrix(const float fieldOfView, const float aspectRatio, const float near, Mat4X4 calc_perspective_projection_matrix(const float field_of_view, const float aspect_ratio, const float near,
const float far) const float far) noexcept
{ {
// NOTE: Need magic number to fix fov calculation, since IW engine inherit Quake proj matrix calculation // NOTE: Need magic number to fix fov calculation, since IW engine inherit Quake proj matrix calculation
constexpr auto kMultiplyFactor = 0.75f; constexpr auto k_multiply_factor = 0.75f;
const float fovHalfTan = std::tan(angles::DegreesToRadians(fieldOfView) / 2.f) * kMultiplyFactor; const float fov_half_tan = std::tan(angles::degrees_to_radians(field_of_view) / 2.f) * k_multiply_factor;
return { return {
{1.f / (aspectRatio * fovHalfTan), 0, 0, 0}, {1.f / (aspect_ratio * fov_half_tan), 0, 0, 0},
{0, 1.f / (fovHalfTan), 0, 0}, {0, 1.f / (fov_half_tan), 0, 0},
{0, 0, (far + near) / (far - near), -(2.f * far * near) / (far - near)}, {0, 0, (far + near) / (far - near), -(2.f * far * near) / (far - near)},
{0, 0, 1, 0}, {0, 0, 1, 0},
}; };

View File

@@ -1 +0,0 @@
target_sources(omath PRIVATE camera.cpp formulas.cpp)

View File

@@ -4,32 +4,30 @@
#include "omath/engines/opengl_engine/camera.hpp" #include "omath/engines/opengl_engine/camera.hpp"
#include "omath/engines/opengl_engine/formulas.hpp" #include "omath/engines/opengl_engine/formulas.hpp"
namespace omath::opengl_engine namespace omath::opengl_engine
{ {
Camera::Camera(const Vector3<float>& position, const ViewAngles& viewAngles, const projection::ViewPort& viewPort, Camera::Camera(const Vector3<float>& position, const ViewAngles& view_angles, const projection::ViewPort& view_port,
const Angle<float, 0.f, 180.f, AngleFlags::Clamped>& fov, const float near, const float far) : const Angle<float, 0.f, 180.f, AngleFlags::Clamped>& fov, const float near, const float far)
projection::Camera<Mat4x4, ViewAngles>(position, viewAngles, viewPort, fov, near, far) : projection::Camera<Mat4X4, ViewAngles>(position, view_angles, view_port, fov, near, far)
{ {
} }
void Camera::LookAt([[maybe_unused]] const Vector3<float>& target) void Camera::look_at([[maybe_unused]] const Vector3<float>& target)
{ {
const float distance = m_origin.DistTo(target); const float distance = m_origin.distance_to(target);
const auto delta = target - m_origin; const auto delta = target - m_origin;
m_view_angles.pitch = PitchAngle::from_radians(std::asin(delta.z / distance));
m_viewAngles.pitch = PitchAngle::FromRadians(std::asin(delta.z / distance)); m_view_angles.yaw = -YawAngle::from_radians(std::atan2(delta.y, delta.x));
m_viewAngles.yaw = -YawAngle::FromRadians(std::atan2(delta.y, delta.x)); m_view_angles.roll = RollAngle::from_radians(0.f);
m_viewAngles.roll = RollAngle::FromRadians(0.f);
} }
Mat4x4 Camera::CalcViewMatrix() const Mat4X4 Camera::calc_view_matrix() const noexcept
{ {
return opengl_engine::CalcViewMatrix(m_viewAngles, m_origin); return opengl_engine::calc_view_matrix(m_view_angles, m_origin);
} }
Mat4x4 Camera::CalcProjectionMatrix() const Mat4X4 Camera::calc_projection_matrix() const noexcept
{ {
return CalcPerspectiveProjectionMatrix(m_fieldOfView.AsDegrees(), m_viewPort.AspectRatio(), m_nearPlaneDistance, return calc_perspective_projection_matrix(m_field_of_view.as_degrees(), m_view_port.aspect_ratio(),
m_farPlaneDistance); m_near_plane_distance, m_far_plane_distance);
} }
} // namespace omath::opengl } // namespace omath::opengl_engine

View File

@@ -3,41 +3,48 @@
// //
#include "omath/engines/opengl_engine/formulas.hpp" #include "omath/engines/opengl_engine/formulas.hpp"
namespace omath::opengl_engine namespace omath::opengl_engine
{ {
Vector3<float> ForwardVector(const ViewAngles& angles) Vector3<float> forward_vector(const ViewAngles& angles) noexcept
{ {
const auto vec = MatRotation(angles) * MatColumnFromVector(kAbsForward); const auto vec
= rotation_matrix(angles) * mat_column_from_vector<float, MatStoreType::COLUMN_MAJOR>(k_abs_forward);
return {vec.At(0, 0), vec.At(1, 0), vec.At(2, 0)}; return {vec.at(0, 0), vec.at(1, 0), vec.at(2, 0)};
} }
Vector3<float> RightVector(const ViewAngles& angles) Vector3<float> right_vector(const ViewAngles& angles) noexcept
{ {
const auto vec = MatRotation(angles) * MatColumnFromVector(kAbsRight); const auto vec
= rotation_matrix(angles) * mat_column_from_vector<float, MatStoreType::COLUMN_MAJOR>(k_abs_right);
return {vec.At(0, 0), vec.At(1, 0), vec.At(2, 0)}; return {vec.at(0, 0), vec.at(1, 0), vec.at(2, 0)};
} }
Vector3<float> UpVector(const ViewAngles& angles) Vector3<float> up_vector(const ViewAngles& angles) noexcept
{ {
const auto vec = MatRotation(angles) * MatColumnFromVector(kAbsUp); const auto vec = rotation_matrix(angles) * mat_column_from_vector<float, MatStoreType::COLUMN_MAJOR>(k_abs_up);
return {vec.At(0, 0), vec.At(1, 0), vec.At(2, 0)}; return {vec.at(0, 0), vec.at(1, 0), vec.at(2, 0)};
} }
Mat4x4 CalcViewMatrix(const ViewAngles& angles, const Vector3<float>& cam_origin) Mat4X4 calc_view_matrix(const ViewAngles& angles, const Vector3<float>& cam_origin) noexcept
{ {
return MatCameraView<float, MatStoreType::COLUMN_MAJOR>(-ForwardVector(angles), RightVector(angles), return mat_camera_view<float, MatStoreType::COLUMN_MAJOR>(-forward_vector(angles), right_vector(angles),
UpVector(angles), cam_origin); up_vector(angles), cam_origin);
} }
Mat4x4 CalcPerspectiveProjectionMatrix(const float fieldOfView, const float aspectRatio, const float near, Mat4X4 rotation_matrix(const ViewAngles& angles) noexcept
const float far)
{ {
const float fovHalfTan = std::tan(angles::DegreesToRadians(fieldOfView) / 2.f); return mat_rotation_axis_x<float, MatStoreType::COLUMN_MAJOR>(-angles.pitch)
* mat_rotation_axis_y<float, MatStoreType::COLUMN_MAJOR>(-angles.yaw)
* mat_rotation_axis_z<float, MatStoreType::COLUMN_MAJOR>(angles.roll);
}
Mat4X4 calc_perspective_projection_matrix(const float field_of_view, const float aspect_ratio, const float near,
const float far) noexcept
{
const float fov_half_tan = std::tan(angles::degrees_to_radians(field_of_view) / 2.f);
return { return {
{1.f / (aspectRatio * fovHalfTan), 0, 0, 0}, {1.f / (aspect_ratio * fov_half_tan), 0, 0, 0},
{0, 1.f / (fovHalfTan), 0, 0}, {0, 1.f / (fov_half_tan), 0, 0},
{0, 0, -(far + near) / (far - near), -(2.f * far * near) / (far - near)}, {0, 0, -(far + near) / (far - near), -(2.f * far * near) / (far - near)},
{0, 0, -1, 0}, {0, 0, -1, 0},
}; };

View File

@@ -1 +0,0 @@
target_sources(omath PRIVATE camera.cpp formulas.cpp)

View File

@@ -4,34 +4,32 @@
#include "omath/engines/source_engine/camera.hpp" #include "omath/engines/source_engine/camera.hpp"
#include "omath/engines/source_engine/formulas.hpp" #include "omath/engines/source_engine/formulas.hpp"
namespace omath::source_engine namespace omath::source_engine
{ {
Camera::Camera(const Vector3<float>& position, const ViewAngles& viewAngles, const projection::ViewPort& viewPort, Camera::Camera(const Vector3<float>& position, const ViewAngles& view_angles, const projection::ViewPort& view_port,
const projection::FieldOfView& fov, const float near, const float far) : const projection::FieldOfView& fov, const float near, const float far)
projection::Camera<Mat4x4, ViewAngles>(position, viewAngles, viewPort, fov, near, far) : projection::Camera<Mat4X4, ViewAngles>(position, view_angles, view_port, fov, near, far)
{ {
} }
void Camera::LookAt(const Vector3<float>& target) void Camera::look_at(const Vector3<float>& target)
{ {
const float distance = m_origin.DistTo(target); const float distance = m_origin.distance_to(target);
const auto delta = target - m_origin; const auto delta = target - m_origin;
m_view_angles.pitch = PitchAngle::from_radians(std::asin(delta.z / distance));
m_viewAngles.pitch = PitchAngle::FromRadians(std::asin(delta.z / distance)); m_view_angles.yaw = -YawAngle::from_radians(std::atan2(delta.y, delta.x));
m_viewAngles.yaw = -YawAngle::FromRadians(std::atan2(delta.y, delta.x)); m_view_angles.roll = RollAngle::from_radians(0.f);
m_viewAngles.roll = RollAngle::FromRadians(0.f);
} }
Mat4x4 Camera::CalcViewMatrix() const Mat4X4 Camera::calc_view_matrix() const noexcept
{ {
return source_engine::CalcViewMatrix(m_viewAngles, m_origin); return source_engine::calc_view_matrix(m_view_angles, m_origin);
} }
Mat4x4 Camera::CalcProjectionMatrix() const Mat4X4 Camera::calc_projection_matrix() const noexcept
{ {
return CalcPerspectiveProjectionMatrix(m_fieldOfView.AsDegrees(), m_viewPort.AspectRatio(), m_nearPlaneDistance, return calc_perspective_projection_matrix(m_field_of_view.as_degrees(), m_view_port.aspect_ratio(),
m_farPlaneDistance); m_near_plane_distance, m_far_plane_distance);
} }
} // namespace omath::source } // namespace omath::source_engine

View File

@@ -3,45 +3,49 @@
// //
#include <omath/engines/source_engine/formulas.hpp> #include <omath/engines/source_engine/formulas.hpp>
namespace omath::source_engine namespace omath::source_engine
{ {
Vector3<float> ForwardVector(const ViewAngles& angles) Vector3<float> forward_vector(const ViewAngles& angles) noexcept
{ {
const auto vec = MatRotation(angles) * MatColumnFromVector(kAbsForward); const auto vec = rotation_matrix(angles) * mat_column_from_vector(k_abs_forward);
return {vec.At(0, 0), vec.At(1, 0), vec.At(2, 0)}; return {vec.at(0, 0), vec.at(1, 0), vec.at(2, 0)};
} }
Vector3<float> RightVector(const ViewAngles& angles) Mat4X4 rotation_matrix(const ViewAngles& angles) noexcept
{ {
const auto vec = MatRotation(angles) * MatColumnFromVector(kAbsRight); return mat_rotation_axis_z(angles.yaw) * mat_rotation_axis_y(angles.pitch) * mat_rotation_axis_x(angles.roll);
return {vec.At(0, 0), vec.At(1, 0), vec.At(2, 0)};
}
Vector3<float> UpVector(const ViewAngles& angles)
{
const auto vec = MatRotation(angles) * MatColumnFromVector(kAbsUp);
return {vec.At(0, 0), vec.At(1, 0), vec.At(2, 0)};
} }
Mat4x4 CalcViewMatrix(const ViewAngles& angles, const Vector3<float>& cam_origin) Vector3<float> right_vector(const ViewAngles& angles) noexcept
{ {
return MatCameraView(ForwardVector(angles), RightVector(angles), UpVector(angles), cam_origin); const auto vec = rotation_matrix(angles) * mat_column_from_vector(k_abs_right);
return {vec.at(0, 0), vec.at(1, 0), vec.at(2, 0)};
}
Vector3<float> up_vector(const ViewAngles& angles) noexcept
{
const auto vec = rotation_matrix(angles) * mat_column_from_vector(k_abs_up);
return {vec.at(0, 0), vec.at(1, 0), vec.at(2, 0)};
} }
Mat4x4 CalcPerspectiveProjectionMatrix(const float fieldOfView, const float aspectRatio, const float near, Mat4X4 calc_view_matrix(const ViewAngles& angles, const Vector3<float>& cam_origin) noexcept
const float far) {
return mat_camera_view(forward_vector(angles), right_vector(angles), up_vector(angles), cam_origin);
}
Mat4X4 calc_perspective_projection_matrix(const float field_of_view, const float aspect_ratio, const float near,
const float far) noexcept
{ {
// NOTE: Need magic number to fix fov calculation, since source inherit Quake proj matrix calculation // NOTE: Need magic number to fix fov calculation, since source inherit Quake proj matrix calculation
constexpr auto kMultiplyFactor = 0.75f; constexpr auto k_multiply_factor = 0.75f;
const float fovHalfTan = std::tan(angles::DegreesToRadians(fieldOfView) / 2.f) * kMultiplyFactor; const float fov_half_tan = std::tan(angles::degrees_to_radians(field_of_view) / 2.f) * k_multiply_factor;
return { return {
{1.f / (aspectRatio * fovHalfTan), 0, 0, 0}, {1.f / (aspect_ratio * fov_half_tan), 0, 0, 0},
{0, 1.f / (fovHalfTan), 0, 0}, {0, 1.f / (fov_half_tan), 0, 0},
{0, 0, (far + near) / (far - near), -(2.f * far * near) / (far - near)}, {0, 0, (far + near) / (far - near), -(2.f * far * near) / (far - near)},
{0, 0, 1, 0}, {0, 0, 1, 0},
}; };

View File

@@ -1 +0,0 @@
target_sources(omath PRIVATE formulas.cpp camera.cpp)

View File

@@ -4,25 +4,24 @@
#include <omath/engines/unity_engine/camera.hpp> #include <omath/engines/unity_engine/camera.hpp>
#include <omath/engines/unity_engine/formulas.hpp> #include <omath/engines/unity_engine/formulas.hpp>
namespace omath::unity_engine namespace omath::unity_engine
{ {
Camera::Camera(const Vector3<float>& position, const ViewAngles& viewAngles, const projection::ViewPort& viewPort, Camera::Camera(const Vector3<float>& position, const ViewAngles& view_angles, const projection::ViewPort& view_port,
const projection::FieldOfView& fov, const float near, const float far) : const projection::FieldOfView& fov, const float near, const float far)
projection::Camera<Mat4x4, ViewAngles>(position, viewAngles, viewPort, fov, near, far) : projection::Camera<Mat4X4, ViewAngles>(position, view_angles, view_port, fov, near, far)
{ {
} }
void Camera::LookAt([[maybe_unused]] const Vector3<float>& target) void Camera::look_at([[maybe_unused]] const Vector3<float>& target)
{ {
throw std::runtime_error("Not implemented"); throw std::runtime_error("Not implemented");
} }
Mat4x4 Camera::CalcViewMatrix() const Mat4X4 Camera::calc_view_matrix() const noexcept
{ {
return unity_engine::CalcViewMatrix(m_viewAngles, m_origin); return unity_engine::calc_view_matrix(m_view_angles, m_origin);
} }
Mat4x4 Camera::CalcProjectionMatrix() const Mat4X4 Camera::calc_projection_matrix() const noexcept
{ {
return CalcPerspectiveProjectionMatrix(m_fieldOfView.AsDegrees(), m_viewPort.AspectRatio(), m_nearPlaneDistance, return calc_perspective_projection_matrix(m_field_of_view.as_degrees(), m_view_port.aspect_ratio(),
m_farPlaneDistance); m_near_plane_distance, m_far_plane_distance);
} }
} // namespace omath::unity_engine } // namespace omath::unity_engine

View File

@@ -3,41 +3,45 @@
// //
#include "omath/engines/unity_engine/formulas.hpp" #include "omath/engines/unity_engine/formulas.hpp"
namespace omath::unity_engine namespace omath::unity_engine
{ {
Vector3<float> ForwardVector(const ViewAngles& angles) Vector3<float> forward_vector(const ViewAngles& angles) noexcept
{ {
const auto vec = MatRotation(angles) * MatColumnFromVector(kAbsForward); const auto vec = rotation_matrix(angles) * mat_column_from_vector(k_abs_forward);
return {vec.At(0, 0), vec.At(1, 0), vec.At(2, 0)}; return {vec.at(0, 0), vec.at(1, 0), vec.at(2, 0)};
} }
Vector3<float> RightVector(const ViewAngles& angles) Vector3<float> right_vector(const ViewAngles& angles) noexcept
{ {
const auto vec = MatRotation(angles) * MatColumnFromVector(kAbsRight); const auto vec = rotation_matrix(angles) * mat_column_from_vector(k_abs_right);
return {vec.At(0, 0), vec.At(1, 0), vec.At(2, 0)}; return {vec.at(0, 0), vec.at(1, 0), vec.at(2, 0)};
} }
Vector3<float> UpVector(const ViewAngles& angles) Vector3<float> up_vector(const ViewAngles& angles) noexcept
{ {
const auto vec = MatRotation(angles) * MatColumnFromVector(kAbsUp); const auto vec = rotation_matrix(angles) * mat_column_from_vector(k_abs_up);
return {vec.At(0, 0), vec.At(1, 0), vec.At(2, 0)}; return {vec.at(0, 0), vec.at(1, 0), vec.at(2, 0)};
} }
Mat4x4 CalcViewMatrix(const ViewAngles& angles, const Vector3<float>& cam_origin) Mat4X4 calc_view_matrix(const ViewAngles& angles, const Vector3<float>& cam_origin) noexcept
{ {
return MatCameraView<float, MatStoreType::ROW_MAJOR>(ForwardVector(angles), -RightVector(angles), return mat_camera_view<float, MatStoreType::ROW_MAJOR>(forward_vector(angles), -right_vector(angles),
UpVector(angles), cam_origin); up_vector(angles), cam_origin);
} }
Mat4x4 CalcPerspectiveProjectionMatrix(const float fieldOfView, const float aspectRatio, const float near, Mat4X4 rotation_matrix(const ViewAngles& angles) noexcept
const float far)
{ {
const float fovHalfTan = std::tan(angles::DegreesToRadians(fieldOfView) / 2.f); return mat_rotation_axis_x<float, MatStoreType::ROW_MAJOR>(angles.pitch)
* mat_rotation_axis_y<float, MatStoreType::ROW_MAJOR>(angles.yaw)
* mat_rotation_axis_z<float, MatStoreType::ROW_MAJOR>(angles.roll);
}
Mat4X4 calc_perspective_projection_matrix(const float field_of_view, const float aspect_ratio, const float near,
const float far) noexcept
{
const float fov_half_tan = std::tan(angles::degrees_to_radians(field_of_view) / 2.f);
return { return {
{1.f / (aspectRatio * fovHalfTan), 0, 0, 0}, {1.f / (aspect_ratio * fov_half_tan), 0, 0, 0},
{0, 1.f / (fovHalfTan), 0, 0}, {0, 1.f / (fov_half_tan), 0, 0},
{0, 0, (far + near) / (far - near), -(2.f * far * near) / (far - near)}, {0, 0, (far + near) / (far - near), -(2.f * far * near) / (far - near)},
{0, 0, -1.f, 0}, {0, 0, -1.f, 0},
}; };

View File

@@ -1,14 +1,11 @@
#include "omath/matrix.hpp" #include "omath/matrix.hpp"
#include "omath/angles.hpp" #include "omath/angles.hpp"
#include "omath/vector3.hpp" #include "omath/vector3.hpp"
#include <complex> #include <complex>
#include <format> #include <format>
#include <stdexcept> #include <stdexcept>
#include <utility> #include <utility>
namespace omath namespace omath
{ {
Matrix::Matrix(const size_t rows, const size_t columns) Matrix::Matrix(const size_t rows, const size_t columns)
@@ -21,7 +18,7 @@ namespace omath
m_data = std::make_unique<float[]>(m_rows * m_columns); m_data = std::make_unique<float[]>(m_rows * m_columns);
Set(0.f); set(0.f);
} }
Matrix::Matrix(const std::initializer_list<std::initializer_list<float>>& rows) Matrix::Matrix(const std::initializer_list<std::initializer_list<float>>& rows)
@@ -29,7 +26,6 @@ namespace omath
m_rows = rows.size(); m_rows = rows.size();
m_columns = rows.begin()->size(); m_columns = rows.begin()->size();
for (const auto& row: rows) for (const auto& row: rows)
if (row.size() != m_columns) if (row.size() != m_columns)
throw std::invalid_argument("All rows must have the same number of columns."); throw std::invalid_argument("All rows must have the same number of columns.");
@@ -41,7 +37,7 @@ namespace omath
{ {
size_t j = 0; size_t j = 0;
for (const auto& value: row) for (const auto& value: row)
At(i, j++) = value; at(i, j++) = value;
++i; ++i;
} }
} }
@@ -55,29 +51,28 @@ namespace omath
for (size_t i = 0; i < m_rows; ++i) for (size_t i = 0; i < m_rows; ++i)
for (size_t j = 0; j < m_columns; ++j) for (size_t j = 0; j < m_columns; ++j)
At(i, j) = other.At(i, j); at(i, j) = other.at(i, j);
} }
Matrix::Matrix(const size_t rows, const size_t columns, const float* pRaw) Matrix::Matrix(const size_t rows, const size_t columns, const float* raw_data)
{ {
m_rows = rows; m_rows = rows;
m_columns = columns; m_columns = columns;
m_data = std::make_unique<float[]>(m_rows * m_columns); m_data = std::make_unique<float[]>(m_rows * m_columns);
for (size_t i = 0; i < rows * columns; ++i) for (size_t i = 0; i < rows * columns; ++i)
At(i / rows, i % columns) = pRaw[i]; at(i / rows, i % columns) = raw_data[i];
} }
size_t Matrix::RowCount() const noexcept size_t Matrix::row_count() const noexcept
{ {
return m_rows; return m_rows;
} }
float& Matrix::operator[](const size_t row, const size_t column) float& Matrix::operator[](const size_t row, const size_t column)
{ {
return At(row, column); return at(row, column);
} }
Matrix::Matrix(Matrix&& other) noexcept Matrix::Matrix(Matrix&& other) noexcept
@@ -92,35 +87,35 @@ namespace omath
other.m_data = nullptr; other.m_data = nullptr;
} }
size_t Matrix::ColumnsCount() const noexcept size_t Matrix::columns_count() const noexcept
{ {
return m_columns; return m_columns;
} }
std::pair<size_t, size_t> Matrix::Size() const noexcept std::pair<size_t, size_t> Matrix::size() const noexcept
{ {
return {RowCount(), ColumnsCount()}; return {row_count(), columns_count()};
} }
float& Matrix::At(const size_t iRow, const size_t iCol) float& Matrix::at(const size_t row, const size_t col)
{ {
return const_cast<float&>(std::as_const(*this).At(iRow, iCol)); return const_cast<float&>(std::as_const(*this).at(row, col));
} }
float Matrix::Sum() float Matrix::sum()
{ {
float sum = 0; float sum = 0;
for (size_t i = 0; i < RowCount(); i++) for (size_t i = 0; i < row_count(); i++)
for (size_t j = 0; j < ColumnsCount(); j++) for (size_t j = 0; j < columns_count(); j++)
sum += At(i, j); sum += at(i, j);
return sum; return sum;
} }
const float& Matrix::At(const size_t iRow, const size_t iCol) const const float& Matrix::at(const size_t row, const size_t col) const
{ {
return m_data[iRow * m_columns + iCol]; return m_data[row * m_columns + col];
} }
Matrix Matrix::operator*(const Matrix& other) const Matrix Matrix::operator*(const Matrix& other) const
@@ -128,15 +123,14 @@ namespace omath
if (m_columns != other.m_rows) if (m_columns != other.m_rows)
throw std::runtime_error("n != m"); throw std::runtime_error("n != m");
auto outMat = Matrix(m_rows, other.m_columns); auto out_mat = Matrix(m_rows, other.m_columns);
for (size_t d = 0; d < m_rows; ++d) for (size_t d = 0; d < m_rows; ++d)
for (size_t i = 0; i < other.m_columns; ++i) for (size_t i = 0; i < other.m_columns; ++i)
for (size_t j = 0; j < other.m_rows; ++j) for (size_t j = 0; j < other.m_rows; ++j)
outMat.At(d, i) += At(d, j) * other.At(j, i); out_mat.at(d, i) += at(d, j) * other.at(j, i);
return out_mat;
return outMat;
} }
Matrix& Matrix::operator*=(const Matrix& other) Matrix& Matrix::operator*=(const Matrix& other)
@@ -150,22 +144,22 @@ namespace omath
auto out = *this; auto out = *this;
for (size_t i = 0; i < m_rows; ++i) for (size_t i = 0; i < m_rows; ++i)
for (size_t j = 0; j < m_columns; ++j) for (size_t j = 0; j < m_columns; ++j)
out.At(i, j) *= f; out.at(i, j) *= f;
return out; return out;
} }
Matrix& Matrix::operator*=(const float f) Matrix& Matrix::operator*=(const float f)
{ {
for (size_t i = 0; i < RowCount(); i++) for (size_t i = 0; i < row_count(); i++)
for (size_t j = 0; j < ColumnsCount(); j++) for (size_t j = 0; j < columns_count(); j++)
At(i, j) *= f; at(i, j) *= f;
return *this; return *this;
} }
void Matrix::Clear() void Matrix::clear()
{ {
Set(0.f); set(0.f);
} }
Matrix& Matrix::operator=(const Matrix& other) Matrix& Matrix::operator=(const Matrix& other)
@@ -175,7 +169,7 @@ namespace omath
for (size_t i = 0; i < m_rows; ++i) for (size_t i = 0; i < m_rows; ++i)
for (size_t j = 0; j < m_columns; ++j) for (size_t j = 0; j < m_columns; ++j)
At(i, j) = other.At(i, j); at(i, j) = other.at(i, j);
return *this; return *this;
} }
@@ -199,7 +193,7 @@ namespace omath
{ {
for (size_t i = 0; i < m_rows; ++i) for (size_t i = 0; i < m_rows; ++i)
for (size_t j = 0; j < m_columns; ++j) for (size_t j = 0; j < m_columns; ++j)
At(i, j) /= f; at(i, j) /= f;
return *this; return *this;
} }
@@ -209,12 +203,12 @@ namespace omath
auto out = *this; auto out = *this;
for (size_t i = 0; i < m_rows; ++i) for (size_t i = 0; i < m_rows; ++i)
for (size_t j = 0; j < m_columns; ++j) for (size_t j = 0; j < m_columns; ++j)
out.At(i, j) /= f; out.at(i, j) /= f;
return out; return out;
} }
std::string Matrix::ToString() const std::string Matrix::to_string() const
{ {
std::string str; std::string str;
@@ -222,7 +216,7 @@ namespace omath
{ {
for (size_t j = 0; j < m_columns; ++j) for (size_t j = 0; j < m_columns; ++j)
{ {
str += std::format("{:.1f}", At(i, j)); str += std::format("{:.1f}", at(i, j));
if (j == m_columns - 1) if (j == m_columns - 1)
str += '\n'; str += '\n';
@@ -233,89 +227,89 @@ namespace omath
return str; return str;
} }
float Matrix::Determinant() const float Matrix::determinant() const // NOLINT(*-no-recursion)
{ {
if (m_rows + m_columns == 2) if (m_rows + m_columns == 2)
return At(0, 0); return at(0, 0);
if (m_rows == 2 and m_columns == 2) if (m_rows == 2 and m_columns == 2)
return At(0, 0) * At(1, 1) - At(0, 1) * At(1, 0); return at(0, 0) * at(1, 1) - at(0, 1) * at(1, 0);
float fDet = 0; float det = 0;
for (size_t i = 0; i < m_columns; i++) for (size_t i = 0; i < m_columns; i++)
fDet += AlgComplement(0, i) * At(0, i); det += alg_complement(0, i) * at(0, i);
return fDet; return det;
} }
float Matrix::AlgComplement(const size_t i, const size_t j) const float Matrix::alg_complement(const size_t i, const size_t j) const // NOLINT(*-no-recursion)
{ {
const auto tmp = Minor(i, j); const auto tmp = minor(i, j);
return ((i + j + 2) % 2 == 0) ? tmp : -tmp; return ((i + j + 2) % 2 == 0) ? tmp : -tmp;
} }
Matrix Matrix::Transpose() const Matrix Matrix::transpose() const
{ {
Matrix transposed = {m_columns, m_rows}; Matrix transposed = {m_columns, m_rows};
for (size_t i = 0; i < m_rows; ++i) for (size_t i = 0; i < m_rows; ++i)
for (size_t j = 0; j < m_columns; ++j) for (size_t j = 0; j < m_columns; ++j)
transposed.At(j, i) = At(i, j); transposed.at(j, i) = at(i, j);
return transposed; return transposed;
} }
Matrix::~Matrix() = default; Matrix::~Matrix() = default;
void Matrix::Set(const float val) void Matrix::set(const float val)
{ {
for (size_t i = 0; i < m_rows; ++i) for (size_t i = 0; i < m_rows; ++i)
for (size_t j = 0; j < m_columns; ++j) for (size_t j = 0; j < m_columns; ++j)
At(i, j) = val; at(i, j) = val;
} }
Matrix Matrix::Strip(const size_t row, const size_t column) const Matrix Matrix::strip(const size_t row, const size_t column) const
{ {
Matrix stripped = {m_rows - 1, m_columns - 1}; Matrix stripped = {m_rows - 1, m_columns - 1};
size_t iStripRowIndex = 0; size_t strip_row_index = 0;
for (size_t i = 0; i < m_rows; i++) for (size_t i = 0; i < m_rows; i++)
{ {
if (i == row) if (i == row)
continue; continue;
size_t iStripColumnIndex = 0; size_t strip_column_index = 0;
for (size_t j = 0; j < m_columns; ++j) for (size_t j = 0; j < m_columns; ++j)
{ {
if (j == column) if (j == column)
continue; continue;
stripped.At(iStripRowIndex, iStripColumnIndex) = At(i, j); stripped.at(strip_row_index, strip_column_index) = at(i, j);
iStripColumnIndex++; strip_column_index++;
} }
iStripRowIndex++; strip_row_index++;
} }
return stripped; return stripped;
} }
float Matrix::Minor(const size_t i, const size_t j) const float Matrix::minor(const size_t i, const size_t j) const // NOLINT(*-no-recursion)
{ {
return Strip(i, j).Determinant(); return strip(i, j).determinant();
} }
Matrix Matrix::ToScreenMatrix(const float screenWidth, const float screenHeight) Matrix Matrix::to_screen_matrix(const float screen_width, const float screen_height)
{ {
return { return {
{screenWidth / 2.f, 0.f, 0.f, 0.f}, {screen_width / 2.f, 0.f, 0.f, 0.f},
{0.f, -screenHeight / 2.f, 0.f, 0.f}, {0.f, -screen_height / 2.f, 0.f, 0.f},
{0.f, 0.f, 1.f, 0.f}, {0.f, 0.f, 1.f, 0.f},
{screenWidth / 2.f, screenHeight / 2.f, 0.f, 1.f}, {screen_width / 2.f, screen_height / 2.f, 0.f, 1.f},
}; };
} }
Matrix Matrix::TranslationMatrix(const Vector3<float>& diff) Matrix Matrix::translation_matrix(const Vector3<float>& diff)
{ {
return { return {
{1.f, 0.f, 0.f, 0.f}, {1.f, 0.f, 0.f, 0.f},
@@ -325,7 +319,8 @@ namespace omath
}; };
} }
Matrix Matrix::OrientationMatrix(const Vector3<float>& forward, const Vector3<float>& right, const Vector3<float>& up) Matrix Matrix::orientation_matrix(const Vector3<float>& forward, const Vector3<float>& right,
const Vector3<float>& up)
{ {
return { return {
{right.x, up.x, forward.x, 0.f}, {right.x, up.x, forward.x, 0.f},
@@ -335,25 +330,26 @@ namespace omath
}; };
} }
Matrix Matrix::ProjectionMatrix(const float fieldOfView, const float aspectRatio, const float near, const float far) Matrix Matrix::projection_matrix(const float field_of_view, const float aspect_ratio, const float near,
const float far)
{ {
const float fovHalfTan = std::tan(angles::DegreesToRadians(fieldOfView) / 2.f); const float fov_half_tan = std::tan(angles::degrees_to_radians(field_of_view) / 2.f);
return {{1.f / (aspectRatio * fovHalfTan), 0.f, 0.f, 0.f}, return {{1.f / (aspect_ratio * fov_half_tan), 0.f, 0.f, 0.f},
{0.f, 1.f / fovHalfTan, 0.f, 0.f}, {0.f, 1.f / fov_half_tan, 0.f, 0.f},
{0.f, 0.f, (far + near) / (far - near), 2.f * near * far / (far - near)}, {0.f, 0.f, (far + near) / (far - near), 2.f * near * far / (far - near)},
{0.f, 0.f, -1.f, 0.f}}; {0.f, 0.f, -1.f, 0.f}};
} }
const float* Matrix::Raw() const const float* Matrix::raw() const
{ {
return m_data.get(); return m_data.get();
} }
void Matrix::SetDataFromRaw(const float* pRawMatrix) void Matrix::set_data_from_raw(const float* raw_matrix)
{ {
for (size_t i = 0; i < m_columns * m_rows; ++i) for (size_t i = 0; i < m_columns * m_rows; ++i)
At(i / m_rows, i % m_columns) = pRawMatrix[i]; at(i / m_rows, i % m_columns) = raw_matrix[i];
} }
Matrix::Matrix() Matrix::Matrix()

View File

@@ -1 +0,0 @@
target_sources(omath PRIVATE navigation_mesh.cpp a_star.cpp)

View File

@@ -2,96 +2,95 @@
// Created by Vlad on 28.07.2024. // Created by Vlad on 28.07.2024.
// //
#include "omath/pathfinding/a_star.hpp" #include "omath/pathfinding/a_star.hpp"
#include <algorithm> #include <algorithm>
#include <optional> #include <optional>
#include <unordered_map> #include <unordered_map>
#include <unordered_set> #include <unordered_set>
namespace omath::pathfinding namespace omath::pathfinding
{ {
struct PathNode final struct PathNode final
{ {
std::optional<Vector3<float>> cameFrom; std::optional<Vector3<float>> came_from;
float gCost = 0.f; float g_cost = 0.f;
}; };
std::vector<Vector3<float>>
std::vector<Vector3<float>> Astar::ReconstructFinalPath(const std::unordered_map<Vector3<float>, PathNode>& closedList, Astar::reconstruct_final_path(const std::unordered_map<Vector3<float>, PathNode>& closed_list,
const Vector3<float>& current) const Vector3<float>& current) noexcept
{ {
std::vector<Vector3<float>> path; std::vector<Vector3<float>> path;
std::optional currentOpt = current; std::optional current_opt = current;
while (currentOpt) while (current_opt)
{ {
path.push_back(*currentOpt); path.push_back(*current_opt);
auto it = closedList.find(*currentOpt); auto it = closed_list.find(*current_opt);
if (it == closedList.end()) if (it == closed_list.end())
break; break;
currentOpt = it->second.cameFrom; current_opt = it->second.came_from;
} }
std::ranges::reverse(path); std::ranges::reverse(path);
return path; return path;
} }
auto Astar::GetPerfectNode(const std::unordered_map<Vector3<float>, PathNode>& openList, const Vector3<float>& endVertex) auto Astar::get_perfect_node(const std::unordered_map<Vector3<float>, PathNode>& open_list,
const Vector3<float>& end_vertex) noexcept
{ {
return std::ranges::min_element(openList, return std::ranges::min_element(open_list,
[&endVertex](const auto& a, const auto& b) [&end_vertex](const auto& a, const auto& b)
{ {
const float fA = a.second.gCost + a.first.DistTo(endVertex); const float fa = a.second.g_cost + a.first.distance_to(end_vertex);
const float fB = b.second.gCost + b.first.DistTo(endVertex); const float fb = b.second.g_cost + b.first.distance_to(end_vertex);
return fA < fB; return fa < fb;
}); });
} }
std::vector<Vector3<float>> Astar::FindPath(const Vector3<float>& start, const Vector3<float>& end, const NavigationMesh& navMesh) std::vector<Vector3<float>> Astar::find_path(const Vector3<float>& start, const Vector3<float>& end,
const NavigationMesh& nav_mesh) noexcept
{ {
std::unordered_map<Vector3<float>, PathNode> closedList; std::unordered_map<Vector3<float>, PathNode> closed_list;
std::unordered_map<Vector3<float>, PathNode> openList; std::unordered_map<Vector3<float>, PathNode> open_list;
auto maybeStartVertex = navMesh.GetClosestVertex(start); auto maybe_start_vertex = nav_mesh.get_closest_vertex(start);
auto maybeEndVertex = navMesh.GetClosestVertex(end); auto maybe_end_vertex = nav_mesh.get_closest_vertex(end);
if (!maybeStartVertex || !maybeEndVertex) if (!maybe_start_vertex || !maybe_end_vertex)
return {}; return {};
const auto startVertex = maybeStartVertex.value(); const auto start_vertex = maybe_start_vertex.value();
const auto endVertex = maybeEndVertex.value(); const auto end_vertex = maybe_end_vertex.value();
open_list.emplace(start_vertex, PathNode{std::nullopt, 0.f});
openList.emplace(startVertex, PathNode{std::nullopt, 0.f}); while (!open_list.empty())
while (!openList.empty())
{ {
auto currentIt = GetPerfectNode(openList, endVertex); auto current_it = get_perfect_node(open_list, end_vertex);
const auto current = currentIt->first; const auto current = current_it->first;
const auto currentNode = currentIt->second; const auto current_node = current_it->second;
if (current == endVertex) if (current == end_vertex)
return ReconstructFinalPath(closedList, current); return reconstruct_final_path(closed_list, current);
closed_list.emplace(current, current_node);
open_list.erase(current_it);
closedList.emplace(current, currentNode); for (const auto& neighbor: nav_mesh.get_neighbors(current))
openList.erase(currentIt);
for (const auto& neighbor: navMesh.GetNeighbors(current))
{ {
if (closedList.contains(neighbor)) if (closed_list.contains(neighbor))
continue; continue;
const float tentativeGCost = currentNode.gCost + neighbor.DistTo(current); const float tentative_g_cost = current_node.g_cost + neighbor.distance_to(current);
const auto openIt = openList.find(neighbor); // ReSharper disable once CppTooWideScopeInitStatement
const auto open_it = open_list.find(neighbor);
if (openIt == openList.end() || tentativeGCost < openIt->second.gCost) if (open_it == open_list.end() || tentative_g_cost < open_it->second.g_cost)
openList[neighbor] = PathNode{current, tentativeGCost}; open_list[neighbor] = PathNode{current, tentative_g_cost};
} }
} }

View File

@@ -2,94 +2,90 @@
// Created by Vlad on 28.07.2024. // Created by Vlad on 28.07.2024.
// //
#include "omath/pathfinding/navigation_mesh.hpp" #include "omath/pathfinding/navigation_mesh.hpp"
#include <algorithm> #include <algorithm>
#include <stdexcept> #include <stdexcept>
namespace omath::pathfinding namespace omath::pathfinding
{ {
std::expected<Vector3<float>, std::string> NavigationMesh::GetClosestVertex(const Vector3<float> &point) const std::expected<Vector3<float>, std::string>
NavigationMesh::get_closest_vertex(const Vector3<float>& point) const noexcept
{ {
const auto res = std::ranges::min_element(m_verTextMap, const auto res = std::ranges::min_element(m_vertex_map, [&point](const auto& a, const auto& b)
[&point](const auto& a, const auto& b) { return a.first.distance_to(point) < b.first.distance_to(point); });
{
return a.first.DistTo(point) < b.first.DistTo(point);
});
if (res == m_verTextMap.cend()) if (res == m_vertex_map.cend())
return std::unexpected("Failed to get clossest point"); return std::unexpected("Failed to get clossest point");
return res->first; return res->first;
} }
const std::vector<Vector3<float>>& NavigationMesh::GetNeighbors(const Vector3<float> &vertex) const const std::vector<Vector3<float>>& NavigationMesh::get_neighbors(const Vector3<float>& vertex) const noexcept
{ {
return m_verTextMap.at(vertex); return m_vertex_map.at(vertex);
} }
bool NavigationMesh::Empty() const bool NavigationMesh::empty() const
{ {
return m_verTextMap.empty(); return m_vertex_map.empty();
} }
std::vector<uint8_t> NavigationMesh::Serialize() const std::vector<uint8_t> NavigationMesh::serialize() const noexcept
{ {
auto dumpToVector =[]<typename T>(const T& t, std::vector<uint8_t>& vec){ auto dump_to_vector = []<typename T>(const T& t, std::vector<uint8_t>& vec)
{
for (size_t i = 0; i < sizeof(t); i++) for (size_t i = 0; i < sizeof(t); i++)
vec.push_back(*(reinterpret_cast<const uint8_t*>(&t)+i)); vec.push_back(*(reinterpret_cast<const uint8_t*>(&t) + i));
}; };
std::vector<uint8_t> raw; std::vector<uint8_t> raw;
for (const auto& [vertex, neighbors]: m_vertex_map)
for (const auto& [vertex, neighbors] : m_verTextMap)
{ {
const auto neighborsCount = neighbors.size(); const auto neighbors_count = neighbors.size();
dumpToVector(vertex, raw); dump_to_vector(vertex, raw);
dumpToVector(neighborsCount, raw); dump_to_vector(neighbors_count, raw);
for (const auto& neighbor : neighbors) for (const auto& neighbor: neighbors)
dumpToVector(neighbor, raw); dump_to_vector(neighbor, raw);
} }
return raw; return raw;
} }
void NavigationMesh::Deserialize(const std::vector<uint8_t> &raw) void NavigationMesh::deserialize(const std::vector<uint8_t>& raw) noexcept
{ {
auto loadFromVector = [](const std::vector<uint8_t>& vec, size_t& offset, auto& value) auto load_from_vector = [](const std::vector<uint8_t>& vec, size_t& offset, auto& value)
{ {
if (offset + sizeof(value) > vec.size()) if (offset + sizeof(value) > vec.size())
{ {
throw std::runtime_error("Deserialize: Invalid input data size."); throw std::runtime_error("Deserialize: Invalid input data size.");
} }
std::copy_n(vec.data() + offset, sizeof(value), (uint8_t*)&value); std::copy_n(vec.data() + offset, sizeof(value), reinterpret_cast<uint8_t*>(&value));
offset += sizeof(value); offset += sizeof(value);
}; };
m_verTextMap.clear(); m_vertex_map.clear();
size_t offset = 0; size_t offset = 0;
while (offset < raw.size()) while (offset < raw.size())
{ {
Vector3<float> vertex; Vector3<float> vertex;
loadFromVector(raw, offset, vertex); load_from_vector(raw, offset, vertex);
uint16_t neighborsCount; uint16_t neighbors_count;
loadFromVector(raw, offset, neighborsCount); load_from_vector(raw, offset, neighbors_count);
std::vector<Vector3<float>> neighbors; std::vector<Vector3<float>> neighbors;
neighbors.reserve(neighborsCount); neighbors.reserve(neighbors_count);
for (size_t i = 0; i < neighborsCount; ++i) for (size_t i = 0; i < neighbors_count; ++i)
{ {
Vector3<float> neighbor; Vector3<float> neighbor;
loadFromVector(raw, offset, neighbor); load_from_vector(raw, offset, neighbor);
neighbors.push_back(neighbor); neighbors.push_back(neighbor);
} }
m_verTextMap.emplace(vertex, std::move(neighbors)); m_vertex_map.emplace(vertex, std::move(neighbors));
} }
} }
} } // namespace omath::pathfinding

View File

@@ -1 +0,0 @@
target_sources(omath PRIVATE proj_pred_engine_legacy.cpp projectile.cpp target.cpp proj_pred_engine_avx2.cpp proj_pred_engine.cpp)

View File

@@ -1,10 +0,0 @@
//
// Created by Vlad on 2/23/2025.
//
#include "omath/projectile_prediction/proj_pred_engine.hpp"
namespace omath::projectile_prediction
{
} // namespace omath::projectile_prediction

View File

@@ -2,19 +2,20 @@
// Created by Vlad on 2/23/2025. // Created by Vlad on 2/23/2025.
// //
#include "omath/projectile_prediction/proj_pred_engine_avx2.hpp" #include "omath/projectile_prediction/proj_pred_engine_avx2.hpp"
#include "source_location" #include <source_location>
#include <stdexcept>
#if defined(OMATH_USE_AVX2) && defined(__i386__) && defined(__x86_64__) #if defined(OMATH_USE_AVX2) && defined(__i386__) && defined(__x86_64__)
#include <immintrin.h> #include <immintrin.h>
#else
#include <format> #include <format>
#endif #endif
namespace omath::projectile_prediction namespace omath::projectile_prediction
{ {
std::optional<Vector3<float>> std::optional<Vector3<float>>
ProjPredEngineAVX2::MaybeCalculateAimPoint([[maybe_unused]] const Projectile& projectile, ProjPredEngineAvx2::maybe_calculate_aim_point([[maybe_unused]] const Projectile& projectile,
[[maybe_unused]] const Target& target) const [[maybe_unused]] const Target& target) const
{ {
#if defined(OMATH_USE_AVX2) && defined(__i386__) && defined(__x86_64__) #if defined(OMATH_USE_AVX2) && defined(__i386__) && defined(__x86_64__)
const float bulletGravity = m_gravityConstant * projectile.m_gravityScale; const float bulletGravity = m_gravityConstant * projectile.m_gravityScale;
@@ -27,16 +28,16 @@ namespace omath::projectile_prediction
for (; currentTime <= m_maximumSimulationTime; currentTime += m_simulationTimeStep * SIMD_FACTOR) for (; currentTime <= m_maximumSimulationTime; currentTime += m_simulationTimeStep * SIMD_FACTOR)
{ {
const __m256 times = const __m256 times
_mm256_setr_ps(currentTime, currentTime + m_simulationTimeStep, = _mm256_setr_ps(currentTime, currentTime + m_simulationTimeStep,
currentTime + m_simulationTimeStep * 2, currentTime + m_simulationTimeStep * 3, currentTime + m_simulationTimeStep * 2, currentTime + m_simulationTimeStep * 3,
currentTime + m_simulationTimeStep * 4, currentTime + m_simulationTimeStep * 5, currentTime + m_simulationTimeStep * 4, currentTime + m_simulationTimeStep * 5,
currentTime + m_simulationTimeStep * 6, currentTime + m_simulationTimeStep * 7); currentTime + m_simulationTimeStep * 6, currentTime + m_simulationTimeStep * 7);
const __m256 targetX = const __m256 targetX
_mm256_fmadd_ps(_mm256_set1_ps(target.m_velocity.x), times, _mm256_set1_ps(target.m_origin.x)); = _mm256_fmadd_ps(_mm256_set1_ps(target.m_velocity.x), times, _mm256_set1_ps(target.m_origin.x));
const __m256 targetY = const __m256 targetY
_mm256_fmadd_ps(_mm256_set1_ps(target.m_velocity.y), times, _mm256_set1_ps(target.m_origin.y)); = _mm256_fmadd_ps(_mm256_set1_ps(target.m_velocity.y), times, _mm256_set1_ps(target.m_origin.y));
const __m256 timesSq = _mm256_mul_ps(times, times); const __m256 timesSq = _mm256_mul_ps(times, times);
const __m256 targetZ = _mm256_fmadd_ps(_mm256_set1_ps(target.m_velocity.z), times, const __m256 targetZ = _mm256_fmadd_ps(_mm256_set1_ps(target.m_velocity.z), times,
_mm256_fnmadd_ps(_mm256_set1_ps(0.5f * m_gravityConstant), timesSq, _mm256_fnmadd_ps(_mm256_set1_ps(0.5f * m_gravityConstant), timesSq,
@@ -111,25 +112,32 @@ namespace omath::projectile_prediction
} }
return std::nullopt; return std::nullopt;
#else
throw std::runtime_error(
std::format("{} AVX2 feature is not enabled!", std::source_location::current().function_name()));
#endif
} }
ProjPredEngineAVX2::ProjPredEngineAVX2(const float gravityConstant, const float simulationTimeStep, ProjPredEngineAvx2::ProjPredEngineAvx2(const float gravity_constant, const float simulation_time_step,
const float maximumSimulationTime) : const float maximum_simulation_time)
m_gravityConstant(gravityConstant), m_simulationTimeStep(simulationTimeStep), : m_gravity_constant(gravity_constant), m_simulation_time_step(simulation_time_step),
m_maximumSimulationTime(maximumSimulationTime) m_maximum_simulation_time(maximum_simulation_time)
{ {
} }
std::optional<float> ProjPredEngineAVX2::CalculatePitch(const Vector3<float>& projOrigin, std::optional<float> ProjPredEngineAvx2::calculate_pitch([[maybe_unused]] const Vector3<float>& proj_origin,
const Vector3<float>& targetPos, const float bulletGravity, [[maybe_unused]] const Vector3<float>& target_pos,
const float v0, const float time) [[maybe_unused]] const float bullet_gravity,
[[maybe_unused]] const float v0,
[[maybe_unused]] const float time)
{ {
#if defined(OMATH_USE_AVX2) && defined(__i386__) && defined(__x86_64__)
if (time <= 0.0f) if (time <= 0.0f)
return std::nullopt; return std::nullopt;
const Vector3 delta = targetPos - projOrigin; const Vector3 delta = target_pos - proj_origin;
const float dSqr = delta.x * delta.x + delta.y * delta.y; const float dSqr = delta.x * delta.x + delta.y * delta.y;
const float h = delta.z; const float h = delta.z;
const float term = h + 0.5f * bulletGravity * time * time; const float term = h + 0.5f * bullet_gravity * time * time;
const float requiredV0Sqr = (dSqr + term * term) / (time * time); const float requiredV0Sqr = (dSqr + term * term) / (time * time);
const float v0Sqr = v0 * v0; const float v0Sqr = v0 * v0;
@@ -139,7 +147,6 @@ namespace omath::projectile_prediction
if (dSqr == 0.0f) if (dSqr == 0.0f)
return term >= 0.0f ? 90.0f : -90.0f; return term >= 0.0f ? 90.0f : -90.0f;
const float d = std::sqrt(dSqr); const float d = std::sqrt(dSqr);
const float tanTheta = term / d; const float tanTheta = term / d;
return angles::RadiansToDegrees(std::atan(tanTheta)); return angles::RadiansToDegrees(std::atan(tanTheta));

View File

@@ -4,65 +4,66 @@
namespace omath::projectile_prediction namespace omath::projectile_prediction
{ {
ProjPredEngineLegacy::ProjPredEngineLegacy(const float gravityConstant, const float simulationTimeStep, ProjPredEngineLegacy::ProjPredEngineLegacy(const float gravity_constant, const float simulation_time_step,
const float maximumSimulationTime, const float distanceTolerance) : const float maximum_simulation_time, const float distance_tolerance)
m_gravityConstant(gravityConstant), m_simulationTimeStep(simulationTimeStep), : m_gravity_constant(gravity_constant), m_simulation_time_step(simulation_time_step),
m_maximumSimulationTime(maximumSimulationTime), m_distanceTolerance(distanceTolerance) m_maximum_simulation_time(maximum_simulation_time), m_distance_tolerance(distance_tolerance)
{ {
} }
std::optional<Vector3<float>> ProjPredEngineLegacy::MaybeCalculateAimPoint(const Projectile& projectile, std::optional<Vector3<float>> ProjPredEngineLegacy::maybe_calculate_aim_point(const Projectile& projectile,
const Target& target) const const Target& target) const
{ {
for (float time = 0.f; time < m_maximumSimulationTime; time += m_simulationTimeStep) for (float time = 0.f; time < m_maximum_simulation_time; time += m_simulation_time_step)
{ {
const auto predictedTargetPosition = target.PredictPosition(time, m_gravityConstant); const auto predicted_target_position = target.predict_position(time, m_gravity_constant);
const auto projectilePitch = MaybeCalculateProjectileLaunchPitchAngle(projectile, predictedTargetPosition); const auto projectile_pitch =
maybe_calculate_projectile_launch_pitch_angle(projectile, predicted_target_position);
if (!projectilePitch.has_value()) [[unlikely]] if (!projectile_pitch.has_value()) [[unlikely]]
continue; continue;
if (!IsProjectileReachedTarget(predictedTargetPosition, projectile, projectilePitch.value(), time)) if (!is_projectile_reached_target(predicted_target_position, projectile, projectile_pitch.value(), time))
continue; continue;
const auto delta2d = (predictedTargetPosition - projectile.m_origin).Length2D(); const auto delta2d = (predicted_target_position - projectile.m_origin).length_2d();
const auto height = delta2d * std::tan(angles::DegreesToRadians(projectilePitch.value())); const auto height = delta2d * std::tan(angles::degrees_to_radians(projectile_pitch.value()));
return Vector3(predictedTargetPosition.x, predictedTargetPosition.y, projectile.m_origin.z + height); return Vector3(predicted_target_position.x, predicted_target_position.y, projectile.m_origin.z + height);
} }
return std::nullopt; return std::nullopt;
} }
std::optional<float> std::optional<float> ProjPredEngineLegacy::maybe_calculate_projectile_launch_pitch_angle(
ProjPredEngineLegacy::MaybeCalculateProjectileLaunchPitchAngle(const Projectile& projectile, const Projectile& projectile, const Vector3<float>& target_position) const noexcept
const Vector3<float>& targetPosition) const
{ {
const auto bulletGravity = m_gravityConstant * projectile.m_gravityScale; const auto bullet_gravity = m_gravity_constant * projectile.m_gravity_scale;
const auto delta = targetPosition - projectile.m_origin; const auto delta = target_position - projectile.m_origin;
const auto distance2d = delta.Length2D(); const auto distance2d = delta.length_2d();
const auto distance2dSqr = distance2d * distance2d; const auto distance2d_sqr = distance2d * distance2d;
const auto launchSpeedSqr = projectile.m_launchSpeed * projectile.m_launchSpeed; const auto launch_speed_sqr = projectile.m_launch_speed * projectile.m_launch_speed;
float root = launchSpeedSqr * launchSpeedSqr - float root = launch_speed_sqr * launch_speed_sqr
bulletGravity * (bulletGravity * distance2dSqr + 2.0f * delta.z * launchSpeedSqr); - bullet_gravity * (bullet_gravity * distance2d_sqr + 2.0f * delta.z * launch_speed_sqr);
if (root < 0.0f) [[unlikely]] if (root < 0.0f) [[unlikely]]
return std::nullopt; return std::nullopt;
root = std::sqrt(root); root = std::sqrt(root);
const float angle = std::atan((launchSpeedSqr - root) / (bulletGravity * distance2d)); const float angle = std::atan((launch_speed_sqr - root) / (bullet_gravity * distance2d));
return angles::RadiansToDegrees(angle); return angles::radians_to_degrees(angle);
} }
bool ProjPredEngineLegacy::IsProjectileReachedTarget(const Vector3<float>& targetPosition, const Projectile& projectile, bool ProjPredEngineLegacy::is_projectile_reached_target(const Vector3<float>& target_position,
const float pitch, const float time) const const Projectile& projectile, const float pitch,
const float time) const noexcept
{ {
const auto yaw = projectile.m_origin.ViewAngleTo(targetPosition).y; const auto yaw = projectile.m_origin.view_angle_to(target_position).y;
const auto projectilePosition = projectile.PredictPosition(pitch, yaw, time, m_gravityConstant); const auto projectile_position = projectile.predict_position(pitch, yaw, time, m_gravity_constant);
return projectilePosition.DistTo(targetPosition) <= m_distanceTolerance; return projectile_position.distance_to(target_position) <= m_distance_tolerance;
} }
} // namespace omath::projectile_prediction } // namespace omath::projectile_prediction

View File

@@ -3,19 +3,20 @@
// //
#include "omath/projectile_prediction/projectile.hpp" #include "omath/projectile_prediction/projectile.hpp"
#include <omath/engines/source_engine/formulas.hpp> #include <omath/engines/source_engine/formulas.hpp>
namespace omath::projectile_prediction namespace omath::projectile_prediction
{ {
Vector3<float> Projectile::PredictPosition(const float pitch, const float yaw, const float time, const float gravity) const Vector3<float> Projectile::predict_position(const float pitch, const float yaw, const float time,
const float gravity) const noexcept
{ {
auto currentPos = m_origin + source_engine::ForwardVector({source_engine::PitchAngle::FromDegrees(-pitch), auto current_pos = m_origin
source_engine::YawAngle::FromDegrees(yaw), + source_engine::forward_vector({source_engine::PitchAngle::from_degrees(-pitch),
source_engine::RollAngle::FromDegrees(0)}) * source_engine::YawAngle::from_degrees(yaw),
m_launchSpeed * time; source_engine::RollAngle::from_degrees(0)})
currentPos.z -= (gravity * m_gravityScale) * (time * time) * 0.5f; * m_launch_speed * time;
current_pos.z -= (gravity * m_gravity_scale) * (time * time) * 0.5f;
return currentPos; return current_pos;
} }
} // namespace omath::prediction } // namespace omath::projectile_prediction

View File

@@ -1,11 +0,0 @@
//
// Created by Vlad on 6/9/2024.
//
#include "omath/projectile_prediction/projectile.hpp"
namespace omath::prediction
{
}

View File

@@ -1 +0,0 @@
target_sources(omath PRIVATE camera.cpp)

View File

@@ -1,9 +0,0 @@
//
// Created by Vlad on 27.08.2024.
//
#include "omath/projection/camera.hpp"
namespace omath::projection
{
}

View File

@@ -1,40 +1,22 @@
enable_testing() enable_testing()
project(unit-tests) project(unit_tests)
include(GoogleTest) include(GoogleTest)
add_executable(unit-tests
general/unit_test_prediction.cpp
general/unit_test_matrix.cpp
general/unit_test_mat.cpp
general/unit_test_a_star.cpp
general/unit_test_projection.cpp
general/unit_test_vector3.cpp
general/unit_test_vector2.cpp
general/unit_test_color.cpp
general/unit_test_vector4.cpp
general/unit_test_line_trace.cpp
general/unit_test_angles.cpp
general/unit_test_view_angles.cpp
general/unit_test_angle.cpp
general/unit_test_triangle.cpp
engines/unit_test_open_gl.cpp file(GLOB_RECURSE UNIT_TESTS_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
engines/unit_test_unity_engine.cpp add_executable(unit_tests ${UNIT_TESTS_SOURCES})
engines/unit_test_source_engine.cpp
engines/unit_test_iw_engine.cpp
) set_target_properties(unit_tests PROPERTIES
set_target_properties(unit-tests PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}" ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}" LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}"
UNITY_BUILD ON UNITY_BUILD ON
UNITY_BUILD_BATCH_SIZE 20 UNITY_BUILD_BATCH_SIZE 20
CXX_STANDARD 23 CXX_STANDARD 23
CXX_STANDARD_REQUIRED ON) CXX_STANDARD_REQUIRED ON)
target_link_libraries(unit-tests PRIVATE gtest gtest_main omath::omath) target_link_libraries(unit_tests PRIVATE gtest gtest_main omath::omath)
gtest_discover_tests(unit-tests) gtest_discover_tests(unit_tests)

View File

@@ -9,33 +9,69 @@
TEST(UnitTestIwEngine, ForwardVector) TEST(UnitTestIwEngine, ForwardVector)
{ {
const auto forward = omath::iw_engine::ForwardVector({}); const auto forward = omath::iw_engine::forward_vector({});
EXPECT_EQ(forward, omath::iw_engine::kAbsForward); EXPECT_EQ(forward, omath::iw_engine::k_abs_forward);
} }
TEST(UnitTestIwEngine, RightVector) TEST(UnitTestIwEngine, RightVector)
{ {
const auto right = omath::iw_engine::RightVector({}); const auto right = omath::iw_engine::right_vector({});
EXPECT_EQ(right, omath::iw_engine::kAbsRight); EXPECT_EQ(right, omath::iw_engine::k_abs_right);
} }
TEST(UnitTestIwEngine, UpVector) TEST(UnitTestIwEngine, UpVector)
{ {
const auto up = omath::iw_engine::UpVector({}); const auto up = omath::iw_engine::up_vector({});
EXPECT_EQ(up, omath::iw_engine::kAbsUp); EXPECT_EQ(up, omath::iw_engine::k_abs_up);
}
TEST(UnitTestIwEngine, ForwardVectorRotationYaw)
{
omath::iw_engine::ViewAngles angles;
angles.yaw = omath::iw_engine::YawAngle::from_degrees(-90.f);
const auto forward = omath::iw_engine::forward_vector(angles);
EXPECT_NEAR(forward.x, omath::iw_engine::k_abs_right.x, 0.00001f);
EXPECT_NEAR(forward.y, omath::iw_engine::k_abs_right.y, 0.00001f);
EXPECT_NEAR(forward.z, omath::iw_engine::k_abs_right.z, 0.00001f);
}
TEST(UnitTestIwEngine, ForwardVectorRotationPitch)
{
omath::iw_engine::ViewAngles angles;
angles.pitch = omath::iw_engine::PitchAngle::from_degrees(-89.f);
const auto forward = omath::iw_engine::forward_vector(angles);
EXPECT_NEAR(forward.x, omath::iw_engine::k_abs_up.x, 0.02f);
EXPECT_NEAR(forward.y, omath::iw_engine::k_abs_up.y, 0.01f);
EXPECT_NEAR(forward.z, omath::iw_engine::k_abs_up.z, 0.01f);
}
TEST(UnitTestIwEngine, ForwardVectorRotationRoll)
{
omath::iw_engine::ViewAngles angles;
angles.roll = omath::iw_engine::RollAngle::from_degrees(90.f);
const auto forward = omath::iw_engine::up_vector(angles);
EXPECT_NEAR(forward.x, omath::iw_engine::k_abs_right.x, 0.00001f);
EXPECT_NEAR(forward.y, omath::iw_engine::k_abs_right.y, 0.00001f);
EXPECT_NEAR(forward.z, omath::iw_engine::k_abs_right.z, 0.00001f);
} }
TEST(UnitTestIwEngine, ProjectTargetMovedFromCamera) TEST(UnitTestIwEngine, ProjectTargetMovedFromCamera)
{ {
constexpr auto fov = omath::projection::FieldOfView::FromDegrees(90.f); constexpr auto fov = omath::projection::FieldOfView::from_degrees(90.f);
const auto cam = omath::iw_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f); const auto cam = omath::iw_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f);
for (float distance = 0.02f; distance < 1000.f; distance += 0.01f) for (float distance = 0.02f; distance < 1000.f; distance += 0.01f)
{ {
const auto projected = cam.WorldToScreen({distance, 0, 0}); const auto projected = cam.world_to_screen({distance, 0, 0});
EXPECT_TRUE(projected.has_value()); EXPECT_TRUE(projected.has_value());
@@ -49,21 +85,21 @@ TEST(UnitTestIwEngine, ProjectTargetMovedFromCamera)
TEST(UnitTestIwEngine, CameraSetAndGetFov) TEST(UnitTestIwEngine, CameraSetAndGetFov)
{ {
constexpr auto fov = omath::projection::FieldOfView::FromDegrees(90.f); constexpr auto fov = omath::projection::FieldOfView::from_degrees(90.f);
auto cam = omath::iw_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f); auto cam = omath::iw_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f);
EXPECT_EQ(cam.GetFieldOfView().AsDegrees(), 90.f); EXPECT_EQ(cam.get_field_of_view().as_degrees(), 90.f);
cam.SetFieldOfView(omath::projection::FieldOfView::FromDegrees(50.f)); cam.set_field_of_view(omath::projection::FieldOfView::from_degrees(50.f));
EXPECT_EQ(cam.GetFieldOfView().AsDegrees(), 50.f); EXPECT_EQ(cam.get_field_of_view().as_degrees(), 50.f);
} }
TEST(UnitTestIwEngine, CameraSetAndGetOrigin) TEST(UnitTestIwEngine, CameraSetAndGetOrigin)
{ {
auto cam = omath::iw_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, {}, 0.01f, 1000.f); auto cam = omath::iw_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, {}, 0.01f, 1000.f);
EXPECT_EQ(cam.GetOrigin(), omath::Vector3<float>{}); EXPECT_EQ(cam.get_origin(), omath::Vector3<float>{});
cam.SetFieldOfView(omath::projection::FieldOfView::FromDegrees(50.f)); cam.set_field_of_view(omath::projection::FieldOfView::from_degrees(50.f));
EXPECT_EQ(cam.GetFieldOfView().AsDegrees(), 50.f); EXPECT_EQ(cam.get_field_of_view().as_degrees(), 50.f);
} }

View File

@@ -9,33 +9,69 @@
TEST(UnitTestOpenGL, ForwardVector) TEST(UnitTestOpenGL, ForwardVector)
{ {
const auto forward = omath::opengl_engine::ForwardVector({}); const auto forward = omath::opengl_engine::forward_vector({});
EXPECT_EQ(forward, omath::opengl_engine::k_abs_forward);
EXPECT_EQ(forward, omath::opengl_engine::kAbsForward);
} }
TEST(UnitTestOpenGL, RightVector) TEST(UnitTestOpenGL, RightVector)
{ {
const auto right = omath::opengl_engine::RightVector({}); const auto right = omath::opengl_engine::right_vector({});
EXPECT_EQ(right, omath::opengl_engine::k_abs_right);
EXPECT_EQ(right, omath::opengl_engine::kAbsRight);
} }
TEST(UnitTestOpenGL, UpVector) TEST(UnitTestOpenGL, UpVector)
{ {
const auto up = omath::opengl_engine::UpVector({}); const auto up = omath::opengl_engine::up_vector({});
EXPECT_EQ(up, omath::opengl_engine::kAbsUp); EXPECT_EQ(up, omath::opengl_engine::k_abs_up);
}
TEST(UnitTestOpenGL, ForwardVectorRotationYaw)
{
omath::opengl_engine::ViewAngles angles;
angles.yaw = omath::opengl_engine::YawAngle::from_degrees(90.f);
const auto forward = omath::opengl_engine::forward_vector(angles);
EXPECT_NEAR(forward.x, omath::opengl_engine::k_abs_right.x, 0.00001f);
EXPECT_NEAR(forward.y, omath::opengl_engine::k_abs_right.y, 0.00001f);
EXPECT_NEAR(forward.z, omath::opengl_engine::k_abs_right.z, 0.00001f);
}
TEST(UnitTestOpenGL, ForwardVectorRotationPitch)
{
omath::opengl_engine::ViewAngles angles;
angles.pitch = omath::opengl_engine::PitchAngle::from_degrees(-90.f);
const auto forward = omath::opengl_engine::forward_vector(angles);
EXPECT_NEAR(forward.x, omath::opengl_engine::k_abs_up.x, 0.00001f);
EXPECT_NEAR(forward.y, omath::opengl_engine::k_abs_up.y, 0.00001f);
EXPECT_NEAR(forward.z, omath::opengl_engine::k_abs_up.z, 0.00001f);
}
TEST(UnitTestOpenGL, ForwardVectorRotationRoll)
{
omath::opengl_engine::ViewAngles angles;
angles.roll = omath::opengl_engine::RollAngle::from_degrees(-90.f);
const auto forward = omath::opengl_engine::up_vector(angles);
EXPECT_NEAR(forward.x, omath::opengl_engine::k_abs_right.x, 0.00001f);
EXPECT_NEAR(forward.y, omath::opengl_engine::k_abs_right.y, 0.00001f);
EXPECT_NEAR(forward.z, omath::opengl_engine::k_abs_right.z, 0.00001f);
} }
TEST(UnitTestOpenGL, ProjectTargetMovedFromCamera) TEST(UnitTestOpenGL, ProjectTargetMovedFromCamera)
{ {
constexpr auto fov = omath::projection::FieldOfView::FromDegrees(90.f); constexpr auto fov = omath::projection::FieldOfView::from_degrees(90.f);
const auto cam = omath::opengl_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f); const auto cam = omath::opengl_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f);
for (float distance = -10.f; distance > -1000.f; distance -= 0.01f) for (float distance = -10.f; distance > -1000.f; distance -= 0.01f)
{ {
const auto projected = cam.WorldToScreen({0, 0, distance}); const auto projected = cam.world_to_screen({0, 0, distance});
EXPECT_TRUE(projected.has_value()); EXPECT_TRUE(projected.has_value());
@@ -49,21 +85,21 @@ TEST(UnitTestOpenGL, ProjectTargetMovedFromCamera)
TEST(UnitTestOpenGL, CameraSetAndGetFov) TEST(UnitTestOpenGL, CameraSetAndGetFov)
{ {
constexpr auto fov = omath::projection::FieldOfView::FromDegrees(90.f); constexpr auto fov = omath::projection::FieldOfView::from_degrees(90.f);
auto cam = omath::opengl_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f); auto cam = omath::opengl_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f);
EXPECT_EQ(cam.GetFieldOfView().AsDegrees(), 90.f); EXPECT_EQ(cam.get_field_of_view().as_degrees(), 90.f);
cam.SetFieldOfView(omath::projection::FieldOfView::FromDegrees(50.f)); cam.set_field_of_view(omath::projection::FieldOfView::from_degrees(50.f));
EXPECT_EQ(cam.GetFieldOfView().AsDegrees(), 50.f); EXPECT_EQ(cam.get_field_of_view().as_degrees(), 50.f);
} }
TEST(UnitTestOpenGL, CameraSetAndGetOrigin) TEST(UnitTestOpenGL, CameraSetAndGetOrigin)
{ {
auto cam = omath::opengl_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, {}, 0.01f, 1000.f); auto cam = omath::opengl_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, {}, 0.01f, 1000.f);
EXPECT_EQ(cam.GetOrigin(), omath::Vector3<float>{}); EXPECT_EQ(cam.get_origin(), omath::Vector3<float>{});
cam.SetFieldOfView(omath::projection::FieldOfView::FromDegrees(50.f)); cam.set_field_of_view(omath::projection::FieldOfView::from_degrees(50.f));
EXPECT_EQ(cam.GetFieldOfView().AsDegrees(), 50.f); EXPECT_EQ(cam.get_field_of_view().as_degrees(), 50.f);
} }

View File

@@ -9,33 +9,69 @@
TEST(UnitTestSourceEngine, ForwardVector) TEST(UnitTestSourceEngine, ForwardVector)
{ {
const auto forward = omath::source_engine::ForwardVector({}); const auto forward = omath::source_engine::forward_vector({});
EXPECT_EQ(forward, omath::source_engine::kAbsForward); EXPECT_EQ(forward, omath::source_engine::k_abs_forward);
} }
TEST(UnitTestSourceEngine, RightVector) TEST(UnitTestSourceEngine, RightVector)
{ {
const auto right = omath::source_engine::RightVector({}); const auto right = omath::source_engine::right_vector({});
EXPECT_EQ(right, omath::source_engine::kAbsRight); EXPECT_EQ(right, omath::source_engine::k_abs_right);
} }
TEST(UnitTestSourceEngine, UpVector) TEST(UnitTestSourceEngine, UpVector)
{ {
const auto up = omath::source_engine::UpVector({}); const auto up = omath::source_engine::up_vector({});
EXPECT_EQ(up, omath::source_engine::kAbsUp); EXPECT_EQ(up, omath::source_engine::k_abs_up);
}
TEST(UnitTestSourceEngine, ForwardVectorRotationYaw)
{
omath::source_engine::ViewAngles angles;
angles.yaw = omath::source_engine::YawAngle::from_degrees(-90.f);
const auto forward = omath::source_engine::forward_vector(angles);
EXPECT_NEAR(forward.x, omath::source_engine::k_abs_right.x, 0.00001f);
EXPECT_NEAR(forward.y, omath::source_engine::k_abs_right.y, 0.00001f);
EXPECT_NEAR(forward.z, omath::source_engine::k_abs_right.z, 0.00001f);
}
TEST(UnitTestSourceEngine, ForwardVectorRotationPitch)
{
omath::source_engine::ViewAngles angles;
angles.pitch = omath::source_engine::PitchAngle::from_degrees(-89.f);
const auto forward = omath::source_engine::forward_vector(angles);
EXPECT_NEAR(forward.x, omath::source_engine::k_abs_up.x, 0.02f);
EXPECT_NEAR(forward.y, omath::source_engine::k_abs_up.y, 0.01f);
EXPECT_NEAR(forward.z, omath::source_engine::k_abs_up.z, 0.01f);
}
TEST(UnitTestSourceEngine, ForwardVectorRotationRoll)
{
omath::source_engine::ViewAngles angles;
angles.roll = omath::source_engine::RollAngle::from_degrees(90.f);
const auto forward = omath::source_engine::up_vector(angles);
EXPECT_NEAR(forward.x, omath::source_engine::k_abs_right.x, 0.00001f);
EXPECT_NEAR(forward.y, omath::source_engine::k_abs_right.y, 0.00001f);
EXPECT_NEAR(forward.z, omath::source_engine::k_abs_right.z, 0.00001f);
} }
TEST(UnitTestSourceEngine, ProjectTargetMovedFromCamera) TEST(UnitTestSourceEngine, ProjectTargetMovedFromCamera)
{ {
constexpr auto fov = omath::projection::FieldOfView::FromDegrees(90.f); constexpr auto fov = omath::projection::FieldOfView::from_degrees(90.f);
const auto cam = omath::source_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f); const auto cam = omath::source_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f);
for (float distance = 0.02f; distance < 1000.f; distance += 0.01f) for (float distance = 0.02f; distance < 1000.f; distance += 0.01f)
{ {
const auto projected = cam.WorldToScreen({distance, 0, 0}); const auto projected = cam.world_to_screen({distance, 0, 0});
EXPECT_TRUE(projected.has_value()); EXPECT_TRUE(projected.has_value());
@@ -49,13 +85,13 @@ TEST(UnitTestSourceEngine, ProjectTargetMovedFromCamera)
TEST(UnitTestSourceEngine, ProjectTargetMovedUp) TEST(UnitTestSourceEngine, ProjectTargetMovedUp)
{ {
constexpr auto fov = omath::projection::FieldOfView::FromDegrees(90.f); constexpr auto fov = omath::projection::FieldOfView::from_degrees(90.f);
const auto cam = omath::source_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f); const auto cam = omath::source_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f);
auto prev = 1080.f; auto prev = 1080.f;
for (float distance = 0.0f; distance < 10.f; distance += 1.f) for (float distance = 0.0f; distance < 10.f; distance += 1.f)
{ {
const auto projected = cam.WorldToScreen({100.f, 0, distance}); const auto projected = cam.world_to_screen({100.f, 0, distance});
EXPECT_TRUE(projected.has_value()); EXPECT_TRUE(projected.has_value());
if (!projected.has_value()) if (!projected.has_value())
@@ -69,21 +105,21 @@ TEST(UnitTestSourceEngine, ProjectTargetMovedUp)
TEST(UnitTestSourceEngine, CameraSetAndGetFov) TEST(UnitTestSourceEngine, CameraSetAndGetFov)
{ {
constexpr auto fov = omath::projection::FieldOfView::FromDegrees(90.f); constexpr auto fov = omath::projection::FieldOfView::from_degrees(90.f);
auto cam = omath::source_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f); auto cam = omath::source_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f);
EXPECT_EQ(cam.GetFieldOfView().AsDegrees(), 90.f); EXPECT_EQ(cam.get_field_of_view().as_degrees(), 90.f);
cam.SetFieldOfView(omath::projection::FieldOfView::FromDegrees(50.f)); cam.set_field_of_view(omath::projection::FieldOfView::from_degrees(50.f));
EXPECT_EQ(cam.GetFieldOfView().AsDegrees(), 50.f); EXPECT_EQ(cam.get_field_of_view().as_degrees(), 50.f);
} }
TEST(UnitTestSourceEngine, CameraSetAndGetOrigin) TEST(UnitTestSourceEngine, CameraSetAndGetOrigin)
{ {
auto cam = omath::source_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, {}, 0.01f, 1000.f); auto cam = omath::source_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, {}, 0.01f, 1000.f);
EXPECT_EQ(cam.GetOrigin(), omath::Vector3<float>{}); EXPECT_EQ(cam.get_origin(), omath::Vector3<float>{});
cam.SetFieldOfView(omath::projection::FieldOfView::FromDegrees(50.f)); cam.set_field_of_view(omath::projection::FieldOfView::from_degrees(50.f));
EXPECT_EQ(cam.GetFieldOfView().AsDegrees(), 50.f); EXPECT_EQ(cam.get_field_of_view().as_degrees(), 50.f);
} }

View File

@@ -5,37 +5,73 @@
#include <omath/engines/unity_engine/camera.hpp> #include <omath/engines/unity_engine/camera.hpp>
#include <omath/engines/unity_engine/constants.hpp> #include <omath/engines/unity_engine/constants.hpp>
#include <omath/engines/unity_engine/formulas.hpp> #include <omath/engines/unity_engine/formulas.hpp>
#include <print>
TEST(UnitTestUnityEngine, ForwardVector) TEST(UnitTestUnityEngine, ForwardVector)
{ {
const auto forward = omath::unity_engine::ForwardVector({}); const auto forward = omath::unity_engine::forward_vector({});
EXPECT_EQ(forward, omath::unity_engine::kAbsForward); EXPECT_EQ(forward, omath::unity_engine::k_abs_forward);
}
TEST(UnitTestUnityEngine, ForwardVectorRotationYaw)
{
omath::unity_engine::ViewAngles angles;
angles.yaw = omath::unity_engine::YawAngle::from_degrees(90.f);
const auto forward = omath::unity_engine::forward_vector(angles);
EXPECT_NEAR(forward.x, omath::unity_engine::k_abs_right.x, 0.00001f);
EXPECT_NEAR(forward.y, omath::unity_engine::k_abs_right.y, 0.00001f);
EXPECT_NEAR(forward.z, omath::unity_engine::k_abs_right.z, 0.00001f);
}
TEST(UnitTestUnityEngine, ForwardVectorRotationPitch)
{
omath::unity_engine::ViewAngles angles;
angles.pitch = omath::unity_engine::PitchAngle::from_degrees(-90.f);
const auto forward = omath::unity_engine::forward_vector(angles);
EXPECT_NEAR(forward.x, omath::unity_engine::k_abs_up.x, 0.00001f);
EXPECT_NEAR(forward.y, omath::unity_engine::k_abs_up.y, 0.00001f);
EXPECT_NEAR(forward.z, omath::unity_engine::k_abs_up.z, 0.00001f);
}
TEST(UnitTestUnityEngine, ForwardVectorRotationRoll)
{
omath::unity_engine::ViewAngles angles;
angles.roll = omath::unity_engine::RollAngle::from_degrees(-90.f);
const auto forward = omath::unity_engine::up_vector(angles);
EXPECT_NEAR(forward.x, omath::unity_engine::k_abs_right.x, 0.00001f);
EXPECT_NEAR(forward.y, omath::unity_engine::k_abs_right.y, 0.00001f);
EXPECT_NEAR(forward.z, omath::unity_engine::k_abs_right.z, 0.00001f);
} }
TEST(UnitTestUnityEngine, RightVector) TEST(UnitTestUnityEngine, RightVector)
{ {
const auto right = omath::unity_engine::RightVector({}); const auto right = omath::unity_engine::right_vector({});
EXPECT_EQ(right, omath::unity_engine::kAbsRight); EXPECT_EQ(right, omath::unity_engine::k_abs_right);
} }
TEST(UnitTestUnityEngine, UpVector) TEST(UnitTestUnityEngine, UpVector)
{ {
const auto up = omath::unity_engine::UpVector({}); const auto up = omath::unity_engine::up_vector({});
EXPECT_EQ(up, omath::unity_engine::kAbsUp); EXPECT_EQ(up, omath::unity_engine::k_abs_up);
} }
TEST(UnitTestUnityEngine, ProjectTargetMovedFromCamera) TEST(UnitTestUnityEngine, ProjectTargetMovedFromCamera)
{ {
constexpr auto fov = omath::projection::FieldOfView::FromDegrees(60.f); constexpr auto fov = omath::projection::FieldOfView::from_degrees(60.f);
const auto cam = omath::unity_engine::Camera({0, 0, 0}, {}, {1280.f, 720.f}, fov, 0.01f, 1000.f); const auto cam = omath::unity_engine::Camera({0, 0, 0}, {}, {1280.f, 720.f}, fov, 0.01f, 1000.f);
for (float distance = 0.02f; distance < 100.f; distance += 0.01f) for (float distance = 0.02f; distance < 100.f; distance += 0.01f)
{ {
const auto projected = cam.WorldToScreen({0, 0, distance}); const auto projected = cam.world_to_screen({0, 0, distance});
EXPECT_TRUE(projected.has_value()); EXPECT_TRUE(projected.has_value());
@@ -48,30 +84,30 @@ TEST(UnitTestUnityEngine, ProjectTargetMovedFromCamera)
} }
TEST(UnitTestUnityEngine, Project) TEST(UnitTestUnityEngine, Project)
{ {
constexpr auto fov = omath::projection::FieldOfView::FromDegrees(60.f); constexpr auto fov = omath::projection::FieldOfView::from_degrees(60.f);
const auto cam = omath::unity_engine::Camera({0, 0, 0}, {}, {1280.f, 720.f}, fov, 0.03f, 1000.f); const auto cam = omath::unity_engine::Camera({0, 0, 0}, {}, {1280.f, 720.f}, fov, 0.03f, 1000.f);
const auto proj = cam.WorldToScreen({5.f, 3, 10.f}); const auto proj = cam.world_to_screen({5.f, 3, 10.f});
std::println("{} {}", proj->x, proj->y); std::println("{} {}", proj->x, proj->y);
} }
TEST(UnitTestUnityEngine, CameraSetAndGetFov) TEST(UnitTestUnityEngine, CameraSetAndGetFov)
{ {
constexpr auto fov = omath::projection::FieldOfView::FromDegrees(90.f); constexpr auto fov = omath::projection::FieldOfView::from_degrees(90.f);
auto cam = omath::unity_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f); auto cam = omath::unity_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, fov, 0.01f, 1000.f);
EXPECT_EQ(cam.GetFieldOfView().AsDegrees(), 90.f); EXPECT_EQ(cam.get_field_of_view().as_degrees(), 90.f);
cam.SetFieldOfView(omath::projection::FieldOfView::FromDegrees(50.f)); cam.set_field_of_view(omath::projection::FieldOfView::from_degrees(50.f));
EXPECT_EQ(cam.GetFieldOfView().AsDegrees(), 50.f); EXPECT_EQ(cam.get_field_of_view().as_degrees(), 50.f);
} }
TEST(UnitTestUnityEngine, CameraSetAndGetOrigin) TEST(UnitTestUnityEngine, CameraSetAndGetOrigin)
{ {
auto cam = omath::unity_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, {}, 0.01f, 1000.f); auto cam = omath::unity_engine::Camera({0, 0, 0}, {}, {1920.f, 1080.f}, {}, 0.01f, 1000.f);
EXPECT_EQ(cam.GetOrigin(), omath::Vector3<float>{}); EXPECT_EQ(cam.get_origin(), omath::Vector3<float>{});
cam.SetFieldOfView(omath::projection::FieldOfView::FromDegrees(50.f)); cam.set_field_of_view(omath::projection::FieldOfView::from_degrees(50.f));
EXPECT_EQ(cam.GetFieldOfView().AsDegrees(), 50.f); EXPECT_EQ(cam.get_field_of_view().as_degrees(), 50.f);
} }

View File

@@ -4,14 +4,13 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <omath/pathfinding/a_star.hpp> #include <omath/pathfinding/a_star.hpp>
TEST(unit_test_a_star, finding_right_path)
TEST(UnitTestAstar, FindingRightPath)
{ {
omath::pathfinding::NavigationMesh mesh; omath::pathfinding::NavigationMesh mesh;
mesh.m_verTextMap[{0.f, 0.f, 0.f}] = {{0.f, 1.f, 0.f}}; mesh.m_vertex_map[{0.f, 0.f, 0.f}] = {{0.f, 1.f, 0.f}};
mesh.m_verTextMap[{0.f, 1.f, 0.f}] = {{0.f, 2.f, 0.f}}; mesh.m_vertex_map[{0.f, 1.f, 0.f}] = {{0.f, 2.f, 0.f}};
mesh.m_verTextMap[{0.f, 2.f, 0.f}] = {{0.f, 3.f, 0.f}}; mesh.m_vertex_map[{0.f, 2.f, 0.f}] = {{0.f, 3.f, 0.f}};
mesh.m_verTextMap[{0.f, 3.f, 0.f}] = {}; mesh.m_vertex_map[{0.f, 3.f, 0.f}] = {};
std::ignore = omath::pathfinding::Astar::FindPath({}, {0.f, 3.f, 0.f}, mesh); std::ignore = omath::pathfinding::Astar::find_path({}, {0.f, 3.f, 0.f}, mesh);
} }

View File

@@ -4,46 +4,46 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <omath/angles.hpp> #include <omath/angles.hpp>
TEST(UnitTestAngles, RadiansToDeg) TEST(unit_test_angles, radians_to_deg)
{ {
constexpr float rad = 67; constexpr float rad = 67;
EXPECT_NEAR(omath::angles::RadiansToDegrees(rad), 3838.82f, 0.01f); EXPECT_NEAR(omath::angles::radians_to_degrees(rad), 3838.82f, 0.01f);
} }
TEST(UnitTestAngles, DegreesToRadians) TEST(unit_test_angles, degrees_to_radians)
{ {
constexpr float degree = 90; constexpr float degree = 90;
EXPECT_NEAR(omath::angles::DegreesToRadians(degree), 1.5708f, 0.01f); EXPECT_NEAR(omath::angles::degrees_to_radians(degree), 1.5708f, 0.01f);
} }
TEST(UnitTestAngles, HorizontalFovToVerical) TEST(unit_test_angles, horizontal_fov_to_verical)
{ {
constexpr float hFov = 90; constexpr float hFov = 90;
constexpr float aspectRation = 16.0f / 9.0f; constexpr float aspectRation = 16.0f / 9.0f;
const auto verticalFov = omath::angles::HorizontalFovToVertical(hFov, aspectRation); const auto verticalFov = omath::angles::horizontal_fov_to_vertical(hFov, aspectRation);
EXPECT_NEAR(verticalFov, 58.71f, 0.01f); EXPECT_NEAR(verticalFov, 58.71f, 0.01f);
} }
TEST(UnitTestAngles, VerticalToHorizontal) TEST(unit_test_angles, vertical_to_horizontal)
{ {
constexpr float vFov = 58.71; constexpr float vFov = 58.71;
constexpr float aspectRation = 16.0f / 9.0f; constexpr float aspectRation = 16.0f / 9.0f;
const auto horizontalFov = omath::angles::VerticalFovToHorizontal(vFov, aspectRation); const auto horizontalFov = omath::angles::vertical_fov_to_horizontal(vFov, aspectRation);
EXPECT_NEAR(horizontalFov, 89.99f, 0.01f); EXPECT_NEAR(horizontalFov, 89.99f, 0.01f);
} }
TEST(UnitTestAngles, WrapAngle) TEST(unit_test_angles, wrap_angle)
{ {
const float wrapped = omath::angles::WrapAngle(361.f, 0.f, 360.f); const float wrapped = omath::angles::wrap_angle(361.f, 0.f, 360.f);
EXPECT_NEAR(wrapped, 1.f, 0.01f); EXPECT_NEAR(wrapped, 1.f, 0.01f);
} }
TEST(UnitTestAngles, WrapAngleNegativeRange) TEST(unit_test_angles, wrap_angle_negative_range)
{ {
const float wrapped = omath::angles::WrapAngle(-90.f, 0.f, 360.f); const float wrapped = omath::angles::wrap_angle(-90.f, 0.f, 360.f);
EXPECT_NEAR(wrapped, 270.f, 0.01f); EXPECT_NEAR(wrapped, 270.f, 0.01f);
} }

View File

@@ -0,0 +1,6 @@
//
// Created by Vlad on 4/18/2025.
//
#include <gtest/gtest.h>
#include <omath/3d_primitives/box.hpp>

View File

@@ -15,8 +15,8 @@ protected:
void SetUp() override void SetUp() override
{ {
color1 = Color::Red(); color1 = Color::red();
color2 = Color::Green(); color2 = Color::green();
} }
}; };
@@ -43,7 +43,7 @@ TEST_F(UnitTestColor, Constructor_Vector4)
// Test static methods for color creation // Test static methods for color creation
TEST_F(UnitTestColor, FromRGBA) TEST_F(UnitTestColor, FromRGBA)
{ {
constexpr Color color = Color::FromRGBA(128, 64, 32, 255); constexpr Color color = Color::from_rgba(128, 64, 32, 255);
EXPECT_FLOAT_EQ(color.x, 128.0f / 255.0f); EXPECT_FLOAT_EQ(color.x, 128.0f / 255.0f);
EXPECT_FLOAT_EQ(color.y, 64.0f / 255.0f); EXPECT_FLOAT_EQ(color.y, 64.0f / 255.0f);
EXPECT_FLOAT_EQ(color.z, 32.0f / 255.0f); EXPECT_FLOAT_EQ(color.z, 32.0f / 255.0f);
@@ -52,7 +52,7 @@ TEST_F(UnitTestColor, FromRGBA)
TEST_F(UnitTestColor, FromHSV) TEST_F(UnitTestColor, FromHSV)
{ {
constexpr Color color = Color::FromHSV(0.0f, 1.0f, 1.0f); // Red in HSV constexpr Color color = Color::from_hsv(0.0f, 1.0f, 1.0f); // Red in HSV
EXPECT_FLOAT_EQ(color.x, 1.0f); EXPECT_FLOAT_EQ(color.x, 1.0f);
EXPECT_FLOAT_EQ(color.y, 0.0f); EXPECT_FLOAT_EQ(color.y, 0.0f);
EXPECT_FLOAT_EQ(color.z, 0.0f); EXPECT_FLOAT_EQ(color.z, 0.0f);
@@ -62,7 +62,7 @@ TEST_F(UnitTestColor, FromHSV)
// Test HSV conversion // Test HSV conversion
TEST_F(UnitTestColor, ToHSV) TEST_F(UnitTestColor, ToHSV)
{ {
HSV hsv = color1.ToHSV(); // Red color Hsv hsv = color1.to_hsv(); // Red color
EXPECT_FLOAT_EQ(hsv.hue, 0.0f); EXPECT_FLOAT_EQ(hsv.hue, 0.0f);
EXPECT_FLOAT_EQ(hsv.saturation, 1.0f); EXPECT_FLOAT_EQ(hsv.saturation, 1.0f);
EXPECT_FLOAT_EQ(hsv.value, 1.0f); EXPECT_FLOAT_EQ(hsv.value, 1.0f);
@@ -71,7 +71,7 @@ TEST_F(UnitTestColor, ToHSV)
// Test color blending // Test color blending
TEST_F(UnitTestColor, Blend) TEST_F(UnitTestColor, Blend)
{ {
Color blended = color1.Blend(color2, 0.5f); Color blended = color1.blend(color2, 0.5f);
EXPECT_FLOAT_EQ(blended.x, 0.5f); EXPECT_FLOAT_EQ(blended.x, 0.5f);
EXPECT_FLOAT_EQ(blended.y, 0.5f); EXPECT_FLOAT_EQ(blended.y, 0.5f);
EXPECT_FLOAT_EQ(blended.z, 0.0f); EXPECT_FLOAT_EQ(blended.z, 0.0f);
@@ -81,9 +81,9 @@ TEST_F(UnitTestColor, Blend)
// Test predefined colors // Test predefined colors
TEST_F(UnitTestColor, PredefinedColors) TEST_F(UnitTestColor, PredefinedColors)
{ {
constexpr Color red = Color::Red(); constexpr Color red = Color::red();
constexpr Color green = Color::Green(); constexpr Color green = Color::green();
constexpr Color blue = Color::Blue(); constexpr Color blue = Color::blue();
EXPECT_FLOAT_EQ(red.x, 1.0f); EXPECT_FLOAT_EQ(red.x, 1.0f);
EXPECT_FLOAT_EQ(red.y, 0.0f); EXPECT_FLOAT_EQ(red.y, 0.0f);
@@ -106,7 +106,7 @@ TEST_F(UnitTestColor, BlendVector3)
{ {
constexpr Color v1(1.0f, 0.0f, 0.0f, 1.f); // Red constexpr Color v1(1.0f, 0.0f, 0.0f, 1.f); // Red
constexpr Color v2(0.0f, 1.0f, 0.0f, 1.f); // Green constexpr Color v2(0.0f, 1.0f, 0.0f, 1.f); // Green
constexpr Color blended = v1.Blend(v2, 0.5f); constexpr Color blended = v1.blend(v2, 0.5f);
EXPECT_FLOAT_EQ(blended.x, 0.5f); EXPECT_FLOAT_EQ(blended.x, 0.5f);
EXPECT_FLOAT_EQ(blended.y, 0.5f); EXPECT_FLOAT_EQ(blended.y, 0.5f);
EXPECT_FLOAT_EQ(blended.z, 0.0f); EXPECT_FLOAT_EQ(blended.z, 0.0f);

View File

@@ -1,80 +1,120 @@
//
// Revised unittest suite for LineTracer (segmentbased MöllerTrumbore)
// Pure ASCII: avoids nonstandard characters that MSVC rejects.
//
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "omath/collision/line_tracer.hpp" #include "omath/collision/line_tracer.hpp"
#include "omath/triangle.hpp" #include "omath/triangle.hpp"
#include "omath/vector3.hpp" #include "omath/vector3.hpp"
#include <cmath>
using namespace omath; using namespace omath;
using namespace omath::collision; using namespace omath::collision;
class LineTracerTest : public ::testing::Test using Vec3 = Vector3<float>;
namespace
{ {
protected:
// Set up common variables for use in each test
Vector3<float> vertex1{0.0f, 0.0f, 0.0f};
Vector3<float> vertex2{1.0f, 0.0f, 0.0f};
Vector3<float> vertex3{0.0f, 1.0f, 0.0f};
Triangle<Vector3<float>> triangle{vertex1, vertex2, vertex3};
};
// Test that a ray intersecting the triangle returns false for CanTraceLine // -----------------------------------------------------------------------------
TEST_F(LineTracerTest, RayIntersectsTriangle) // Constants & helpers
{ // -----------------------------------------------------------------------------
constexpr Ray ray{{0.3f, 0.3f, -1.0f}, {0.3f, 0.3f, 1.0f}}; constexpr float kTol = 1e-5f;
EXPECT_FALSE(LineTracer::CanTraceLine(ray, triangle));
}
// Test that a ray parallel to the triangle plane returns true for CanTraceLine bool VecEqual(const Vec3& a, const Vec3& b, float tol = kTol)
TEST_F(LineTracerTest, RayParallelToTriangle) {
{ return std::fabs(a.x - b.x) < tol &&
constexpr Ray ray{{0.3f, 0.3f, 1.0f}, {0.3f, 0.3f, 2.0f}}; std::fabs(a.y - b.y) < tol &&
EXPECT_TRUE(LineTracer::CanTraceLine(ray, triangle)); std::fabs(a.z - b.z) < tol;
} }
// Test that a ray starting inside the triangle but pointing away returns true // -----------------------------------------------------------------------------
TEST_F(LineTracerTest, RayStartsInTriangleButDoesNotIntersect) // Fixture with one canonical rightangled triangle in the XY plane.
{ // -----------------------------------------------------------------------------
constexpr Ray ray{{0.3f, 0.3f, 0.0f}, {0.3f, 0.3f, -1.0f}}; class LineTracerFixture : public ::testing::Test
EXPECT_TRUE(LineTracer::CanTraceLine(ray, triangle)); {
} protected:
LineTracerFixture() :
triangle({0.f, 0.f, 0.f}, {1.f, 0.f, 0.f}, {0.f, 1.f, 0.f})
{
}
// Test that a ray not intersecting the triangle plane returns true Triangle<Vec3> triangle;
TEST_F(LineTracerTest, RayMissesTriangle)
{
constexpr Ray ray{{2.0f, 2.0f, -1.0f}, {2.0f, 2.0f, 1.0f}};
EXPECT_TRUE(LineTracer::CanTraceLine(ray, triangle));
}
// Test that a ray lying exactly in the plane of the triangle without intersecting returns true
TEST_F(LineTracerTest, RayInPlaneNotIntersecting)
{
constexpr Ray ray{{-1.0f, -1.0f, 0.0f}, {1.5f, 1.5f, 0.0f}};
EXPECT_TRUE(LineTracer::CanTraceLine(ray, triangle));
}
TEST_F(LineTracerTest, RayIntersectsVertex)
{
const Ray ray{{-1.0f, -1.0f, -1.0f}, vertex1}; // Intersecting at vertex1
EXPECT_TRUE(LineTracer::CanTraceLine(ray, triangle));
}
TEST_F(LineTracerTest, RayIntersectsEdge)
{
constexpr Ray ray{{-1.0f, 0.0f, -1.0f}, {0.5f, 0.0f, 0.0f}};
// Intersecting on the edge between vertex1 and vertex2
EXPECT_TRUE(LineTracer::CanTraceLine(ray, triangle));
}
TEST_F(LineTracerTest, TriangleFarBeyondRayEndPoint)
{
// Define a ray with a short length
constexpr Ray ray{{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}};
// Define a triangle far beyond the ray's endpoint
constexpr Triangle<Vector3<float>> distantTriangle{
{1000.0f, 1000.0f, 1000.0f}, {1001.0f, 1000.0f, 1000.0f}, {1000.0f, 1001.0f, 1000.0f}
}; };
// Expect true because the ray ends long before it could reach the distant triangle // -----------------------------------------------------------------------------
EXPECT_TRUE(LineTracer::CanTraceLine(ray, distantTriangle)); // Datadriven tests for CanTraceLine
} // -----------------------------------------------------------------------------
struct TraceCase
{
Ray ray;
bool expected_clear; // true => segment does NOT hit the triangle
};
class CanTraceLineParam : public LineTracerFixture,
public ::testing::WithParamInterface<TraceCase>
{
};
TEST_P(CanTraceLineParam, VariousRays)
{
const auto& p = GetParam();
EXPECT_EQ(LineTracer::can_trace_line(p.ray, triangle), p.expected_clear);
}
INSTANTIATE_TEST_SUITE_P(
BasicScenarios,
CanTraceLineParam,
::testing::Values(
TraceCase{Ray{{ 0.3f, 0.3f, -1.f},{ 0.3f, 0.3f, 1.f}}, false}, // hit through centre
TraceCase{Ray{{ 0.3f, 0.3f, 1.f},{ 0.3f, 0.3f, 2.f}}, true}, // parallel above
TraceCase{Ray{{ 0.3f, 0.3f, 0.f},{ 0.3f, 0.3f,-1.f}}, true}, // starts inside, goes away
TraceCase{Ray{{ 2.0f, 2.0f, -1.f},{ 2.0f, 2.0f, 1.f}}, true}, // misses entirely
TraceCase{Ray{{-1.0f,-1.0f, 0.f},{ 1.5f, 1.5f, 0.f}},true}, // lies in plane, outside tri
TraceCase{Ray{{-1.0f,-1.0f, -1.f},{ 0.0f, 0.0f, 0.f}}, true}, // endpoint on vertex
TraceCase{Ray{{-1.0f, 0.0f, -1.f},{ 0.5f, 0.0f, 0.f}}, true} // endpoint on edge
)
);
// -----------------------------------------------------------------------------
// Validate that the reported hit point is correct for a genuine intersection.
// -----------------------------------------------------------------------------
TEST_F(LineTracerFixture, HitPointCorrect)
{
constexpr Ray ray{{0.3f, 0.3f, -1.f}, {0.3f, 0.3f, 1.f}};
constexpr Vec3 expected{0.3f, 0.3f, 0.f};
const Vec3 hit = LineTracer::get_ray_hit_point(ray, triangle);
ASSERT_FALSE(VecEqual(hit, ray.end));
EXPECT_TRUE(VecEqual(hit, expected));
}
// -----------------------------------------------------------------------------
// Triangle far beyond the ray should not block.
// -----------------------------------------------------------------------------
TEST_F(LineTracerFixture, DistantTriangleClear)
{
constexpr Ray short_ray{{0.f, 0.f, 0.f}, {0.f, 0.f, 1.f}};
constexpr Triangle<Vec3> distant{{1000.f, 1000.f, 1000.f},
{1001.f, 1000.f, 1000.f},
{1000.f, 1001.f, 1000.f}};
EXPECT_TRUE(LineTracer::can_trace_line(short_ray, distant));
}
TEST(LineTracerTraceRayEdge, CantHit)
{
constexpr omath::Triangle<Vector3<float>> triangle{{2, 0, 0}, {2, 2, 0}, {2, 2, 2}};
constexpr Ray ray{{}, {1.0, 0, 0}, false};
EXPECT_TRUE(omath::collision::LineTracer::can_trace_line(ray, triangle));
}
TEST(LineTracerTraceRayEdge, CanHit)
{
constexpr omath::Triangle<Vector3<float>> triangle{{2, 0, 0}, {2, 2, 0}, {2, 2, 2}};
constexpr Ray ray{{}, {2.1, 0, 0}, false};
EXPECT_FALSE(omath::collision::LineTracer::can_trace_line(ray, triangle));
}
} // namespace

View File

@@ -22,22 +22,22 @@ protected:
TEST_F(UnitTestMat, Constructor_Default) TEST_F(UnitTestMat, Constructor_Default)
{ {
Mat<3, 3> m; Mat<3, 3> m;
EXPECT_EQ(m.RowCount(), 3); EXPECT_EQ(m.row_count(), 3);
EXPECT_EQ(m.ColumnsCount(), 3); EXPECT_EQ(m.columns_count(), 3);
for (size_t i = 0; i < 3; ++i) for (size_t i = 0; i < 3; ++i)
for (size_t j = 0; j < 3; ++j) for (size_t j = 0; j < 3; ++j)
EXPECT_FLOAT_EQ(m.At(i, j), 0.0f); EXPECT_FLOAT_EQ(m.at(i, j), 0.0f);
} }
TEST_F(UnitTestMat, Constructor_InitializerList) TEST_F(UnitTestMat, Constructor_InitializerList)
{ {
constexpr Mat<2, 2> m{{1.0f, 2.0f}, {3.0f, 4.0f}}; constexpr Mat<2, 2> m{{1.0f, 2.0f}, {3.0f, 4.0f}};
EXPECT_EQ(m.RowCount(), 2); EXPECT_EQ(m.row_count(), 2);
EXPECT_EQ(m.ColumnsCount(), 2); EXPECT_EQ(m.columns_count(), 2);
EXPECT_FLOAT_EQ(m.At(0, 0), 1.0f); EXPECT_FLOAT_EQ(m.at(0, 0), 1.0f);
EXPECT_FLOAT_EQ(m.At(0, 1), 2.0f); EXPECT_FLOAT_EQ(m.at(0, 1), 2.0f);
EXPECT_FLOAT_EQ(m.At(1, 0), 3.0f); EXPECT_FLOAT_EQ(m.at(1, 0), 3.0f);
EXPECT_FLOAT_EQ(m.At(1, 1), 4.0f); EXPECT_FLOAT_EQ(m.at(1, 1), 4.0f);
} }
TEST_F(UnitTestMat, Operator_SquareBrackets) TEST_F(UnitTestMat, Operator_SquareBrackets)
@@ -51,19 +51,19 @@ TEST_F(UnitTestMat, Operator_SquareBrackets)
TEST_F(UnitTestMat, Constructor_Copy) TEST_F(UnitTestMat, Constructor_Copy)
{ {
Mat<2, 2> m3 = m2; Mat<2, 2> m3 = m2;
EXPECT_EQ(m3.RowCount(), m2.RowCount()); EXPECT_EQ(m3.row_count(), m2.row_count());
EXPECT_EQ(m3.ColumnsCount(), m2.ColumnsCount()); EXPECT_EQ(m3.columns_count(), m2.columns_count());
EXPECT_FLOAT_EQ(m3.At(0, 0), m2.At(0, 0)); EXPECT_FLOAT_EQ(m3.at(0, 0), m2.at(0, 0));
EXPECT_FLOAT_EQ(m3.At(1, 1), m2.At(1, 1)); EXPECT_FLOAT_EQ(m3.at(1, 1), m2.at(1, 1));
} }
TEST_F(UnitTestMat, Constructor_Move) TEST_F(UnitTestMat, Constructor_Move)
{ {
Mat<2, 2> m3 = std::move(m2); Mat<2, 2> m3 = std::move(m2);
EXPECT_EQ(m3.RowCount(), 2); EXPECT_EQ(m3.row_count(), 2);
EXPECT_EQ(m3.ColumnsCount(), 2); EXPECT_EQ(m3.columns_count(), 2);
EXPECT_FLOAT_EQ(m3.At(0, 0), 1.0f); EXPECT_FLOAT_EQ(m3.at(0, 0), 1.0f);
EXPECT_FLOAT_EQ(m3.At(1, 1), 4.0f); EXPECT_FLOAT_EQ(m3.at(1, 1), 4.0f);
// m2 is in a valid but unspecified state after move // m2 is in a valid but unspecified state after move
} }
@@ -71,61 +71,61 @@ TEST_F(UnitTestMat, Constructor_Move)
TEST_F(UnitTestMat, Operator_Multiplication_Matrix) TEST_F(UnitTestMat, Operator_Multiplication_Matrix)
{ {
Mat<2, 2> m3 = m2 * m2; Mat<2, 2> m3 = m2 * m2;
EXPECT_EQ(m3.RowCount(), 2); EXPECT_EQ(m3.row_count(), 2);
EXPECT_EQ(m3.ColumnsCount(), 2); EXPECT_EQ(m3.columns_count(), 2);
EXPECT_FLOAT_EQ(m3.At(0, 0), 7.0f); EXPECT_FLOAT_EQ(m3.at(0, 0), 7.0f);
EXPECT_FLOAT_EQ(m3.At(0, 1), 10.0f); EXPECT_FLOAT_EQ(m3.at(0, 1), 10.0f);
EXPECT_FLOAT_EQ(m3.At(1, 0), 15.0f); EXPECT_FLOAT_EQ(m3.at(1, 0), 15.0f);
EXPECT_FLOAT_EQ(m3.At(1, 1), 22.0f); EXPECT_FLOAT_EQ(m3.at(1, 1), 22.0f);
} }
TEST_F(UnitTestMat, Operator_Multiplication_Scalar) TEST_F(UnitTestMat, Operator_Multiplication_Scalar)
{ {
Mat<2, 2> m3 = m2 * 2.0f; Mat<2, 2> m3 = m2 * 2.0f;
EXPECT_FLOAT_EQ(m3.At(0, 0), 2.0f); EXPECT_FLOAT_EQ(m3.at(0, 0), 2.0f);
EXPECT_FLOAT_EQ(m3.At(1, 1), 8.0f); EXPECT_FLOAT_EQ(m3.at(1, 1), 8.0f);
} }
TEST_F(UnitTestMat, Operator_Division_Scalar) TEST_F(UnitTestMat, Operator_Division_Scalar)
{ {
Mat<2, 2> m3 = m2 / 2.0f; Mat<2, 2> m3 = m2 / 2.0f;
EXPECT_FLOAT_EQ(m3.At(0, 0), 0.5f); EXPECT_FLOAT_EQ(m3.at(0, 0), 0.5f);
EXPECT_FLOAT_EQ(m3.At(1, 1), 2.0f); EXPECT_FLOAT_EQ(m3.at(1, 1), 2.0f);
} }
// Test matrix functions // Test matrix functions
TEST_F(UnitTestMat, Transpose) TEST_F(UnitTestMat, Transpose)
{ {
Mat<2, 2> m3 = m2.Transposed(); Mat<2, 2> m3 = m2.transposed();
EXPECT_FLOAT_EQ(m3.At(0, 0), m2.At(0, 0)); EXPECT_FLOAT_EQ(m3.at(0, 0), m2.at(0, 0));
EXPECT_FLOAT_EQ(m3.At(0, 1), m2.At(1, 0)); EXPECT_FLOAT_EQ(m3.at(0, 1), m2.at(1, 0));
EXPECT_FLOAT_EQ(m3.At(1, 0), m2.At(0, 1)); EXPECT_FLOAT_EQ(m3.at(1, 0), m2.at(0, 1));
EXPECT_FLOAT_EQ(m3.At(1, 1), m2.At(1, 1)); EXPECT_FLOAT_EQ(m3.at(1, 1), m2.at(1, 1));
} }
TEST_F(UnitTestMat, Determinant) TEST_F(UnitTestMat, Determinant)
{ {
const float det = m2.Determinant(); const float det = m2.determinant();
EXPECT_FLOAT_EQ(det, -2.0f); EXPECT_FLOAT_EQ(det, -2.0f);
} }
TEST_F(UnitTestMat, Sum) TEST_F(UnitTestMat, Sum)
{ {
const float sum = m2.Sum(); const float sum = m2.sum();
EXPECT_FLOAT_EQ(sum, 10.0f); EXPECT_FLOAT_EQ(sum, 10.0f);
} }
TEST_F(UnitTestMat, Clear) TEST_F(UnitTestMat, Clear)
{ {
m2.Clear(); m2.clear();
for (size_t i = 0; i < m2.RowCount(); ++i) for (size_t i = 0; i < m2.row_count(); ++i)
for (size_t j = 0; j < m2.ColumnsCount(); ++j) for (size_t j = 0; j < m2.columns_count(); ++j)
EXPECT_FLOAT_EQ(m2.At(i, j), 0.0f); EXPECT_FLOAT_EQ(m2.at(i, j), 0.0f);
} }
TEST_F(UnitTestMat, ToString) TEST_F(UnitTestMat, ToString)
{ {
const std::string str = m2.ToString(); const std::string str = m2.to_string();
EXPECT_FALSE(str.empty()); EXPECT_FALSE(str.empty());
EXPECT_EQ(str, "[[ 1.000, 2.000]\n [ 3.000, 4.000]]"); EXPECT_EQ(str, "[[ 1.000, 2.000]\n [ 3.000, 4.000]]");
} }
@@ -135,72 +135,82 @@ TEST_F(UnitTestMat, AssignmentOperator_Copy)
{ {
Mat<2, 2> m3; Mat<2, 2> m3;
m3 = m2; m3 = m2;
EXPECT_EQ(m3.RowCount(), m2.RowCount()); EXPECT_EQ(m3.row_count(), m2.row_count());
EXPECT_EQ(m3.ColumnsCount(), m2.ColumnsCount()); EXPECT_EQ(m3.columns_count(), m2.columns_count());
EXPECT_FLOAT_EQ(m3.At(0, 0), m2.At(0, 0)); EXPECT_FLOAT_EQ(m3.at(0, 0), m2.at(0, 0));
} }
TEST_F(UnitTestMat, AssignmentOperator_Move) TEST_F(UnitTestMat, AssignmentOperator_Move)
{ {
Mat<2, 2> m3; Mat<2, 2> m3;
m3 = std::move(m2); m3 = std::move(m2);
EXPECT_EQ(m3.RowCount(), 2); EXPECT_EQ(m3.row_count(), 2);
EXPECT_EQ(m3.ColumnsCount(), 2); EXPECT_EQ(m3.columns_count(), 2);
EXPECT_FLOAT_EQ(m3.At(0, 0), 1.0f); EXPECT_FLOAT_EQ(m3.at(0, 0), 1.0f);
EXPECT_FLOAT_EQ(m3.At(1, 1), 4.0f); EXPECT_FLOAT_EQ(m3.at(1, 1), 4.0f);
// m2 is in a valid but unspecified state after move // m2 is in a valid but unspecified state after move
} }
// Test static methods // Test static methods
TEST_F(UnitTestMat, StaticMethod_ToScreenMat) TEST_F(UnitTestMat, StaticMethod_ToScreenMat)
{ {
Mat<4, 4> screenMat = Mat<4, 4>::ToScreenMat(800.0f, 600.0f); Mat<4, 4> screenMat = Mat<4, 4>::to_screen_mat(800.0f, 600.0f);
EXPECT_FLOAT_EQ(screenMat.At(0, 0), 400.0f); EXPECT_FLOAT_EQ(screenMat.at(0, 0), 400.0f);
EXPECT_FLOAT_EQ(screenMat.At(1, 1), -300.0f); EXPECT_FLOAT_EQ(screenMat.at(1, 1), -300.0f);
EXPECT_FLOAT_EQ(screenMat.At(3, 0), 400.0f); EXPECT_FLOAT_EQ(screenMat.at(3, 0), 400.0f);
EXPECT_FLOAT_EQ(screenMat.At(3, 1), 300.0f); EXPECT_FLOAT_EQ(screenMat.at(3, 1), 300.0f);
EXPECT_FLOAT_EQ(screenMat.At(3, 3), 1.0f); EXPECT_FLOAT_EQ(screenMat.at(3, 3), 1.0f);
} }
// Test exception handling in At() method // Test exception handling in At() method
TEST_F(UnitTestMat, Method_At_OutOfRange) TEST_F(UnitTestMat, Method_At_OutOfRange)
{ {
#if !defined(NDEBUG) && defined(OMATH_SUPRESS_SAFETY_CHECKS)
EXPECT_THROW(std::ignore = m2.At(2, 0), std::out_of_range); EXPECT_THROW(std::ignore = m2.At(2, 0), std::out_of_range);
EXPECT_THROW(std::ignore = m2.At(0, 2), std::out_of_range); EXPECT_THROW(std::ignore = m2.At(0, 2), std::out_of_range);
#endif
} }
// Test Determinant for 3x3 matrix // Test Determinant for 3x3 matrix
TEST(UnitTestMatStandalone, Determinant_3x3) TEST(UnitTestMatStandalone, Determinant_3x3)
{ {
constexpr auto det = Mat<3, 3>{{6, 1, 1}, {4, -2, 5}, {2, 8, 7}}.Determinant(); constexpr auto det = Mat<3, 3>{{6, 1, 1}, {4, -2, 5}, {2, 8, 7}}.determinant();
EXPECT_FLOAT_EQ(det, -306.0f); EXPECT_FLOAT_EQ(det, -306.0f);
} }
// Test Minor for 3x3 matrix // Test Minor for 3x3 matrix
TEST(UnitTestMatStandalone, Minor_3x3) TEST(UnitTestMatStandalone, Strip_3x3)
{ {
constexpr Mat<3, 3> m{{3, 0, 2}, {2, 0, -2}, {0, 1, 1}}; constexpr Mat<3, 3> m{{3, 0, 2}, {2, 0, -2}, {0, 1, 1}};
auto minor = m.Minor(0, 0); auto minor = m.strip(0, 0);
EXPECT_EQ(minor.RowCount(), 2); EXPECT_EQ(minor.row_count(), 2);
EXPECT_EQ(minor.ColumnsCount(), 2); EXPECT_EQ(minor.columns_count(), 2);
EXPECT_FLOAT_EQ(minor.At(0, 0), 0.0f); EXPECT_FLOAT_EQ(minor.at(0, 0), 0.0f);
EXPECT_FLOAT_EQ(minor.At(0, 1), -2.0f); EXPECT_FLOAT_EQ(minor.at(0, 1), -2.0f);
EXPECT_FLOAT_EQ(minor.At(1, 0), 1.0f); EXPECT_FLOAT_EQ(minor.at(1, 0), 1.0f);
EXPECT_FLOAT_EQ(minor.At(1, 1), 1.0f); EXPECT_FLOAT_EQ(minor.at(1, 1), 1.0f);
} }
// Test Transpose for non-square matrix // Test Transpose for non-square matrix
TEST(UnitTestMatStandalone, Transpose_NonSquare) TEST(UnitTestMatStandalone, Transpose_NonSquare)
{ {
constexpr Mat<2, 3> m{{1.0f, 2.0f, 3.0f}, {4.0f, 5.0f, 6.0f}}; constexpr Mat<2, 3> m{{1.0f, 2.0f, 3.0f}, {4.0f, 5.0f, 6.0f}};
auto transposed = m.Transposed(); auto transposed = m.transposed();
EXPECT_EQ(transposed.RowCount(), 3); EXPECT_EQ(transposed.row_count(), 3);
EXPECT_EQ(transposed.ColumnsCount(), 2); EXPECT_EQ(transposed.columns_count(), 2);
EXPECT_FLOAT_EQ(transposed.At(0, 0), 1.0f); EXPECT_FLOAT_EQ(transposed.at(0, 0), 1.0f);
EXPECT_FLOAT_EQ(transposed.At(1, 0), 2.0f); EXPECT_FLOAT_EQ(transposed.at(1, 0), 2.0f);
EXPECT_FLOAT_EQ(transposed.At(2, 0), 3.0f); EXPECT_FLOAT_EQ(transposed.at(2, 0), 3.0f);
EXPECT_FLOAT_EQ(transposed.At(0, 1), 4.0f); EXPECT_FLOAT_EQ(transposed.at(0, 1), 4.0f);
EXPECT_FLOAT_EQ(transposed.At(1, 1), 5.0f); EXPECT_FLOAT_EQ(transposed.at(1, 1), 5.0f);
EXPECT_FLOAT_EQ(transposed.At(2, 1), 6.0f); EXPECT_FLOAT_EQ(transposed.at(2, 1), 6.0f);
}
TEST(UnitTestMatStandalone, Enverse)
{
constexpr Mat<2, 2> m{{1.0f, 3.0f}, {2.0f, 5.0f}};
constexpr Mat<2,2> mv{{-5.0f, 3.0f}, {2.0f, -1.0f}};
EXPECT_EQ(mv, m.inverted());
} }

View File

@@ -25,8 +25,8 @@ protected:
TEST_F(UnitTestMatrix, Constructor_Size) TEST_F(UnitTestMatrix, Constructor_Size)
{ {
const Matrix m(3, 3); const Matrix m(3, 3);
EXPECT_EQ(m.RowCount(), 3); EXPECT_EQ(m.row_count(), 3);
EXPECT_EQ(m.ColumnsCount(), 3); EXPECT_EQ(m.columns_count(), 3);
} }
TEST_F(UnitTestMatrix, Operator_SquareBrackets) TEST_F(UnitTestMatrix, Operator_SquareBrackets)
@@ -41,120 +41,120 @@ TEST_F(UnitTestMatrix, Operator_SquareBrackets)
TEST_F(UnitTestMatrix, Constructor_InitializerList) TEST_F(UnitTestMatrix, Constructor_InitializerList)
{ {
Matrix m{{1.0f, 2.0f}, {3.0f, 4.0f}}; Matrix m{{1.0f, 2.0f}, {3.0f, 4.0f}};
EXPECT_EQ(m.RowCount(), 2); EXPECT_EQ(m.row_count(), 2);
EXPECT_EQ(m.ColumnsCount(), 2); EXPECT_EQ(m.columns_count(), 2);
EXPECT_FLOAT_EQ(m.At(0, 0), 1.0f); EXPECT_FLOAT_EQ(m.at(0, 0), 1.0f);
EXPECT_FLOAT_EQ(m.At(1, 1), 4.0f); EXPECT_FLOAT_EQ(m.at(1, 1), 4.0f);
} }
TEST_F(UnitTestMatrix, Constructor_Copy) TEST_F(UnitTestMatrix, Constructor_Copy)
{ {
Matrix m3 = m2; Matrix m3 = m2;
EXPECT_EQ(m3.RowCount(), m2.RowCount()); EXPECT_EQ(m3.row_count(), m2.row_count());
EXPECT_EQ(m3.ColumnsCount(), m2.ColumnsCount()); EXPECT_EQ(m3.columns_count(), m2.columns_count());
EXPECT_FLOAT_EQ(m3.At(0, 0), m2.At(0, 0)); EXPECT_FLOAT_EQ(m3.at(0, 0), m2.at(0, 0));
} }
TEST_F(UnitTestMatrix, Constructor_Move) TEST_F(UnitTestMatrix, Constructor_Move)
{ {
Matrix m3 = std::move(m2); Matrix m3 = std::move(m2);
EXPECT_EQ(m3.RowCount(), 2); EXPECT_EQ(m3.row_count(), 2);
EXPECT_EQ(m3.ColumnsCount(), 2); EXPECT_EQ(m3.columns_count(), 2);
EXPECT_FLOAT_EQ(m3.At(0, 0), 1.0f); EXPECT_FLOAT_EQ(m3.at(0, 0), 1.0f);
EXPECT_EQ(m2.RowCount(), 0); // m2 should be empty after the move EXPECT_EQ(m2.row_count(), 0); // m2 should be empty after the move
EXPECT_EQ(m2.ColumnsCount(), 0); EXPECT_EQ(m2.columns_count(), 0);
} }
// Test matrix operations // Test matrix operations
TEST_F(UnitTestMatrix, Operator_Multiplication_Matrix) TEST_F(UnitTestMatrix, Operator_Multiplication_Matrix)
{ {
Matrix m3 = m2 * m2; Matrix m3 = m2 * m2;
EXPECT_EQ(m3.RowCount(), 2); EXPECT_EQ(m3.row_count(), 2);
EXPECT_EQ(m3.ColumnsCount(), 2); EXPECT_EQ(m3.columns_count(), 2);
EXPECT_FLOAT_EQ(m3.At(0, 0), 7.0f); EXPECT_FLOAT_EQ(m3.at(0, 0), 7.0f);
EXPECT_FLOAT_EQ(m3.At(1, 1), 22.0f); EXPECT_FLOAT_EQ(m3.at(1, 1), 22.0f);
} }
TEST_F(UnitTestMatrix, Operator_Multiplication_Scalar) TEST_F(UnitTestMatrix, Operator_Multiplication_Scalar)
{ {
Matrix m3 = m2 * 2.0f; Matrix m3 = m2 * 2.0f;
EXPECT_FLOAT_EQ(m3.At(0, 0), 2.0f); EXPECT_FLOAT_EQ(m3.at(0, 0), 2.0f);
EXPECT_FLOAT_EQ(m3.At(1, 1), 8.0f); EXPECT_FLOAT_EQ(m3.at(1, 1), 8.0f);
} }
TEST_F(UnitTestMatrix, Operator_Division_Scalar) TEST_F(UnitTestMatrix, Operator_Division_Scalar)
{ {
Matrix m3 = m2 / 2.0f; Matrix m3 = m2 / 2.0f;
EXPECT_FLOAT_EQ(m3.At(0, 0), 0.5f); EXPECT_FLOAT_EQ(m3.at(0, 0), 0.5f);
EXPECT_FLOAT_EQ(m3.At(1, 1), 2.0f); EXPECT_FLOAT_EQ(m3.at(1, 1), 2.0f);
} }
// Test matrix functions // Test matrix functions
TEST_F(UnitTestMatrix, Transpose) TEST_F(UnitTestMatrix, Transpose)
{ {
Matrix m3 = m2.Transpose(); Matrix m3 = m2.transpose();
EXPECT_FLOAT_EQ(m3.At(0, 1), 3.0f); EXPECT_FLOAT_EQ(m3.at(0, 1), 3.0f);
EXPECT_FLOAT_EQ(m3.At(1, 0), 2.0f); EXPECT_FLOAT_EQ(m3.at(1, 0), 2.0f);
} }
TEST_F(UnitTestMatrix, Determinant) TEST_F(UnitTestMatrix, Determinant)
{ {
const float det = m2.Determinant(); const float det = m2.determinant();
EXPECT_FLOAT_EQ(det, -2.0f); EXPECT_FLOAT_EQ(det, -2.0f);
} }
TEST_F(UnitTestMatrix, Minor) TEST_F(UnitTestMatrix, Minor)
{ {
const float minor = m2.Minor(0, 0); const float minor = m2.minor(0, 0);
EXPECT_FLOAT_EQ(minor, 4.0f); EXPECT_FLOAT_EQ(minor, 4.0f);
} }
TEST_F(UnitTestMatrix, AlgComplement) TEST_F(UnitTestMatrix, AlgComplement)
{ {
const float algComp = m2.AlgComplement(0, 0); const float algComp = m2.alg_complement(0, 0);
EXPECT_FLOAT_EQ(algComp, 4.0f); EXPECT_FLOAT_EQ(algComp, 4.0f);
} }
TEST_F(UnitTestMatrix, Strip) TEST_F(UnitTestMatrix, Strip)
{ {
Matrix m3 = m2.Strip(0, 0); Matrix m3 = m2.strip(0, 0);
EXPECT_EQ(m3.RowCount(), 1); EXPECT_EQ(m3.row_count(), 1);
EXPECT_EQ(m3.ColumnsCount(), 1); EXPECT_EQ(m3.columns_count(), 1);
EXPECT_FLOAT_EQ(m3.At(0, 0), 4.0f); EXPECT_FLOAT_EQ(m3.at(0, 0), 4.0f);
} }
TEST_F(UnitTestMatrix, ProjectionMatrix) TEST_F(UnitTestMatrix, ProjectionMatrix)
{ {
const Matrix proj = Matrix::ProjectionMatrix(45.0f, 1.33f, 0.1f, 100.0f); const Matrix proj = Matrix::projection_matrix(45.0f, 1.33f, 0.1f, 100.0f);
EXPECT_EQ(proj.RowCount(), 4); EXPECT_EQ(proj.row_count(), 4);
EXPECT_EQ(proj.ColumnsCount(), 4); EXPECT_EQ(proj.columns_count(), 4);
// Further checks on projection matrix elements could be added // Further checks on projection matrix elements could be added
} }
// Test other member functions // Test other member functions
TEST_F(UnitTestMatrix, Set) TEST_F(UnitTestMatrix, Set)
{ {
m1.Set(3.0f); m1.set(3.0f);
EXPECT_FLOAT_EQ(m1.At(0, 0), 3.0f); EXPECT_FLOAT_EQ(m1.at(0, 0), 3.0f);
EXPECT_FLOAT_EQ(m1.At(1, 1), 3.0f); EXPECT_FLOAT_EQ(m1.at(1, 1), 3.0f);
} }
TEST_F(UnitTestMatrix, Sum) TEST_F(UnitTestMatrix, Sum)
{ {
const float sum = m2.Sum(); const float sum = m2.sum();
EXPECT_FLOAT_EQ(sum, 10.0f); EXPECT_FLOAT_EQ(sum, 10.0f);
} }
TEST_F(UnitTestMatrix, Clear) TEST_F(UnitTestMatrix, Clear)
{ {
m2.Clear(); m2.clear();
EXPECT_FLOAT_EQ(m2.At(0, 0), 0.0f); EXPECT_FLOAT_EQ(m2.at(0, 0), 0.0f);
EXPECT_FLOAT_EQ(m2.At(1, 1), 0.0f); EXPECT_FLOAT_EQ(m2.at(1, 1), 0.0f);
} }
TEST_F(UnitTestMatrix, ToString) TEST_F(UnitTestMatrix, ToString)
{ {
const std::string str = m2.ToString(); const std::string str = m2.to_string();
EXPECT_FALSE(str.empty()); EXPECT_FALSE(str.empty());
} }
@@ -163,18 +163,18 @@ TEST_F(UnitTestMatrix, AssignmentOperator_Copy)
{ {
Matrix m3(2, 2); Matrix m3(2, 2);
m3 = m2; m3 = m2;
EXPECT_EQ(m3.RowCount(), m2.RowCount()); EXPECT_EQ(m3.row_count(), m2.row_count());
EXPECT_EQ(m3.ColumnsCount(), m2.ColumnsCount()); EXPECT_EQ(m3.columns_count(), m2.columns_count());
EXPECT_FLOAT_EQ(m3.At(0, 0), m2.At(0, 0)); EXPECT_FLOAT_EQ(m3.at(0, 0), m2.at(0, 0));
} }
TEST_F(UnitTestMatrix, AssignmentOperator_Move) TEST_F(UnitTestMatrix, AssignmentOperator_Move)
{ {
Matrix m3(2, 2); Matrix m3(2, 2);
m3 = std::move(m2); m3 = std::move(m2);
EXPECT_EQ(m3.RowCount(), 2); EXPECT_EQ(m3.row_count(), 2);
EXPECT_EQ(m3.ColumnsCount(), 2); EXPECT_EQ(m3.columns_count(), 2);
EXPECT_FLOAT_EQ(m3.At(0, 0), 1.0f); EXPECT_FLOAT_EQ(m3.at(0, 0), 1.0f);
EXPECT_EQ(m2.RowCount(), 0); // m2 should be empty after the move EXPECT_EQ(m2.row_count(), 0); // m2 should be empty after the move
EXPECT_EQ(m2.ColumnsCount(), 0); EXPECT_EQ(m2.columns_count(), 0);
} }

View File

@@ -4,13 +4,13 @@
TEST(UnitTestPrediction, PredictionTest) TEST(UnitTestPrediction, PredictionTest)
{ {
constexpr omath::projectile_prediction::Target target{ constexpr omath::projectile_prediction::Target target{
.m_origin = {100, 0, 90}, .m_velocity = {0, 0, 0}, .m_isAirborne = false}; .m_origin = {100, 0, 90}, .m_velocity = {0, 0, 0}, .m_is_airborne = false};
constexpr omath::projectile_prediction::Projectile proj = { constexpr omath::projectile_prediction::Projectile proj = {
.m_origin = {3, 2, 1}, .m_launchSpeed = 5000, .m_gravityScale = 0.4}; .m_origin = {3, 2, 1}, .m_launch_speed = 5000, .m_gravity_scale = 0.4};
const auto viewPoint = const auto viewPoint =
omath::projectile_prediction::ProjPredEngineLegacy(400, 1.f / 1000.f, 50, 5.f).MaybeCalculateAimPoint(proj, target); omath::projectile_prediction::ProjPredEngineLegacy(400, 1.f / 1000.f, 50, 5.f).maybe_calculate_aim_point(proj, target);
const auto [pitch, yaw, _] = proj.m_origin.ViewAngleTo(viewPoint.value()).AsTuple(); const auto [pitch, yaw, _] = proj.m_origin.view_angle_to(viewPoint.value()).as_tuple();
EXPECT_NEAR(42.547142, pitch, 0.01f); EXPECT_NEAR(42.547142, pitch, 0.01f);
EXPECT_NEAR(-1.181189, yaw, 0.01f); EXPECT_NEAR(-1.181189, yaw, 0.01f);

View File

@@ -9,9 +9,9 @@
TEST(UnitTestProjection, Projection) TEST(UnitTestProjection, Projection)
{ {
const auto x = omath::Angle<float, 0.f, 180.f, omath::AngleFlags::Clamped>::FromDegrees(90.f); const auto x = omath::Angle<float, 0.f, 180.f, omath::AngleFlags::Clamped>::from_degrees(90.f);
auto cam = omath::source_engine::Camera({0, 0, 0}, omath::source_engine::ViewAngles{}, {1920.f, 1080.f}, x, 0.01f, 1000.f); auto cam = omath::source_engine::Camera({0, 0, 0}, omath::source_engine::ViewAngles{}, {1920.f, 1080.f}, x, 0.01f, 1000.f);
const auto projected = cam.WorldToScreen({1000, 0, 50}); const auto projected = cam.world_to_screen({1000, 0, 50});
std::print("{} {} {}", projected->x, projected->y, projected->z); std::print("{} {} {}", projected->x, projected->y, projected->z);
} }

View File

@@ -68,14 +68,14 @@ TEST_F(UnitTestTriangle, Constructor)
TEST_F(UnitTestTriangle, CalculateNormal) TEST_F(UnitTestTriangle, CalculateNormal)
{ {
// For t1, the normal should point in the +Z direction (0, 0, 1) or (0, 0, -1) // For t1, the normal should point in the +Z direction (0, 0, 1) or (0, 0, -1)
const Vector3 normal_t1 = t1.CalculateNormal(); const Vector3 normal_t1 = t1.calculate_normal();
// Check if it's normalized and pointed along Z (sign can differ, so use absolute check) // Check if it's normalized and pointed along Z (sign can differ, so use absolute check)
EXPECT_NEAR(std::fabs(normal_t1.z), 1.0f, 1e-5f); EXPECT_NEAR(std::fabs(normal_t1.z), 1.0f, 1e-5f);
EXPECT_NEAR(normal_t1.Length(), 1.0f, 1e-5f); EXPECT_NEAR(normal_t1.length(), 1.0f, 1e-5f);
// For t3, we expect the normal to be along +Z as well // For t3, we expect the normal to be along +Z as well
const Vector3 normal_t3 = t3.CalculateNormal(); const Vector3 normal_t3 = t3.calculate_normal();
EXPECT_NEAR(std::fabs(normal_t3.z), 1.0f, 1e-5f); EXPECT_NEAR(std::fabs(normal_t3.z), 1.0f, 1e-5f);
} }
@@ -83,29 +83,29 @@ TEST_F(UnitTestTriangle, CalculateNormal)
TEST_F(UnitTestTriangle, SideLengths) TEST_F(UnitTestTriangle, SideLengths)
{ {
// For t1 side lengths // For t1 side lengths
EXPECT_FLOAT_EQ(t1.SideALength(), std::sqrt(1.0f)); // distance between (0,0,0) and (1,0,0) EXPECT_FLOAT_EQ(t1.side_a_length(), std::sqrt(1.0f)); // distance between (0,0,0) and (1,0,0)
EXPECT_FLOAT_EQ(t1.SideBLength(), std::sqrt(1.0f + 1.0f)); // distance between (4,5,6) & (7,8,9)... but we are testing t1, so let's be accurate: EXPECT_FLOAT_EQ(t1.side_b_length(), std::sqrt(1.0f + 1.0f)); // distance between (4,5,6) & (7,8,9)... but we are testing t1, so let's be accurate:
// Actually, for t1: vertex2=(1,0,0), vertex3=(0,1,0) // Actually, for t1: vertex2=(1,0,0), vertex3=(0,1,0)
// Dist between (0,1,0) and (1,0,0) = sqrt((1-0)^2 + (0-1)^2) = sqrt(1 + 1) = sqrt(2) // Dist between (0,1,0) and (1,0,0) = sqrt((1-0)^2 + (0-1)^2) = sqrt(1 + 1) = sqrt(2)
EXPECT_FLOAT_EQ(t1.SideBLength(), std::sqrt(2.0f)); EXPECT_FLOAT_EQ(t1.side_b_length(), std::sqrt(2.0f));
// For t3, side a = distance between vertex1=(0,0,0) and vertex2=(2,0,0), which is 2 // For t3, side a = distance between vertex1=(0,0,0) and vertex2=(2,0,0), which is 2
// side b = distance between vertex3=(0,2,0) and vertex2=(2,0,0), which is sqrt(2^2 + (-2)^2)= sqrt(8)= 2.828... // side b = distance between vertex3=(0,2,0) and vertex2=(2,0,0), which is sqrt(2^2 + (-2)^2)= sqrt(8)= 2.828...
// We'll just check side a first: // We'll just check side a first:
EXPECT_FLOAT_EQ(t3.SideALength(), 2.0f); EXPECT_FLOAT_EQ(t3.side_a_length(), 2.0f);
// Then side b: // Then side b:
EXPECT_FLOAT_EQ(t3.SideBLength(), std::sqrt(8.0f)); EXPECT_FLOAT_EQ(t3.side_b_length(), std::sqrt(8.0f));
} }
// Test side vectors // Test side vectors
TEST_F(UnitTestTriangle, SideVectors) TEST_F(UnitTestTriangle, SideVectors)
{ {
const Vector3 sideA_t1 = t1.SideAVector(); // m_vertex1 - m_vertex2 const Vector3 sideA_t1 = t1.side_a_vector(); // m_vertex1 - m_vertex2
EXPECT_FLOAT_EQ(sideA_t1.x, 0.0f - 1.0f); EXPECT_FLOAT_EQ(sideA_t1.x, 0.0f - 1.0f);
EXPECT_FLOAT_EQ(sideA_t1.y, 0.0f - 0.0f); EXPECT_FLOAT_EQ(sideA_t1.y, 0.0f - 0.0f);
EXPECT_FLOAT_EQ(sideA_t1.z, 0.0f - 0.0f); EXPECT_FLOAT_EQ(sideA_t1.z, 0.0f - 0.0f);
const Vector3 sideB_t1 = t1.SideBVector(); // m_vertex3 - m_vertex2 const Vector3 sideB_t1 = t1.side_b_vector(); // m_vertex3 - m_vertex2
EXPECT_FLOAT_EQ(sideB_t1.x, 0.0f - 1.0f); EXPECT_FLOAT_EQ(sideB_t1.x, 0.0f - 1.0f);
EXPECT_FLOAT_EQ(sideB_t1.y, 1.0f - 0.0f); EXPECT_FLOAT_EQ(sideB_t1.y, 1.0f - 0.0f);
EXPECT_FLOAT_EQ(sideB_t1.z, 0.0f - 0.0f); EXPECT_FLOAT_EQ(sideB_t1.z, 0.0f - 0.0f);
@@ -113,19 +113,19 @@ TEST_F(UnitTestTriangle, SideVectors)
TEST_F(UnitTestTriangle, IsRectangular) TEST_F(UnitTestTriangle, IsRectangular)
{ {
EXPECT_TRUE(Triangle<Vector3<float>>({2,0,0}, {}, {0,2,0}).IsRectangular()); EXPECT_TRUE(Triangle<Vector3<float>>({2,0,0}, {}, {0,2,0}).is_rectangular());
} }
// Test midpoint // Test midpoint
TEST_F(UnitTestTriangle, MidPoint) TEST_F(UnitTestTriangle, MidPoint)
{ {
// For t1, midpoint of (0,0,0), (1,0,0), (0,1,0) // For t1, midpoint of (0,0,0), (1,0,0), (0,1,0)
const Vector3 mid1 = t1.MidPoint(); const Vector3 mid1 = t1.mid_point();
EXPECT_FLOAT_EQ(mid1.x, (0.0f + 1.0f + 0.0f) / 3.0f); EXPECT_FLOAT_EQ(mid1.x, (0.0f + 1.0f + 0.0f) / 3.0f);
EXPECT_FLOAT_EQ(mid1.y, (0.0f + 0.0f + 1.0f) / 3.0f); EXPECT_FLOAT_EQ(mid1.y, (0.0f + 0.0f + 1.0f) / 3.0f);
EXPECT_FLOAT_EQ(mid1.z, 0.0f); EXPECT_FLOAT_EQ(mid1.z, 0.0f);
// For t2, midpoint of (1,2,3), (4,5,6), (7,8,9) // For t2, midpoint of (1,2,3), (4,5,6), (7,8,9)
const Vector3 mid2 = t2.MidPoint(); const Vector3 mid2 = t2.mid_point();
EXPECT_FLOAT_EQ(mid2.x, (1.0f + 4.0f + 7.0f) / 3.0f); EXPECT_FLOAT_EQ(mid2.x, (1.0f + 4.0f + 7.0f) / 3.0f);
EXPECT_FLOAT_EQ(mid2.y, (2.0f + 5.0f + 8.0f) / 3.0f); EXPECT_FLOAT_EQ(mid2.y, (2.0f + 5.0f + 8.0f) / 3.0f);
EXPECT_FLOAT_EQ(mid2.z, (3.0f + 6.0f + 9.0f) / 3.0f); EXPECT_FLOAT_EQ(mid2.z, (3.0f + 6.0f + 9.0f) / 3.0f);

View File

@@ -150,76 +150,76 @@ TEST_F(UnitTestVector2, SubtractionAssignmentOperator_Float)
// Test other member functions // Test other member functions
TEST_F(UnitTestVector2, DistTo) TEST_F(UnitTestVector2, DistTo)
{ {
const float dist = v1.DistTo(v2); const float dist = v1.distance_to(v2);
EXPECT_FLOAT_EQ(dist, std::sqrt(18.0f)); EXPECT_FLOAT_EQ(dist, std::sqrt(18.0f));
} }
TEST_F(UnitTestVector2, DistTo_SamePoint) TEST_F(UnitTestVector2, DistTo_SamePoint)
{ {
const float dist = v1.DistTo(v1); const float dist = v1.distance_to(v1);
EXPECT_FLOAT_EQ(dist, 0.0f); EXPECT_FLOAT_EQ(dist, 0.0f);
} }
TEST_F(UnitTestVector2, DistToSqr) TEST_F(UnitTestVector2, DistToSqr)
{ {
constexpr float distSqr = Vector2(1.0f, 2.0f).DistToSqr(Vector2(4.0f, 5.0f)); constexpr float distSqr = Vector2(1.0f, 2.0f).distance_to_sqr(Vector2(4.0f, 5.0f));
EXPECT_FLOAT_EQ(distSqr, 18.0f); EXPECT_FLOAT_EQ(distSqr, 18.0f);
} }
TEST_F(UnitTestVector2, DistToSqr_SamePoint) TEST_F(UnitTestVector2, DistToSqr_SamePoint)
{ {
constexpr float distSqr = Vector2(1.0f, 2.0f).DistToSqr(Vector2(1.0f, 2.0f)); constexpr float distSqr = Vector2(1.0f, 2.0f).distance_to_sqr(Vector2(1.0f, 2.0f));
EXPECT_FLOAT_EQ(distSqr, 0.0f); EXPECT_FLOAT_EQ(distSqr, 0.0f);
} }
TEST_F(UnitTestVector2, DotProduct) TEST_F(UnitTestVector2, DotProduct)
{ {
constexpr float dot = Vector2(1.0f, 2.0f).Dot(Vector2(4.0f, 5.0f)); constexpr float dot = Vector2(1.0f, 2.0f).dot(Vector2(4.0f, 5.0f));
EXPECT_FLOAT_EQ(dot, 14.0f); EXPECT_FLOAT_EQ(dot, 14.0f);
} }
TEST_F(UnitTestVector2, DotProduct_PerpendicularVectors) TEST_F(UnitTestVector2, DotProduct_PerpendicularVectors)
{ {
constexpr float dot = Vector2(1.0f, 0.0f).Dot(Vector2(0.0f, 1.0f)); constexpr float dot = Vector2(1.0f, 0.0f).dot(Vector2(0.0f, 1.0f));
EXPECT_FLOAT_EQ(dot, 0.0f); EXPECT_FLOAT_EQ(dot, 0.0f);
} }
TEST_F(UnitTestVector2, DotProduct_ParallelVectors) TEST_F(UnitTestVector2, DotProduct_ParallelVectors)
{ {
constexpr float dot = Vector2(1.0f, 1.0f).Dot(Vector2(2.0f, 2.0f)); constexpr float dot = Vector2(1.0f, 1.0f).dot(Vector2(2.0f, 2.0f));
EXPECT_FLOAT_EQ(dot, 4.0f); EXPECT_FLOAT_EQ(dot, 4.0f);
} }
TEST_F(UnitTestVector2, Length) TEST_F(UnitTestVector2, Length)
{ {
const float length = v1.Length(); const float length = v1.length();
EXPECT_FLOAT_EQ(length, std::sqrt(5.0f)); EXPECT_FLOAT_EQ(length, std::sqrt(5.0f));
} }
TEST_F(UnitTestVector2, Length_ZeroVector) TEST_F(UnitTestVector2, Length_ZeroVector)
{ {
constexpr Vector2 v_zero(0.0f, 0.0f); constexpr Vector2 v_zero(0.0f, 0.0f);
const float length = v_zero.Length(); const float length = v_zero.length();
EXPECT_FLOAT_EQ(length, 0.0f); EXPECT_FLOAT_EQ(length, 0.0f);
} }
TEST_F(UnitTestVector2, Length_LargeValues) TEST_F(UnitTestVector2, Length_LargeValues)
{ {
constexpr Vector2 v_large(FLT_MAX, FLT_MAX); constexpr Vector2 v_large(FLT_MAX, FLT_MAX);
const float length = v_large.Length(); const float length = v_large.length();
EXPECT_TRUE(std::isinf(length)); EXPECT_TRUE(std::isinf(length));
} }
TEST_F(UnitTestVector2, LengthSqr) TEST_F(UnitTestVector2, LengthSqr)
{ {
constexpr float lengthSqr = Vector2(1.0f, 2.0f).LengthSqr(); constexpr float lengthSqr = Vector2(1.0f, 2.0f).length_sqr();
EXPECT_FLOAT_EQ(lengthSqr, 5.0f); EXPECT_FLOAT_EQ(lengthSqr, 5.0f);
} }
TEST_F(UnitTestVector2, Abs) TEST_F(UnitTestVector2, Abs)
{ {
Vector2 v3(-1.0f, -2.0f); Vector2 v3(-1.0f, -2.0f);
v3.Abs(); v3.abs();
EXPECT_FLOAT_EQ(v3.x, 1.0f); EXPECT_FLOAT_EQ(v3.x, 1.0f);
EXPECT_FLOAT_EQ(v3.y, 2.0f); EXPECT_FLOAT_EQ(v3.y, 2.0f);
} }
@@ -227,7 +227,7 @@ TEST_F(UnitTestVector2, Abs)
TEST_F(UnitTestVector2, Abs_PositiveValues) TEST_F(UnitTestVector2, Abs_PositiveValues)
{ {
Vector2 v3(1.0f, 2.0f); Vector2 v3(1.0f, 2.0f);
v3.Abs(); v3.abs();
EXPECT_FLOAT_EQ(v3.x, 1.0f); EXPECT_FLOAT_EQ(v3.x, 1.0f);
EXPECT_FLOAT_EQ(v3.y, 2.0f); EXPECT_FLOAT_EQ(v3.y, 2.0f);
} }
@@ -235,26 +235,26 @@ TEST_F(UnitTestVector2, Abs_PositiveValues)
TEST_F(UnitTestVector2, Abs_ZeroValues) TEST_F(UnitTestVector2, Abs_ZeroValues)
{ {
Vector2 v3(0.0f, 0.0f); Vector2 v3(0.0f, 0.0f);
v3.Abs(); v3.abs();
EXPECT_FLOAT_EQ(v3.x, 0.0f); EXPECT_FLOAT_EQ(v3.x, 0.0f);
EXPECT_FLOAT_EQ(v3.y, 0.0f); EXPECT_FLOAT_EQ(v3.y, 0.0f);
} }
TEST_F(UnitTestVector2, Sum) TEST_F(UnitTestVector2, Sum)
{ {
constexpr float sum = Vector2(1.0f, 2.0f).Sum(); constexpr float sum = Vector2(1.0f, 2.0f).sum();
EXPECT_FLOAT_EQ(sum, 3.0f); EXPECT_FLOAT_EQ(sum, 3.0f);
} }
TEST_F(UnitTestVector2, Sum_NegativeValues) TEST_F(UnitTestVector2, Sum_NegativeValues)
{ {
constexpr float sum = Vector2(-1.0f, -2.0f).Sum(); constexpr float sum = Vector2(-1.0f, -2.0f).sum();
EXPECT_FLOAT_EQ(sum, -3.0f); EXPECT_FLOAT_EQ(sum, -3.0f);
} }
TEST_F(UnitTestVector2, Normalized) TEST_F(UnitTestVector2, Normalized)
{ {
const Vector2 v3 = v1.Normalized(); const Vector2 v3 = v1.normalized();
EXPECT_NEAR(v3.x, 0.44721f, 0.0001f); EXPECT_NEAR(v3.x, 0.44721f, 0.0001f);
EXPECT_NEAR(v3.y, 0.89443f, 0.0001f); EXPECT_NEAR(v3.y, 0.89443f, 0.0001f);
} }
@@ -262,7 +262,7 @@ TEST_F(UnitTestVector2, Normalized)
TEST_F(UnitTestVector2, Normalized_ZeroVector) TEST_F(UnitTestVector2, Normalized_ZeroVector)
{ {
constexpr Vector2 v_zero(0.0f, 0.0f); constexpr Vector2 v_zero(0.0f, 0.0f);
const Vector2 v_norm = v_zero.Normalized(); const Vector2 v_norm = v_zero.normalized();
EXPECT_FLOAT_EQ(v_norm.x, 0.0f); EXPECT_FLOAT_EQ(v_norm.x, 0.0f);
EXPECT_FLOAT_EQ(v_norm.y, 0.0f); EXPECT_FLOAT_EQ(v_norm.y, 0.0f);
} }
@@ -270,7 +270,7 @@ TEST_F(UnitTestVector2, Normalized_ZeroVector)
// Test AsTuple method // Test AsTuple method
TEST_F(UnitTestVector2, AsTuple) TEST_F(UnitTestVector2, AsTuple)
{ {
const auto tuple = v1.AsTuple(); const auto tuple = v1.as_tuple();
EXPECT_FLOAT_EQ(std::get<0>(tuple), v1.x); EXPECT_FLOAT_EQ(std::get<0>(tuple), v1.x);
EXPECT_FLOAT_EQ(std::get<1>(tuple), v1.y); EXPECT_FLOAT_EQ(std::get<1>(tuple), v1.y);
} }
@@ -347,7 +347,7 @@ TEST_F(UnitTestVector2, NegationOperator_ZeroVector)
} }
// Static assertions (compile-time checks) // Static assertions (compile-time checks)
static_assert(Vector2(1.0f, 2.0f).LengthSqr() == 5.0f, "LengthSqr should be 5"); static_assert(Vector2(1.0f, 2.0f).length_sqr() == 5.0f, "LengthSqr should be 5");
static_assert(Vector2(1.0f, 2.0f).Dot(Vector2(4.0f, 5.0f)) == 14.0f, "Dot product should be 14"); static_assert(Vector2(1.0f, 2.0f).dot(Vector2(4.0f, 5.0f)) == 14.0f, "Dot product should be 14");
static_assert(Vector2(4.0f, 5.0f).DistToSqr(Vector2(1.0f, 2.0f)) == 18.0f, "DistToSqr should be 18"); static_assert(Vector2(4.0f, 5.0f).distance_to_sqr(Vector2(1.0f, 2.0f)) == 18.0f, "DistToSqr should be 18");
static_assert(Vector2(-1.0f, -2.0f).Abs() == Vector2(1.0f, 2.0f), "Abs should convert negative values to positive"); static_assert(Vector2(-1.0f, -2.0f).abs() == Vector2(1.0f, 2.0f), "Abs should convert negative values to positive");

View File

@@ -164,26 +164,26 @@ TEST_F(UnitTestVector3, NegationOperator)
// Test other member functions // Test other member functions
TEST_F(UnitTestVector3, DistToSqr) TEST_F(UnitTestVector3, DistToSqr)
{ {
constexpr auto distSqr = Vector3(1.0f, 2.0f, 3.0f).DistToSqr(Vector3(4.0f, 5.0f, 6.0f)); constexpr auto distSqr = Vector3(1.0f, 2.0f, 3.0f).distance_to_sqr(Vector3(4.0f, 5.0f, 6.0f));
EXPECT_FLOAT_EQ(distSqr, 27.0f); EXPECT_FLOAT_EQ(distSqr, 27.0f);
} }
TEST_F(UnitTestVector3, DotProduct) TEST_F(UnitTestVector3, DotProduct)
{ {
constexpr auto dot = Vector3(1.0f, 2.0f, 3.0f).Dot(Vector3(4.0f, 5.0f, 6.0f)); constexpr auto dot = Vector3(1.0f, 2.0f, 3.0f).dot(Vector3(4.0f, 5.0f, 6.0f));
EXPECT_FLOAT_EQ(dot, 32.0f); EXPECT_FLOAT_EQ(dot, 32.0f);
} }
TEST_F(UnitTestVector3, LengthSqr) TEST_F(UnitTestVector3, LengthSqr)
{ {
constexpr auto lengthSqr = Vector3(1.0f, 2.0f, 3.0f).LengthSqr(); constexpr auto lengthSqr = Vector3(1.0f, 2.0f, 3.0f).length_sqr();
EXPECT_FLOAT_EQ(lengthSqr, 14.0f); EXPECT_FLOAT_EQ(lengthSqr, 14.0f);
} }
TEST_F(UnitTestVector3, Abs) TEST_F(UnitTestVector3, Abs)
{ {
auto v3 = Vector3(-1.0f, -2.0f, -3.0f); auto v3 = Vector3(-1.0f, -2.0f, -3.0f);
v3.Abs(); v3.abs();
EXPECT_FLOAT_EQ(v3.x, 1.0f); EXPECT_FLOAT_EQ(v3.x, 1.0f);
EXPECT_FLOAT_EQ(v3.y, 2.0f); EXPECT_FLOAT_EQ(v3.y, 2.0f);
EXPECT_FLOAT_EQ(v3.z, 3.0f); EXPECT_FLOAT_EQ(v3.z, 3.0f);
@@ -191,19 +191,19 @@ TEST_F(UnitTestVector3, Abs)
TEST_F(UnitTestVector3, Sum) TEST_F(UnitTestVector3, Sum)
{ {
constexpr auto sum = Vector3(1.0f, 2.0f, 3.0f).Sum(); constexpr auto sum = Vector3(1.0f, 2.0f, 3.0f).sum();
EXPECT_FLOAT_EQ(sum, 6.0f); EXPECT_FLOAT_EQ(sum, 6.0f);
} }
TEST_F(UnitTestVector3, Sum2D) TEST_F(UnitTestVector3, Sum2D)
{ {
constexpr auto sum2D = Vector3(1.0f, 2.0f, 3.0f).Sum2D(); constexpr auto sum2D = Vector3(1.0f, 2.0f, 3.0f).sum_2d();
EXPECT_FLOAT_EQ(sum2D, 3.0f); EXPECT_FLOAT_EQ(sum2D, 3.0f);
} }
TEST_F(UnitTestVector3, CrossProduct) TEST_F(UnitTestVector3, CrossProduct)
{ {
constexpr Vector3 v3 = Vector3(1.0f, 2.0f, 3.0f).Cross(Vector3(4.0f, 5.0f, 6.0f)); constexpr Vector3 v3 = Vector3(1.0f, 2.0f, 3.0f).cross(Vector3(4.0f, 5.0f, 6.0f));
EXPECT_FLOAT_EQ(v3.x, -3.0f); EXPECT_FLOAT_EQ(v3.x, -3.0f);
EXPECT_FLOAT_EQ(v3.y, 6.0f); EXPECT_FLOAT_EQ(v3.y, 6.0f);
EXPECT_FLOAT_EQ(v3.z, -3.0f); EXPECT_FLOAT_EQ(v3.z, -3.0f);
@@ -298,41 +298,41 @@ TEST_F(UnitTestVector3, Division_WithNaN)
// Test Length, Length2D, and Normalized // Test Length, Length2D, and Normalized
TEST_F(UnitTestVector3, Length) TEST_F(UnitTestVector3, Length)
{ {
const float length = v1.Length(); const float length = v1.length();
EXPECT_FLOAT_EQ(length, std::sqrt(14.0f)); EXPECT_FLOAT_EQ(length, std::sqrt(14.0f));
} }
TEST_F(UnitTestVector3, Length_ZeroVector) TEST_F(UnitTestVector3, Length_ZeroVector)
{ {
constexpr Vector3 v_zero(0.0f, 0.0f, 0.0f); constexpr Vector3 v_zero(0.0f, 0.0f, 0.0f);
const float length = v_zero.Length(); const float length = v_zero.length();
EXPECT_FLOAT_EQ(length, 0.0f); EXPECT_FLOAT_EQ(length, 0.0f);
} }
TEST_F(UnitTestVector3, Length_LargeValues) TEST_F(UnitTestVector3, Length_LargeValues)
{ {
constexpr Vector3 v_large(FLT_MAX, FLT_MAX, FLT_MAX); constexpr Vector3 v_large(FLT_MAX, FLT_MAX, FLT_MAX);
const float length = v_large.Length(); const float length = v_large.length();
EXPECT_TRUE(std::isinf(length)); EXPECT_TRUE(std::isinf(length));
} }
TEST_F(UnitTestVector3, Length2D) TEST_F(UnitTestVector3, Length2D)
{ {
const float length2D = v1.Length2D(); const float length2D = v1.length_2d();
EXPECT_FLOAT_EQ(length2D, std::sqrt(5.0f)); EXPECT_FLOAT_EQ(length2D, std::sqrt(5.0f));
} }
TEST_F(UnitTestVector3, Normalized) TEST_F(UnitTestVector3, Normalized)
{ {
const Vector3 v_norm = v1.Normalized(); const Vector3 v_norm = v1.normalized();
const float length = v_norm.Length(); const float length = v_norm.length();
EXPECT_NEAR(length, 1.0f, 0.0001f); EXPECT_NEAR(length, 1.0f, 0.0001f);
} }
TEST_F(UnitTestVector3, Normalized_ZeroVector) TEST_F(UnitTestVector3, Normalized_ZeroVector)
{ {
constexpr Vector3 v_zero(0.0f, 0.0f, 0.0f); constexpr Vector3 v_zero(0.0f, 0.0f, 0.0f);
const Vector3 v_norm = v_zero.Normalized(); const Vector3 v_norm = v_zero.normalized();
EXPECT_FLOAT_EQ(v_norm.x, 0.0f); EXPECT_FLOAT_EQ(v_norm.x, 0.0f);
EXPECT_FLOAT_EQ(v_norm.y, 0.0f); EXPECT_FLOAT_EQ(v_norm.y, 0.0f);
EXPECT_FLOAT_EQ(v_norm.z, 0.0f); EXPECT_FLOAT_EQ(v_norm.z, 0.0f);
@@ -343,7 +343,7 @@ TEST_F(UnitTestVector3, CrossProduct_ParallelVectors)
{ {
constexpr Vector3 v_a(1.0f, 2.0f, 3.0f); constexpr Vector3 v_a(1.0f, 2.0f, 3.0f);
constexpr Vector3 v_b = v_a * 2.0f; // Parallel to v_a constexpr Vector3 v_b = v_a * 2.0f; // Parallel to v_a
constexpr Vector3 cross = v_a.Cross(v_b); constexpr Vector3 cross = v_a.cross(v_b);
EXPECT_FLOAT_EQ(cross.x, 0.0f); EXPECT_FLOAT_EQ(cross.x, 0.0f);
EXPECT_FLOAT_EQ(cross.y, 0.0f); EXPECT_FLOAT_EQ(cross.y, 0.0f);
EXPECT_FLOAT_EQ(cross.z, 0.0f); EXPECT_FLOAT_EQ(cross.z, 0.0f);
@@ -353,7 +353,7 @@ TEST_F(UnitTestVector3, CrossProduct_OrthogonalVectors)
{ {
constexpr Vector3 v_a(1.0f, 0.0f, 0.0f); constexpr Vector3 v_a(1.0f, 0.0f, 0.0f);
constexpr Vector3 v_b(0.0f, 1.0f, 0.0f); constexpr Vector3 v_b(0.0f, 1.0f, 0.0f);
constexpr Vector3 cross = v_a.Cross(v_b); constexpr Vector3 cross = v_a.cross(v_b);
EXPECT_FLOAT_EQ(cross.x, 0.0f); EXPECT_FLOAT_EQ(cross.x, 0.0f);
EXPECT_FLOAT_EQ(cross.y, 0.0f); EXPECT_FLOAT_EQ(cross.y, 0.0f);
EXPECT_FLOAT_EQ(cross.z, 1.0f); EXPECT_FLOAT_EQ(cross.z, 1.0f);
@@ -381,7 +381,7 @@ TEST_F(UnitTestVector3, Subtraction_NegativeValues)
// Test AsTuple method // Test AsTuple method
TEST_F(UnitTestVector3, AsTuple) TEST_F(UnitTestVector3, AsTuple)
{ {
const auto tuple = v1.AsTuple(); const auto tuple = v1.as_tuple();
EXPECT_FLOAT_EQ(std::get<0>(tuple), v1.x); EXPECT_FLOAT_EQ(std::get<0>(tuple), v1.x);
EXPECT_FLOAT_EQ(std::get<1>(tuple), v1.y); EXPECT_FLOAT_EQ(std::get<1>(tuple), v1.y);
EXPECT_FLOAT_EQ(std::get<2>(tuple), v1.z); EXPECT_FLOAT_EQ(std::get<2>(tuple), v1.z);
@@ -390,20 +390,20 @@ TEST_F(UnitTestVector3, AsTuple)
// Test AsTuple method // Test AsTuple method
TEST_F(UnitTestVector3, AngleBeatween) TEST_F(UnitTestVector3, AngleBeatween)
{ {
EXPECT_EQ(Vector3(0.0f, 0.0f, 1.0f).AngleBetween({1, 0 ,0}).value().AsDegrees(), 90.0f); EXPECT_EQ(Vector3(0.0f, 0.0f, 1.0f).angle_between({1, 0 ,0}).value().as_degrees(), 90.0f);
EXPECT_EQ(Vector3(0.0f, 0.0f, 1.0f).AngleBetween({0.0f, 0.0f, 1.0f}).value().AsDegrees(), 0.0f); EXPECT_EQ(Vector3(0.0f, 0.0f, 1.0f).angle_between({0.0f, 0.0f, 1.0f}).value().as_degrees(), 0.0f);
EXPECT_FALSE(Vector3(0.0f, 0.0f, 0.0f).AngleBetween({0.0f, 0.0f, 1.0f}).has_value()); EXPECT_FALSE(Vector3(0.0f, 0.0f, 0.0f).angle_between({0.0f, 0.0f, 1.0f}).has_value());
} }
TEST_F(UnitTestVector3, IsPerpendicular) TEST_F(UnitTestVector3, IsPerpendicular)
{ {
EXPECT_EQ(Vector3(0.0f, 0.0f, 1.0f).IsPerpendicular({1, 0 ,0}), true); EXPECT_EQ(Vector3(0.0f, 0.0f, 1.0f).is_perpendicular({1, 0 ,0}), true);
EXPECT_EQ(Vector3(0.0f, 0.0f, 1.0f).IsPerpendicular({0.0f, 0.0f, 1.0f}), false); EXPECT_EQ(Vector3(0.0f, 0.0f, 1.0f).is_perpendicular({0.0f, 0.0f, 1.0f}), false);
EXPECT_FALSE(Vector3(0.0f, 0.0f, 0.0f).IsPerpendicular({0.0f, 0.0f, 1.0f})); EXPECT_FALSE(Vector3(0.0f, 0.0f, 0.0f).is_perpendicular({0.0f, 0.0f, 1.0f}));
} }
// Static assertions (compile-time checks) // Static assertions (compile-time checks)
static_assert(Vector3(1.0f, 2.0f, 3.0f).LengthSqr() == 14.0f, "LengthSqr should be 14"); static_assert(Vector3(1.0f, 2.0f, 3.0f).length_sqr() == 14.0f, "LengthSqr should be 14");
static_assert(Vector3(1.0f, 2.0f, 3.0f).Dot(Vector3(4.0f, 5.0f, 6.0f)) == 32.0f, "Dot product should be 32"); static_assert(Vector3(1.0f, 2.0f, 3.0f).dot(Vector3(4.0f, 5.0f, 6.0f)) == 32.0f, "Dot product should be 32");
static_assert(Vector3(4.0f, 5.0f, 6.0f).DistToSqr(Vector3(1.0f, 2.0f, 3.0f)) == 27.0f, "DistToSqr should be 27"); static_assert(Vector3(4.0f, 5.0f, 6.0f).distance_to_sqr(Vector3(1.0f, 2.0f, 3.0f)) == 27.0f, "DistToSqr should be 27");
static_assert(Vector3(-1.0f, -2.0f, -3.0f).Abs() == Vector3(1.0f, 2.0f, 3.0f), "Abs should convert negative values to positive"); static_assert(Vector3(-1.0f, -2.0f, -3.0f).abs() == Vector3(1.0f, 2.0f, 3.0f), "Abs should convert negative values to positive");

View File

@@ -180,20 +180,20 @@ TEST_F(UnitTestVector4, NegationOperator)
// Test other member functions // Test other member functions
TEST_F(UnitTestVector4, LengthSqr) TEST_F(UnitTestVector4, LengthSqr)
{ {
constexpr float lengthSqr = Vector4(1.0f, 2.0f, 3.0f, 4.0f).LengthSqr(); constexpr float lengthSqr = Vector4(1.0f, 2.0f, 3.0f, 4.0f).length_sqr();
EXPECT_FLOAT_EQ(lengthSqr, 30.0f); EXPECT_FLOAT_EQ(lengthSqr, 30.0f);
} }
TEST_F(UnitTestVector4, DotProduct) TEST_F(UnitTestVector4, DotProduct)
{ {
constexpr float dot = Vector4(1.0f, 2.0f, 3.0f, 4.0f).Dot(Vector4(4.0f, 5.0f, 6.0f, 7.0f)); constexpr float dot = Vector4(1.0f, 2.0f, 3.0f, 4.0f).dot(Vector4(4.0f, 5.0f, 6.0f, 7.0f));
EXPECT_FLOAT_EQ(dot, 60.0f); EXPECT_FLOAT_EQ(dot, 60.0f);
} }
TEST_F(UnitTestVector4, Abs) TEST_F(UnitTestVector4, Abs)
{ {
Vector4 v3 = Vector4(-1.0f, -2.0f, -3.0f, -4.0f); Vector4 v3 = Vector4(-1.0f, -2.0f, -3.0f, -4.0f);
v3.Abs(); v3.abs();
EXPECT_FLOAT_EQ(v3.x, 1.0f); EXPECT_FLOAT_EQ(v3.x, 1.0f);
EXPECT_FLOAT_EQ(v3.y, 2.0f); EXPECT_FLOAT_EQ(v3.y, 2.0f);
EXPECT_FLOAT_EQ(v3.z, 3.0f); EXPECT_FLOAT_EQ(v3.z, 3.0f);
@@ -202,14 +202,14 @@ TEST_F(UnitTestVector4, Abs)
TEST_F(UnitTestVector4, Sum) TEST_F(UnitTestVector4, Sum)
{ {
constexpr float sum = Vector4(1.0f, 2.0f, 3.0f, 4.0f).Sum(); constexpr float sum = Vector4(1.0f, 2.0f, 3.0f, 4.0f).sum();
EXPECT_FLOAT_EQ(sum, 10.0f); EXPECT_FLOAT_EQ(sum, 10.0f);
} }
TEST_F(UnitTestVector4, Clamp) TEST_F(UnitTestVector4, Clamp)
{ {
Vector4 v3 = Vector4(1.0f, 2.0f, 3.0f, 4.0f); Vector4 v3 = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
v3.Clamp(1.5f, 2.5f); v3.clamp(1.5f, 2.5f);
EXPECT_FLOAT_EQ(v3.x, 1.5f); EXPECT_FLOAT_EQ(v3.x, 1.5f);
EXPECT_FLOAT_EQ(v3.y, 2.0f); EXPECT_FLOAT_EQ(v3.y, 2.0f);
EXPECT_FLOAT_EQ(v3.z, 2.5f); EXPECT_FLOAT_EQ(v3.z, 2.5f);