diff --git a/Bin/DLL/GamePhysics_x86D.exp b/Bin/DLL/GamePhysics_x86D.exp new file mode 100644 index 00000000..0cea5aa6 Binary files /dev/null and b/Bin/DLL/GamePhysics_x86D.exp differ diff --git a/Bin/DLL/PLACEHOLDER b/Bin/DLL/PLACEHOLDER deleted file mode 100644 index e69de29b..00000000 diff --git a/Code/DanBias.sln b/Code/DanBias.sln index 609eedd3..2e047aee 100644 --- a/Code/DanBias.sln +++ b/Code/DanBias.sln @@ -29,6 +29,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "GamePhysics", "GamePhysics\ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Tester", "Tester\Tester.vcxproj", "{1B3BEA4C-CF75-438A-9693-60FB8444BBF3}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DanBiasGame", "DanBiasGame\DanBiasGame.vcxproj", "{2A1BC987-AF42-4500-802D-89CD32FC1309}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Mixed Platforms = Debug|Mixed Platforms @@ -175,6 +177,7 @@ Global {104FA3E9-94D9-4E1D-A941-28A03BC8A095}.Debug|Win32.ActiveCfg = Debug|Win32 {104FA3E9-94D9-4E1D-A941-28A03BC8A095}.Debug|Win32.Build.0 = Debug|Win32 {104FA3E9-94D9-4E1D-A941-28A03BC8A095}.Debug|x64.ActiveCfg = Debug|x64 + {104FA3E9-94D9-4E1D-A941-28A03BC8A095}.Debug|x64.Build.0 = Debug|x64 {104FA3E9-94D9-4E1D-A941-28A03BC8A095}.Release|Mixed Platforms.ActiveCfg = Release|Win32 {104FA3E9-94D9-4E1D-A941-28A03BC8A095}.Release|Mixed Platforms.Build.0 = Release|Win32 {104FA3E9-94D9-4E1D-A941-28A03BC8A095}.Release|Win32.ActiveCfg = Release|Win32 @@ -190,6 +193,18 @@ Global {1B3BEA4C-CF75-438A-9693-60FB8444BBF3}.Release|Win32.ActiveCfg = Release|Win32 {1B3BEA4C-CF75-438A-9693-60FB8444BBF3}.Release|Win32.Build.0 = Release|Win32 {1B3BEA4C-CF75-438A-9693-60FB8444BBF3}.Release|x64.ActiveCfg = Release|Win32 + {2A1BC987-AF42-4500-802D-89CD32FC1309}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 + {2A1BC987-AF42-4500-802D-89CD32FC1309}.Debug|Mixed Platforms.Build.0 = Debug|Win32 + {2A1BC987-AF42-4500-802D-89CD32FC1309}.Debug|Win32.ActiveCfg = Debug|Win32 + {2A1BC987-AF42-4500-802D-89CD32FC1309}.Debug|Win32.Build.0 = Debug|Win32 + {2A1BC987-AF42-4500-802D-89CD32FC1309}.Debug|x64.ActiveCfg = Debug|x64 + {2A1BC987-AF42-4500-802D-89CD32FC1309}.Debug|x64.Build.0 = Debug|x64 + {2A1BC987-AF42-4500-802D-89CD32FC1309}.Release|Mixed Platforms.ActiveCfg = Release|Win32 + {2A1BC987-AF42-4500-802D-89CD32FC1309}.Release|Mixed Platforms.Build.0 = Release|Win32 + {2A1BC987-AF42-4500-802D-89CD32FC1309}.Release|Win32.ActiveCfg = Release|Win32 + {2A1BC987-AF42-4500-802D-89CD32FC1309}.Release|Win32.Build.0 = Release|Win32 + {2A1BC987-AF42-4500-802D-89CD32FC1309}.Release|x64.ActiveCfg = Release|x64 + {2A1BC987-AF42-4500-802D-89CD32FC1309}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Code/DanBiasGame/DanBiasGame.vcxproj b/Code/DanBiasGame/DanBiasGame.vcxproj new file mode 100644 index 00000000..88181e55 --- /dev/null +++ b/Code/DanBiasGame/DanBiasGame.vcxproj @@ -0,0 +1,193 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {2A1BC987-AF42-4500-802D-89CD32FC1309} + Win32Proj + DanBiasGame + + + + Application + true + v110 + Unicode + + + Application + true + v110 + Unicode + + + Application + false + v110 + true + Unicode + + + Application + false + v110 + true + Unicode + + + + + + + + + + + + + + + + + + + true + $(SolutionDir)..\Bin\Executable\ + $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ + $(ProjectName)_$(PlatformShortName)D + C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath)$(SolutionDir)..\External\Lib\Input;$(SolutionDir)..\Bin\DLL; + + + true + $(SolutionDir)..\Bin\Executable\ + $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ + $(ProjectName)_$(PlatformShortName)D + C:\Program Files %28x86%29\Visual Leak Detector\lib\Win64;$(LibraryPath)$(SolutionDir)..\External\Lib\Input;$(SolutionDir)..\Bin\DLL; + + + false + $(SolutionDir)..\Bin\Executable\ + $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ + $(ProjectName)_$(PlatformShortName) + C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath)$(SolutionDir)..\External\Lib\Input;$(SolutionDir)..\Bin\DLL; + + + false + $(SolutionDir)..\Bin\Executable\ + $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ + $(ProjectName)_$(PlatformShortName) + C:\Program Files %28x86%29\Visual Leak Detector\lib\Win64;$(LibraryPath)$(SolutionDir)..\External\Lib\Input;$(SolutionDir)..\Bin\DLL; + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + $(SolutionDir)GameLogic;$(SolutionDir)Input;$(SolutionDir)OysterGraphics;$(SolutionDir)Misc;$(SolutionDir)OysterMath;%(AdditionalIncludeDirectories) + + + Windows + true + OysterGraphics_$(PlatformShortName)D.lib;Input_$(PlatformShortName)D.lib;GameLogic_$(PlatformShortName)D.lib;%(AdditionalDependencies) + OysterGraphics_$(PlatformShortName)D.dll;GameLogic_$(PlatformShortName)D.dll;%(DelayLoadDLLs) + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + $(SolutionDir)GameLogic;$(SolutionDir)Input;$(SolutionDir)OysterGraphics;$(SolutionDir)Misc;$(SolutionDir)OysterMath;%(AdditionalIncludeDirectories) + + + Windows + true + OysterGraphics_$(PlatformShortName)D.lib;Input_$(PlatformShortName)D.lib;GameLogic_$(PlatformShortName)D.lib;%(AdditionalDependencies) + OysterGraphics_$(PlatformShortName)D.dll;GameLogic_$(PlatformShortName)D.dll;%(DelayLoadDLLs) + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + $(SolutionDir)GameLogic;$(SolutionDir)Input;$(SolutionDir)OysterGraphics;$(SolutionDir)Misc;$(SolutionDir)OysterMath;%(AdditionalIncludeDirectories) + + + Windows + true + true + true + OysterGraphics_$(PlatformShortName).lib;Input_$(PlatformShortName).lib;GameLogic_$(PlatformShortName).lib;%(AdditionalDependencies) + OysterGraphics_$(PlatformShortName)D.dll;GameLogic_$(PlatformShortName)D.dll;%(DelayLoadDLLs) + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + $(SolutionDir)GameLogic;$(SolutionDir)Input;$(SolutionDir)OysterGraphics;$(SolutionDir)Misc;$(SolutionDir)OysterMath;%(AdditionalIncludeDirectories) + + + Windows + true + true + true + OysterGraphics_$(PlatformShortName).lib;Input_$(PlatformShortName).lib;GameLogic_$(PlatformShortName).lib;%(AdditionalDependencies) + OysterGraphics_$(PlatformShortName)D.dll;GameLogic_$(PlatformShortName)D.dll;%(DelayLoadDLLs) + + + + + {b1195bb9-b3a5-47f0-906c-8dea384d1520} + + + {7e3990d2-3d94-465c-b58d-64a74b3ecf9b} + + + {f10cbc03-9809-4cba-95d8-327c287b18ee} + + + {4285bd3f-3c6c-4670-b7af-a29afef5f6a8} + + + + + + + + + \ No newline at end of file diff --git a/Code/DanBiasGame/DanBiasMaincpp.cpp b/Code/DanBiasGame/DanBiasMaincpp.cpp new file mode 100644 index 00000000..688a916f --- /dev/null +++ b/Code/DanBiasGame/DanBiasMaincpp.cpp @@ -0,0 +1,302 @@ +//-------------------------------------------------------------------------------------- +// File: TemplateMain.cpp +// +// BTH-D3D-Template +// +// Copyright (c) Stefan Petersson 2011. All rights reserved. +//-------------------------------------------------------------------------------------- +#define NOMINMAX +#include + +#include "DllInterfaces/GFXAPI.h" +#include "IGame.h" + +#include "L_inputClass.h" + +// debug window include +#include +#include +#include +#include + + + + +//-------------------------------------------------------------------------------------- +// Global Variables +//-------------------------------------------------------------------------------------- +HINSTANCE g_hInst = NULL; +HWND g_hWnd = NULL; + +GameLogic::IGame* game; +InputClass* inputObj; + + +//-------------------------------------------------------------------------------------- +// Forward declarations +//-------------------------------------------------------------------------------------- +HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow ); +LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); +HRESULT Render(float deltaTime); +HRESULT Update(float deltaTime); +HRESULT InitGame(); +HRESULT CleanUp(); + + + +//-------------------------------------------------------------------------------------- +// Entry point to the program. Initializes everything and goes into a message processing +// loop. Idle time is used to render the scene. +//-------------------------------------------------------------------------------------- + +void SetStdOutToNewConsole() +{ + // allocate a console for this app + AllocConsole(); + + // redirect unbuffered STDOUT to the console + HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); + int fileDescriptor = _open_osfhandle((intptr_t)consoleHandle, _O_TEXT); + FILE *fp = _fdopen( fileDescriptor, "w" ); + *stdout = *fp; + setvbuf( stdout, NULL, _IONBF, 0 ); + + // give the console window a nicer title + + SetConsoleTitle(L"Debug Output"); + + // give the console window a bigger buffer size + CONSOLE_SCREEN_BUFFER_INFO csbi; + if ( GetConsoleScreenBufferInfo(consoleHandle, &csbi) ) + { + COORD bufferSize; + bufferSize.X = csbi.dwSize.X; + bufferSize.Y = 50; + SetConsoleScreenBufferSize(consoleHandle, bufferSize); + } +} + +int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) +{ + BOOL success = SetDllDirectory(L"..\\..\\DLL"); + if (success == 0) + { + return 0; + } + + + if( FAILED( InitWindow( hInstance, nCmdShow ) ) ) + return 0; + + if( FAILED( InitGame() ) ) + return 0; + + __int64 cntsPerSec = 0; + QueryPerformanceFrequency((LARGE_INTEGER*)&cntsPerSec); + float secsPerCnt = 1.0f / (float)cntsPerSec; + + __int64 prevTimeStamp = 0; + QueryPerformanceCounter((LARGE_INTEGER*)&prevTimeStamp); + + //debug window + //SetStdOutToNewConsole(); + + // Main message loop + MSG msg = {0}; + while(WM_QUIT != msg.message) + { + if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE) ) + { + TranslateMessage( &msg ); + DispatchMessage( &msg ); + } + else + { + __int64 currTimeStamp = 0; + QueryPerformanceCounter((LARGE_INTEGER*)&currTimeStamp); + float dt = (currTimeStamp - prevTimeStamp) * secsPerCnt; + + //render + Update(dt); + Render(dt); + + prevTimeStamp = currTimeStamp; + } + } + CleanUp(); + return (int) msg.wParam; +} + +//-------------------------------------------------------------------------------------- +// Register class and create window +//-------------------------------------------------------------------------------------- +HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow ) +{ + // Register class + WNDCLASSEX wcex; + wcex.cbSize = sizeof(WNDCLASSEX); + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = WndProc; + wcex.cbClsExtra = 0; + wcex.cbWndExtra = 0; + wcex.hInstance = hInstance; + wcex.hIcon = 0; + wcex.hCursor = LoadCursor(NULL, IDC_ARROW); + wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); + wcex.lpszMenuName = NULL; + wcex.lpszClassName = L"BTH_D3D_Template"; + wcex.hIconSm = 0; + if( !RegisterClassEx(&wcex) ) + return E_FAIL; + + // Adjust and create window + g_hInst = hInstance; + RECT rc = { 0, 0, 1024, 768 }; + AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE ); + + if(!(g_hWnd = CreateWindow( + L"BTH_D3D_Template", + L"BTH - Direct3D 11.0 Template", + WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, + CW_USEDEFAULT, + rc.right - rc.left, + rc.bottom - rc.top, + NULL, + NULL, + hInstance, + NULL))) + { + return E_FAIL; + } + + ShowWindow( g_hWnd, nCmdShow ); + + return S_OK; +} + + +HRESULT InitGame() +{ + inputObj = new InputClass; + if(!inputObj->Initialize(g_hInst, g_hWnd, 1024, 768)) + { + MessageBox(0, L"Could not initialize the input object.", L"Error", MB_OK); + return false; + } + if(Oyster::Graphics::API::Init(g_hWnd, false, false, Oyster::Math::Float2( 1024, 768)) != Oyster::Graphics::API::Sucsess) + return E_FAIL; + + + game = new GameLogic::IGame(); + game->Init(); + game->StartGame(); + + + + return S_OK; +} +HRESULT Update(float deltaTime) +{ + inputObj->Update(); + GameLogic::keyInput key = GameLogic::keyInput_none; + + if(inputObj->IsKeyPressed(DIK_W)) + { + key = GameLogic::keyInput_W; + } + else if(inputObj->IsKeyPressed(DIK_A)) + { + key = GameLogic::keyInput_A; + } + else if(inputObj->IsKeyPressed(DIK_S)) + { + key = GameLogic::keyInput_S; + } + else if(inputObj->IsKeyPressed(DIK_D)) + { + key = GameLogic::keyInput_D; + } + + game->Update(key); + + return S_OK; +} + +HRESULT Render(float deltaTime) +{ + int isPressed = 0; + if(inputObj->IsKeyPressed(DIK_A)) + { + isPressed = 1; + //std::cout<<"test"; + } + + // test view and projection matrix + Oyster::Math::Float3 dir = Oyster::Math::Float3(0,0,-1); + Oyster::Math::Float3 up =Oyster::Math::Float3(0,1,0); + Oyster::Math::Float3 pos = Oyster::Math::Float3(0, 0, 100); + + Oyster::Math::Float4x4 view =Oyster::Math3D::OrientationMatrix_LookAtDirection(dir, up, pos); + view = view.GetInverse(); + + Oyster::Math::Float4x4 proj = Oyster::Math3D::ProjectionMatrix_Perspective(3.14f/2, 1024/768, 1, 1000); + + Oyster::Graphics::API::NewFrame(view, proj); + + game->Render(); + wchar_t title[255]; + swprintf(title, sizeof(title), L"| Pressing A: %d | \n", (int)(isPressed)); + SetWindowText(g_hWnd, title); + + Oyster::Graphics::API::EndFrame(); + + return S_OK; +} + +HRESULT CleanUp() +{ + + if(game) + { + delete game; + game = NULL; + } + return S_OK; +} +//-------------------------------------------------------------------------------------- +// Called every time the application receives a message +//-------------------------------------------------------------------------------------- +LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) +{ + PAINTSTRUCT ps; + HDC hdc; + + switch (message) + { + case WM_PAINT: + hdc = BeginPaint(hWnd, &ps); + EndPaint(hWnd, &ps); + break; + + case WM_DESTROY: + PostQuitMessage(0); + break; + + case WM_KEYDOWN: + + switch(wParam) + { + case VK_ESCAPE: + PostQuitMessage(0); + break; + } + break; + + default: + return DefWindowProc(hWnd, message, wParam, lParam); + } + + return 0; +} + diff --git a/Code/GameLogic/CollisionManager.cpp b/Code/GameLogic/CollisionManager.cpp new file mode 100644 index 00000000..253056cc --- /dev/null +++ b/Code/GameLogic/CollisionManager.cpp @@ -0,0 +1,82 @@ +#include "CollisionManager.h" + + + +namespace GameLogic +{ + + namespace CollisionManager + { + + + + + void ColisionEvent(Oyster::Physics::ICustomBody &obj1, Oyster::Physics::ICustomBody &obj2) + { + + + //Object *realObj1 = refManager.GetMap(obj1); + //Object *realObj2 = refManager.GetMap(obj2); + // + //switch(realObj1->GetType()) + //{ + //case Object::OBJECT_TYPE_PLAYER: + + // if (realObj2->GetType() == Object::OBJECT_TYPE_BOX ) + // { + //CollisionManager::PlayerVBox(*((Player*)realObj1),*((DynamicObject*)realObj2)); + // } + + // break; + //case Object::OBJECT_TYPE_BOX: + + // if (realObj2->GetType() == Object::OBJECT_TYPE_PLAYER) + // { + // CollisionManager::PlayerVBox(*((Player*)realObj2),*((DynamicObject*)realObj1)); + // } + + // break; + //} + + } + + void PlayerCollision(Oyster::Physics::ICustomBody &rigidBodyPlayer,Oyster::Physics::ICustomBody &obj) + { + Player *player = ((Player*)GameLogic::RefManager::getInstance()->GetMap(rigidBodyPlayer)); + Object *realObj = GameLogic::RefManager::getInstance()->GetMap(obj); + + switch (realObj->GetType()) + { + case Object::OBJECT_TYPE_BOX: + PlayerVBox(*player,(*(DynamicObject*) realObj)); + break; + case Object::OBJECT_TYPE_PLAYER: + + break; + } + + //spela ljud? ta skada? etc etc + } + + void PlayerVBox(Player &player, DynamicObject &box) + { + //spela ljud? ta skada? etc etc + } + + void BoxCollision(Oyster::Physics::ICustomBody &rigidBodyBox, Oyster::Physics::ICustomBody &obj) + { + DynamicObject *box = ((DynamicObject*)GameLogic::RefManager::getInstance()->GetMap(rigidBodyBox)); + Object *realObj = GameLogic::RefManager::getInstance()->GetMap(obj); + + switch (realObj->GetType()) + { + case Object::OBJECT_TYPE_BOX: + + break; + case Object::OBJECT_TYPE_PLAYER: + PlayerVBox(*(Player*)realObj,*box); + break; + } + } + } +} \ No newline at end of file diff --git a/Code/GameLogic/CollisionManager.h b/Code/GameLogic/CollisionManager.h new file mode 100644 index 00000000..878d6f25 --- /dev/null +++ b/Code/GameLogic/CollisionManager.h @@ -0,0 +1,27 @@ +#ifndef COLLISIONMANAGER_H +#define COLLISIONMANAGER_H + +#include "Object.h" +#include "PhysicsAPI.h" +#include "RefManager.h" +#include "DynamicObject.h" +#include "Player.h" + +namespace GameLogic +{ + + namespace CollisionManager + { + void PlayerCollision(Oyster::Physics::ICustomBody &rigidBodyPlayer,Oyster::Physics::ICustomBody &obj); + void BoxCollision(Oyster::Physics::ICustomBody &rigidBodyBox, Oyster::Physics::ICustomBody &obj); + + + + void PlayerVBox(Player &player, DynamicObject &box); + void BoxVBox(DynamicObject &box1, DynamicObject &box2); + + }; + +} + +#endif \ No newline at end of file diff --git a/Code/GameLogic/DynamicObject.cpp b/Code/GameLogic/DynamicObject.cpp new file mode 100644 index 00000000..ec175f59 --- /dev/null +++ b/Code/GameLogic/DynamicObject.cpp @@ -0,0 +1,21 @@ +#include "DynamicObject.h" + +using namespace GameLogic; +using namespace Oyster::Physics; +using namespace Utility::DynamicMemory; + +DynamicObject::DynamicObject(void) +{ + rigidBody = API::Instance().CreateSimpleRigidBody(); + API::Instance().AddObject(rigidBody); +} + + +DynamicObject::~DynamicObject(void) +{ +} + +void DynamicObject::Update() +{ + //updatera objectet +} \ No newline at end of file diff --git a/Code/GameLogic/DynamicObject.h b/Code/GameLogic/DynamicObject.h new file mode 100644 index 00000000..2d6ffdc8 --- /dev/null +++ b/Code/GameLogic/DynamicObject.h @@ -0,0 +1,28 @@ +////////////////////////////////////////////////// +//Created by Erik and Linda of the GameLogic team +////////////////////////////////////////////////// + + +#ifndef DYNAMICOBJECT_H +#define DYNAMICOBJECT_H + +#include "Object.h" + +namespace GameLogic +{ + + + class DynamicObject : public Object + { + + public: + DynamicObject(void); + ~DynamicObject(void); + + void Update(); + + }; + +} + +#endif \ No newline at end of file diff --git a/Code/GameLogic/Game.cpp b/Code/GameLogic/Game.cpp new file mode 100644 index 00000000..6d6d367d --- /dev/null +++ b/Code/GameLogic/Game.cpp @@ -0,0 +1,35 @@ +#include "Game.h" +using namespace GameLogic; + +Game::Game(void) +{ + +} + + +Game::~Game(void) +{ + //SAFE_DELETE(player); + if(player) + { + delete player; + player = NULL; + } +} + +void Game::Init() +{ + player = new Player(); +} +void Game::StartGame() +{ + +} +void Game::Update(keyInput keyPressed) +{ + player->Update(keyPressed); +} +void Game::Render() +{ + player->Render(); +} \ No newline at end of file diff --git a/Code/GameLogic/Game.h b/Code/GameLogic/Game.h new file mode 100644 index 00000000..ab2e57e5 --- /dev/null +++ b/Code/GameLogic/Game.h @@ -0,0 +1,31 @@ +#ifndef GAME_H +#define GAME_H + +#include "Level.h" +#include "Player.h" +#include "IGame.h" + +namespace GameLogic +{ + + + class Game + { + public: + Game(); + ~Game(); + + void Init(); + void StartGame(); + void Update(keyInput keyPressed); + void Render(); + + + private: + Level* level; + Player* player; + + + }; +} +#endif \ No newline at end of file diff --git a/Code/GameLogic/GameLogic.vcxproj b/Code/GameLogic/GameLogic.vcxproj index 900f0834..e4e48526 100644 --- a/Code/GameLogic/GameLogic.vcxproj +++ b/Code/GameLogic/GameLogic.vcxproj @@ -24,30 +24,30 @@ - StaticLibrary + DynamicLibrary true v110 - MultiByte + Unicode - StaticLibrary + DynamicLibrary true v110 - MultiByte + Unicode - StaticLibrary + DynamicLibrary false v110 true - MultiByte + Unicode - StaticLibrary + DynamicLibrary false v110 true - MultiByte + Unicode @@ -66,34 +66,41 @@ - $(SolutionDir)..\External\Lib\$(ProjectName)\ + $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D + $(SolutionDir)..\External\Lib\Input;$(SolutionDir)..\Bin\DLL;$(LibraryPath) + .dll - $(SolutionDir)..\External\Lib\$(ProjectName)\ + $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) + $(SolutionDir)..\External\Lib\Input;$(SolutionDir)..\Bin\DLL;$(LibraryPath) - $(SolutionDir)..\External\Lib\$(ProjectName)\ + $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D + $(SolutionDir)..\External\Lib\Input;$(SolutionDir)..\Bin\DLL;$(LibraryPath) - $(SolutionDir)..\External\Lib\$(ProjectName)\ + $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) + $(SolutionDir)..\External\Lib\Input;$(SolutionDir)..\Bin\DLL;$(LibraryPath) Level3 Disabled true - $(SolutionDir)Misc;$(SolutionDir)OysterMath;$(SolutionDir)OysterPhysics3D;$(SolutionDir)GamePhysics;%(AdditionalIncludeDirectories) + $(SolutionDir)Input;$(SolutionDir)OysterGraphics;$(SolutionDir)Misc;$(SolutionDir)OysterMath;$(SolutionDir)OysterPhysics3D;$(SolutionDir)GamePhysics;%(AdditionalIncludeDirectories) + GAME_DLL_EXPORT;_WINDLL;%(PreprocessorDefinitions) true + OysterGraphics_$(PlatformShortName)D.lib;Input_$(PlatformShortName)D.lib;GamePhysics_$(PlatformShortName)D.lib;%(AdditionalDependencies) @@ -101,10 +108,12 @@ Level3 Disabled true - $(SolutionDir)Misc;$(SolutionDir)OysterMath;$(SolutionDir)OysterPhysics3D;$(SolutionDir)GamePhysics;%(AdditionalIncludeDirectories) + $(SolutionDir)Input;$(SolutionDir)OysterGraphics;$(SolutionDir)Misc;$(SolutionDir)OysterMath;$(SolutionDir)OysterPhysics3D;$(SolutionDir)GamePhysics;%(AdditionalIncludeDirectories) + GAME_DLL_EXPORT;_WINDLL;%(PreprocessorDefinitions) true + OysterGraphics_$(PlatformShortName)D.lib;Input_$(PlatformShortName)D.lib;GamePhysics_$(PlatformShortName)D.lib;%(AdditionalDependencies) @@ -114,12 +123,14 @@ true true true - $(SolutionDir)Misc;$(SolutionDir)OysterMath;$(SolutionDir)OysterPhysics3D;$(SolutionDir)GamePhysics;%(AdditionalIncludeDirectories) + $(SolutionDir)Input;$(SolutionDir)OysterGraphics;$(SolutionDir)Misc;$(SolutionDir)OysterMath;$(SolutionDir)OysterPhysics3D;$(SolutionDir)GamePhysics;%(AdditionalIncludeDirectories) + GAME_DLL_EXPORT;_WINDLL;%(PreprocessorDefinitions) true true true + OysterGraphics_$(PlatformShortName).lib;Input_$(PlatformShortName).lib;GamePhysics_$(PlatformShortName).lib;%(AdditionalDependencies) @@ -129,21 +140,34 @@ true true true - $(SolutionDir)Misc;$(SolutionDir)OysterMath;$(SolutionDir)OysterPhysics3D;$(SolutionDir)GamePhysics;%(AdditionalIncludeDirectories) + $(SolutionDir)Input;$(SolutionDir)OysterGraphics;$(SolutionDir)Misc;$(SolutionDir)OysterMath;$(SolutionDir)OysterPhysics3D;$(SolutionDir)GamePhysics;%(AdditionalIncludeDirectories) + GAME_DLL_EXPORT;_WINDLL;%(PreprocessorDefinitions) true true true + OysterGraphics_$(PlatformShortName).lib;Input_$(PlatformShortName).lib;GamePhysics_$(PlatformShortName).lib;%(AdditionalDependencies) {104fa3e9-94d9-4e1d-a941-28a03bc8a095} + false + true + false + false + false + + + {7e3990d2-3d94-465c-b58d-64a74b3ecf9b} {2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee} + + {0ec83e64-230e-48ef-b08c-6ac9651b4f82} + {f10cbc03-9809-4cba-95d8-327c287b18ee} @@ -151,6 +175,29 @@ {4285bd3f-3c6c-4670-b7af-a29afef5f6a8} + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Code/GameLogic/GameLogic.vcxproj.filters b/Code/GameLogic/GameLogic.vcxproj.filters index d7ef6a1a..38b2d5fa 100644 --- a/Code/GameLogic/GameLogic.vcxproj.filters +++ b/Code/GameLogic/GameLogic.vcxproj.filters @@ -14,4 +14,65 @@ rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + \ No newline at end of file diff --git a/Code/GameLogic/GameMode.cpp b/Code/GameLogic/GameMode.cpp new file mode 100644 index 00000000..0eddb7f9 --- /dev/null +++ b/Code/GameLogic/GameMode.cpp @@ -0,0 +1,15 @@ +#include "GameMode.h" + +using namespace GameLogic; + + +GameMode::GameMode(void) +{ + +} + + +GameMode::~GameMode(void) +{ + +} diff --git a/Code/GameLogic/GameMode.h b/Code/GameLogic/GameMode.h new file mode 100644 index 00000000..42273946 --- /dev/null +++ b/Code/GameLogic/GameMode.h @@ -0,0 +1,22 @@ +////////////////////////////////////////////////// +//Created by Erik and Linda of the GameLogic team +////////////////////////////////////////////////// + + +#ifndef GAMEMODE_H +#define GAMEMODE_H + +namespace GameLogic +{ + + class GameMode + { + public: + GameMode(void); + ~GameMode(void); + private: + //variabels that control what game rules the level runs on + }; + +} +#endif \ No newline at end of file diff --git a/Code/GameLogic/IGame.cpp b/Code/GameLogic/IGame.cpp new file mode 100644 index 00000000..883a9285 --- /dev/null +++ b/Code/GameLogic/IGame.cpp @@ -0,0 +1,45 @@ +#include "IGame.h" +#include "Game.h" +#include + +BOOL WINAPI DllMain( + _In_ HINSTANCE hinstDLL, + _In_ DWORD fdwReason, + _In_ LPVOID lpvReserved + ) +{ + + return TRUE; +} +using namespace GameLogic; +IGame::IGame() +{ + gameModule = new Game(); +} + + +IGame::~IGame() +{ + delete gameModule; +} + +void IGame::Init() +{ + gameModule->Init(); +} +void IGame::StartGame() +{ + gameModule->StartGame(); +} +void IGame::Update(keyInput keyPressed) +{ + gameModule->Update(keyPressed); +} +void IGame::Render() +{ + gameModule->Render(); +} +Game* IGame::getGameModule() +{ + return gameModule; +} \ No newline at end of file diff --git a/Code/GameLogic/IGame.h b/Code/GameLogic/IGame.h new file mode 100644 index 00000000..ce46b7d8 --- /dev/null +++ b/Code/GameLogic/IGame.h @@ -0,0 +1,47 @@ +////////////////////////////////////////////////// +//Created by Erik and Linda of the GameLogic team +////////////////////////////////////////////////// + +#ifndef IGAME_H +#define IGAME_H + +#if defined GAME_DLL_EXPORT +#define GAME_DLL_USAGE __declspec(dllexport) +#else +#define GAME_DLL_USAGE __declspec(dllimport) +#endif + +namespace GameLogic +{ + class Game; + + enum keyInput + { + keyInput_W, + keyInput_A, + keyInput_S, + keyInput_D, + keyInput_none + }; + + class GAME_DLL_USAGE IGame + { + private: + Game* gameModule; + public: + IGame(); + ~IGame(); + + + void Init(); + void StartGame(); + /************************************************************************/ + /* Get key input to update the player */ + /************************************************************************/ + void Update(keyInput keyPressed); + void Render(); + Game* getGameModule(); + private: + }; +} +#endif \ No newline at end of file diff --git a/Code/GameLogic/Level.cpp b/Code/GameLogic/Level.cpp new file mode 100644 index 00000000..32fbe2d5 --- /dev/null +++ b/Code/GameLogic/Level.cpp @@ -0,0 +1,12 @@ +#include "Level.h" + +using namespace GameLogic; + +Level::Level(void) +{ +} + + +Level::~Level(void) +{ +} diff --git a/Code/GameLogic/Level.h b/Code/GameLogic/Level.h new file mode 100644 index 00000000..b43f193d --- /dev/null +++ b/Code/GameLogic/Level.h @@ -0,0 +1,37 @@ +////////////////////////////////////////////////// +//Created by Erik and Linda of the GameLogic team +////////////////////////////////////////////////// + + +#ifndef LEVEL_H +#define LEVEL_H + +#include "StaticObject.h" +#include "DynamicObject.h" +#include "GameMode.h" + +namespace GameLogic +{ + + class Level + { + + public: + Level(void); + ~Level(void); + + private: + StaticObject** staticObjects; + int nrOfStaticObjects; + + DynamicObject** dynamicObjects; + int nrOfDynamicObjects; + + GameMode* gameMode; + + + + }; + +} +#endif \ No newline at end of file diff --git a/Code/GameLogic/Object.cpp b/Code/GameLogic/Object.cpp new file mode 100644 index 00000000..a83d1fb6 --- /dev/null +++ b/Code/GameLogic/Object.cpp @@ -0,0 +1,52 @@ +#include "Object.h" +#include "OysterMath.h" +#include "DllInterfaces\GFXAPI.h" +#include "CollisionManager.h" + + +using namespace GameLogic; + +using namespace Oyster::Math; +using namespace Oyster::Graphics::Model; + +using namespace Utility::DynamicMemory; +using namespace Oyster::Physics; + +Object::Object(void) +{ + + model = new Model(); + model = Oyster::Graphics::API::CreateModel(L"bth.obj"); + + ICustomBody* temp = rigidBody = API::Instance().CreateSimpleRigidBody().Release(); + + rigidBody->SetCenter(Float3(50,0,0)); + rigidBody->SetMass_KeepMomentum(30); + rigidBody->SetSize(Float3(2,2,2)); + rigidBody->SetSubscription(true); + rigidBody->SetMomentOfInertiaTensor_KeepMomentum(Float4x4(MomentOfInertia::CreateCuboidMatrix(30, 2, 2, 2))); + + + GameLogic::RefManager::getInstance()->AddMapping(*rigidBody, *this); + +} + + +Object::~Object(void) +{ + + Oyster::Graphics::API::DeleteModel(model); + +} + +void Object::Render() +{ + this->rigidBody->GetOrientation(model->WorldMatrix); + Oyster::Graphics::API::RenderScene(model, 1); + +} + +Object::OBJECT_TYPE Object::GetType() +{ + return this->type; +} diff --git a/Code/GameLogic/Object.h b/Code/GameLogic/Object.h new file mode 100644 index 00000000..be2f77a6 --- /dev/null +++ b/Code/GameLogic/Object.h @@ -0,0 +1,49 @@ +////////////////////////////////////////////////// +//Created by Erik and Linda of the GameLogic team +////////////////////////////////////////////////// + + +#ifndef OBJECT_H +#define OBJECT_H + +#include "PhysicsAPI.h" +#include "DllInterfaces/GFXAPI.h" + +#include "Model/Model.h" +#include "Utilities.h" + + + +namespace GameLogic +{ + class Object + { + public: + Object(void); + virtual ~Object(void); + + enum OBJECT_TYPE + { + OBJECT_TYPE_PLAYER, + OBJECT_TYPE_BOX, + }; + + void Render(); + + OBJECT_TYPE GetType(); + + private: + OBJECT_TYPE type; + + protected: + //either a model pointer or an ID to an arraypos filled with models that are to be rendered + //rigidBody + + Oyster::Physics::ICustomBody *rigidBody; + Oyster::Graphics::Model::Model *model; + + }; + +} + +#endif \ No newline at end of file diff --git a/Code/GameLogic/Player.cpp b/Code/GameLogic/Player.cpp new file mode 100644 index 00000000..3a9ae029 --- /dev/null +++ b/Code/GameLogic/Player.cpp @@ -0,0 +1,56 @@ +#include "Player.h" +#include "OysterMath.h" + + +using namespace GameLogic; +using namespace Oyster::Physics; +using namespace Utility::DynamicMemory; + + + + +Player::Player(void) + :Object() +{ + life = 100; +} + + +Player::~Player(void) +{ + delete this->rigidBody; +} +void Player::Update(keyInput keyPressed) +{ + if(keyPressed != keyInput_none) + { + Move(); + + if(keyPressed == keyInput_A) + { + Oyster::Math::Float3 pos = this->rigidBody->GetCenter(); + pos.x -= 0.1; + rigidBody->SetCenter(pos); + } + if(keyPressed == keyInput_D) + { + Oyster::Math::Float3 pos = this->rigidBody->GetCenter(); + pos.x += 0.1; + rigidBody->SetCenter(pos); + } + } + +} + +void Player::Move() +{ + //API::Instance().Update(); + /*Oyster::Math::Float3 pos = this->rigidBody->GetCenter(); + pos.x += 0.1; + rigidBody->SetCenter(pos);*/ + //API::Instance().SetCenter(rigidBody, pos); +} +void Player::Shoot() +{ + +} diff --git a/Code/GameLogic/Player.h b/Code/GameLogic/Player.h new file mode 100644 index 00000000..7726fed4 --- /dev/null +++ b/Code/GameLogic/Player.h @@ -0,0 +1,39 @@ +////////////////////////////////////////////////// +//Created by Erik and Linda of the GameLogic team +////////////////////////////////////////////////// + + +#ifndef PLAYER_H +#define PLAYER_H + +#include "Object.h" +#include "Weapon.h" +#include "IGame.h" + + +namespace GameLogic +{ + + + class Player : public Object + { + + public: + Player(void); + ~Player(void); + + void Update(keyInput keyPressed); + + void Move(); + void Shoot(); + + + private: + int life; + Weapon *weapon; + + + }; + +} +#endif \ No newline at end of file diff --git a/Code/GameLogic/RefManager.cpp b/Code/GameLogic/RefManager.cpp new file mode 100644 index 00000000..a119898c --- /dev/null +++ b/Code/GameLogic/RefManager.cpp @@ -0,0 +1,47 @@ +#include "RefManager.h" + +using namespace GameLogic; + +typedef std::pair mapData; + +RefManager* RefManager::instance = 0; + +RefManager::RefManager(void) +{ +} + + +RefManager::~RefManager(void) +{ +} + +void RefManager::Release() +{ + if (instance) + { + delete instance; + instance = NULL; + } + +} + +RefManager* RefManager::getInstance( ) +{ + if (!instance) + { + instance = new RefManager(); + }; + return instance; +} + +Object* RefManager::GetMap(Oyster::Physics::ICustomBody &body) +{ + return mapper[&body]; +} + +void RefManager::AddMapping(Oyster::Physics::ICustomBody &body, Object &obj) +{ + mapper.insert(mapData(&body,&obj)); +} + + diff --git a/Code/GameLogic/RefManager.h b/Code/GameLogic/RefManager.h new file mode 100644 index 00000000..b5fd91d2 --- /dev/null +++ b/Code/GameLogic/RefManager.h @@ -0,0 +1,37 @@ +////////////////////////////////////////////////// +//Created by Erik and Linda of the GameLogic team +////////////////////////////////////////////////// + + +#ifndef REFMANAGER_H +#define REFMANAGER_H + +#include +#include "Object.h" +#include "PhysicsAPI.h" + +namespace GameLogic +{ + + class RefManager + { + public: + RefManager(void); + ~RefManager(void); + + static RefManager* getInstance( ); + void Release(); + + + Object* GetMap(Oyster::Physics::ICustomBody &body); //returns the object of an rigidBody, mainly used for CollisionHandler + void AddMapping(Oyster::Physics::ICustomBody &body, Object &obj); //adds a mapping with body as key and the object as a value + + + private: + static RefManager* instance; + std::map mapper; //mapper points a rigidBody to an actual game object + + + }; +} +#endif \ No newline at end of file diff --git a/Code/GameLogic/StaticObject.cpp b/Code/GameLogic/StaticObject.cpp new file mode 100644 index 00000000..855ef645 --- /dev/null +++ b/Code/GameLogic/StaticObject.cpp @@ -0,0 +1,12 @@ +#include "StaticObject.h" + +using namespace GameLogic; + +StaticObject::StaticObject(void) +{ +} + + +StaticObject::~StaticObject(void) +{ +} diff --git a/Code/GameLogic/StaticObject.h b/Code/GameLogic/StaticObject.h new file mode 100644 index 00000000..07d23311 --- /dev/null +++ b/Code/GameLogic/StaticObject.h @@ -0,0 +1,25 @@ +////////////////////////////////////////////////// +//Created by Erik and Linda of the GameLogic team +////////////////////////////////////////////////// + + +#ifndef STATICOBJECT_H +#define STATICOBJECT_H + +#include "Object.h" + +namespace GameLogic +{ + + class StaticObject : public Object + { + + public: + StaticObject(void); + ~StaticObject(void); + + }; + +} + +#endif \ No newline at end of file diff --git a/Code/GameLogic/TestGLMain.cpp b/Code/GameLogic/TestGLMain.cpp new file mode 100644 index 00000000..8cf34e5f --- /dev/null +++ b/Code/GameLogic/TestGLMain.cpp @@ -0,0 +1,337 @@ +//-------------------------------------------------------------------------------------- +// File: TemplateMain.cpp +// +// BTH-D3D-Template +// +// Copyright (c) Stefan Petersson 2011. All rights reserved. +//-------------------------------------------------------------------------------------- +#define NOMINMAX +#include +#include "Core/Core.h" +#include "DllInterfaces/GFXAPI.h" +#include "IGame.h" + +#include "L_inputClass.h" + +// debug window include +#include +#include +#include +#include + + + + +//-------------------------------------------------------------------------------------- +// Global Variables +//-------------------------------------------------------------------------------------- +HINSTANCE g_hInst = NULL; +HWND g_hWnd = NULL; + +GameLogic::IGame* game; +InputClass* inputObj; + + +//-------------------------------------------------------------------------------------- +// Forward declarations +//-------------------------------------------------------------------------------------- +HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow ); +LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); +HRESULT Render(float deltaTime); +HRESULT Update(float deltaTime); +HRESULT InitDirect3D(); +HRESULT InitGame(); +HRESULT CleanUp(); + + + +//-------------------------------------------------------------------------------------- +// Entry point to the program. Initializes everything and goes into a message processing +// loop. Idle time is used to render the scene. +//-------------------------------------------------------------------------------------- + +void SetStdOutToNewConsole() +{ + // allocate a console for this app + AllocConsole(); + + // redirect unbuffered STDOUT to the console + HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); + int fileDescriptor = _open_osfhandle((intptr_t)consoleHandle, _O_TEXT); + FILE *fp = _fdopen( fileDescriptor, "w" ); + *stdout = *fp; + setvbuf( stdout, NULL, _IONBF, 0 ); + + // give the console window a nicer title + + SetConsoleTitle(L"Debug Output"); + + // give the console window a bigger buffer size + CONSOLE_SCREEN_BUFFER_INFO csbi; + if ( GetConsoleScreenBufferInfo(consoleHandle, &csbi) ) + { + COORD bufferSize; + bufferSize.X = csbi.dwSize.X; + bufferSize.Y = 50; + SetConsoleScreenBufferSize(consoleHandle, bufferSize); + } +} + +int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) +{ + if( FAILED( InitWindow( hInstance, nCmdShow ) ) ) + return 0; + + if( FAILED( InitDirect3D() ) ) + return 0; + + if( FAILED( InitGame() ) ) + return 0; + + __int64 cntsPerSec = 0; + QueryPerformanceFrequency((LARGE_INTEGER*)&cntsPerSec); + float secsPerCnt = 1.0f / (float)cntsPerSec; + + __int64 prevTimeStamp = 0; + QueryPerformanceCounter((LARGE_INTEGER*)&prevTimeStamp); + + //debugwindow + //SetStdOutToNewConsole(); + // Main message loop + MSG msg = {0}; + while(WM_QUIT != msg.message) + { + if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE) ) + { + TranslateMessage( &msg ); + DispatchMessage( &msg ); + } + else + { + __int64 currTimeStamp = 0; + QueryPerformanceCounter((LARGE_INTEGER*)&currTimeStamp); + float dt = (currTimeStamp - prevTimeStamp) * secsPerCnt; + + //render + Update(dt); + Render(dt); + + prevTimeStamp = currTimeStamp; + } + } + CleanUp(); + return (int) msg.wParam; +} + +//-------------------------------------------------------------------------------------- +// Register class and create window +//-------------------------------------------------------------------------------------- +HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow ) +{ + // Register class + WNDCLASSEX wcex; + wcex.cbSize = sizeof(WNDCLASSEX); + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = WndProc; + wcex.cbClsExtra = 0; + wcex.cbWndExtra = 0; + wcex.hInstance = hInstance; + wcex.hIcon = 0; + wcex.hCursor = LoadCursor(NULL, IDC_ARROW); + wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); + wcex.lpszMenuName = NULL; + wcex.lpszClassName = L"BTH_D3D_Template"; + wcex.hIconSm = 0; + if( !RegisterClassEx(&wcex) ) + return E_FAIL; + + // Adjust and create window + g_hInst = hInstance; + RECT rc = { 0, 0, 1024, 768 }; + AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE ); + + if(!(g_hWnd = CreateWindow( + L"BTH_D3D_Template", + L"BTH - Direct3D 11.0 Template", + WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, + CW_USEDEFAULT, + rc.right - rc.left, + rc.bottom - rc.top, + NULL, + NULL, + hInstance, + NULL))) + { + return E_FAIL; + } + + ShowWindow( g_hWnd, nCmdShow ); + + return S_OK; +} + + + +//-------------------------------------------------------------------------------------- +// Create Direct3D device and swap chain +//-------------------------------------------------------------------------------------- +HRESULT InitDirect3D() +{ + /*HRESULT hr = S_OK;; + + Oyster::Graphics::Core::resolution = Oyster::Math::Float2( 1024, 768 ); + + if(Oyster::Graphics::Core::Init::FullInit(g_hWnd,false,false)==Oyster::Graphics::Core::Init::Fail) + return E_FAIL; + + + + std::wstring ShaderPath = L"..\\OysterGraphics\\Shader\\HLSL\\"; + std::wstring EffectPath = L"SimpleDebug\\"; + + Oyster::Graphics::Core::ShaderManager::Init(ShaderPath + EffectPath + L"DebugPixel.hlsl",Oyster::Graphics::Core::ShaderManager::ShaderType::Pixel,L"Debug",false); + Oyster::Graphics::Core::ShaderManager::Init(ShaderPath + EffectPath + L"DebugVertex.hlsl",Oyster::Graphics::Core::ShaderManager::ShaderType::Vertex,L"PassThroughFloat4",false); + + Oyster::Graphics::Core::ShaderManager::Set::Vertex(Oyster::Graphics::Core::ShaderManager::Get::Vertex(L"PassThroughFloat4")); + Oyster::Graphics::Core::ShaderManager::Set::Pixel(Oyster::Graphics::Core::ShaderManager::Get::Pixel(L"Debug")); + + D3D11_INPUT_ELEMENT_DESC inputDesc[] = + { + { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 } + }; + + ID3D11InputLayout* layout; + + Oyster::Graphics::Core::ShaderManager::CreateInputLayout( inputDesc, 1, Oyster::Graphics::Core::ShaderManager::Get::Vertex(L"PassThroughFloat4"), layout); + + Oyster::Graphics::Core::deviceContext->IASetInputLayout(layout); + Oyster::Graphics::Core::deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + + Oyster::Graphics::Render::Preparations::Basic::BindBackBufferRTV(); + + Oyster::Graphics::Render::Preparations::Basic::SetViewPort();*/ + + return S_OK; +} + +HRESULT InitGame() +{ + + if(Oyster::Graphics::API::Init(g_hWnd, false, false, Oyster::Math::Float2( 1024, 768)) != Oyster::Graphics::API::Sucsess) + return E_FAIL; + + inputObj = new InputClass; + if(!inputObj->Initialize(g_hInst, g_hWnd, 1024, 768)) + { + MessageBox(0, L"Could not initialize the input object.", L"Error", MB_OK); + return false; + } + game = new GameLogic::IGame(); + game->Init(); + game->StartGame(); + + + + return S_OK; +} +HRESULT Update(float deltaTime) +{ + inputObj->Update(); + GameLogic::keyInput key = GameLogic::keyInput_none; + + if(inputObj->IsKeyPressed(DIK_W)) + { + key = GameLogic::keyInput_W; + } + else if(inputObj->IsKeyPressed(DIK_A)) + { + key = GameLogic::keyInput_A; + } + else if(inputObj->IsKeyPressed(DIK_S)) + { + key = GameLogic::keyInput_S; + } + else if(inputObj->IsKeyPressed(DIK_D)) + { + key = GameLogic::keyInput_D; + } + + game->Update(key); + + return S_OK; +} + +HRESULT Render(float deltaTime) +{ + int isPressed = 0; + if(inputObj->IsKeyPressed(DIK_A)) + { + isPressed = 1; + //std::cout<<"test"; + } + + // test view and projection matrix + Oyster::Math::Float3 dir = Oyster::Math::Float3(0,0,-1); + Oyster::Math::Float3 up =Oyster::Math::Float3(0,1,0); + Oyster::Math::Float3 pos = Oyster::Math::Float3(0, 0, 100); + + Oyster::Math::Float4x4 view =Oyster::Math3D::OrientationMatrix_LookAtDirection(dir, up, pos); + view = view.GetInverse(); + + Oyster::Math::Float4x4 proj = Oyster::Math3D::ProjectionMatrix_Perspective(PI/2, 1024/768, 1, 1000); + + Oyster::Graphics::API::NewFrame(view, proj); + + game->Render(); + wchar_t title[255]; + swprintf(title, sizeof(title), L"| Pressing A: %d | \n", (int)(isPressed)); + SetWindowText(g_hWnd, title); + + Oyster::Graphics::API::EndFrame(); + + return S_OK; +} + +HRESULT CleanUp() +{ + + SAFE_DELETE(game); + return S_OK; +} +//-------------------------------------------------------------------------------------- +// Called every time the application receives a message +//-------------------------------------------------------------------------------------- +LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) +{ + PAINTSTRUCT ps; + HDC hdc; + + switch (message) + { + case WM_PAINT: + hdc = BeginPaint(hWnd, &ps); + EndPaint(hWnd, &ps); + break; + + case WM_DESTROY: + PostQuitMessage(0); + break; + + case WM_KEYDOWN: + + switch(wParam) + { + case VK_ESCAPE: + PostQuitMessage(0); + break; + } + break; + + default: + return DefWindowProc(hWnd, message, wParam, lParam); + } + + return 0; +} + diff --git a/Code/GameLogic/Weapon.cpp b/Code/GameLogic/Weapon.cpp new file mode 100644 index 00000000..2cbd4e71 --- /dev/null +++ b/Code/GameLogic/Weapon.cpp @@ -0,0 +1,12 @@ +#include "Weapon.h" + +using namespace GameLogic; + +Weapon::Weapon(void) +{ +} + + +Weapon::~Weapon(void) +{ +} diff --git a/Code/GameLogic/Weapon.h b/Code/GameLogic/Weapon.h new file mode 100644 index 00000000..e8d37a15 --- /dev/null +++ b/Code/GameLogic/Weapon.h @@ -0,0 +1,26 @@ +////////////////////////////////////////////////// +//Created by Erik and Linda of the GameLogic team +////////////////////////////////////////////////// + + +#ifndef WEAPON_H +#define WEAPON_H + +#include "Object.h" + +namespace GameLogic +{ + + class Weapon : public Object + { + + public: + Weapon(void); + ~Weapon(void); + + private: + + }; + +} +#endif \ No newline at end of file diff --git a/Code/GamePhysics/GamePhysics.vcxproj b/Code/GamePhysics/GamePhysics.vcxproj index f3a87a2a..540002a1 100644 --- a/Code/GamePhysics/GamePhysics.vcxproj +++ b/Code/GamePhysics/GamePhysics.vcxproj @@ -24,7 +24,7 @@ - StaticLibrary + DynamicLibrary true v110 MultiByte @@ -66,22 +66,22 @@ - $(SolutionDir)..\External\Bin\DLL\ + $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D - $(SolutionDir)..\External\Bin\DLL\ + $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) - $(SolutionDir)..\External\Bin\DLL\ + $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D - $(SolutionDir)..\External\Bin\DLL\ + $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) @@ -90,6 +90,7 @@ Level3 Disabled $(SolutionDir)Misc;$(SolutionDir)OysterMath;$(SolutionDir)OysterPhysics3D;%(AdditionalIncludeDirectories) + _WINDLL;PHYSICS_DLL_EXPORT;%(PreprocessorDefinitions) true @@ -100,6 +101,7 @@ Level3 Disabled $(SolutionDir)Misc;$(SolutionDir)OysterMath;$(SolutionDir)OysterPhysics3D;%(AdditionalIncludeDirectories) + _WINDLL;PHYSICS_DLL_EXPORT;%(PreprocessorDefinitions) true @@ -112,6 +114,7 @@ true true $(SolutionDir)Misc;$(SolutionDir)OysterMath;$(SolutionDir)OysterPhysics3D;%(AdditionalIncludeDirectories) + _WINDLL;PHYSICS_DLL_EXPORT;%(PreprocessorDefinitions) true @@ -126,6 +129,7 @@ true true $(SolutionDir)Misc;$(SolutionDir)OysterMath;$(SolutionDir)OysterPhysics3D;%(AdditionalIncludeDirectories) + _WINDLL;PHYSICS_DLL_EXPORT;%(PreprocessorDefinitions) true @@ -145,11 +149,18 @@ + + + + + + + diff --git a/Code/GamePhysics/GamePhysics.vcxproj.filters b/Code/GamePhysics/GamePhysics.vcxproj.filters index 07661556..72b83568 100644 --- a/Code/GamePhysics/GamePhysics.vcxproj.filters +++ b/Code/GamePhysics/GamePhysics.vcxproj.filters @@ -27,10 +27,31 @@ Header Files\Implementation + + Header Files\Implementation + + + Header Files\Implementation + + + Header Files\Implementation + Source Files + + Source Files + + + Source Files + + + Source Files + + + Header Files\Implementation + \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/DLLMain.cpp b/Code/GamePhysics/Implementation/DLLMain.cpp new file mode 100644 index 00000000..e46d1c83 --- /dev/null +++ b/Code/GamePhysics/Implementation/DLLMain.cpp @@ -0,0 +1,11 @@ +#define NOMINMAX + +#include +#include "OysterMath.h" + +BOOL WINAPI DllMain( _In_ HINSTANCE hinstDLL, + _In_ DWORD fdwReason, + _In_ LPVOID lpvReserved ) +{ + return ::Oyster::Math::IsSupported(); +} \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/Octree.cpp b/Code/GamePhysics/Implementation/Octree.cpp new file mode 100644 index 00000000..6a6416b8 --- /dev/null +++ b/Code/GamePhysics/Implementation/Octree.cpp @@ -0,0 +1,119 @@ +#include "Octree.h" + +using namespace Oyster; +using namespace Physics; + +Octree::Octree(unsigned int bufferSize, unsigned char numLayers, Math::Float3 worldSize) +{ + this->worldNode.dataPtr = NULL; + + this->worldNode.container.maxVertex = worldSize*0.5f; + this->worldNode.container.minVertex = -worldSize*0.5f; +} + +Octree::~Octree() +{ + +} + +Octree& Octree::operator=(const Octree& orig) +{ + this->leafData = orig.leafData; + this->updateQueue = orig.updateQueue; + this->worldNode = orig.worldNode; + this->mapReferences = orig.mapReferences; + + return *this; +} + +void Octree::AddObject(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef) +{ + Data data; + //Data* tempPtr = this->worldNode.dataPtr; + + data.container = customBodyRef->GetBoundingSphere(); + data.queueRef = -1; + data.next = NULL; + data.prev = NULL; + data.customBodyRef = customBodyRef; + this->mapReferences.insert(std::pair (customBodyRef, this->leafData.size())); + this->leafData.push_back(data); + + /*if(tempPtr != NULL) + { + tempPtr->prev->next = &this->leafData[this->leafData.size() - 1]; + this->leafData[this->leafData.size() - 1].prev = tempPtr->prev; + tempPtr->prev = &this->leafData[this->leafData.size() - 1]; + this->leafData[this->leafData.size() - 1].next = tempPtr; + } + else + { + this->worldNode.dataPtr = &this->leafData[this->leafData.size() - 1]; + this->worldNode.dataPtr->next = this->worldNode.dataPtr; + this->worldNode.dataPtr->prev = this->worldNode.dataPtr; + }*/ +} + +void Octree::MoveToUpdateQueue(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef) +{ + /*this->leafData[this->mapReferences[customBodyRef]].queueRef = this->updateQueue.size(); + this->updateQueue.push_back(&this->leafData[this->mapReferences[customBodyRef]]);*/ +} + +void Octree::DestroyObject(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef) +{ + std::map::iterator it = this->mapReferences.find(customBodyRef); + + this->mapReferences.erase(it); + + this->leafData.erase(this->leafData.begin() + this->leafData[this->mapReferences[customBodyRef]].queueRef); +} + +std::vector Octree::Sample(ICustomBody* customBodyRef) +{ + std::vector list; + + auto object = this->mapReferences.find(customBodyRef); + + if(object == this->mapReferences.end()) + { + return list; + } + + unsigned int tempRef = object->second; + + for(unsigned int i = 0; ileafData.size(); i++) + { + if(tempRef != i) if(this->leafData[tempRef].container.Intersects(this->leafData[i].container)) + { + list.push_back(this->leafData[i].customBodyRef); + } + } + + return list; +} + +void Octree::Visit(ICustomBody* customBodyRef, VistorAction hitAction ) +{ + auto object = this->mapReferences.find(customBodyRef); + + if(object == this->mapReferences.end()) + { + return; + } + + unsigned int tempRef = object->second; + + for(unsigned int i = 0; ileafData.size(); i++) + { + if(tempRef != i) if(this->leafData[tempRef].container.Intersects(this->leafData[i].container)) + { + hitAction(*this, tempRef, i); + } + } +} + +ICustomBody* Octree::GetCustomBody(const unsigned int tempRef) +{ + return this->leafData[tempRef].customBodyRef; +} \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/Octree.h b/Code/GamePhysics/Implementation/Octree.h new file mode 100644 index 00000000..8d111329 --- /dev/null +++ b/Code/GamePhysics/Implementation/Octree.h @@ -0,0 +1,67 @@ +#ifndef OCTREE_H +#define OCTREE_H + +#include +#include +#include "Sphere.h" +#include "BoxAxisAligned.h" +#include "Utilities.h" +#include "../PhysicsAPI.h" + +namespace Oyster +{ + namespace Physics + { + class Octree + { + public: + typedef void(*VistorAction)(Octree&, unsigned int, unsigned int); + + struct Data + { + Data* prev; + Data* next; + + Collision3D::Sphere container; + + ::Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef; + + unsigned int queueRef; + }; + + struct OctreeNode + { + OctreeNode* children[8]; + Data* dataPtr; + Collision3D::BoxAxisAligned container; + }; + + Octree(unsigned int bufferSize = 0, unsigned char numLayers = 0, Math::Float3 worldSize = Math::Float3::null); + virtual ~Octree(); + + Octree& operator=(const Octree& orig); + + void AddObject(::Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); + + void MoveToUpdateQueue(::Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); + + void DestroyObject(::Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); + + std::vector Sample(ICustomBody* customBodyRef); + void Visit(ICustomBody* customBodyRef, VistorAction hitAction ); + + ICustomBody* GetCustomBody(const unsigned int tempRef); + + private: + std::vector < Data > leafData; + std::vector < Data* > updateQueue; + + std::map< ICustomBody*, unsigned int > mapReferences; + + OctreeNode worldNode; + }; + } + +} + +#endif \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp index 09d0b1b5..6c9b212a 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp @@ -1,40 +1,79 @@ #include "PhysicsAPI_Impl.h" +#include "OysterPhysics3D.h" +#include "SimpleRigidBody.h" +#include "SphericalRigidBody.h" -using namespace Oyster; -using namespace Physics; +using namespace ::Oyster::Physics; +using namespace ::Oyster::Physics3D; +using namespace ::Oyster::Math; +using namespace ::Oyster::Collision3D; +using namespace ::Utility::DynamicMemory; -API_Impl instance; +API_Impl API_instance; -API & Instance() +Float4x4 & MomentOfInertia::CreateSphereMatrix( const Float mass, const Float radius) { - return instance; + return Formula::MomentOfInertia::Sphere(mass, radius); +} + +Float4x4 & MomentOfInertia::CreateHollowSphereMatrix( const Float mass, const Float radius) +{ + return Formula::MomentOfInertia::HollowSphere(mass, radius); +} + +Float4x4 & MomentOfInertia::CreateCuboidMatrix( const Float mass, const Float height, const Float width, const Float depth ) +{ + return Formula::MomentOfInertia::Cuboid(mass, height, width, depth); +} + +Float4x4 & MomentOfInertia::CreateCylinderMatrix( const Float mass, const Float height, const Float radius ) +{ + return Formula::MomentOfInertia::Cylinder(mass, height, radius); +} + +Float4x4 & MomentOfInertia::CreateRodMatrix( const Float mass, const Float length ) +{ + return Formula::MomentOfInertia::RodCenter(mass, length); +} + +API & API::Instance() +{ + return API_instance; } API_Impl::API_Impl() -{ - /** @todo TODO: Fix this constructor.*/ -} + : gravityConstant( Constant::gravity_constant ), + updateFrameLength( 1.0f / 120.0f ), + destructionAction( Default::EventAction_Destruction ) +{} -API_Impl::~API_Impl() +API_Impl::~API_Impl() {} + +void API_Impl::Init( unsigned int numObjects, unsigned int numGravityWells , const Float3 &worldSize ) { - /** @todo TODO: Fix this destructor.*/ + //! @todo TODO: implement stub } void API_Impl::SetDeltaTime( float deltaTime ) { - /** @todo TODO: Fix this function.*/ + updateFrameLength = deltaTime; } + void API_Impl::SetGravityConstant( float g ) { - /** @todo TODO: Fix this function.*/ + this->gravityConstant = g; } -void API_Impl::SetAction( EventAction_Collision functionPointer ) + +void API_Impl::SetSubscription( API::EventAction_Destruction functionPointer ) { - /** @todo TODO: Fix this function.*/ -} -void API_Impl::SetAction( EventAction_Destruction functionPointer ) -{ - /** @todo TODO: Fix this function.*/ + if( functionPointer ) + { + this->destructionAction = functionPointer; + } + else + { + this->destructionAction = Default::EventAction_Destruction; + } } void API_Impl::Update() @@ -42,22 +81,106 @@ void API_Impl::Update() /** @todo TODO: Fix this function.*/ } -void API_Impl::MoveToLimbo( unsigned int objRef ) +bool API_Impl::IsInLimbo( const ICustomBody* objRef ) +{ + //! @todo TODO: implement stub + return true; +} + +void API_Impl::MoveToLimbo( const ICustomBody* objRef ) { /** @todo TODO: Fix this function.*/ } -void API_Impl::ReleaseFromLimbo( unsigned int objRef ) +void API_Impl::ReleaseFromLimbo( const ICustomBody* objRef ) { /** @todo TODO: Fix this function.*/ } -unsigned int API_Impl::AddObject( ::Utility::DynamicMemory::UniquePointer handle ) +void API_Impl::AddObject( ::Utility::DynamicMemory::UniquePointer handle ) { /** @todo TODO: Fix this function.*/ - - return 0; } -void API_Impl::DestroyObject( unsigned int objRef ) + +::Utility::DynamicMemory::UniquePointer API_Impl::ExtractObject( const ICustomBody* objRef ) +{ + //! @todo TODO: implement stub + return NULL; +} + +void API_Impl::DestroyObject( const ICustomBody* objRef ) { /** @todo TODO: Fix this function.*/ -} \ No newline at end of file +} + +void API_Impl::ApplyForceAt( const ICustomBody* objRef, const Float3 &worldPos, const Float3 &worldF ) +{ + //! @todo TODO: implement stub +} + +void API_Impl::ApplyCollisionResponse( const ICustomBody* objRefA, const ICustomBody* objRefB, Float &deltaWhen, Float3 &worldPointOfContact ) +{ + //! @todo TODO: implement stub +} + +void API_Impl::SetMomentOfInertiaTensor_KeepVelocity( const ICustomBody* objRef, const Float4x4 &localI ) +{ + //! @todo TODO: implement stub +} + +void API_Impl::SetMomentOfInertiaTensor_KeepMomentum( const ICustomBody* objRef, const Float4x4 &localI ) +{ + //! @todo TODO: implement stub +} + +void API_Impl::SetMass_KeepVelocity( const ICustomBody* objRef, Float m ) +{ + //! @todo TODO: implement stub +} + +void API_Impl::SetMass_KeepMomentum( const ICustomBody* objRef, Float m ) +{ + //! @todo TODO: implement stub +} + +void API_Impl::SetCenter( const ICustomBody* objRef, const Float3 &worldPos ) +{ + //! @todo TODO: implement stub +} + +void API_Impl::SetRotation( const ICustomBody* objRef, const Float4x4 &rotation ) +{ + //! @todo TODO: implement stub +} + +void API_Impl::SetOrientation( const ICustomBody* objRef, const Float4x4 &orientation ) +{ + //! @todo TODO: implement stub +} + +void API_Impl::SetSize( const ICustomBody* objRef, const Float3 &size ) +{ + //! @todo TODO: implement stub +} + +UniquePointer API_Impl::CreateRigidBody( const API::SimpleBodyDescription &desc ) const +{ + return new SimpleRigidBody( desc ); +} + +UniquePointer API_Impl::CreateRigidBody( const API::SphericalBodyDescription &desc ) const +{ + return new SphericalRigidBody( desc ); +} + +namespace Oyster { namespace Physics { namespace Default +{ + + void EventAction_Destruction( ::Utility::DynamicMemory::UniquePointer<::Oyster::Physics::ICustomBody> proto ) + { /* Do nothing except allowing the proto uniquePointer destroy itself. */ } + + ::Oyster::Physics::ICustomBody::SubscriptMessage EventAction_Collision( const ::Oyster::Physics::ICustomBody *proto, const ::Oyster::Physics::ICustomBody *deuter ) + { /* Do nothing except returning business as usual. */ + return ::Oyster::Physics::ICustomBody::SubscriptMessage_none; + } + +} } } \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h index 445080b5..7d6858f0 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h @@ -13,22 +13,48 @@ namespace Oyster API_Impl(); virtual ~API_Impl(); + void Init( unsigned int numObjects, unsigned int numGravityWells , const ::Oyster::Math::Float3 &worldSize ); + void SetDeltaTime( float deltaTime ); void SetGravityConstant( float g ); - void SetAction( EventAction_Collision functionPointer ); - void SetAction( EventAction_Destruction functionPointer ); + void SetSubscription( EventAction_Destruction functionPointer ); void Update(); - void MoveToLimbo( unsigned int objRef ); - void ReleaseFromLimbo( unsigned int objRef ); + bool IsInLimbo( const ICustomBody* objRef ); + void MoveToLimbo( const ICustomBody* objRef ); + void ReleaseFromLimbo( const ICustomBody* objRef ); - unsigned int AddObject( ::Utility::DynamicMemory::UniquePointer handle ); - void DestroyObject( unsigned int objRef ); + void AddObject( ::Utility::DynamicMemory::UniquePointer handle ); + ::Utility::DynamicMemory::UniquePointer ExtractObject( const ICustomBody* objRef ); + void DestroyObject( const ICustomBody* objRef ); + + void ApplyForceAt( const ICustomBody* objRef, const ::Oyster::Math::Float3 &worldPos, const ::Oyster::Math::Float3 &worldF ); + void ApplyCollisionResponse( const ICustomBody* objRefA, const ICustomBody* objRefB, ::Oyster::Math::Float &deltaWhen, ::Oyster::Math::Float3 &worldPointOfContact ); + + void SetMomentOfInertiaTensor_KeepVelocity( const ICustomBody* objRef, const ::Oyster::Math::Float4x4 &localI ); + void SetMomentOfInertiaTensor_KeepMomentum( const ICustomBody* objRef, const ::Oyster::Math::Float4x4 &localI ); + void SetMass_KeepVelocity( const ICustomBody* objRef, ::Oyster::Math::Float m ); + void SetMass_KeepMomentum( const ICustomBody* objRef, ::Oyster::Math::Float m ); + void SetCenter( const ICustomBody* objRef, const ::Oyster::Math::Float3 &worldPos ); + void SetRotation( const ICustomBody* objRef, const ::Oyster::Math::Float4x4 &rotation ); + void SetOrientation( const ICustomBody* objRef, const ::Oyster::Math::Float4x4 &orientation ); + void SetSize( const ICustomBody* objRef, const ::Oyster::Math::Float3 &size ); + + ::Utility::DynamicMemory::UniquePointer CreateRigidBody( const SimpleBodyDescription &desc ) const; + ::Utility::DynamicMemory::UniquePointer CreateRigidBody( const SphericalBodyDescription &desc ) const; + + private: + ::Oyster::Math::Float gravityConstant, updateFrameLength; + EventAction_Destruction destructionAction; }; - - } + namespace Default + { + void EventAction_Destruction( ::Utility::DynamicMemory::UniquePointer<::Oyster::Physics::ICustomBody> proto ); + ::Oyster::Physics::ICustomBody::SubscriptMessage EventAction_Collision( const ::Oyster::Physics::ICustomBody *proto, const ::Oyster::Physics::ICustomBody *deuter ); + } + } } #endif \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/SimpleRigidBody.cpp b/Code/GamePhysics/Implementation/SimpleRigidBody.cpp new file mode 100644 index 00000000..40a1b7ee --- /dev/null +++ b/Code/GamePhysics/Implementation/SimpleRigidBody.cpp @@ -0,0 +1,175 @@ +#include "SimpleRigidBody.h" +#include "PhysicsAPI_Impl.h" + +using namespace ::Oyster::Physics; +using namespace ::Oyster::Physics3D; +using namespace ::Oyster::Math3D; +using namespace ::Oyster::Collision3D; +using namespace ::Utility::DynamicMemory; +using namespace ::Utility::Value; + +SimpleRigidBody::SimpleRigidBody() +{ + this->rigid = RigidBody( Box(Float4x4::identity, Float3::null, Float3(1.0f)), 16.0f, Float4x4::identity ); + this->gravityNormal = Float3::null; + this->collisionAction = Default::EventAction_Collision; + this->ignoreGravity = false; +} + +SimpleRigidBody::SimpleRigidBody( const API::SimpleBodyDescription &desc ) +{ + this->rigid = RigidBody( Box( desc.rotation, desc.centerPosition, desc.size ), + desc.mass, + desc.inertiaTensor ); + this->gravityNormal = Float3::null; + + if( desc.subscription ) + { + this->collisionAction = desc.subscription; + } + else + { + this->collisionAction = Default::EventAction_Collision; + } + + this->ignoreGravity = desc.ignoreGravity; +} + +SimpleRigidBody::~SimpleRigidBody() {} + +UniquePointer SimpleRigidBody::Clone() const +{ + return new SimpleRigidBody( *this ); +} + +bool SimpleRigidBody::IsAffectedByGravity() const +{ + return !this->ignoreGravity; +} + +bool SimpleRigidBody::Intersects( const ICustomBody &object, Float timeStepLength, Float &deltaWhen, Float3 &worldPointOfContact ) const +{ + if( object.Intersects(this->rigid.box) ) + { //! @todo TODO: better implementation needed + deltaWhen = timeStepLength; + worldPointOfContact = Average( this->rigid.box.center, object.GetCenter() ); + return true; + } + else + { + return false; + } +} + +bool SimpleRigidBody::Intersects( const ICollideable &shape ) const +{ + return this->rigid.box.Intersects( shape ); +} + +Sphere & SimpleRigidBody::GetBoundingSphere( Sphere &targetMem ) const +{ + return targetMem = Sphere( this->rigid.box.center, this->rigid.box.boundingOffset.GetMagnitude() ); +} + +Float3 & SimpleRigidBody::GetNormalAt( const Float3 &worldPos, Float3 &targetMem ) const +{ + //! @todo TODO: better implementation needed + return targetMem = (worldPos - this->rigid.box.center).GetNormalized(); +} + +Float3 & SimpleRigidBody::GetGravityNormal( Float3 &targetMem ) const +{ + return targetMem = this->gravityNormal; +} + +Float3 & SimpleRigidBody::GetCenter( Float3 &targetMem ) const +{ + return targetMem = this->rigid.box.center; +} + +Float4x4 & SimpleRigidBody::GetRotation( Float4x4 &targetMem ) const +{ + return targetMem = this->rigid.box.rotation; +} + +Float4x4 & SimpleRigidBody::GetOrientation( Float4x4 &targetMem ) const +{ + return targetMem = this->rigid.GetOrientation(); +} + +Float4x4 & SimpleRigidBody::GetView( Float4x4 &targetMem ) const +{ + return targetMem = this->rigid.GetView(); +} + +UpdateState SimpleRigidBody::Update( Float timeStepLength ) +{ + this->rigid.Update_LeapFrog( timeStepLength ); + + // compare previous and new state and return result + //return this->current == this->previous ? UpdateState_resting : UpdateState_altered; + return UpdateState_altered; +} + +void SimpleRigidBody::SetSubscription( ICustomBody::EventAction_Collision functionPointer ) +{ + if( functionPointer ) + { + this->collisionAction = functionPointer; + } + else + { + this->collisionAction = Default::EventAction_Collision; + } +} + +void SimpleRigidBody::SetGravity( bool ignore) +{ + this->ignoreGravity = ignore; + this->gravityNormal = Float3::null; +} + +void SimpleRigidBody::SetGravityNormal( const Float3 &normalizedVector ) +{ + this->gravityNormal = normalizedVector; +} + +void SimpleRigidBody::SetMomentOfInertiaTensor_KeepVelocity( const Float4x4 &localI ) +{ + this->rigid.SetMomentOfInertia_KeepVelocity( localI ); +} + +void SimpleRigidBody::SetMomentOfInertiaTensor_KeepMomentum( const Float4x4 &localI ) +{ + this->rigid.SetMomentOfInertia_KeepMomentum( localI ); +} + +void SimpleRigidBody::SetMass_KeepVelocity( Float m ) +{ + this->rigid.SetMass_KeepVelocity( m ); +} + +void SimpleRigidBody::SetMass_KeepMomentum( Float m ) +{ + this->rigid.SetMass_KeepMomentum( m ); +} + +void SimpleRigidBody::SetCenter( const Float3 &worldPos ) +{ + this->rigid.SetCenter( worldPos ); +} + +void SimpleRigidBody::SetRotation( const Float4x4 &rotation ) +{ + this->rigid.SetRotation( rotation ); +} + +void SimpleRigidBody::SetOrientation( const Float4x4 &orientation ) +{ + this->rigid.SetOrientation( orientation ); +} + +void SimpleRigidBody::SetSize( const Float3 &size ) +{ + this->rigid.SetSize( size ); +} \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/SimpleRigidBody.h b/Code/GamePhysics/Implementation/SimpleRigidBody.h new file mode 100644 index 00000000..c76f6a51 --- /dev/null +++ b/Code/GamePhysics/Implementation/SimpleRigidBody.h @@ -0,0 +1,52 @@ +#ifndef OYSTER_PHYSICS_SIMPLE_RIGIDBODY_H +#define OYSTER_PHYSICS_SIMPLE_RIGIDBODY_H + +#include "..\PhysicsAPI.h" +#include "RigidBody.h" + +namespace Oyster { namespace Physics +{ + class SimpleRigidBody : public ICustomBody + { + public: + SimpleRigidBody(); + SimpleRigidBody( const API::SimpleBodyDescription &desc ); + virtual ~SimpleRigidBody(); + + ::Utility::DynamicMemory::UniquePointer Clone() const; + + bool IsAffectedByGravity() const; + bool Intersects( const ICustomBody &object, ::Oyster::Math::Float timeStepLength, ::Oyster::Math::Float &deltaWhen, ::Oyster::Math::Float3 &worldPointOfContact ) const; + bool Intersects( const ::Oyster::Collision3D::ICollideable &shape ) const; + + ::Oyster::Collision3D::Sphere & GetBoundingSphere( ::Oyster::Collision3D::Sphere &targetMem = ::Oyster::Collision3D::Sphere() ) const; + ::Oyster::Math::Float3 & GetNormalAt( const ::Oyster::Math::Float3 &worldPos, ::Oyster::Math::Float3 &targetMem = ::Oyster::Math::Float3() ) const; + ::Oyster::Math::Float3 & GetGravityNormal( ::Oyster::Math::Float3 &targetMem = ::Oyster::Math::Float3() ) const; + ::Oyster::Math::Float3 & GetCenter( ::Oyster::Math::Float3 &targetMem = ::Oyster::Math::Float3() ) const; + ::Oyster::Math::Float4x4 & GetRotation( ::Oyster::Math::Float4x4 &targetMem = ::Oyster::Math::Float4x4() ) const; + ::Oyster::Math::Float4x4 & GetOrientation( ::Oyster::Math::Float4x4 &targetMem = ::Oyster::Math::Float4x4() ) const; + ::Oyster::Math::Float4x4 & GetView( ::Oyster::Math::Float4x4 &targetMem = ::Oyster::Math::Float4x4() ) const; + + UpdateState Update( ::Oyster::Math::Float timeStepLength ); + + void SetSubscription( EventAction_Collision functionPointer ); + void SetGravity( bool ignore); + void SetGravityNormal( const ::Oyster::Math::Float3 &normalizedVector ); + void SetMomentOfInertiaTensor_KeepVelocity( const ::Oyster::Math::Float4x4 &localI ); + void SetMomentOfInertiaTensor_KeepMomentum( const ::Oyster::Math::Float4x4 &localI ); + void SetMass_KeepVelocity( ::Oyster::Math::Float m ); + void SetMass_KeepMomentum( ::Oyster::Math::Float m ); + void SetCenter( const ::Oyster::Math::Float3 &worldPos ); + void SetRotation( const ::Oyster::Math::Float4x4 &rotation ); + void SetOrientation( const ::Oyster::Math::Float4x4 &orientation ); + void SetSize( const ::Oyster::Math::Float3 &size ); + + private: + ::Oyster::Physics3D::RigidBody rigid; + ::Oyster::Math::Float3 gravityNormal; + EventAction_Collision collisionAction; + bool ignoreGravity; + }; +} } + +#endif \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp new file mode 100644 index 00000000..292a2dd2 --- /dev/null +++ b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp @@ -0,0 +1,181 @@ +#include "SphericalRigidBody.h" +#include "PhysicsAPI_Impl.h" + +using namespace ::Oyster::Physics; +using namespace ::Oyster::Physics3D; +using namespace ::Oyster::Math3D; +using namespace ::Oyster::Collision3D; +using namespace ::Utility::DynamicMemory; +using namespace ::Utility::Value; + +SphericalRigidBody::SphericalRigidBody() +{ + this->rigid = RigidBody( Box(Float4x4::identity, Float3::null, Float3(1.0f)), 10.0f, Float4x4::identity ); + this->gravityNormal = Float3::null; + this->collisionAction = Default::EventAction_Collision; + this->ignoreGravity = false; + this->body = Sphere( Float3::null, 0.5f ); +} + +SphericalRigidBody::SphericalRigidBody( const API::SphericalBodyDescription &desc ) +{ + this->rigid = RigidBody( Box( desc.rotation, desc.centerPosition, Float3(2.0f * desc.radius) ), + desc.mass, + MomentOfInertia::CreateSphereMatrix( desc.mass, desc.radius ) ); + this->gravityNormal = Float3::null; + + if( desc.subscription ) + { + this->collisionAction = desc.subscription; + } + else + { + this->collisionAction = Default::EventAction_Collision; + } + + this->ignoreGravity = desc.ignoreGravity; + this->body = Sphere( desc.centerPosition, desc.radius ); +} + +SphericalRigidBody::~SphericalRigidBody() {} + +UniquePointer SphericalRigidBody::Clone() const +{ + return new SphericalRigidBody( *this ); +} + +bool SphericalRigidBody::IsAffectedByGravity() const +{ + return !this->ignoreGravity; +} + +bool SphericalRigidBody::Intersects( const ICustomBody &object, Float timeStepLength, Float &deltaWhen, Float3 &worldPointOfContact ) const +{ + if( object.Intersects(this->body) ) + { //! @todo TODO: better implementation needed + deltaWhen = timeStepLength; + worldPointOfContact = Average( this->body.center, object.GetCenter() ); + return true; + } + else + { + return false; + } +} + +bool SphericalRigidBody::Intersects( const ICollideable &shape ) const +{ + return this->rigid.box.Intersects( shape ); +} + +Sphere & SphericalRigidBody::GetBoundingSphere( Sphere &targetMem ) const +{ + return targetMem = this->body; +} + +Float3 & SphericalRigidBody::GetNormalAt( const Float3 &worldPos, Float3 &targetMem ) const +{ + //! @todo TODO: better implementation needed + return targetMem = (worldPos - this->rigid.box.center).GetNormalized(); +} + +Float3 & SphericalRigidBody::GetGravityNormal( Float3 &targetMem ) const +{ + return targetMem = this->gravityNormal; +} + +Float3 & SphericalRigidBody::GetCenter( Float3 &targetMem ) const +{ + return targetMem = this->rigid.box.center; +} + +Float4x4 & SphericalRigidBody::GetRotation( Float4x4 &targetMem ) const +{ + return targetMem = this->rigid.box.rotation; +} + +Float4x4 & SphericalRigidBody::GetOrientation( Float4x4 &targetMem ) const +{ + return targetMem = this->rigid.GetOrientation(); +} + +Float4x4 & SphericalRigidBody::GetView( Float4x4 &targetMem ) const +{ + return targetMem = this->rigid.GetView(); +} + +UpdateState SphericalRigidBody::Update( Float timeStepLength ) +{ + this->rigid.Update_LeapFrog( timeStepLength ); + this->body.center = this->rigid.GetCenter(); + + // compare previous and new state and return result + //return this->current == this->previous ? UpdateState_resting : UpdateState_altered; + return UpdateState_altered; +} + +void SphericalRigidBody::SetSubscription( ICustomBody::EventAction_Collision functionPointer ) +{ + if( functionPointer ) + { + this->collisionAction = functionPointer; + } + else + { + this->collisionAction = Default::EventAction_Collision; + } +} + +void SphericalRigidBody::SetGravity( bool ignore) +{ + this->ignoreGravity = ignore; + this->gravityNormal = Float3::null; +} + +void SphericalRigidBody::SetGravityNormal( const Float3 &normalizedVector ) +{ + this->gravityNormal = normalizedVector; +} + +void SphericalRigidBody::SetMomentOfInertiaTensor_KeepVelocity( const Float4x4 &localI ) +{ + this->rigid.SetMomentOfInertia_KeepVelocity( localI ); +} + +void SphericalRigidBody::SetMomentOfInertiaTensor_KeepMomentum( const Float4x4 &localI ) +{ + this->rigid.SetMomentOfInertia_KeepMomentum( localI ); +} + +void SphericalRigidBody::SetMass_KeepVelocity( Float m ) +{ + this->rigid.SetMass_KeepVelocity( m ); +} + +void SphericalRigidBody::SetMass_KeepMomentum( Float m ) +{ + this->rigid.SetMass_KeepMomentum( m ); +} + +void SphericalRigidBody::SetCenter( const Float3 &worldPos ) +{ + this->rigid.SetCenter( worldPos ); + this->body.center = worldPos; +} + +void SphericalRigidBody::SetRotation( const Float4x4 &rotation ) +{ + this->rigid.SetRotation( rotation ); +} + +void SphericalRigidBody::SetOrientation( const Float4x4 &orientation ) +{ + this->rigid.SetOrientation( orientation ); + this->body.center = orientation.v[3].xyz; +} + +void SphericalRigidBody::SetSize( const Float3 &size ) +{ + this->rigid.SetSize( size ); + this->body.radius = 0.5f * Min( Min( size.x, size.y ), size.z ); // inline Min( FloatN )? +} \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/SphericalRigidBody.h b/Code/GamePhysics/Implementation/SphericalRigidBody.h new file mode 100644 index 00000000..61f5d604 --- /dev/null +++ b/Code/GamePhysics/Implementation/SphericalRigidBody.h @@ -0,0 +1,55 @@ +#ifndef OYSTER_PHYSICS_SPHERICAL_RIGIDBODY_H +#define OYSTER_PHYSICS_SPHERICAL_RIGIDBODY_H + +#include "..\PhysicsAPI.h" +#include "RigidBody.h" +#include "Sphere.h" + +namespace Oyster { namespace Physics +{ + class SphericalRigidBody : public ICustomBody + { + public: + SphericalRigidBody(); + SphericalRigidBody( const API::SphericalBodyDescription &desc ); + virtual ~SphericalRigidBody(); + + ::Utility::DynamicMemory::UniquePointer Clone() const; + + bool IsSubscribingCollisions() const; + bool IsAffectedByGravity() const; + bool Intersects( const ICustomBody &object, ::Oyster::Math::Float timeStepLength, ::Oyster::Math::Float &deltaWhen, ::Oyster::Math::Float3 &worldPointOfContact ) const; + bool Intersects( const ::Oyster::Collision3D::ICollideable &shape ) const; + + ::Oyster::Collision3D::Sphere & GetBoundingSphere( ::Oyster::Collision3D::Sphere &targetMem = ::Oyster::Collision3D::Sphere() ) const; + ::Oyster::Math::Float3 & GetNormalAt( const ::Oyster::Math::Float3 &worldPos, ::Oyster::Math::Float3 &targetMem = ::Oyster::Math::Float3() ) const; + ::Oyster::Math::Float3 & GetGravityNormal( ::Oyster::Math::Float3 &targetMem = ::Oyster::Math::Float3() ) const; + ::Oyster::Math::Float3 & GetCenter( ::Oyster::Math::Float3 &targetMem = ::Oyster::Math::Float3() ) const; + ::Oyster::Math::Float4x4 & GetRotation( ::Oyster::Math::Float4x4 &targetMem = ::Oyster::Math::Float4x4() ) const; + ::Oyster::Math::Float4x4 & GetOrientation( ::Oyster::Math::Float4x4 &targetMem = ::Oyster::Math::Float4x4() ) const; + ::Oyster::Math::Float4x4 & GetView( ::Oyster::Math::Float4x4 &targetMem = ::Oyster::Math::Float4x4() ) const; + + UpdateState Update( ::Oyster::Math::Float timeStepLength ); + + void SetSubscription( EventAction_Collision functionPointer ); + void SetGravity( bool ignore); + void SetGravityNormal( const ::Oyster::Math::Float3 &normalizedVector ); + void SetMomentOfInertiaTensor_KeepVelocity( const ::Oyster::Math::Float4x4 &localI ); + void SetMomentOfInertiaTensor_KeepMomentum( const ::Oyster::Math::Float4x4 &localI ); + void SetMass_KeepVelocity( ::Oyster::Math::Float m ); + void SetMass_KeepMomentum( ::Oyster::Math::Float m ); + void SetCenter( const ::Oyster::Math::Float3 &worldPos ); + void SetRotation( const ::Oyster::Math::Float4x4 &rotation ); + void SetOrientation( const ::Oyster::Math::Float4x4 &orientation ); + void SetSize( const ::Oyster::Math::Float3 &size ); + + private: + ::Oyster::Physics3D::RigidBody rigid; + ::Oyster::Math::Float3 gravityNormal; + EventAction_Collision collisionAction; + bool ignoreGravity; + ::Oyster::Collision3D::Sphere body; + }; +} } + +#endif \ No newline at end of file diff --git a/Code/GamePhysics/Include/PhysicsAPI.h b/Code/GamePhysics/Include/PhysicsAPI.h deleted file mode 100644 index 3b40e705..00000000 --- a/Code/GamePhysics/Include/PhysicsAPI.h +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef PHYSICS_API_H -#define PHYSICS_API_H - -#include "OysterMath.h" - -namespace Oyster -{ - namespace Physics - { - class API; - class IRigidBody; - class IParticle; - - class API - { - public: - static API & Instance(); - }; - - class IRigidBody - { - public: - - }; - - class IParticle - { - public: - - }; - } - - namespace Collision - {} -} -#endif \ No newline at end of file diff --git a/Code/GamePhysics/PhysicsAPI.h b/Code/GamePhysics/PhysicsAPI.h index d9ae0a59..6cba993c 100644 --- a/Code/GamePhysics/PhysicsAPI.h +++ b/Code/GamePhysics/PhysicsAPI.h @@ -3,74 +3,431 @@ #include "OysterCollision3D.h" #include "OysterMath.h" -#include "Utilities.h" + +#if defined PHYSICS_DLL_EXPORT + #define PHYSICS_DLL_USAGE __declspec(dllexport) +#else + #define PHYSICS_DLL_USAGE __declspec(dllimport) +#endif namespace Oyster { namespace Physics { class API; - class IRigidBody; - class IParticle; + class ICustomBody; enum UpdateState { - resting, - altered + UpdateState_resting, + UpdateState_altered }; namespace Constant { - const float gravity_constant = (const float)6.67284e-11; // The _big_G_! ( N(m/kg)^2 ) Used in real gravityforcefields. + const float gravity_constant = (const float)6.67284e-11; //!< The _big_G_! ( N(m/kg)^2 ) Used in real gravityforcefields. } - class API + class PHYSICS_DLL_USAGE MomentOfInertia { public: - typedef void (*EventAction_Collision)( unsigned int, unsigned int ); - typedef void (*EventAction_Destruction)( unsigned int, ::Utility::DynamicMemory::UniquePointer ); + static ::Oyster::Math::Float4x4 & CreateSphereMatrix( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius); + + static ::Oyster::Math::Float4x4 & CreateHollowSphereMatrix( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius); + static ::Oyster::Math::Float4x4 & CreateCuboidMatrix( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float height, const ::Oyster::Math::Float width, const ::Oyster::Math::Float depth ); + + static ::Oyster::Math::Float4x4 & CreateCylinderMatrix( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float height, const ::Oyster::Math::Float radius ); + + static ::Oyster::Math::Float4x4 & CreateRodMatrix( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float length ); + }; + + class PHYSICS_DLL_USAGE API + { + public: + struct SimpleBodyDescription; + struct SphericalBodyDescription; + + typedef void (*EventAction_Destruction)( ::Utility::DynamicMemory::UniquePointer proto ); + + /** Gets the Physics instance. */ static API & Instance(); - virtual void SetDeltaTime( float deltaTime ) = 0; - virtual void SetGravityConstant( float g ) = 0; - virtual void SetAction( EventAction_Collision functionPointer ) = 0; - virtual void SetAction( EventAction_Destruction functionPointer ) = 0; + /******************************************************** + * Clears all content and reset Engine assetts such as buffers. + * @param numObjects: The predicted max number of active objects. + * @param numGravityWells: The predicted max number of active gravity wells. + * @param worldSize: The size of acceptable physics space. + ********************************************************/ + virtual void Init( unsigned int numObjects, unsigned int numGravityWells , const ::Oyster::Math::Float3 &worldSize ) = 0; + /******************************************************** + * Sets the time length of each physics update frame. + ********************************************************/ + virtual void SetDeltaTime( float seconds ) = 0; + + /******************************************************** + * Sets the Gravityconstant in the physics that will be + * used in ForceField calculations. + * @param g: Default is the real world Constant::gravity_constant [N(m/kg)^2] + ********************************************************/ + virtual void SetGravityConstant( float g ) = 0; + + /******************************************************** + * Sets the function that will be called by the engine + * whenever an object is being destroyed for some reason. + * - Because DestroyObject(...) were called. + * - Out of memory forced engine to destroy an object. + * @param functionPointer: If NULL, an empty default function will be set. + ********************************************************/ + virtual void SetSubscription( EventAction_Destruction functionPointer ) = 0; + + /******************************************************** + * Triggers the engine to run next update frame. + * All accumulated forces and changes will be consumed. + * EventAction functions might be called. + ********************************************************/ virtual void Update() = 0; - virtual bool IsInLimbo( unsigned int objRef ) = 0; - virtual void MoveToLimbo( unsigned int objRef ) = 0; - virtual void ReleaseFromLimbo( unsigned int objRef ) = 0; + /******************************************************** + * An object in limbo state will be ignored during the physics frame Update. + * @param objRef: A pointer to the ICustomBody representing a physical object. + * @return true if object is in limbo state. + ********************************************************/ + virtual bool IsInLimbo( const ICustomBody* objRef ) = 0; + + /******************************************************** + * An object in limbo state will be ignored during the physics frame Update. + * This will put an object in Limbo state. + * @param objRef: A pointer to the ICustomBody representing a physical object. + ********************************************************/ + virtual void MoveToLimbo( const ICustomBody* objRef ) = 0; + + /******************************************************** + * An object in limbo state will be ignored during the physics frame Update. + * This will clear the accumulated force/torque and remove the Limbo state. + * @param objRef: A pointer to the ICustomBody representing a physical object. + ********************************************************/ + virtual void ReleaseFromLimbo( const ICustomBody* objRef ) = 0; - virtual unsigned int AddObject( ::Utility::DynamicMemory::UniquePointer handle ) = 0; - virtual ::Utility::DynamicMemory::UniquePointer ExtractObject( unsigned int objRef ) = 0; - virtual void DestroyObject( unsigned int objRef ) = 0; + /******************************************************** + * Introduces a new object into the engine. + * @param handle: A pointer along with the responsibility to delete. + ********************************************************/ + virtual void AddObject( ::Utility::DynamicMemory::UniquePointer handle ) = 0; + + /******************************************************** + * Fetches and removes an object from the engine. + * Will not call the provided EventAction_Destruction method. + * @param objRef: A pointer to the ICustomBody representing a physical object. + * @return A pointer along with the responsibility to delete. NULL if faulty objRef. + ********************************************************/ + virtual ::Utility::DynamicMemory::UniquePointer ExtractObject( const ICustomBody* objRef ) = 0; + + /******************************************************** + * Removes an object from the engine. + * Will call the provided EventAction_Destruction method. Not if objRef is faulty. + * @param objRef: A pointer to the ICustomBody representing a physical object. + ********************************************************/ + virtual void DestroyObject( const ICustomBody* objRef ) = 0; + + /******************************************************** + * Apply force on an object. + * @param objRef: A pointer to the ICustomBody representing a physical object. + * @param worldPos: Relative to the world origo. (Not relative to object) [m] + * @param worldF: Vector with the direction and magnitude of the force. [N] + ********************************************************/ + virtual void ApplyForceAt( const ICustomBody* objRef, const ::Oyster::Math::Float3 &worldPos, const ::Oyster::Math::Float3 &worldF ) = 0; + + /******************************************************** + * Apply force on an object. + * @param objRefA: A pointer to the ICustomBody representing a physical object. + * @param objRefB: A pointer to the ICustomBody representing a physical object. + * @param deltaWhen: The elapsed simulation time since last update frame. [s] + * @param worldPointOfContact: Point of Collision, relative to the world origo. (Not relative to the objects) [m] + ********************************************************/ + virtual void ApplyCollisionResponse( const ICustomBody* objRefA, const ICustomBody* objRefB, ::Oyster::Math::Float &deltaWhen, ::Oyster::Math::Float3 &worldPointOfContact ) = 0; + + /******************************************************** + * Sets the MomentOfInertia tensor matrix of an object without changing it's angular velocity. + * Noticeable effect: The angular momentum will change. Changing the amount of kinetic energy. + * @param objRef: A pointer to the ICustomBody representing a physical object. + * @param localI: The tensor matrix relative to the axises of the object. @see MomentOfInertia namespace. + ********************************************************/ + virtual void SetMomentOfInertiaTensor_KeepVelocity( const ICustomBody* objRef, const ::Oyster::Math::Float4x4 &localI ) = 0; + + /******************************************************** + * Sets the MomentOfInertia tensor matrix of an object without changing it's angular momentum. + * Noticeable effect: The angular velocity will change. Can be used to create slow effects. + * @param objRef: A pointer to the ICustomBody representing a physical object. + * @param localI: The tensor matrix relative to the axises of the object. @see MomentOfInertia namespace. + ********************************************************/ + virtual void SetMomentOfInertiaTensor_KeepMomentum( const ICustomBody* objRef, const ::Oyster::Math::Float4x4 &localI ) = 0; + + /******************************************************** + * Sets the mass of an object without changing it's linear velocity. + * Noticeable effect: The linear momentum will change. Changing the amount of kinetic energy. + * @param objRef: A pointer to the ICustomBody representing a physical object. + * @param m: [kg] + ********************************************************/ + virtual void SetMass_KeepVelocity( const ICustomBody* objRef, ::Oyster::Math::Float m ) = 0; + + /******************************************************** + * Sets the mass of an object without changing it's linear velocity. + * Noticeable effect: The linear velocity will change. Can be used to create slow effects. + * @param objRef: A pointer to the ICustomBody representing a physical object. + * @param m: [kg] + ********************************************************/ + virtual void SetMass_KeepMomentum( const ICustomBody* objRef, ::Oyster::Math::Float m ) = 0; + + /******************************************************** + * Instantly moves an object. + * @param objRef: A pointer to the ICustomBody representing a physical object. + * @param worldPos: Relative to the world origo. (Not relative to object) [m] + ********************************************************/ + virtual void SetCenter( const ICustomBody* objRef, const ::Oyster::Math::Float3 &worldPos ) = 0; + + /******************************************************** + * Instantly redirects object. + * @param objRef: A pointer to the ICustomBody representing a physical object. + * @param rotation: New rotation. + ********************************************************/ + virtual void SetRotation( const ICustomBody* objRef, const ::Oyster::Math::Float4x4 &rotation ) = 0; + + /******************************************************** + * Instantly moves and redirects object. + * @param objRef: A pointer to the ICustomBody representing a physical object. + * @param orientation: New orientation. + ********************************************************/ + virtual void SetOrientation( const ICustomBody* objRef, const ::Oyster::Math::Float4x4 &orientation ) = 0; + + /******************************************************** + * Resizes the boundingBox. + * @param objRef: A pointer to the ICustomBody representing a physical object. + * @param size: New size of this [m] + ********************************************************/ + virtual void SetSize( const ICustomBody* objRef, const ::Oyster::Math::Float3 &size ) = 0; + + /******************************************************** + * Creates a new dynamically allocated object that can be used as a component for more complex ICustomBodies. + * @param desc: @see API::SimpleBodyDescription + * @return A pointer along with the responsibility to delete. + ********************************************************/ + virtual ::Utility::DynamicMemory::UniquePointer CreateRigidBody( const SimpleBodyDescription &desc ) const = 0; + + /******************************************************** + * Creates a new dynamically allocated object that can be used as a component for more complex ICustomBodies. + * @param desc: @see API::SphericalBodyDescription + * @return A pointer along with the responsibility to delete. + ********************************************************/ + virtual ::Utility::DynamicMemory::UniquePointer CreateRigidBody( const SphericalBodyDescription &desc ) const = 0; + + protected: + virtual ~API() {} }; - class IRigidBody + //! The root interface for all physical representations processable by the engine. + class PHYSICS_DLL_USAGE ICustomBody { public: - virtual ~IRigidBody() {}; + enum SubscriptMessage + { + SubscriptMessage_none, + SubscriptMessage_ignore_collision_response + }; - virtual UpdateState Update( ::Oyster::Math::Float timeStepLength ) = 0; - - virtual bool IsSubscribingCollisions() const = 0; - virtual bool IsIntersecting( const IRigidBody &object, ::Oyster::Math::Float &deltaWhen, ::Oyster::Math::Float3 &worldPointOfContact ) = 0; + typedef SubscriptMessage (*EventAction_Collision)( const ICustomBody *proto, const ICustomBody *deuter ); - virtual unsigned int GetReference() const = 0; + virtual ~ICustomBody() {}; + + /******************************************************** + * Creates a complete copy of the current (type)object. + * @return An ICustomBody pointer along with the responsibility to delete. + ********************************************************/ + virtual ::Utility::DynamicMemory::UniquePointer Clone() const = 0; + + /******************************************************** + * @return true if Engine should apply gravity on this object. + ********************************************************/ + virtual bool IsAffectedByGravity() const = 0; + + /******************************************************** + * Performs a detailed Intersect test and returns if, when and where. + * @param object: What this is intersect testing against. + * @param timeStepLength: The value set by API::SetDeltaTime(...) + * @param deltaWhen: Time in seconds since last update frame til timeOfContact. 0.0f <= deltaWhen <= timeStepLength + * @param worldPointOfContact: Where at timeOfContact, this and object touches eachother. + * @return true if this truly intersects with object. + ********************************************************/ + virtual bool Intersects( const ICustomBody &object, ::Oyster::Math::Float timeStepLength, ::Oyster::Math::Float &deltaWhen, ::Oyster::Math::Float3 &worldPointOfContact ) const = 0; + + /******************************************************** + * param shape: Any defined sample shape. + * @return true if this truly intersects with shape. + ********************************************************/ + virtual bool Intersects( const ::Oyster::Collision3D::ICollideable &shape ) const = 0; + + /******************************************************** + * Required by Engine's Collision Search. + * @param targetMem: Provided memory that written into and then returned. + * @return a sphere shape that contains the ICustomBody. + ********************************************************/ virtual ::Oyster::Collision3D::Sphere & GetBoundingSphere( ::Oyster::Collision3D::Sphere &targetMem = ::Oyster::Collision3D::Sphere() ) const = 0; + + /******************************************************** + * Required by Engine's Collision Responsing. + * @param worldPos: Should be worldPointOfContact from Intersects( ... ) + * @param targetMem: Provided memory that written into and then returned. + * @return a surface normal in worldSpace. + ********************************************************/ virtual ::Oyster::Math::Float3 & GetNormalAt( const ::Oyster::Math::Float3 &worldPos, ::Oyster::Math::Float3 &targetMem = ::Oyster::Math::Float3() ) const = 0; + + /******************************************************** + * The gravity normal will have same direction as the total gravity force pulling on this and have the magnitude of 1.0f. + * @param targetMem: Provided memory that written into and then returned. + * @return a normalized vector in worldSpace. Exception: Null vector if no gravity been applied. + ********************************************************/ + virtual ::Oyster::Math::Float3 & GetGravityNormal( ::Oyster::Math::Float3 &targetMem = ::Oyster::Math::Float3() ) const = 0; + + /******************************************************** + * The world position of this center of gravity. + * @param targetMem: Provided memory that written into and then returned. + * @return a position in worldSpace. + ********************************************************/ + virtual ::Oyster::Math::Float3 & GetCenter( ::Oyster::Math::Float3 &targetMem = ::Oyster::Math::Float3() ) const = 0; + + /******************************************************** + * @param targetMem: Provided memory that written into and then returned. + * @return a copy of this's rotation matrix. + ********************************************************/ + virtual ::Oyster::Math::Float4x4 & GetRotation( ::Oyster::Math::Float4x4 &targetMem = ::Oyster::Math::Float4x4() ) const = 0; + + /******************************************************** + * @param targetMem: Provided memory that written into and then returned. + * @return a copy of this's orientation matrix. + ********************************************************/ + virtual ::Oyster::Math::Float4x4 & GetOrientation( ::Oyster::Math::Float4x4 &targetMem = ::Oyster::Math::Float4x4() ) const = 0; + + /******************************************************** + * @param targetMem: Provided memory that written into and then returned. + * @return a copy of this's view matrix. + ********************************************************/ + virtual ::Oyster::Math::Float4x4 & GetView( ::Oyster::Math::Float4x4 &targetMem = ::Oyster::Math::Float4x4() ) const = 0; + + /******************************************************** + * To not be called if is in Engine + * Is called during API::Update + ********************************************************/ + virtual UpdateState Update( ::Oyster::Math::Float timeStepLength ) = 0; + + /******************************************************** + * Sets the function that will be called by the engine + * whenever a collision occurs. + * @param functionPointer: If NULL, an empty default function will be set. + ********************************************************/ + virtual void SetSubscription( EventAction_Collision functionPointer ) = 0; + + /******************************************************** + * @param ignore: True if Engine should not apply Gravity. + ********************************************************/ + virtual void SetGravity( bool ignore) = 0; + + /******************************************************** + * Used by Engine + * @param normalizedVector: Should have same direction as the pullinggravity. + ********************************************************/ + virtual void SetGravityNormal( const ::Oyster::Math::Float3 &normalizedVector ) = 0; + + /******************************************************** + * To not be called if is in Engine + * Use API::SetMomentOfInertiaTensor_KeepVelocity(...) instead + ********************************************************/ + virtual void SetMomentOfInertiaTensor_KeepVelocity( const ::Oyster::Math::Float4x4 &localI ) = 0; + + /******************************************************** + * To not be called if is in Engine + * Use API::SetMomentOfInertiaTensor_KeepMomentum(...) + ********************************************************/ + virtual void SetMomentOfInertiaTensor_KeepMomentum( const ::Oyster::Math::Float4x4 &localI ) = 0; + + /******************************************************** + * To not be called if is in Engine + * Use API::SetMass_KeepVelocity(...) + ********************************************************/ + virtual void SetMass_KeepVelocity( ::Oyster::Math::Float m ) = 0; + + /******************************************************** + * To not be called if is in Engine + * Use API::SetMass_KeepMomentum(...) + ********************************************************/ + virtual void SetMass_KeepMomentum( ::Oyster::Math::Float m ) = 0; + + /******************************************************** + * To not be called if is in Engine + * Use API::SetCenter(...) + ********************************************************/ + virtual void SetCenter( const ::Oyster::Math::Float3 &worldPos ) = 0; + + /******************************************************** + * To not be called if is in Engine + * Use API::SetRotation(...) + ********************************************************/ + virtual void SetRotation( const ::Oyster::Math::Float4x4 &rotation ) = 0; + + /******************************************************** + * To not be called if is in Engine + * Use API::SetOrientation(...) + ********************************************************/ + virtual void SetOrientation( const ::Oyster::Math::Float4x4 &orientation ) = 0; + + /******************************************************** + * To not be called if is in Engine + * Use API::SetSize(...) + ********************************************************/ + virtual void SetSize( const ::Oyster::Math::Float3 &size ) = 0; }; - class IParticle + struct API::SimpleBodyDescription { - public: + ::Oyster::Math::Float4x4 rotation; + ::Oyster::Math::Float3 centerPosition; + ::Oyster::Math::Float3 size; + ::Oyster::Math::Float mass; + ::Oyster::Math::Float4x4 inertiaTensor; + ICustomBody::EventAction_Collision subscription; + bool ignoreGravity; + SimpleBodyDescription() + { + this->rotation = ::Oyster::Math::Float4x4::identity; + this->centerPosition = ::Oyster::Math::Float3::null; + this->size = ::Oyster::Math::Float3( 1.0f ); + this->mass = 12.0f; + this->inertiaTensor = ::Oyster::Math::Float4x4::identity; + this->subscription = NULL; + this->ignoreGravity = false; + } + }; + + struct API::SphericalBodyDescription + { + ::Oyster::Math::Float4x4 rotation; + ::Oyster::Math::Float3 centerPosition; + ::Oyster::Math::Float radius; + ::Oyster::Math::Float mass; + ICustomBody::EventAction_Collision subscription; + bool ignoreGravity; + + SphericalBodyDescription() + { + this->rotation = ::Oyster::Math::Float4x4::identity; + this->centerPosition = ::Oyster::Math::Float3::null; + this->radius = 0.5f; + this->mass = 10.0f; + this->subscription = NULL; + this->ignoreGravity = false; + } }; } - - namespace Collision - {} } #endif \ No newline at end of file diff --git a/Code/Input/Input.vcxproj b/Code/Input/Input.vcxproj index df018aab..6788f744 100644 --- a/Code/Input/Input.vcxproj +++ b/Code/Input/Input.vcxproj @@ -18,13 +18,19 @@ x64 + + + + + + {7E3990D2-3D94-465C-B58D-64A74B3ECF9B} Input - Application + StaticLibrary true v110 Unicode diff --git a/Code/Input/Input.vcxproj.filters b/Code/Input/Input.vcxproj.filters index d7ef6a1a..fc15cc38 100644 --- a/Code/Input/Input.vcxproj.filters +++ b/Code/Input/Input.vcxproj.filters @@ -14,4 +14,14 @@ rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + Source Files + + + + + Header Files + + \ No newline at end of file diff --git a/Code/Input/L_inputClass.cpp b/Code/Input/L_inputClass.cpp new file mode 100644 index 00000000..e644b5dc --- /dev/null +++ b/Code/Input/L_inputClass.cpp @@ -0,0 +1,203 @@ +#include "L_inputclass.h" + +InputClass::InputClass() +{ + m_directInput = NULL; + m_keyboard = NULL; + m_mouse = NULL; +} + +InputClass::~InputClass() +{ + // Release the mouse. + if(m_mouse) + { + (m_mouse)->Unacquire(); + (m_mouse)->Release(); + (m_mouse) = NULL; + } + //SAFE_UNACQUIRE(m_mouse); + + // Release the keyboard. + if(m_keyboard) + { + (m_keyboard)->Unacquire(); + (m_keyboard)->Release(); + (m_keyboard) = NULL; + } + //SAFE_UNACQUIRE(m_keyboard); + + // Release the main interface to direct input. + if( m_directInput ) + { + (m_directInput)->Release(); + (m_directInput) = NULL; + } + //SAFE_RELEASE(m_directInput); + + return; +} + +bool InputClass::Initialize(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight) +{ + HRESULT result; + + // Initialize the main direct input interface. + result = DirectInput8Create(hinstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_directInput, NULL); + if(FAILED(result)) + { + return false; + } + + // Initialize the direct input interface for the keyboard. + result = m_directInput->CreateDevice(GUID_SysKeyboard, &m_keyboard, NULL); + if(FAILED(result)) + { + return false; + } + + // Set the cooperative level of the keyboard to not share with other programs. + result = m_keyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE); + if(FAILED(result)) + { + return false; + } + // Set the data format. In this case since it is a keyboard we can use the predefined data format. + result = m_keyboard->SetDataFormat(&c_dfDIKeyboard); + if(FAILED(result)) + { + return false; + } + + // Now acquire the keyboard. + result = m_keyboard->Acquire(); + if(FAILED(result)) + { + return false; + } + + // Initialize the direct input interface for the mouse. + result = m_directInput->CreateDevice(GUID_SysMouse, &m_mouse, NULL); + if(FAILED(result)) + { + return false; + } + + // Set the data format for the mouse using the pre-defined mouse data format. + result = m_mouse->SetDataFormat(&c_dfDIMouse); + if(FAILED(result)) + { + return false; + } + + // Set the cooperative level of the mouse to share with other programs. + result = m_mouse->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE); + if(FAILED(result)) + { + return false; + } + + // Acquire the mouse. + result = m_mouse->Acquire(); + if(FAILED(result)) + { + return false; + } + + return true; +} + +bool InputClass::Update() +{ + bool result; + + //Read the current state of the keyboard. + result = ReadKeyboard(); + if(!result) + { + return false; + } + + // Read the current state of the mouse. + result = ReadMouse(); + if(!result) + { + return false; + } + + return true; +} + +bool InputClass::ReadKeyboard() +{ + HRESULT result; + + // Read the keyboard device. + result = m_keyboard->GetDeviceState(sizeof(m_keyboardState), (LPVOID)&m_keyboardState); + if(FAILED(result)) + { + // If the keyboard lost focus or was not acquired then try to get control back. + if((result == DIERR_INPUTLOST) || (result == DIERR_NOTACQUIRED)) + { + m_keyboard->Acquire(); + } + else + { + return false; + } + } + + return true; +} + +bool InputClass::ReadMouse() +{ + HRESULT result; + + // Read the mouse device. + result = m_mouse->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&m_mouseState); + if(FAILED(result)) + { + // If the mouse lost focus or was not acquired then try to get control back. + if((result == DIERR_INPUTLOST) || (result == DIERR_NOTACQUIRED)) + { + m_mouse->Acquire(); + } + else + { + return false; + } + } + + return true; +} + +void InputClass::MouseMove(float &Pitch, float &RotateY ) +{ + //if left mouse button is pressed + if (m_mouseState.rgbButtons[0]) + { + float dx = (static_cast( m_mouseState.lX)/150); + float dy = (static_cast( m_mouseState.lY)/150); + + // + Pitch=dy; + RotateY=dx; + + } +} +bool InputClass::IsMousePressed() +{ + if (m_mouseState.rgbButtons[0]) + { + return true; + } + return false; +} +bool InputClass::IsKeyPressed(int key) +{ + if( m_keyboardState[key] & 0x80 ) + return true; + + return false; +} diff --git a/Code/Input/L_inputClass.h b/Code/Input/L_inputClass.h new file mode 100644 index 00000000..b5a08c31 --- /dev/null +++ b/Code/Input/L_inputClass.h @@ -0,0 +1,45 @@ +#ifndef _INPUTCLASS_H_ +#define _INPUTCLASS_H_ + + +#define DIRECTINPUT_VERSION 0x0800 + +#pragma comment(lib, "dinput8.lib") +#pragma comment(lib, "dxguid.lib") + +#include + + + +class InputClass +{ +private: + IDirectInput8* m_directInput; + IDirectInputDevice8* m_keyboard; + IDirectInputDevice8* m_mouse; + + unsigned char m_keyboardState[256]; + DIMOUSESTATE m_mouseState; + + bool ReadKeyboard(); + bool ReadMouse(); + + +public: + + InputClass(); + ~InputClass(); + + // Initialize DirectInput8Create and acquire the mouse and keyboard + bool Initialize(HINSTANCE, HWND, int, int); + + //read the mouse and keyboard and send back + // delta mouse pos and if any button is pressed + bool Update(); + + bool IsKeyPressed(int key); + bool IsMousePressed(); + void MouseMove(float &Pitch, float &RoateY); +}; + +#endif \ No newline at end of file diff --git a/Code/Misc/Misc.vcxproj b/Code/Misc/Misc.vcxproj index ca39cada..e2947725 100644 --- a/Code/Misc/Misc.vcxproj +++ b/Code/Misc/Misc.vcxproj @@ -150,17 +150,12 @@ - - - - - diff --git a/Code/Misc/Misc.vcxproj.filters b/Code/Misc/Misc.vcxproj.filters index abee7ddd..6eae993b 100644 --- a/Code/Misc/Misc.vcxproj.filters +++ b/Code/Misc/Misc.vcxproj.filters @@ -33,12 +33,6 @@ Source Files - - Source Files - - - Source Files - @@ -56,14 +50,5 @@ Header Files - - Header Files - - - Header Files - - - Header Files - \ No newline at end of file diff --git a/Code/Misc/Resource/Loaders/ByteLoader.cpp b/Code/Misc/Resource/Loaders/ByteLoader.cpp index b20364ff..ee1538d9 100644 --- a/Code/Misc/Resource/Loaders/ByteLoader.cpp +++ b/Code/Misc/Resource/Loaders/ByteLoader.cpp @@ -1,6 +1,3 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// #include "..\OResource.h" #include "..\..\Utilities.h" diff --git a/Code/Misc/Resource/Loaders/CustomLoader.cpp.orig b/Code/Misc/Resource/Loaders/CustomLoader.cpp.orig new file mode 100644 index 00000000..15dea599 --- /dev/null +++ b/Code/Misc/Resource/Loaders/CustomLoader.cpp.orig @@ -0,0 +1,65 @@ + +#include "..\OResource.h" +#include "..\..\Utilities.h" + +#include + +using namespace Oyster::Resource; + + +OResource* OResource::CustomLoader(const wchar_t filename[], CustomLoadFunction fnc) +{ +<<<<<<< HEAD + const CustomData &data = fnc(); +======= + CustomData data; + memset(&data, 0, sizeof(CustomData)); + + fnc(filename, data); + + if(!data.loadedData) + { + return 0; + } + if(!data.resourceUnloadFnc) + { + return 0; + } + /** For some wierd reason that i don't understand when trying to send data.loadedData directly as a + * parameter to OResource constructor, the value is changed when it arrives in the constructor. + * Doing it like this, storing in a temporary variable, the value stays correct. (What the fuck! I must be overloking something...)*/ + //OHRESOURCE temp = data.loadedData; + OResource *resource = new OResource(data.loadedData, ResourceType_UNKNOWN, 0, 0, filename); +>>>>>>> origin/MiscBranch + + resource->customData = new CustomResourceData(); + resource->customData->unloadingFunction = data.resourceUnloadFnc; + resource->customData->loadingFunction = fnc; + + return resource; +} +void OResource::CustomUnloader() +{ + this->customData->unloadingFunction(this->resourceData); +} +OResource* OResource::CustomReloader() +{ + CustomUnloader(); + +<<<<<<< HEAD + const CustomData &data = this->customData->loadingFunction(); +======= + CustomData data; + memset(&data, 0, sizeof(CustomData)); + + this->customData->loadingFunction(this->resourceFilename.c_str(), data); +>>>>>>> origin/MiscBranch + this->resourceData = (OHRESOURCE)data.loadedData; + + if(data.resourceUnloadFnc) + { + this->customData->unloadingFunction = data.resourceUnloadFnc; + } + return this; +} + diff --git a/Code/Misc/Resource/OResource.cpp b/Code/Misc/Resource/OResource.cpp index e2aab644..f1dc1c63 100644 --- a/Code/Misc/Resource/OResource.cpp +++ b/Code/Misc/Resource/OResource.cpp @@ -1,7 +1,3 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// - #include "OResource.h" using namespace Oyster::Resource; diff --git a/Code/Misc/Resource/OResource.h b/Code/Misc/Resource/OResource.h index a0573c92..3b0d0c17 100644 --- a/Code/Misc/Resource/OResource.h +++ b/Code/Misc/Resource/OResource.h @@ -61,7 +61,7 @@ namespace Oyster static OResource* Reload (OResource* resource); static bool Release (OResource* resource); - Utility::DynamicMemory::ReferenceCount resourceRef; + Utility::DynamicMemory::RefCount resourceRef; private: static OResource* ByteLoader (const wchar_t filename[], ResourceType type, OResource* old = 0); diff --git a/Code/Misc/Resource/OResourceHandler.cpp.orig b/Code/Misc/Resource/OResourceHandler.cpp.orig new file mode 100644 index 00000000..923ab706 --- /dev/null +++ b/Code/Misc/Resource/OResourceHandler.cpp.orig @@ -0,0 +1,258 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + + +#include "OysterResource.h" +#include "OResource.h" +#include +#include + +using namespace Oyster::Resource; + +class ResourcePrivate +{ +public: + + std::map resources; + + OResource* FindResource(const OHRESOURCE& h) const; + OResource* FindResource(const wchar_t c[]) const; + void SaveResource(OResource* r, bool addNew = true); + +} resourcePrivate; + + +OHRESOURCE OysterResource::LoadResource(const wchar_t* filename, ResourceType type, int customID, bool force) +{ + if(!filename) return 0; + + OResource *resourceData = resourcePrivate.FindResource(filename); + + if(resourceData) + { + if(force) + { + return OysterResource::ReloadResource(filename); + } + else + { + //Add new reference + resourcePrivate.SaveResource(resourceData, false); + return resourceData->GetResourceHandle(); + } + } + else + { + resourceData = OResource::Load(filename, type); + if(resourceData) + { + resourceData->SetResourceID(customID); + resourcePrivate.SaveResource(resourceData); + } + } + + return resourceData->GetResourceHandle(); +} +OHRESOURCE OysterResource::LoadResource(const wchar_t filename[], CustomLoadFunction loadFnc, int customId, bool force) +{ + if(!filename) + { + return 0; + } + if(!loadFnc) + { + return 0; + } + + OResource *resourceData = resourcePrivate.FindResource(filename); + if(resourceData) + { + if(force) + { + return OysterResource::ReloadResource(filename); + } + else + { + //Add new reference + resourcePrivate.SaveResource(resourceData, false); + return resourceData->GetResourceHandle(); + } + } + else + { + resourceData = OResource::Load(filename, loadFnc); + if(resourceData) + { + resourceData->SetResourceID(customId); + resourcePrivate.SaveResource(resourceData); + } + } +<<<<<<< HEAD + + resourceData = OResource::Load(filename, loadFnc); + + if(!resourceData) return 0; + + if(resourceData) resourceData->SetResourceID(CustomId); + resourcePrivate.SaveResource(resourceData); +======= +>>>>>>> origin/MiscBranch + + return (OHRESOURCE)resourceData->GetResourceHandle(); +} + +OHRESOURCE OysterResource::ReloadResource(const wchar_t filename[]) +{ + OResource *resourceData = resourcePrivate.FindResource(filename); + if(!resourceData) return 0; //The resource has not been loaded + + return OResource::Reload(resourceData)->GetResourceHandle(); +} +OHRESOURCE OysterResource::ReloadResource(OHRESOURCE resource) +{ + OResource *resourceData = resourcePrivate.FindResource(resource); + if(!resourceData) return 0; //The resource has not been loaded + + return OResource::Reload(resourceData)->GetResourceHandle(); +} + +void OysterResource::Clean() +{ + auto i = resourcePrivate.resources.begin(); + auto last = resourcePrivate.resources.end(); + + for (i; i != last; i++) + { + //Remove all the references + while (!OResource::Release(i->second)); + + const wchar_t* temp = i->second->GetResourceFilename(); + delete resourcePrivate.resources[temp]; + resourcePrivate.resources.erase(temp); + + } +} +void OysterResource::ReleaseResource(const OHRESOURCE& resourceData) +{ + OResource* t = resourcePrivate.FindResource(resourceData); + if(t) + { + if(OResource::Release(t)) + { + const wchar_t* temp = t->GetResourceFilename(); + delete resourcePrivate.resources[temp]; + resourcePrivate.resources.erase(temp); + } + } +} +void OysterResource::ReleaseResource(const wchar_t filename[]) +{ + OResource* t = resourcePrivate.FindResource(filename); + if(t) + { + if(OResource::Release(t)) + { + const wchar_t* temp = t->GetResourceFilename(); + delete resourcePrivate.resources[temp]; + resourcePrivate.resources.erase(temp); + } + } +} + +void OysterResource::SetResourceId (const OHRESOURCE& resourceData, unsigned int id) +{ + OResource* t = resourcePrivate.FindResource(resourceData); + + if(t) t->SetResourceID(id); +} +void OysterResource::SetResourceId(const wchar_t c[], unsigned int id) +{ + OResource* t = resourcePrivate.FindResource(c); + + if(t) t->SetResourceID(id); +} +ResourceType OysterResource::GetResourceType (const OHRESOURCE& resourceData) +{ + OResource* t = resourcePrivate.FindResource(resourceData); + + if(t) return t->GetResourceType(); + + return ResourceType_INVALID; +} +ResourceType OysterResource::GetResourceType (const wchar_t c[]) +{ + OResource* t = resourcePrivate.FindResource(c); + + if(t) return t->GetResourceType(); + + return ResourceType_INVALID; +} +const wchar_t* OysterResource::GetResourceFilename (const OHRESOURCE& resourceData) +{ + OResource* t = resourcePrivate.FindResource(resourceData); + + if(t) return t->GetResourceFilename(); + + return 0; +} +OHRESOURCE OysterResource::GetResourceHandle(const wchar_t filename[]) +{ + OResource* t = resourcePrivate.FindResource(filename); + + if(t) return t->GetResourceHandle(); + + return 0; +} +int OysterResource::GetResourceId (const OHRESOURCE& resourceData) +{ + OResource* t = resourcePrivate.FindResource(resourceData); + + if(t) return t->GetResourceID(); + + return -1; +} +int OysterResource::GetResourceId(const wchar_t c[]) +{ + OResource* t = resourcePrivate.FindResource(c); + + if(t) return t->GetResourceID(); + + return -1; +} + + +OResource* ResourcePrivate::FindResource(const OHRESOURCE& h) const +{ + for (auto i = this->resources.begin(); i != this->resources.end() ; i++) + { + if(i->second->GetResourceHandle() == h) + { + return i->second; + } + } + return 0; +} +OResource* ResourcePrivate::FindResource(const wchar_t c[]) const +{ + std::wstring temp = c; + auto t = this->resources.find(c); + if(t == this->resources.end()) return 0; + + return t->second; +} +void ResourcePrivate::SaveResource( OResource* r, bool addNew ) +{ + if(!r) return; + + if(addNew) + { + this->resources[r->GetResourceFilename()] = r; + } + + r->resourceRef.Incref(); +} + + + + diff --git a/Code/Misc/Resource/OysterResource.h b/Code/Misc/Resource/OysterResource.h index 4906e6c7..d6509b54 100644 --- a/Code/Misc/Resource/OysterResource.h +++ b/Code/Misc/Resource/OysterResource.h @@ -28,7 +28,7 @@ namespace Oyster ResourceType_Byte_UNICODE, /**< Handle can be interpeted as char[] or char* */ ResourceType_Byte_UTF16LE, /**< Handle can be interpeted as char[] or char* */ - ResourceType_COUNT, /**< Not used. */ + ResourceType_COUNT, /**< Handle can be interpeted as ? */ ResourceType_UNKNOWN = -1, /**< Handle can be interpeted as void* */ ResourceType_INVALID = -2, /**< Invalid or non existing resource */ diff --git a/Code/Misc/Resource/OysterResource.h.orig b/Code/Misc/Resource/OysterResource.h.orig new file mode 100644 index 00000000..906b77fb --- /dev/null +++ b/Code/Misc/Resource/OysterResource.h.orig @@ -0,0 +1,164 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + +#ifndef MISC_OYSTER_RESOURCE_H +#define MISC_OYSTER_RESOURCE_H + + +namespace Oyster +{ + namespace Resource + { + struct CustomData; + /** A Resource handle representing various resources */ +<<<<<<< HEAD + typedef unsigned long OHRESOURCE; + typedef void(*CustomUnloadFunction)(void*); + typedef const CustomData&(*CustomLoadFunction)(); +======= + typedef void* OHRESOURCE; + /** Typedef on a fuction required for custom unloading */ + typedef void(*CustomUnloadFunction)(void* loadedData); + /** Typedef on a fuction required for custom loading */ + typedef void(*CustomLoadFunction)(const wchar_t filename[], CustomData& outData); +>>>>>>> origin/MiscBranch + + /** An enum class representing all avalible resources that is supported. */ + enum ResourceType + { + //Byte + ResourceType_Byte_Raw, /**< Handle can be interpeted as char[] or char* */ + ResourceType_Byte_ANSI, /**< Handle can be interpeted as char[] or char* */ + ResourceType_Byte_UTF8, /**< Handle can be interpeted as char[] or char* */ + ResourceType_Byte_UNICODE, /**< Handle can be interpeted as char[] or char* */ + ResourceType_Byte_UTF16LE, /**< Handle can be interpeted as char[] or char* */ + + ResourceType_COUNT, /**< Handle can be interpeted as ? */ + + ResourceType_UNKNOWN = -1, /**< Handle can be interpeted as void* */ + ResourceType_INVALID = -2, /**< Invalid or non existing resource */ + }; + + /** A struct to fill when doing a custom resource Load. */ + struct CustomData + { + void* loadedData; // +#include +#include + +namespace Oyster +{ + namespace Thread + { + class OysterMutex + { + public: + OysterMutex(); + OysterMutex(bool initialOwnership); + virtual~OysterMutex(); + void LockMutex(); + void LockMutex(unsigned int timeSpan); + void UnlockMutex(); + /** Returns true if mutex is taken */ + bool IsTaken(); + + private: + std::mutex mutex; + std::thread::id id; + + OysterMutex(const OysterMutex&); + }; + } +} + +#endif // !MISC_OYSTER_MUTEX_H diff --git a/Code/Misc/Thread/OysterThread.h b/Code/Misc/Thread/OysterThread.h.orig similarity index 100% rename from Code/Misc/Thread/OysterThread.h rename to Code/Misc/Thread/OysterThread.h.orig diff --git a/Code/Misc/Thread/OysterThread_Impl.cpp b/Code/Misc/Thread/OysterThread_Impl.cpp.orig similarity index 100% rename from Code/Misc/Thread/OysterThread_Impl.cpp rename to Code/Misc/Thread/OysterThread_Impl.cpp.orig diff --git a/Code/Misc/Utilities-InlineImpl.h b/Code/Misc/Utilities-InlineImpl.h index 0cd164d8..50d13652 100644 --- a/Code/Misc/Utilities-InlineImpl.h +++ b/Code/Misc/Utilities-InlineImpl.h @@ -2,7 +2,6 @@ // Inline and template implementations for // the Utility Collection of Miscellanious Handy Functions // © Dan Andersson 2013 -// © Dennis Andersen 2013 TODO: Is this correct? ///////////////////////////////////////////////////////////////////// #ifndef UTILITIES_INLINE_IMPL_H @@ -38,6 +37,14 @@ namespace Utility this->ownedInstance = assignedInstance; } + template + UniquePointer::UniquePointer( const UniquePointer &donor ) + { + this->ownedInstance = donor.ownedInstance; + donor.ownedInstance = NULL; + + } + template UniquePointer::~UniquePointer() { @@ -91,6 +98,18 @@ namespace Utility return this->ownedInstance != NULL; } + template + bool UniquePointer::operator == ( Type *stray ) const + { + return this->ownedInstance == stray; + } + + template + bool UniquePointer::operator != ( Type *stray ) const + { + return this->ownedInstance != stray; + } + template Type* UniquePointer::Release() { @@ -111,6 +130,14 @@ namespace Utility this->ownedArray = assignedArray; } + template + UniqueArray::UniqueArray( const UniqueArray &donor ) + { + this->ownedArray = donor.ownedArray; + donor.ownedArray = NULL; + + } + template UniqueArray::~UniqueArray() { @@ -150,7 +177,20 @@ namespace Utility return this->ownedArray != NULL; } - templateType* UniqueArray::Release() + template + bool UniqueArray::operator == ( Type *stray ) const + { + return this->ownedArray == stray; + } + + template + bool UniqueArray::operator != ( Type *stray ) const + { + return this->ownedArray != stray; + } + + template + Type* UniqueArray::Release() { Type *copy = this->ownedArray; this->ownedArray = NULL; @@ -162,7 +202,7 @@ namespace Utility { return this->operator bool(); } - + namespace SmartPointer { template void StdSmartPointer::Destroy() diff --git a/Code/Misc/Utilities-InlineImpl.h.orig b/Code/Misc/Utilities-InlineImpl.h.orig new file mode 100644 index 00000000..107ea730 --- /dev/null +++ b/Code/Misc/Utilities-InlineImpl.h.orig @@ -0,0 +1,315 @@ +///////////////////////////////////////////////////////////////////// +// Inline and template implementations for +// the Utility Collection of Miscellanious Handy Functions +// © Dan Andersson 2013 +///////////////////////////////////////////////////////////////////// + +#ifndef UTILITIES_INLINE_IMPL_H +#define UTILITIES_INLINE_IMPL_H + +#include "Utilities.h" + +namespace Utility +{ + namespace DynamicMemory + { + template + inline void SafeDeleteInstance( Type *dynamicInstance ) + { + if( dynamicInstance ) + { + delete dynamicInstance; + } + } + + template + void SafeDeleteArray( Type dynamicArray[] ) + { + if( dynamicArray ) + { + delete [] dynamicArray; + } + } + + template + UniquePointer::UniquePointer( Type *assignedInstance ) + { + this->ownedInstance = assignedInstance; + } + + template + UniquePointer::UniquePointer( const UniquePointer &donor ) + { + this->ownedInstance = donor.ownedInstance; + donor.ownedInstance = NULL; + + } + + template + UniquePointer::~UniquePointer() + { + SafeDeleteInstance( this->ownedInstance ); + } + + template + UniquePointer & UniquePointer::operator = ( Type *assignedInstance ) + { + SafeDeleteInstance( this->ownedInstance ); + this->ownedInstance = assignedInstance; + return *this; + } + + template + UniquePointer & UniquePointer::operator = ( const UniquePointer &donor ) + { + SafeDeleteInstance( this->ownedInstance ); + this->ownedInstance = donor.ownedInstance; + donor.ownedInstance = NULL; + return *this; + } + + template + UniquePointer::operator Type* () + { + return this->ownedInstance; + } + + template + UniquePointer::operator const Type* () const + { + return this->ownedInstance; + } + + template + Type * UniquePointer::operator -> () + { + return this->ownedInstance; + } + + template + const Type * UniquePointer::operator -> () const + { + return this->ownedInstance; + } + + template + UniquePointer::operator bool() const + { + return this->ownedInstance != NULL; + } + + template + bool UniquePointer::operator == ( Type *stray ) const + { + return this->ownedInstance == stray; + } + + template + bool UniquePointer::operator != ( Type *stray ) const + { + return this->ownedInstance != stray; + } + + template + Type* UniquePointer::Release() + { + Type *copy = this->ownedInstance; + this->ownedInstance = NULL; + return copy; + } + + template + inline bool UniquePointer::HaveOwnership() const + { + return this->operator bool(); + } + + template + UniqueArray::UniqueArray( Type assignedArray[] ) + { + this->ownedArray = assignedArray; + } + + template + UniqueArray::UniqueArray( const UniqueArray &donor ) + { + this->ownedArray = donor.ownedArray; + donor.ownedArray = NULL; + + } + + template + UniqueArray::~UniqueArray() + { + SafeDeleteArray( this->ownedArray ); + } + + template + UniqueArray & UniqueArray::operator = ( Type assignedArray[] ) + { + SafeDeleteArray( this->ownedArray ); + this->ownedArray = assignedArray; + } + + template + UniqueArray & UniqueArray::operator = ( const UniqueArray &donor ) + { + SafeDeleteArray( this->ownedArray ); + this->ownedArray = donor.ownedInstance; + donor.owned = NULL; + } + + template template + Type & UniqueArray::operator [] ( Index i ) + { + return this->ownedArray[i]; + } + + template template + const Type & UniqueArray::operator [] ( Index i ) const + { + return this->ownedArray[i]; + } + + template + UniqueArray::operator bool () const + { + return this->ownedArray != NULL; + } + + template + bool UniqueArray::operator == ( Type *stray ) const + { + return this->ownedArray == stray; + } + + template + bool UniqueArray::operator != ( Type *stray ) const + { + return this->ownedArray != stray; + } + + template + Type* UniqueArray::Release() + { + Type *copy = this->ownedArray; + this->ownedArray = NULL; + return copy; + } + + template + inline bool UniqueArray::HaveOwnership() const + { + return this->operator bool(); + } +<<<<<<< HEAD +======= + + namespace SmartPointer + { + template void StdSmartPointer::Destroy() + { + delete this->_rc; + this->_rc = NULL; + delete this->_ptr; + this->_ptr = NULL; + } + template StdSmartPointer::StdSmartPointer() + :_rc(0), _ptr(0) + { } + template StdSmartPointer::StdSmartPointer(T* p) + :_ptr(p) + { + this->_rc = new ReferenceCount(); + this->_rc->Incref(); + } + template StdSmartPointer::StdSmartPointer(const StdSmartPointer& d) + :_ptr(d._ptr), _rc(d._rc) + { + if(this->_rc) + this->_rc->Incref(); + } + template StdSmartPointer::~StdSmartPointer() + { + if (this->_rc && this->_rc->Decref() == 0) + { + Destroy(); + } + } + template StdSmartPointer& StdSmartPointer::operator= (const StdSmartPointer& p) + { + if (this != &p) + { + //Last to go? + if(this->_rc && this->_rc->Decref() == 0) + { + //Call child specific + Destroy(); + } + + this->_ptr = p._ptr; + this->_rc = p._rc; + this->_rc->Incref(); + } + return *this; + } + template StdSmartPointer& StdSmartPointer::operator= (T* p) + { + if (this->_ptr != p) + { + //Last to go? + if(this->_rc) + { + if(this->_rc->Decref() == 0) + { + //Call child specific + Destroy(); + this->_rc = new ReferenceCount(); + } + } + else + this->_rc = new ReferenceCount(); + + this->_ptr = p; + this->_rc->Incref(); + } + return *this; + } + template inline bool StdSmartPointer::operator== (const StdSmartPointer& d) + { + return d._ptr == this->_ptr; + } + template inline bool StdSmartPointer::operator== (const T& p) + { + return &p == this->_ptr; + } + template inline T& StdSmartPointer::operator* () + { + return *this->_ptr; + } + template inline T* StdSmartPointer::operator-> () + { + return this->_ptr; + } + template inline StdSmartPointer::operator T* () + { + return this->_ptr; + } + template inline StdSmartPointer::operator bool() + { + return (this->_ptr != 0); + } + template inline T* StdSmartPointer::Get() + { + return this->_ptr; + } + template inline bool StdSmartPointer::IsValid() + { + return (this->_ptr != NULL) ? true : false; + } + } +>>>>>>> origin/MiscBranch + } +} + +#endif \ No newline at end of file diff --git a/Code/Misc/Utilities.h b/Code/Misc/Utilities.h index f34907de..2294918e 100644 --- a/Code/Misc/Utilities.h +++ b/Code/Misc/Utilities.h @@ -1,8 +1,7 @@ -///////////////////////////////////////////////////////////////////// +//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//! // Utility Collection of Miscellanious Handy Functions // © Dan Andersson 2013 -// © Dennis Andersen 2013 -///////////////////////////////////////////////////////////////////// +//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//! #ifndef UTILITIES_H #define UTILITIES_H @@ -18,50 +17,60 @@ namespace Utility { namespace DynamicMemory { - /// If dynamicInstance is not NULL, then delete + //! If dynamicInstance is not NULL, then delete template void SafeDeleteInstance( Type *dynamicInstance ); - /// If dynamicArray is not NULL, then delete [] + //! If dynamicArray is not NULL, then delete [] template void SafeDeleteArray( Type dynamicArray[] ); - template - struct UniquePointer - { /// Wrapper to safely transfer dynamic ownership/responsibility + //! Wrapper to safely transfer dynamic ownership/responsibility + template struct UniquePointer + { public: - /// Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. - /// If NULL is assigned is equavalent with clearing all responsibilities from this UniquePointer. + //! Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. + //! If NULL is assigned is equivalent with clearing all responsibilities from this UniquePointer. UniquePointer( Type *assignedInstance = NULL ); - /// Will auto delete assigned dynamic instance. + //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. + //! If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. + UniquePointer( const UniquePointer &donor ); + + //! Will auto delete assigned dynamic instance. ~UniquePointer(); - /// Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. - /// If NULL is assigned is equavalent with clearing all responsibilities from this UniquePointer. + //! Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. + //! If NULL is assigned is equivalent with clearing all responsibilities from this UniquePointer. UniquePointer & operator = ( Type *assignedInstance ); - /// Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. - /// If donor had nothing, is equavalent with clearing all responsibilities from this UniquePointer. + //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. + //! If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. UniquePointer & operator = ( const UniquePointer &donor ); - /// Access the assigned dynamic instance. Will crash if nothing there + //! Access the assigned dynamic instance. Will crash if nothing there operator Type* (); - /// Access the assigned dynamic instance. Will crash if nothing there + //! Access the assigned dynamic instance. Will crash if nothing there operator const Type* () const; - /// Access members of the assigned dynamic instance. Will crash if nothing there + //! Access members of the assigned dynamic instance. Will crash if nothing there Type * operator -> (); - /// Access members of the assigned dynamic instance. Will crash if nothing there + //! Access members of the assigned dynamic instance. Will crash if nothing there const Type * operator -> () const; - /// If true, this UniquePointer have a current ownership/responsibility of a dynamic instance. + //! If true, this UniquePointer have a current ownership/responsibility of a dynamic instance. operator bool () const; - /// This UniquePointer drops all claims of ownership/responsibility and returns the dynamic instance. Now it is your responsibility to delete. + //! @return true if this ownedInstance matches with stray + bool operator == ( Type *stray ) const; + + //! @return false if this ownedInstance matches with stray + bool operator != ( Type *stray ) const; + + //! This UniquePointer drops all claims of ownership/responsibility and returns the dynamic instance. Now it is your responsibility to delete. Type* Release(); - /// (inline) If true, this UniquePointer have a current ownership/responsibility of a dynamic instance. + //! (inline) If true, this UniquePointer have a current ownership/responsibility of a dynamic instance. bool HaveOwnership() const; private: @@ -70,38 +79,48 @@ namespace Utility template struct UniqueArray - { /// Wrapper to safely transfer dynamic ownership/responsibility + { //! Wrapper to safely transfer dynamic ownership/responsibility public: - /// Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. - /// If NULL is assigned is equavalent with clearing all responsibilities from this UniqueArray. + //! Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. + //! If NULL is assigned is equivalent with clearing all responsibilities from this UniqueArray. UniqueArray( Type assignedArray[] = NULL ); - /// Will auto delete assigned dynamic array. + //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. + //! If donor had nothing, is equivalent with clearing all responsibilities from this UniqueArray. + UniqueArray( const UniqueArray &donor ); + + //! Will auto delete assigned dynamic array. ~UniqueArray(); - /// Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. - /// If NULL is assigned is equavalent with clearing all responsibilities from this UniqueArray. + //! Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. + //! If NULL is assigned is equivalent with clearing all responsibilities from this UniqueArray. UniqueArray & operator = ( Type assignedArray[] ); - /// Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. - /// If donor had nothing, is equavalent with clearing all responsibilities from this UniqueArray. + //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. + //! If donor had nothing, is equivalent with clearing all responsibilities from this UniqueArray. UniqueArray & operator = ( const UniqueArray &donor ); - /// Accesses the instance at index i of this UniqeArray's owned dynamic array. - /// Will crash if out-of-bound or there is no assigned array. + //! Accesses the instance at index i of this UniqeArray's owned dynamic array. + //! Will crash if out-of-bound or there is no assigned array. template Type & operator [] ( Index i ); - /// Accesses the instance at index i of this UniqeArray's owned dynamic array. - /// Will crash if out-of-bound or there is no assigned array. + //! Accesses the instance at index i of this UniqeArray's owned dynamic array. + //! Will crash if out-of-bound or there is no assigned array. template const Type & operator [] ( Index i ) const; - /// If true, this UniqueArray have a current ownership/responsibility of a dynamic instance. + //! If true, this UniqueArray have a current ownership/responsibility of a dynamic instance. operator bool () const; - /// This UniqueArray drops all claims of ownership/responsibility and returns the dynamic array. Now it is your responsibility to delete. + //! @return true if this ownedInstance matches with stray + bool operator == ( Type *stray ) const; + + //! @return false if this ownedInstance matches with stray + bool operator != ( Type *stray ) const; + + //! This UniqueArray drops all claims of ownership/responsibility and returns the dynamic array. Now it is your responsibility to delete. Type* Release(); - /// (inline) If true, this UniqueArray have a current ownership/responsibility of a dynamic array. + //! (inline) If true, this UniqueArray have a current ownership/responsibility of a dynamic array. bool HaveOwnership() const; private: @@ -260,7 +279,7 @@ namespace Utility inline ValueType Degree( const ValueType &radian ) { return radian * (180.0f / 3.1415926535897932384626433832795f); } - // SPECIALIZATIONS ////////////////////////////////////////// + // SPECIALIZATIONS //!//!//!//!//!//!//!//!//!//!//!//!//!//! template<> inline char Average( const char &valueA, const char &valueB ) { return (valueA + valueB) >> 1; } diff --git a/Code/Misc/Utilities.h.orig b/Code/Misc/Utilities.h.orig new file mode 100644 index 00000000..55c4820f --- /dev/null +++ b/Code/Misc/Utilities.h.orig @@ -0,0 +1,347 @@ +//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//! +// Utility Collection of Miscellanious Handy Functions +// © Dan Andersson 2013 +//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//! + +#ifndef UTILITIES_H +#define UTILITIES_H + +#include +#include +#include +#include +#include +#include + +namespace Utility +{ + namespace DynamicMemory + { + //! If dynamicInstance is not NULL, then delete + template void SafeDeleteInstance( Type *dynamicInstance ); + + //! If dynamicArray is not NULL, then delete [] + template void SafeDeleteArray( Type dynamicArray[] ); + + //! Wrapper to safely transfer dynamic ownership/responsibility + template struct UniquePointer + { + public: + //! Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. + //! If NULL is assigned is equivalent with clearing all responsibilities from this UniquePointer. + UniquePointer( Type *assignedInstance = NULL ); + + //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. + //! If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. + UniquePointer( const UniquePointer &donor ); + + //! Will auto delete assigned dynamic instance. + ~UniquePointer(); + + //! Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. + //! If NULL is assigned is equivalent with clearing all responsibilities from this UniquePointer. + UniquePointer & operator = ( Type *assignedInstance ); + + //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. + //! If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. + UniquePointer & operator = ( const UniquePointer &donor ); + + //! Access the assigned dynamic instance. Will crash if nothing there + operator Type* (); + + //! Access the assigned dynamic instance. Will crash if nothing there + operator const Type* () const; + + //! Access members of the assigned dynamic instance. Will crash if nothing there + Type * operator -> (); + + //! Access members of the assigned dynamic instance. Will crash if nothing there + const Type * operator -> () const; + + //! If true, this UniquePointer have a current ownership/responsibility of a dynamic instance. + operator bool () const; + + //! @return true if this ownedInstance matches with stray + bool operator == ( Type *stray ) const; + + //! @return false if this ownedInstance matches with stray + bool operator != ( Type *stray ) const; + + //! This UniquePointer drops all claims of ownership/responsibility and returns the dynamic instance. Now it is your responsibility to delete. + Type* Release(); + + //! (inline) If true, this UniquePointer have a current ownership/responsibility of a dynamic instance. + bool HaveOwnership() const; + + private: + mutable Type *ownedInstance; + }; + + template + struct UniqueArray + { //! Wrapper to safely transfer dynamic ownership/responsibility + public: + //! Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. + //! If NULL is assigned is equivalent with clearing all responsibilities from this UniqueArray. + UniqueArray( Type assignedArray[] = NULL ); + + //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. + //! If donor had nothing, is equivalent with clearing all responsibilities from this UniqueArray. + UniqueArray( const UniqueArray &donor ); + + //! Will auto delete assigned dynamic array. + ~UniqueArray(); + + //! Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. + //! If NULL is assigned is equivalent with clearing all responsibilities from this UniqueArray. + UniqueArray & operator = ( Type assignedArray[] ); + + //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. + //! If donor had nothing, is equivalent with clearing all responsibilities from this UniqueArray. + UniqueArray & operator = ( const UniqueArray &donor ); + + //! Accesses the instance at index i of this UniqeArray's owned dynamic array. + //! Will crash if out-of-bound or there is no assigned array. + template Type & operator [] ( Index i ); + + //! Accesses the instance at index i of this UniqeArray's owned dynamic array. + //! Will crash if out-of-bound or there is no assigned array. + template const Type & operator [] ( Index i ) const; + + //! If true, this UniqueArray have a current ownership/responsibility of a dynamic instance. + operator bool () const; + + //! @return true if this ownedInstance matches with stray + bool operator == ( Type *stray ) const; + + //! @return false if this ownedInstance matches with stray + bool operator != ( Type *stray ) const; + + //! This UniqueArray drops all claims of ownership/responsibility and returns the dynamic array. Now it is your responsibility to delete. + Type* Release(); + + //! (inline) If true, this UniqueArray have a current ownership/responsibility of a dynamic array. + bool HaveOwnership() const; + + private: + mutable Type *ownedArray; + }; + + struct RefCount + { + private: + std::atomic count; + + public: +<<<<<<< HEAD + RefCount() :count(0) { } + RefCount(const RefCount& o) { count = o.count; } + const RefCount& operator=(const RefCount& o) { count = o.count; return *this;} + void Incref() { this->count++; } + void Incref(int c) { this->count += c; } + int Decref() { return --this->count;} + void Reset() { this->count = 0; } + }; +======= + ReferenceCount() :count(0) { } + ReferenceCount(const ReferenceCount& o) { count.store(o.count); } + inline const ReferenceCount& operator=(const ReferenceCount& o) { count.store(o.count); return *this;} + inline void Incref() { this->count++; } + inline void Incref(int c) { this->count += c; } + inline int Decref() { return --this->count;} + inline void Reset() { this->count = 0; } + }; + + namespace SmartPointer + { + //! Smart pointer for a regular object. + /** + * Regular objects, objects that is deleted normaly (ie not COM objects, or array pointers) + * can use this class to easy the use of dynamic memory + */ + template + struct StdSmartPointer + { + private: + ReferenceCount *_rc; + T *_ptr; + + /** Destroys the pointer and returns the memory allocated. */ + void Destroy(); + + public: + StdSmartPointer(); + StdSmartPointer(T* p); + StdSmartPointer(const StdSmartPointer& d); + virtual~StdSmartPointer(); + StdSmartPointer& operator= (const StdSmartPointer& p); + StdSmartPointer& operator= (T* p); + bool operator== (const StdSmartPointer& d); + bool operator== (const T& p); + T& operator* (); + T* operator-> (); + operator T* (); + operator bool(); + + /** + * Returns the connected pointer */ + T* Get(); + + /** Checks if the pointer is valid (not NULL) + Returns true for valid, else false. */ + bool IsValid(); + }; + } + + +>>>>>>> origin/MiscBranch + } + + namespace String + { + // string + + ::std::vector<::std::string> & Split( ::std::vector<::std::string> &output, const ::std::string &str, char delim, ::std::string::size_type offset = 0 ); + ::std::vector<::std::string> & Split( ::std::vector<::std::string> &output, const ::std::string &str, const ::std::string &delim, ::std::string::size_type offset = 0 ); + ::std::vector<::std::string> & Split( ::std::vector<::std::string> &output, const ::std::string &str, const ::std::vector<::std::string> &delim, ::std::string::size_type offset = 0 ); + ::std::string Trim( const ::std::string &str ); + ::std::string & ToLowerCase( ::std::string &output, const ::std::string &str ); + ::std::string & ToLowerCase( ::std::string &str ); + ::std::string & ToUpperCase( ::std::string &output, const ::std::string &str ); + ::std::string & ToUpperCase( ::std::string &str ); + ::std::string & ExtractDirPath( ::std::string &output, const ::std::string &file, char dirDelimeter ); + ::std::string & ExtractDirPath( ::std::string &output, const ::std::string &file, const ::std::string &dirDelimeter ); + ::std::string & ReplaceCharacters( ::std::string &str, char characterToReplace, char newCharacter, const ::std::string::size_type &offset = 0, const ::std::string::size_type &end = ::std::string::npos ); + + // wstring + + ::std::vector<::std::wstring> & Split( ::std::vector<::std::wstring> &output, const ::std::wstring &str, char delim, ::std::wstring::size_type offset = 0 ); + ::std::vector<::std::wstring> & Split( ::std::vector<::std::wstring> &output, const ::std::wstring &str, const ::std::wstring &delim, ::std::wstring::size_type offset = 0 ); + ::std::vector<::std::wstring> & Split( ::std::vector<::std::wstring> &output, const ::std::wstring &str, const ::std::vector<::std::wstring> &delim, ::std::wstring::size_type offset = 0 ); + ::std::wstring & wToLowerCase( ::std::wstring &output, const ::std::wstring &str ); + ::std::wstring & wToLowerCase( ::std::wstring &str ); + + //To wstring + + ::std::wstring & StringToWstring( const ::std::string &str, ::std::wstring &wstr ); + ::std::string & WStringToString( const ::std::wstring &wstr, ::std::string &str ); + } + + namespace Stream + { + float* ReadFloats( float *output, ::std::istream &input, unsigned int numFloats ); + } + + namespace StaticArray + { + template + inline unsigned int NumElementsOf( const ScalarType(&)[num] ) + { return num; } + + template + inline ScalarType & FirstElementOf( ScalarType (&arr)[num] ) + { return arr[0]; } + + template + inline ScalarType & LastElementOf( ScalarType (&arr)[num] ) + { return arr[num-1]; } + } + + namespace Element + { + template + inline void Swap( ScalarType &elementA, ScalarType &elementB, ScalarType &swapSpace ) + { swapSpace = elementA; elementA = elementB; elementB = swapSpace; } + + template + inline void Swap( ScalarType &elementA, ScalarType &elementB ) + { ScalarType swapSpace; Swap( elementA, elementB, swapSpace ); } + } + + namespace Value + { + using ::std::numeric_limits; + + template + inline ValueType Abs( const ValueType &value ) + { return value < 0 ? value * -1 : value; } + + template + inline ValueType Max( const ValueType &valueA, const ValueType &valueB ) + { return valueA > valueB ? valueA : valueB; } + + template + inline ValueType Min( const ValueType &valueA, const ValueType &valueB ) + { return valueA < valueB ? valueA : valueB; } + + template + inline ValueType Average( const ValueType &valueA, const ValueType &valueB ) + { return (valueA + valueB) * 0.5f; } + + template + inline ValueType AverageWithDelta( const ValueType &origin, const ValueType &delta ) + { return origin + (delta * 0.5f); } + + template + inline ValueType Radian( const ValueType °ree ) + { return degree * (3.1415926535897932384626433832795f / 180.0f); } + + template + inline ValueType Degree( const ValueType &radian ) + { return radian * (180.0f / 3.1415926535897932384626433832795f); } + + // SPECIALIZATIONS //!//!//!//!//!//!//!//!//!//!//!//!//!//! + + template<> inline char Average( const char &valueA, const char &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline unsigned char Average( const unsigned char &valueA, const unsigned char &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline int Average( const int &valueA, const int &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline unsigned int Average( const unsigned int &valueA, const unsigned int &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline long Average( const long &valueA, const long &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline unsigned long Average( const unsigned long &valueA, const unsigned long &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline long long Average( const long long &valueA, const long long &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline unsigned long long Average( const unsigned long long &valueA, const unsigned long long &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline char AverageWithDelta( const char &origin, const char &delta ) + { return origin + (delta >> 1); } + + template<> inline unsigned char AverageWithDelta( const unsigned char &origin, const unsigned char &delta ) + { return origin + (delta >> 1); } + + template<> inline int AverageWithDelta( const int &origin, const int &delta ) + { return origin + (delta >> 1); } + + template<> inline unsigned int AverageWithDelta( const unsigned int &origin, const unsigned int &delta ) + { return origin + (delta >> 1); } + + template<> inline long AverageWithDelta( const long &origin, const long &delta ) + { return origin + (delta >> 1); } + + template<> inline unsigned long AverageWithDelta( const unsigned long &origin, const unsigned long &delta ) + { return origin + (delta >> 1); } + + template<> inline long long AverageWithDelta( const long long &origin, const long long &delta ) + { return origin + (delta >> 1); } + + template<> inline unsigned long long AverageWithDelta( const unsigned long long &origin, const unsigned long long &delta ) + { return origin + (delta >> 1); } + } +} + +#include "Utilities-InlineImpl.h" + +#endif \ No newline at end of file diff --git a/Code/OysterGraphics/Core/Buffer.cpp b/Code/OysterGraphics/Core/Buffer.cpp index f530239c..b34dd9c4 100644 --- a/Code/OysterGraphics/Core/Buffer.cpp +++ b/Code/OysterGraphics/Core/Buffer.cpp @@ -1,19 +1,18 @@ -#include "Buffer.h" #include "Core.h" using namespace Oyster::Graphics; -Buffer::Buffer() +Core::Buffer::Buffer() { mBuffer = NULL; } -Buffer::~Buffer() +Core::Buffer::~Buffer() { SAFE_RELEASE(mBuffer); } -HRESULT Buffer::Apply(UINT32 misc) const +HRESULT Core::Buffer::Apply(UINT32 misc) const { HRESULT hr = S_OK; @@ -59,7 +58,7 @@ HRESULT Buffer::Apply(UINT32 misc) const return hr; } -HRESULT Buffer::Init(const BUFFER_INIT_DESC& initDesc) +HRESULT Core::Buffer::Init(const BUFFER_INIT_DESC& initDesc) { D3D11_BUFFER_DESC bufferDesc; @@ -154,13 +153,13 @@ HRESULT Buffer::Init(const BUFFER_INIT_DESC& initDesc) if(FAILED(hr)) { - MessageBox(NULL, "Unable to create buffer.", "Slenda Error", MB_ICONERROR | MB_OK); + //MessageBox(NULL, L"Unable to create buffer.", L"Slenda Error", MB_ICONERROR | MB_OK); } return hr; } -void* Buffer::Map() +void* Core::Buffer::Map() { void* ret = NULL; if(mUsage == BUFFER_CPU_WRITE || mUsage == BUFFER_CPU_READ || mUsage == BUFFER_CPU_WRITE_DISCARD) @@ -192,17 +191,17 @@ void* Buffer::Map() } -void Buffer::Unmap() +void Core::Buffer::Unmap() { Core::deviceContext->Unmap( mBuffer, 0 ); } -Buffer::operator ID3D11Buffer *() +Core::Buffer::operator ID3D11Buffer *() { return this->mBuffer; } -Buffer::operator const ID3D11Buffer *() const +Core::Buffer::operator const ID3D11Buffer *() const { return this->mBuffer; } \ No newline at end of file diff --git a/Code/OysterGraphics/Core/Buffer.h b/Code/OysterGraphics/Core/Buffer.h deleted file mode 100644 index 1a52d3f8..00000000 --- a/Code/OysterGraphics/Core/Buffer.h +++ /dev/null @@ -1,79 +0,0 @@ -#pragma once -#ifndef CoreBuffer -#define CoreBuffer - -#include "CoreIncludes.h" - -namespace Oyster -{ - namespace Graphics - { - class Buffer - { - public: - enum BUFFER_TYPE - { - VERTEX_BUFFER, - INDEX_BUFFER, - CONSTANT_BUFFER_VS, - CONSTANT_BUFFER_GS, - CONSTANT_BUFFER_PS, - CONSTANT_BUFFER_CS, - STRUCTURED_BUFFER, - BUFFER_TYPE_COUNT - }; - - enum BUFFER_USAGE - { - BUFFER_DEFAULT, - BUFFER_STREAM_OUT_TARGET, - BUFFER_CPU_WRITE, - BUFFER_CPU_WRITE_DISCARD, - BUFFER_CPU_READ, - BUFFER_USAGE_COUNT, - BUFFER_USAGE_IMMUTABLE - }; - - struct BUFFER_INIT_DESC - { - BUFFER_TYPE Type; - UINT32 NumElements; - UINT32 ElementSize; - BUFFER_USAGE Usage; - void* InitData; - - BUFFER_INIT_DESC() - { - InitData = NULL; - Usage = BUFFER_DEFAULT; - } - }; - protected: - ID3D11Buffer* mBuffer; - BUFFER_TYPE mType; - BUFFER_USAGE mUsage; - - UINT32 mElementSize; - UINT32 mElementCount; - public: - Buffer(); - virtual ~Buffer(); - - HRESULT Init(const BUFFER_INIT_DESC& initDesc); - - void* Map(); - void Unmap(); - - operator ID3D11Buffer*(); - operator const ID3D11Buffer*() const; - - HRESULT Apply(UINT32 misc = 0) const; - - ID3D11Buffer* GetBufferPointer(); - UINT32 GetVertexSize(); - UINT32 GetElementCount(); - }; - } -} - -#endif \ No newline at end of file diff --git a/Code/OysterGraphics/Core/Core.h b/Code/OysterGraphics/Core/Core.h index bc93777f..4efb5b8d 100644 --- a/Code/OysterGraphics/Core/Core.h +++ b/Code/OysterGraphics/Core/Core.h @@ -4,9 +4,8 @@ #define Core_h -#include "CoreIncludes.h" +#include "Dx11Includes.h" #include -#include "Buffer.h" #include "OysterMath.h" namespace Oyster @@ -35,6 +34,72 @@ namespace Oyster static D3D11_VIEWPORT* viewPort; static Oyster::Math::Float2 resolution; + + class Buffer + { + public: + enum BUFFER_TYPE + { + VERTEX_BUFFER, + INDEX_BUFFER, + CONSTANT_BUFFER_VS, + CONSTANT_BUFFER_GS, + CONSTANT_BUFFER_PS, + CONSTANT_BUFFER_CS, + STRUCTURED_BUFFER, + BUFFER_TYPE_COUNT + }; + + enum BUFFER_USAGE + { + BUFFER_DEFAULT, + BUFFER_STREAM_OUT_TARGET, + BUFFER_CPU_WRITE, + BUFFER_CPU_WRITE_DISCARD, + BUFFER_CPU_READ, + BUFFER_USAGE_COUNT, + BUFFER_USAGE_IMMUTABLE + }; + + struct BUFFER_INIT_DESC + { + BUFFER_TYPE Type; + UINT32 NumElements; + UINT32 ElementSize; + BUFFER_USAGE Usage; + void* InitData; + + BUFFER_INIT_DESC() + { + InitData = NULL; + Usage = BUFFER_DEFAULT; + } + }; + protected: + ID3D11Buffer* mBuffer; + BUFFER_TYPE mType; + BUFFER_USAGE mUsage; + + UINT32 mElementSize; + UINT32 mElementCount; + public: + Buffer(); + virtual ~Buffer(); + + HRESULT Init(const BUFFER_INIT_DESC& initDesc); + + void* Map(); + void Unmap(); + + operator ID3D11Buffer*(); + operator const ID3D11Buffer*() const; + + HRESULT Apply(UINT32 misc = 0) const; + + ID3D11Buffer* GetBufferPointer(); + UINT32 GetVertexSize(); + UINT32 GetElementCount(); + }; class ShaderManager diff --git a/Code/OysterGraphics/Core/CoreIncludes.h b/Code/OysterGraphics/Core/Dx11Includes.h similarity index 95% rename from Code/OysterGraphics/Core/CoreIncludes.h rename to Code/OysterGraphics/Core/Dx11Includes.h index 26b1ce0c..037431a0 100644 --- a/Code/OysterGraphics/Core/CoreIncludes.h +++ b/Code/OysterGraphics/Core/Dx11Includes.h @@ -6,10 +6,14 @@ // http://lolengine.net/blog/2011/3/4/fuck-you-microsoft-near-far-macros #include #include -#include #pragma comment(lib, "d3d11.lib") + +#ifdef _DEBUG +#include #pragma comment(lib, "d3dcompiler.lib") +#endif + #include diff --git a/Code/OysterGraphics/Core/Init.cpp b/Code/OysterGraphics/Core/Init.cpp index 7802654c..48abd444 100644 --- a/Code/OysterGraphics/Core/Init.cpp +++ b/Code/OysterGraphics/Core/Init.cpp @@ -103,8 +103,8 @@ namespace Oyster desc.BufferDesc.RefreshRate.Denominator=1; desc.BufferDesc.RefreshRate.Numerator=60; - desc.BufferDesc.Height = Size.y; - desc.BufferDesc.Width = Size.x; + desc.BufferDesc.Height = (UINT)Size.y; + desc.BufferDesc.Width = (UINT)Size.x; if(Core::swapChain) { @@ -180,8 +180,8 @@ namespace Oyster desc.BindFlags = D3D11_BIND_DEPTH_STENCIL; desc.CPUAccessFlags=0; desc.MiscFlags=0; - desc.Height = Size.y; - desc.Width = Size.x; + desc.Height = (UINT)Size.y; + desc.Width = (UINT)Size.x; if(Core::depthStencil) { diff --git a/Code/OysterGraphics/Core/ShaderManager.cpp b/Code/OysterGraphics/Core/ShaderManager.cpp index 448a4b49..0b0c4fba 100644 --- a/Code/OysterGraphics/Core/ShaderManager.cpp +++ b/Code/OysterGraphics/Core/ShaderManager.cpp @@ -1,5 +1,6 @@ #include "Core.h" #include +#include const char* ShaderFunction = "main"; diff --git a/Code/OysterGraphics/Definitions/GraphicalDefinition.h b/Code/OysterGraphics/Definitions/GraphicalDefinition.h index 8a254fe5..177c6763 100644 --- a/Code/OysterGraphics/Definitions/GraphicalDefinition.h +++ b/Code/OysterGraphics/Definitions/GraphicalDefinition.h @@ -1,4 +1,4 @@ -#include "..\OysterGraphics\Core\CoreIncludes.h" +#include "..\OysterGraphics\Core\Dx11Includes.h" #include "OysterMath.h" namespace Oyster @@ -19,6 +19,18 @@ namespace Oyster Oyster::Math::Matrix V; Oyster::Math::Matrix P; }; + + struct FinalVertex + { + Oyster::Math::Float3 pos; + Oyster::Math::Float2 uv; + Oyster::Math::Float3 normal; + Oyster::Math::Float3 tangent; + Oyster::Math::Float3 biTangent; + Oyster::Math::Float4 boneIndex; + Oyster::Math::Float4 boneWeights; + }; + } } } \ No newline at end of file diff --git a/Code/OysterGraphics/DllInterfaces/GFXAPI.cpp b/Code/OysterGraphics/DllInterfaces/GFXAPI.cpp new file mode 100644 index 00000000..e19d497f --- /dev/null +++ b/Code/OysterGraphics/DllInterfaces/GFXAPI.cpp @@ -0,0 +1,66 @@ +#include "GFXAPI.h" +#include "../Core/Core.h" +#include "../Render/Resources/Resources.h" +#include "../Render/Rendering/Render.h" +#include "../FileLoader/ObjReader.h" + +namespace Oyster +{ + namespace Graphics + { + API::State API::Init(HWND Window, bool MSAA_Quality, bool Fullscreen, Math::Float2 resulotion) + { + Core::resolution = resulotion; + + if(Core::Init::FullInit(Window, MSAA_Quality, Fullscreen) == Core::Init::Fail) + { + return API::Fail; + } + if(Render::Resources::Init() == Core::Init::Fail) + { + return API::Fail; + } + + Render::Preparations::Basic::SetViewPort(); + return API::Sucsess; + } + + void API::NewFrame(Oyster::Math::Float4x4 View, Oyster::Math::Float4x4 Projection) + { + Render::Rendering::Basic::NewFrame(View, Projection); + } + + void API::RenderScene(Model::Model* models, int count) + { + Render::Rendering::Basic::RenderScene(models,count); + } + + void API::EndFrame() + { + Render::Rendering::Basic::EndFrame(); + } + + API::State API::SetOptions(API::Option option) + { + return API::Sucsess; + } + + Model::Model* API::CreateModel(std::wstring filename) + { + Model::Model* m = new Model::Model(); + m->WorldMatrix = Oyster::Math::Float4x4::identity; + m->Visible = true; + + OBJReader or; + or.readOBJFile(filename); + m->info = or.toModel(); + + return m; + } + + void API::DeleteModel(Model::Model* model) + { + delete model; + } + } +} \ No newline at end of file diff --git a/Code/OysterGraphics/DllInterfaces/GFXAPI.h b/Code/OysterGraphics/DllInterfaces/GFXAPI.h new file mode 100644 index 00000000..052d99d8 --- /dev/null +++ b/Code/OysterGraphics/DllInterfaces/GFXAPI.h @@ -0,0 +1,42 @@ +#pragma once +#include +#include "..\Model\Model.h" +#include "OysterMath.h" +#include + +#if defined GFX_DLL_EXPORT + #define GFX_DLL_USAGE __declspec(dllexport) +#else + #define GFX_DLL_USAGE __declspec(dllimport) +#endif + + +namespace Oyster +{ + namespace Graphics + { + class GFX_DLL_USAGE API + { + public: + enum State + { + Sucsess, + Fail + }; + struct Option + { + }; + + static State Init(HWND Window, bool MSAA_Quality, bool Fullscreen, Oyster::Math::Float2 StartResulotion); + //! @brief from Oyster::Math Float4x4, expects corect methods + static void NewFrame(Oyster::Math::Float4x4 View, Oyster::Math::Float4x4 Projection); + static void RenderScene(Oyster::Graphics::Model::Model* models, int count); + static void EndFrame(); + + static Oyster::Graphics::Model::Model* CreateModel(std::wstring filename); + static void DeleteModel(Oyster::Graphics::Model::Model* model); + + static State SetOptions(Option); + }; + } +} diff --git a/Code/OysterGraphics/FileLoader/ObjReader.cpp b/Code/OysterGraphics/FileLoader/ObjReader.cpp index b8ca24ae..aa613710 100644 --- a/Code/OysterGraphics/FileLoader/ObjReader.cpp +++ b/Code/OysterGraphics/FileLoader/ObjReader.cpp @@ -2,6 +2,7 @@ #include "..\Definitions\GraphicalDefinition.h" #include #include +#include "TextureLoader.h" using namespace std; OBJReader::OBJReader() @@ -95,17 +96,17 @@ void OBJReader::readOBJFile( std::wstring fileName ) inStream.close(); } -Oyster::Graphics::Render::ModelInfo* OBJReader::toModel() +Oyster::Graphics::Model::ModelInfo* OBJReader::toModel() { - Oyster::Graphics::Buffer* b = new Oyster::Graphics::Buffer(); - Oyster::Graphics::Buffer::BUFFER_INIT_DESC desc; - Oyster::Graphics::Render::ModelInfo* modelInfo = new Oyster::Graphics::Render::ModelInfo(); + Oyster::Graphics::Core::Buffer* b = new Oyster::Graphics::Core::Buffer(); + Oyster::Graphics::Core::Buffer::BUFFER_INIT_DESC desc; + Oyster::Graphics::Model::ModelInfo* modelInfo = new Oyster::Graphics::Model::ModelInfo(); desc.ElementSize = 32; desc.InitData = &this->_myOBJ[0]; desc.NumElements = this->_myOBJ.size(); - desc.Type = Oyster::Graphics::Buffer::BUFFER_TYPE::VERTEX_BUFFER; - desc.Usage = Oyster::Graphics::Buffer::BUFFER_DEFAULT; + desc.Type = Oyster::Graphics::Core::Buffer::BUFFER_TYPE::VERTEX_BUFFER; + desc.Usage = Oyster::Graphics::Core::Buffer::BUFFER_DEFAULT; HRESULT hr = S_OK; hr = b->Init(desc); @@ -117,6 +118,8 @@ Oyster::Graphics::Render::ModelInfo* OBJReader::toModel() modelInfo->VertexCount = (int)desc.NumElements; modelInfo->Vertices = b; + //Oyster::Resource::OysterResource::LoadResource(L"Normal.png",(Oyster::Resource::CustomLoadFunction)Oyster::Graphics::Loading::LoadTexture); + return modelInfo; } diff --git a/Code/OysterGraphics/FileLoader/ObjReader.h b/Code/OysterGraphics/FileLoader/ObjReader.h index 6760ac09..ed579023 100644 --- a/Code/OysterGraphics/FileLoader/ObjReader.h +++ b/Code/OysterGraphics/FileLoader/ObjReader.h @@ -49,7 +49,7 @@ class OBJReader ~OBJReader(); void readOBJFile( std::wstring fileName); - Oyster::Graphics::Render::ModelInfo* toModel(); + Oyster::Graphics::Model::ModelInfo* toModel(); }; #endif \ No newline at end of file diff --git a/Code/OysterGraphics/FileLoader/TextureLoader.cpp b/Code/OysterGraphics/FileLoader/TextureLoader.cpp new file mode 100644 index 00000000..24caeae3 --- /dev/null +++ b/Code/OysterGraphics/FileLoader/TextureLoader.cpp @@ -0,0 +1,7 @@ +#include "TextureLoader.h" +#include "..\Core\Dx11Includes.h" + +Oyster::Resource::CustomData* Oyster::Graphics::Loading::LoadTexture() +{ + return NULL; +} \ No newline at end of file diff --git a/Code/OysterGraphics/FileLoader/TextureLoader.h b/Code/OysterGraphics/FileLoader/TextureLoader.h new file mode 100644 index 00000000..a5148fb4 --- /dev/null +++ b/Code/OysterGraphics/FileLoader/TextureLoader.h @@ -0,0 +1,13 @@ +#pragma once +#include "..\..\Misc\Resource\OysterResource.h" +namespace Oyster +{ + namespace Graphics + { + namespace Loading + { + void UnloadTexture(); + Oyster::Resource::CustomData* LoadTexture(); + } + } +} \ No newline at end of file diff --git a/Code/OysterGraphics/Model/Model.h b/Code/OysterGraphics/Model/Model.h index 805f2ec3..0103b143 100644 --- a/Code/OysterGraphics/Model/Model.h +++ b/Code/OysterGraphics/Model/Model.h @@ -1,28 +1,19 @@ #pragma once #ifndef Mesh_h #define Mesh_h - -//#include "../Engine.h" - - -//#include "..\Core\CoreIncludes.h" -//#include "..\Core\Buffer.h" #include "OysterMath.h" -//#include "ICollideable.h" -#include "ModelInfo.h" - -//using namespace Oyster::Math; namespace Oyster { namespace Graphics { - namespace Render + namespace Model { struct Model { - ModelInfo* info; - Oyster::Math::Float4x4 World; + //! do not Edit, linked to render data + void* info; + Oyster::Math::Float4x4 WorldMatrix; bool Visible; }; } diff --git a/Code/OysterGraphics/Model/ModelInfo.h b/Code/OysterGraphics/Model/ModelInfo.h index fb4a51b9..6c1d0cfe 100644 --- a/Code/OysterGraphics/Model/ModelInfo.h +++ b/Code/OysterGraphics/Model/ModelInfo.h @@ -2,26 +2,19 @@ #ifndef MODELINFO_h #define MODELINFO_h -//#include "../Engine.h" - -#include "..\Core\CoreIncludes.h" -#include "..\Core\Buffer.h" -//#include "OysterMath.h" -//#include "ICollideable.h" - -//using namespace Oyster::Math; +#include "..\Core\Core.h" namespace Oyster { namespace Graphics { - namespace Render + namespace Model { struct ModelInfo { std::vector Material; - Buffer *Vertices,*Indecies; + Core::Buffer *Vertices,*Indecies; bool Indexed; int VertexCount; }; diff --git a/Code/OysterGraphics/OysterGraphics.vcxproj b/Code/OysterGraphics/OysterGraphics.vcxproj index 4c4b8646..09f743b7 100644 --- a/Code/OysterGraphics/OysterGraphics.vcxproj +++ b/Code/OysterGraphics/OysterGraphics.vcxproj @@ -24,7 +24,7 @@ - StaticLibrary + DynamicLibrary true v110 MultiByte @@ -66,22 +66,22 @@ - $(SolutionDir)..\External\Lib\$(ProjectName)\ + $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D - $(SolutionDir)..\External\Lib\$(ProjectName)\ + $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) - $(SolutionDir)..\External\Lib\$(ProjectName)\ + $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D - $(SolutionDir)..\External\Lib\$(ProjectName)\ + $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) @@ -91,6 +91,7 @@ Disabled true $(SolutionDir)OysterMath;$(SolutionDir)Misc;%(AdditionalIncludeDirectories) + GFX_DLL_EXPORT;%(PreprocessorDefinitions) true @@ -105,6 +106,7 @@ Disabled true ..\OysterPhysic3D\Collision;..\OysterPhysics3D;..\OysterMath;..\Misc;%(AdditionalIncludeDirectories) + GFX_DLL_EXPORT;%(PreprocessorDefinitions) true @@ -118,6 +120,7 @@ true true ..\OysterPhysics3D;..\OysterMath;..\Misc;%(AdditionalIncludeDirectories) + GFX_DLL_EXPORT;%(PreprocessorDefinitions) true @@ -133,6 +136,7 @@ true true ..\OysterPhysics3D;..\OysterMath;..\Misc;%(AdditionalIncludeDirectories) + GFX_DLL_EXPORT;%(PreprocessorDefinitions) true @@ -145,16 +149,19 @@ + + - - + + + @@ -171,6 +178,20 @@ + + Pixel + Pixel + Pixel + Pixel + 5.0 + + + Vertex + Vertex + Vertex + Vertex + 5.0 + Vertex Vertex @@ -203,6 +224,11 @@ + + + + + diff --git a/Code/OysterGraphics/OysterGraphics.vcxproj.filters b/Code/OysterGraphics/OysterGraphics.vcxproj.filters index c93b6439..3bb4036f 100644 --- a/Code/OysterGraphics/OysterGraphics.vcxproj.filters +++ b/Code/OysterGraphics/OysterGraphics.vcxproj.filters @@ -1,80 +1,40 @@  - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Code/OysterGraphics/Render/Rendering/BasicRender.cpp b/Code/OysterGraphics/Render/Rendering/BasicRender.cpp index 5b8723a2..5e1fbb48 100644 --- a/Code/OysterGraphics/Render/Rendering/BasicRender.cpp +++ b/Code/OysterGraphics/Render/Rendering/BasicRender.cpp @@ -1,6 +1,7 @@ #include "Render.h" #include "../Resources/Resources.h" #include "../../Definitions/GraphicalDefinition.h" +#include "../../Model/ModelInfo.h" namespace Oyster { @@ -28,27 +29,30 @@ namespace Oyster Resources::VPData.Apply(); } - void Basic::RenderScene(Model* models, int count) + void Basic::RenderScene(Model::Model* models, int count) { for(int i = 0; i < count; ++i) { if(models[i].Visible) { void* data = Resources::ModelData.Map(); - memcpy(data,&(models[i].World),64); + memcpy(data,&(models[i].WorldMatrix),sizeof(Math::Float4x4)); Resources::ModelData.Unmap(); //Set Materials :: NONE - models[i].info->Vertices->Apply(); - if(models[i].info->Indexed) + Model + ::ModelInfo* info = (Model::ModelInfo*)models[i].info; + + info->Vertices->Apply(); + if(info->Indexed) { - models[i].info->Indecies->Apply(); - Oyster::Graphics::Core::deviceContext->DrawIndexed(models[i].info->VertexCount,0,0); + info->Indecies->Apply(); + Oyster::Graphics::Core::deviceContext->DrawIndexed(info->VertexCount,0,0); } else { - Oyster::Graphics::Core::deviceContext->Draw(models[i].info->VertexCount,0); + Oyster::Graphics::Core::deviceContext->Draw(info->VertexCount,0); } } } diff --git a/Code/OysterGraphics/Render/Rendering/Render.h b/Code/OysterGraphics/Render/Rendering/Render.h index 1764ba3d..5aa61742 100644 --- a/Code/OysterGraphics/Render/Rendering/Render.h +++ b/Code/OysterGraphics/Render/Rendering/Render.h @@ -17,7 +17,7 @@ namespace Oyster public: static void NewFrame(Oyster::Math::Float4x4 View, Oyster::Math::Float4x4 Projection); - static void RenderScene(Model* models, int count); + static void RenderScene(Model::Model* models, int count); static void EndFrame(); }; } diff --git a/Code/OysterGraphics/Render/Resources/Resources.cpp b/Code/OysterGraphics/Render/Resources/Resources.cpp index d5393b4a..3ff3fa3c 100644 --- a/Code/OysterGraphics/Render/Resources/Resources.cpp +++ b/Code/OysterGraphics/Render/Resources/Resources.cpp @@ -1,7 +1,9 @@ #include "Resources.h" #include "..\OysterGraphics\Definitions\GraphicalDefinition.h" -const std::wstring PathFromExeToHlsl = L"..\\OysterGraphics\\Shader\\HLSL\\"; +// /Bin/Executable/Tester -> +// /Code/OysterGraphics/Shader/HLSL +const std::wstring PathFromExeToHlsl = L"..\\..\\..\\Code\\OysterGraphics\\Shader\\HLSL\\"; const std::wstring VertexTransformDebug = L"TransformDebugVertex"; const std::wstring VertexDebug = L"DebugVertex"; const std::wstring PixelRed = L"DebugPixel"; @@ -9,6 +11,7 @@ const std::wstring PixelRed = L"DebugPixel"; typedef Oyster::Graphics::Core::ShaderManager::ShaderType ShaderType; typedef Oyster::Graphics::Core::ShaderManager::Get GetShader; typedef Oyster::Graphics::Core::ShaderManager Shader; +typedef Oyster::Graphics::Core::Buffer Buffer; namespace Oyster { @@ -96,8 +99,8 @@ namespace Oyster obj.CBuffers.Vertex.push_back(&VPData); obj.RenderStates.Rasterizer = rs; + ModelData.Apply(1); #pragma endregion - return Core::Init::Sucsess; } } diff --git a/Code/OysterGraphics/Render/Resources/Resources.h b/Code/OysterGraphics/Render/Resources/Resources.h index dc10c8e8..daf77760 100644 --- a/Code/OysterGraphics/Render/Resources/Resources.h +++ b/Code/OysterGraphics/Render/Resources/Resources.h @@ -16,8 +16,8 @@ namespace Oyster { public: static Core::ShaderManager::ShaderEffect obj; - static Buffer ModelData; - static Buffer VPData; + static Core::Buffer ModelData; + static Core::Buffer VPData; static Core::Init::State Init(); }; diff --git a/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/GBufferHeader.hlsli b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/GBufferHeader.hlsli new file mode 100644 index 00000000..d39f6ae5 --- /dev/null +++ b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/GBufferHeader.hlsli @@ -0,0 +1,41 @@ +struct VertexIn +{ + float3 pos : POSITION; + float2 UV : TEXCOORD; + float3 normal : NORMAL; + float3 tangent : TANGENT; + float3 biTangent : BITANGENT; + float4 boneIndex : BONEINDEX; + float4 boneWeight : BONEWEIGHT; +}; + +struct VertexOut +{ + float4 pos : SV_POSITION; + float4 ViewPos : POSITION; + float2 UV : TEXCOORD; + float3 normal : NORMAL; + float3 tangent : TANGENT; + float3 biTangent : BITANGENT; +}; + +struct PixelOut +{ + float4 DiffuseGlow : SV_TARGET0; + float4 NormalSpec : SV_TARGET1; +}; + +Texture2D Diffuse : register(t0); +Texture2D Specular : register(t1); + +cbuffer PerFrame : register(b0) +{ + matrix View; + float4x4 Projection; + matrix VP; +} + +cbuffer PerModel : register(b1) +{ + matrix World; +} \ No newline at end of file diff --git a/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/PixelGatherData.hlsl b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/PixelGatherData.hlsl new file mode 100644 index 00000000..61f0e20f --- /dev/null +++ b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/PixelGatherData.hlsl @@ -0,0 +1,9 @@ +#include "GBufferHeader.hlsli" + +PixelOut main(VertexOut input) +{ + PixelOut output; + output.DiffuseGlow = float4(1.0f, 0.0f, 0.0f, 1.0f); + output.NormalSpec = float4(input.normal, 1.0f); + return output; +} \ No newline at end of file diff --git a/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/VertexGatherData.hlsl b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/VertexGatherData.hlsl new file mode 100644 index 00000000..d5751ac4 --- /dev/null +++ b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/VertexGatherData.hlsl @@ -0,0 +1,12 @@ +#include "GBufferHeader.hlsli" + +VertexOut main( VertexIn input ) +{ + VertexOut output; + matrix WV = mul(View, World); + output.ViewPos = mul(WV, float4(input.pos,1)); + output.pos = mul(Projection, output.ViewPos); + output.UV = input.UV; + output.normal = float4(input.normal, 0); + return output; +} \ No newline at end of file diff --git a/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugCameraVertex.hlsl b/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugCameraVertex.hlsl index fadd7332..76e7dbed 100644 --- a/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugCameraVertex.hlsl +++ b/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugCameraVertex.hlsl @@ -18,11 +18,11 @@ struct VertexIn float4 main( VertexIn input ) : SV_POSITION { - float4 postTransform = float4(input.pos*0.1f,1); - postTransform.y += 1.5f; + float4 postTransform = mul( World, float4(input.pos,1) ); + //float4 postTransform = float4(input.pos,1); //return postTransform; //return mul(View, float4(input.pos,1)); matrix VP = mul(Projection, View); //matrix WVP = mul(World, VP); - return mul(VP, float4(input.pos*0.1f,1) ); + return mul(VP, postTransform ); } \ No newline at end of file diff --git a/Code/OysterMath/LinearMath.h b/Code/OysterMath/LinearMath.h index 184ea1a7..0495939d 100644 --- a/Code/OysterMath/LinearMath.h +++ b/Code/OysterMath/LinearMath.h @@ -444,8 +444,8 @@ namespace LinearAlgebra3D ScalarType c = 1 / (nearClip - farClip); return targetMem = ::LinearAlgebra::Matrix4x4( 2/width, 0, 0, 0, 0, 2/height, 0, 0, - 0, 0, -c, 0, 0, - 0, nearClip*c, 1 ); + 0, 0, -c, nearClip*c, + 0, 0, 0, 1 ); } /******************************************************************* @@ -460,15 +460,27 @@ namespace LinearAlgebra3D *******************************************************************/ template ::LinearAlgebra::Matrix4x4 & ProjectionMatrix_Perspective( const ScalarType &vertFoV, const ScalarType &aspect, const ScalarType &nearClip, const ScalarType &farClip, ::LinearAlgebra::Matrix4x4 &targetMem = ::LinearAlgebra::Matrix4x4() ) - { /** @todo TODO: not tested */ + { ScalarType fov = 1 / ::std::tan( vertFoV * 0.5f ), dDepth = farClip / (farClip - nearClip); - return targetMem = ::LinearAlgebra::Matrix4x4( fov / aspect, 0, 0, 0, + return targetMem = ::LinearAlgebra::Matrix4x4( fov / aspect, 0, 0, 0, 0, fov, 0, 0, 0, 0, dDepth, -(dDepth * nearClip), 0, 0, 1, 0 ); } + template + ::LinearAlgebra::Matrix4x4 & ProjectionMatrix_Perspective( const ScalarType &left, const ScalarType &right, const ScalarType &top, const ScalarType &bottom, const ScalarType &nearClip, const ScalarType &farClip, ::LinearAlgebra::Matrix4x4 &targetMem = ::LinearAlgebra::Matrix4x4() ) + { /** @todo TODO: not tested */ + ScalarType fov = 1 / ::std::tan( vertFoV * 0.5f ), + dDepth = farClip / (farClip - nearClip); + return targetMem = ::LinearAlgebra::Matrix4x4( 2*nearClip/(right - left), 0, -(right + left)/(right - left), 0, + 0, 2*nearClip/(top - bottom), -(top + bottom)/(top - bottom), 0, + 0, 0, dDepth, -(dDepth * nearClip), + 0, 0, 1, 0 ); + } + + template inline ::LinearAlgebra::Vector3 VectorProjection( const ::LinearAlgebra::Vector3 &vector, const ::LinearAlgebra::Vector3 &axis ) { return axis * ( vector.Dot(axis) / axis.Dot(axis) ); } diff --git a/Code/OysterMath/Matrix.h b/Code/OysterMath/Matrix.h index c5c8735e..c7b6b9e0 100644 --- a/Code/OysterMath/Matrix.h +++ b/Code/OysterMath/Matrix.h @@ -29,7 +29,7 @@ namespace LinearAlgebra Matrix2x2( ); Matrix2x2( const ScalarType &m11, const ScalarType &m12, const ScalarType &m21, const ScalarType &m22 ); - Matrix2x2( const Vector2 vec[2] ); + explicit Matrix2x2( const Vector2 vec[2] ); Matrix2x2( const Vector2 &vec1, const Vector2 &vec2 ); explicit Matrix2x2( const ScalarType element[4] ); Matrix2x2( const Matrix2x2 &matrix ); @@ -80,7 +80,7 @@ namespace LinearAlgebra Matrix3x3( const ScalarType &m11, const ScalarType &m12, const ScalarType &m13, const ScalarType &m21, const ScalarType &m22, const ScalarType &m23, const ScalarType &m31, const ScalarType &m32, const ScalarType &m33 ); - Matrix3x3( const Vector3 vec[3] ); + explicit Matrix3x3( const Vector3 vec[3] ); Matrix3x3( const Vector3 &vec1, const Vector3 &vec2, const Vector3 &vec3 ); explicit Matrix3x3( const ScalarType element[9] ); Matrix3x3( const Matrix3x3 &matrix ); @@ -132,7 +132,7 @@ namespace LinearAlgebra const ScalarType &m21, const ScalarType &m22, const ScalarType &m23, const ScalarType &m24, const ScalarType &m31, const ScalarType &m32, const ScalarType &m33, const ScalarType &m34, const ScalarType &m41, const ScalarType &m42, const ScalarType &m43, const ScalarType &m44 ); - Matrix4x4( const Vector4 vec[4] ); + explicit Matrix4x4( const Vector4 vec[4] ); Matrix4x4( const Vector4 &vec1, const Vector4 &vec2, const Vector4 &vec3, const Vector4 &vec4 ); explicit Matrix4x4( const ScalarType element[16] ); Matrix4x4( const Matrix4x4 &matrix ); diff --git a/Code/OysterMath/OysterMath.cpp b/Code/OysterMath/OysterMath.cpp index 35df5975..a82658ee 100644 --- a/Code/OysterMath/OysterMath.cpp +++ b/Code/OysterMath/OysterMath.cpp @@ -141,6 +141,16 @@ namespace Oyster { namespace Math3D return targetMem = ::LinearAlgebra3D::OrientationMatrix_LookAtPos( worldLookAt, normalizedUpVector, worldPos ); } + Float4x4 & ViewMatrix_LookAtDirection( const Float3 &normalizedDirection, const Float3 &normalizedUpVector, const Float3 &worldPos, Float4x4 &targetMem ) + { + return ::LinearAlgebra3D::InverseOrientationMatrix( ::LinearAlgebra3D::OrientationMatrix_LookAtDirection( normalizedDirection, normalizedUpVector, worldPos ), targetMem ); + } + + Float4x4 & ViewMatrix_LookAtPos( const Float3 &worldLookAt, const Float3 &normalizedUpVector, const Float3 &worldPos, Float4x4 &targetMem ) + { + return ::LinearAlgebra3D::InverseOrientationMatrix( ::LinearAlgebra3D::OrientationMatrix_LookAtPos( worldLookAt, normalizedUpVector, worldPos ), targetMem ); + } + Float4x4 & InverseOrientationMatrix( const Float4x4 &orientationMatrix, Float4x4 &targetMem ) { return ::LinearAlgebra3D::InverseOrientationMatrix( orientationMatrix, targetMem ); diff --git a/Code/OysterMath/OysterMath.h b/Code/OysterMath/OysterMath.h index 125fd29d..ab3b307f 100644 --- a/Code/OysterMath/OysterMath.h +++ b/Code/OysterMath/OysterMath.h @@ -213,6 +213,12 @@ namespace Oyster { namespace Math3D /// Oyster's native math library specialized //! @todo TODO: Add documentation and not tested Float4x4 & OrientationMatrix_LookAtPos( const Float3 &worldLookAt, const Float3 &normalizedUpVector, const Float3 &worldPos, Float4x4 &targetMem = Float4x4() ); + //! @todo TODO: Add documentation and not tested + Float4x4 & ViewMatrix_LookAtDirection( const Float3 &normalizedDirection, const Float3 &normalizedUpVector, const Float3 &worldPos, Float4x4 &targetMem = Float4x4() ); + + //! @todo TODO: Add documentation and not tested + Float4x4 & ViewMatrix_LookAtPos( const Float3 &worldLookAt, const Float3 &normalizedUpVector, const Float3 &worldPos, Float4x4 &targetMem = Float4x4() ); + /// If orientationMatrix is assumed to be by all definitions a rigid orientation matrix aka rigid body matrix. Then this is a much faster inverse method. Float4x4 & InverseOrientationMatrix( const Float4x4 &orientationMatrix, Float4x4 &targetMem = Float4x4() ); diff --git a/Code/OysterPhysics3D/Box.cpp b/Code/OysterPhysics3D/Box.cpp index ba97c5c5..382c6732 100644 --- a/Code/OysterPhysics3D/Box.cpp +++ b/Code/OysterPhysics3D/Box.cpp @@ -8,13 +8,19 @@ using namespace ::Oyster::Collision3D; using namespace ::Oyster::Math3D; -Box::Box( ) - : ICollideable(Type_box), rotation(Float4x4::identity), center(0.0f), boundingOffset(0.5f) -{} +Box::Box( ) : ICollideable(Type_box) +{ + this->rotation = Float4x4::identity; + this->center =0.0f; + this->boundingOffset = Float3(0.5f); +} -Box::Box( const Float4x4 &r, const Float3 &p, const Float3 &s ) - : ICollideable(Type_box), rotation(r), center(p), boundingOffset(s*0.5) -{} +Box::Box( const Float4x4 &r, const Float3 &p, const Float3 &s ) : ICollideable(Type_box) +{ + this->rotation = r; + this->center = p; + this->boundingOffset = Float3(s*0.5); +} Box::~Box( ) {} @@ -31,28 +37,28 @@ Box & Box::operator = ( const Box &box ) return ::Utility::DynamicMemory::UniquePointer( new Box(*this) ); } -bool Box::Intersects( const ICollideable *target ) const +bool Box::Intersects( const ICollideable &target ) const { - switch( target->type ) + switch( target.type ) { case Type_universe: return true; - case Type_point: return Utility::Intersect( *this, *(Point*)target ); - case Type_ray: return Utility::Intersect( *this, *(Ray*)target, ((Ray*)target)->collisionDistance ); - case Type_sphere: return Utility::Intersect( *this, *(Sphere*)target ); - case Type_plane: return Utility::Intersect( *this, *(Plane*)target ); + case Type_point: return Utility::Intersect( *this, *(Point*)&target ); + case Type_ray: return Utility::Intersect( *this, *(Ray*)&target, ((Ray*)&target)->collisionDistance ); + case Type_sphere: return Utility::Intersect( *this, *(Sphere*)&target ); + case Type_plane: return Utility::Intersect( *this, *(Plane*)&target ); // case Type_triangle: return false; // TODO: : - case Type_box_axis_aligned: return Utility::Intersect( *this, *(BoxAxisAligned*)target ); - case Type_box: return Utility::Intersect( *this, *(Box*)target ); + case Type_box_axis_aligned: return Utility::Intersect( *this, *(BoxAxisAligned*)&target ); + case Type_box: return Utility::Intersect( *this, *(Box*)&target ); // case Type_frustrum: return false; // TODO: : default: return false; } } -bool Box::Contains( const ICollideable *target ) const +bool Box::Contains( const ICollideable &target ) const { - switch( target->type ) + switch( target.type ) { - case Type_point: return Utility::Intersect( *this, *(Point*)target ); + case Type_point: return Utility::Intersect( *this, *(Point*)&target ); // case Type_sphere: return false; // TODO: // case Type_triangle: return false; // TODO: // case Type_box_axis_aligned: return false; // TODO: diff --git a/Code/OysterPhysics3D/Box.h b/Code/OysterPhysics3D/Box.h index ee46d6b6..d40c9f30 100644 --- a/Code/OysterPhysics3D/Box.h +++ b/Code/OysterPhysics3D/Box.h @@ -33,8 +33,8 @@ namespace Oyster { namespace Collision3D Box & operator = ( const Box &box ); virtual ::Utility::DynamicMemory::UniquePointer Clone( ) const; - bool Intersects( const ICollideable *target ) const; - bool Contains( const ICollideable *target ) const; + bool Intersects( const ICollideable &target ) const; + bool Contains( const ICollideable &target ) const; }; } } diff --git a/Code/OysterPhysics3D/BoxAxisAligned.cpp b/Code/OysterPhysics3D/BoxAxisAligned.cpp index 04bc53f1..f50f4b6d 100644 --- a/Code/OysterPhysics3D/BoxAxisAligned.cpp +++ b/Code/OysterPhysics3D/BoxAxisAligned.cpp @@ -8,10 +8,24 @@ using namespace ::Oyster::Collision3D; using namespace ::Oyster::Math3D; -BoxAxisAligned::BoxAxisAligned( ) : ICollideable(Type_box_axis_aligned), minVertex(-0.5f,-0.5f,-0.5f), maxVertex(0.5f,0.5f,0.5f) {} -BoxAxisAligned::BoxAxisAligned( const Float3 &_minVertex, const Float3 &_maxVertex ) : ICollideable(Type_box_axis_aligned), minVertex(_minVertex), maxVertex(_maxVertex) {} -BoxAxisAligned::BoxAxisAligned( const Float &leftClip, const Float &rightClip, const Float &topClip, const Float &bottomClip, const Float &nearClip, const Float &farClip ) - : ICollideable(Type_box_axis_aligned), minVertex(leftClip, bottomClip, nearClip), maxVertex(rightClip, topClip, farClip) {} +BoxAxisAligned::BoxAxisAligned( ) : ICollideable(Type_box_axis_aligned) +{ + this->minVertex = Float3(-0.5f,-0.5f,-0.5f ); + this->maxVertex = Float3( 0.5f, 0.5f, 0.5f ); +} + +BoxAxisAligned::BoxAxisAligned( const Float3 &_minVertex, const Float3 &_maxVertex ) : ICollideable(Type_box_axis_aligned) +{ + this->minVertex = _minVertex; + this->maxVertex = _maxVertex; +} + +BoxAxisAligned::BoxAxisAligned( const Float &leftClip, const Float &rightClip, const Float &topClip, const Float &bottomClip, const Float &nearClip, const Float &farClip ) : ICollideable(Type_box_axis_aligned) +{ + this->minVertex = Float3( leftClip, bottomClip, nearClip ); + this->maxVertex = Float3( rightClip, topClip, farClip ); +} + BoxAxisAligned::~BoxAxisAligned( ) {} BoxAxisAligned & BoxAxisAligned::operator = ( const BoxAxisAligned &box ) @@ -22,28 +36,30 @@ BoxAxisAligned & BoxAxisAligned::operator = ( const BoxAxisAligned &box ) } ::Utility::DynamicMemory::UniquePointer BoxAxisAligned::Clone( ) const -{ return ::Utility::DynamicMemory::UniquePointer( new BoxAxisAligned(*this) ); } - -bool BoxAxisAligned::Intersects( const ICollideable *target ) const { - switch( target->type ) + return ::Utility::DynamicMemory::UniquePointer( new BoxAxisAligned(*this) ); +} + +bool BoxAxisAligned::Intersects( const ICollideable &target ) const +{ + switch( target.type ) { case Type_universe: return true; - case Type_point: return Utility::Intersect( *this, *(Point*)target ); - case Type_ray: return Utility::Intersect( *this, *(Ray*)target, ((Ray*)target)->collisionDistance ); - case Type_sphere: return Utility::Intersect( *this, *(Sphere*)target ); - case Type_plane: return Utility::Intersect( *this, *(Plane*)target ); + case Type_point: return Utility::Intersect( *this, *(Point*)&target ); + case Type_ray: return Utility::Intersect( *this, *(Ray*)&target, ((Ray*)&target)->collisionDistance ); + case Type_sphere: return Utility::Intersect( *this, *(Sphere*)&target ); + case Type_plane: return Utility::Intersect( *this, *(Plane*)&target ); // case Type_triangle: return false; // TODO: - case Type_box_axis_aligned: return Utility::Intersect( *this, *(BoxAxisAligned*)target ); + case Type_box_axis_aligned: return Utility::Intersect( *this, *(BoxAxisAligned*)&target ); // case Type_box: return false; // TODO: // case Type_frustrum: return false; // TODO: default: return false; } } -bool BoxAxisAligned::Contains( const ICollideable *target ) const +bool BoxAxisAligned::Contains( const ICollideable &target ) const { - switch( target->type ) + switch( target.type ) { // case Type_point: return false; // TODO: // case Type_sphere: return false; // TODO: diff --git a/Code/OysterPhysics3D/BoxAxisAligned.h b/Code/OysterPhysics3D/BoxAxisAligned.h index 9810c39a..a0e109b2 100644 --- a/Code/OysterPhysics3D/BoxAxisAligned.h +++ b/Code/OysterPhysics3D/BoxAxisAligned.h @@ -28,8 +28,8 @@ namespace Oyster { namespace Collision3D BoxAxisAligned & operator = ( const BoxAxisAligned &box ); virtual ::Utility::DynamicMemory::UniquePointer Clone( ) const; - bool Intersects( const ICollideable *target ) const; - bool Contains( const ICollideable *target ) const; + bool Intersects( const ICollideable &target ) const; + bool Contains( const ICollideable &target ) const; }; } } diff --git a/Code/OysterPhysics3D/Frustrum.cpp b/Code/OysterPhysics3D/Frustrum.cpp index 9e45f579..7099c2ce 100644 --- a/Code/OysterPhysics3D/Frustrum.cpp +++ b/Code/OysterPhysics3D/Frustrum.cpp @@ -74,13 +74,22 @@ namespace PrivateStatic } } -Frustrum::Frustrum() : ICollideable(Type_frustrum), - leftPlane(Float3::standard_unit_x, -0.5f), rightPlane(-Float3::standard_unit_x, 0.5f), - bottomPlane(Float3::standard_unit_y, -0.5f), topPlane(-Float3::standard_unit_y, 0.5f), - nearPlane(Float3::standard_unit_z, -0.5f), farPlane(-Float3::standard_unit_z, 0.5f) {} +Frustrum::Frustrum() : ICollideable(Type_frustrum) +{ + this->leftPlane = Plane( Float3::standard_unit_x, -0.5f ); + this->rightPlane = Plane(-Float3::standard_unit_x, 0.5f ), + this->bottomPlane = Plane( Float3::standard_unit_y, -0.5f ); + this->topPlane = Plane(-Float3::standard_unit_y, 0.5f ); + this->nearPlane = Plane( Float3::standard_unit_z, -0.5f ); + this->farPlane = Plane(-Float3::standard_unit_z, 0.5f ); +} Frustrum::Frustrum( const Float4x4 &vp ) : ICollideable(Type_frustrum) -{ PrivateStatic::VP_ToPlanes( this->leftPlane, this->rightPlane, this->bottomPlane, this->topPlane, this->nearPlane, this->farPlane, vp ); } +{ + PrivateStatic::VP_ToPlanes( this->leftPlane, this->rightPlane, this->bottomPlane, + this->topPlane, this->nearPlane, this->farPlane, + vp ); +} Frustrum::~Frustrum() {} @@ -191,29 +200,29 @@ void Frustrum::WriteToByte( unsigned int &nextIndex, unsigned char targetMem[] ) ::Utility::DynamicMemory::UniquePointer Frustrum::Clone( ) const { return ::Utility::DynamicMemory::UniquePointer( new Frustrum(*this) ); } -bool Frustrum::Intersects( const ICollideable *target ) const +bool Frustrum::Intersects( const ICollideable &target ) const { - switch( target->type ) + switch( target.type ) { case Type_universe: return true; - case Type_point: return Utility::Intersect( *this, *(Point*)target ); - case Type_ray: return Utility::Intersect( *this, *(Ray*)target, ((Ray*)target)->collisionDistance ); - case Type_sphere: return Utility::Intersect( *this, *(Sphere*)target ); - case Type_plane: return Utility::Intersect( *this, *(Plane*)target ); + case Type_point: return Utility::Intersect( *this, *(Point*)&target ); + case Type_ray: return Utility::Intersect( *this, *(Ray*)&target, ((Ray*)&target)->collisionDistance ); + case Type_sphere: return Utility::Intersect( *this, *(Sphere*)&target ); + case Type_plane: return Utility::Intersect( *this, *(Plane*)&target ); // case Type_triangle: return false; // TODO: - case Type_box_axis_aligned: return Utility::Intersect( *this, *(BoxAxisAligned*)target ); - case Type_box: return Utility::Intersect( *this, *(Box*)target ); - case Type_frustrum: return Utility::Intersect( *this, *(Frustrum*)target ); + case Type_box_axis_aligned: return Utility::Intersect( *this, *(BoxAxisAligned*)&target ); + case Type_box: return Utility::Intersect( *this, *(Box*)&target ); + case Type_frustrum: return Utility::Intersect( *this, *(Frustrum*)&target ); // case Type_line: return false; // TODO: default: return false; } } -bool Frustrum::Contains( const ICollideable *target ) const +bool Frustrum::Contains( const ICollideable &target ) const { - switch( target->type ) + switch( target.type ) { - case Type_point: return Utility::Intersect( *this, *(Point*)target ); + case Type_point: return Utility::Intersect( *this, *(Point*)&target ); // case Type_ray: return false; // TODO: // case Type_sphere: return false; // TODO: // case Type_plane: return false; // TODO: diff --git a/Code/OysterPhysics3D/Frustrum.h b/Code/OysterPhysics3D/Frustrum.h index c711c9af..afd8d8bd 100644 --- a/Code/OysterPhysics3D/Frustrum.h +++ b/Code/OysterPhysics3D/Frustrum.h @@ -38,8 +38,8 @@ namespace Oyster { namespace Collision3D void WriteToByte( unsigned char targetMem[], unsigned int &nextIndex ) const; /// DEPRECATED virtual ::Utility::DynamicMemory::UniquePointer Clone( ) const; - bool Intersects( const ICollideable *target ) const; - bool Contains( const ICollideable *target ) const; + bool Intersects( const ICollideable &target ) const; + bool Contains( const ICollideable &target ) const; }; // INLINE IMPLEMENTATIONS /////////////////////////////////////// diff --git a/Code/OysterPhysics3D/ICollideable.cpp b/Code/OysterPhysics3D/ICollideable.cpp index 89effa36..b0af99e4 100644 --- a/Code/OysterPhysics3D/ICollideable.cpp +++ b/Code/OysterPhysics3D/ICollideable.cpp @@ -6,7 +6,5 @@ using namespace ::Oyster::Collision3D; -ICollideable::ICollideable( Type _type ) - : type(_type) {} - +ICollideable::ICollideable( Type _type ) : type(_type) {} ICollideable::~ICollideable() {} \ No newline at end of file diff --git a/Code/OysterPhysics3D/ICollideable.h b/Code/OysterPhysics3D/ICollideable.h index 4b620506..34a86f7b 100644 --- a/Code/OysterPhysics3D/ICollideable.h +++ b/Code/OysterPhysics3D/ICollideable.h @@ -8,7 +8,7 @@ #include "Utilities.h" -namespace Oyster { namespace Collision3D /// Contains a collection of 3D shapes and intercollission algorithms. +namespace Oyster { namespace Collision3D //! Contains a collection of 3D shapes and intercollission algorithms. { class ICollideable { @@ -34,8 +34,8 @@ namespace Oyster { namespace Collision3D /// Contains a collection of 3D shapes virtual ~ICollideable(); virtual ::Utility::DynamicMemory::UniquePointer Clone( ) const = 0; - virtual bool Intersects( const ICollideable *target ) const = 0; - virtual bool Contains( const ICollideable *target ) const = 0; + virtual bool Intersects( const ICollideable &target ) const = 0; + virtual bool Contains( const ICollideable &target ) const = 0; }; } } #endif \ No newline at end of file diff --git a/Code/OysterPhysics3D/Line.cpp b/Code/OysterPhysics3D/Line.cpp index 7093f6b2..17fe55f7 100644 --- a/Code/OysterPhysics3D/Line.cpp +++ b/Code/OysterPhysics3D/Line.cpp @@ -8,9 +8,24 @@ using namespace ::Oyster::Collision3D; using namespace ::Oyster::Math3D; -Line::Line( ) : ICollideable(Type_line), ray(), length(0.0f) {} -Line::Line( const class Ray &_ray, const Float &_length ) : ICollideable(Type_line), ray(_ray), length(_length) {} -Line::Line( const Float3 &origin, const Float3 &normalizedDirection, const Float &_length ) : ICollideable(Type_line), ray(origin, normalizedDirection), length(_length) {} +Line::Line( ) : ICollideable(Type_line) +{ + this->ray = Ray(); + this->length = 0.0f; +} + +Line::Line( const class Ray &_ray, const Float &_length ) : ICollideable(Type_line) +{ + this->ray = _ray; + this->length = _length; +} + +Line::Line( const Float3 &origin, const Float3 &normalizedDirection, const Float &_length ) : ICollideable(Type_line) +{ + this->ray = Ray( origin, normalizedDirection ); + this->length = _length; +} + Line::~Line( ) {} Line & Line::operator = ( const Line &line ) @@ -23,9 +38,9 @@ Line & Line::operator = ( const Line &line ) ::Utility::DynamicMemory::UniquePointer Line::Clone( ) const { return ::Utility::DynamicMemory::UniquePointer( new Line(*this) ); } -bool Line::Intersects( const ICollideable *target ) const +bool Line::Intersects( const ICollideable &target ) const { - if( target->type == Type_universe ) + if( target.type == Type_universe ) { this->ray.collisionDistance = 0.0f; return true; @@ -38,5 +53,5 @@ bool Line::Intersects( const ICollideable *target ) const return false; } -bool Line::Contains( const ICollideable *target ) const +bool Line::Contains( const ICollideable &target ) const { /* TODO: : */ return false; } diff --git a/Code/OysterPhysics3D/Line.h b/Code/OysterPhysics3D/Line.h index fecc0bd2..f062c0dc 100644 --- a/Code/OysterPhysics3D/Line.h +++ b/Code/OysterPhysics3D/Line.h @@ -29,8 +29,8 @@ namespace Oyster { namespace Collision3D Line & operator = ( const Line &line ); virtual ::Utility::DynamicMemory::UniquePointer Clone( ) const; - bool Intersects( const ICollideable *target ) const; - bool Contains( const ICollideable *target ) const; + bool Intersects( const ICollideable &target ) const; + bool Contains( const ICollideable &target ) const; }; } } diff --git a/Code/OysterPhysics3D/OysterPhysics3D.h b/Code/OysterPhysics3D/OysterPhysics3D.h index ca9948a8..614a4a29 100644 --- a/Code/OysterPhysics3D/OysterPhysics3D.h +++ b/Code/OysterPhysics3D/OysterPhysics3D.h @@ -201,6 +201,96 @@ namespace Oyster { namespace Physics3D namespace MomentOfInertia { /// Library of Formulas to calculate moment of inerta for simple shapes /** @todo TODO: add MomentOfInertia tensor formulas */ + inline ::Oyster::Math::Float CalculateSphere( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ) + { + return (2.0f/5.0f)*mass*radius*radius; + } + + inline ::Oyster::Math::Float4x4 Sphere( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ) + { + ::Oyster::Math::Float4x4 inertia = ::Oyster::Math::Float4x4::identity; + inertia.m[0][0] = ::Oyster::Physics3D::Formula::MomentOfInertia::CalculateSphere( mass , radius ); + inertia.m[1][1] = inertia.m[0][0]; + inertia.m[2][2] = inertia.m[0][0]; + + return inertia; + } + + inline ::Oyster::Math::Float CalculateHollowSphere( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ) + { + return (2.0f/3.0f)*mass*radius*radius; + } + + inline ::Oyster::Math::Float4x4 HollowSphere( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ) + { + ::Oyster::Math::Float4x4 inertia = ::Oyster::Math::Float4x4::identity; + inertia.m[0][0] = ::Oyster::Physics3D::Formula::MomentOfInertia::CalculateHollowSphere( mass, radius ); + inertia.m[1][1] = inertia.m[0][0]; + inertia.m[2][2] = inertia.m[0][0]; + + return inertia; + } + + inline ::Oyster::Math::Float CalculateCuboidX( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float height, const ::Oyster::Math::Float depth ) + { + return (1.0f/12.0f)*mass*(height*height + depth*depth); + } + + inline ::Oyster::Math::Float CalculateCuboidY( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float width, const ::Oyster::Math::Float depth ) + { + return (1.0f/12.0f)*mass*(width*width + depth*depth); + } + + inline ::Oyster::Math::Float CalculateCuboidZ( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float width, const ::Oyster::Math::Float height ) + { + return (1.0f/12.0f)*mass*(height*height + width*width); + } + + inline ::Oyster::Math::Float4x4 Cuboid( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float height, const ::Oyster::Math::Float width, const ::Oyster::Math::Float depth ) + { + ::Oyster::Math::Float4x4 inertia = ::Oyster::Math::Float4x4::identity; + inertia.m[0][0] = ::Oyster::Physics3D::Formula::MomentOfInertia::CalculateCuboidX( mass , height, depth ); + inertia.m[1][1] = ::Oyster::Physics3D::Formula::MomentOfInertia::CalculateCuboidY( mass , width, depth ); + inertia.m[2][2] = ::Oyster::Physics3D::Formula::MomentOfInertia::CalculateCuboidZ( mass , height, width ); + + return inertia; + } + + inline ::Oyster::Math::Float CalculateRodCenter( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float length ) + { + return (1.0f/12.0f)*mass*(length*length); + } + + inline ::Oyster::Math::Float4x4 RodCenter( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float length ) + { + ::Oyster::Math::Float4x4 inertia = ::Oyster::Math::Float4x4::identity; + inertia.m[0][0] = ::Oyster::Physics3D::Formula::MomentOfInertia::CalculateRodCenter( mass , length ); + inertia.m[1][1] = inertia.m[0][0]; + inertia.m[2][2] = inertia.m[0][0]; + + return inertia; + } + + inline ::Oyster::Math::Float CalculateCylinderXY( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float height, const ::Oyster::Math::Float radius ) + { + return (1.0f/12.0f)*mass*(3.0f*radius*radius + height*height); + } + + inline ::Oyster::Math::Float CalculateCylinderZ( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ) + { + return 0.5f*mass*(radius*radius); + } + + inline ::Oyster::Math::Float4x4 Cylinder( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float height, const ::Oyster::Math::Float radius ) + { + ::Oyster::Math::Float4x4 inertia = ::Oyster::Math::Float4x4::identity; + inertia.m[0][0] = ::Oyster::Physics3D::Formula::MomentOfInertia::CalculateCylinderXY( mass , height, radius ); + inertia.m[1][1] = inertia.m[0][0]; + inertia.m[2][2] = ::Oyster::Physics3D::Formula::MomentOfInertia::CalculateCylinderZ( mass , radius ); + + return inertia; + } + } } } } diff --git a/Code/OysterPhysics3D/Plane.cpp b/Code/OysterPhysics3D/Plane.cpp index c999324b..a1a16b14 100644 --- a/Code/OysterPhysics3D/Plane.cpp +++ b/Code/OysterPhysics3D/Plane.cpp @@ -8,8 +8,18 @@ using namespace ::Oyster::Collision3D; using namespace ::Oyster::Math; -Plane::Plane( ) : ICollideable(Type_plane), normal(), phasing(0.0f) {} -Plane::Plane( const Float3 &n, const Float &p ) : ICollideable(Type_plane), normal(n), phasing(p) {} +Plane::Plane( ) : ICollideable(Type_plane) +{ + this->normal = Float3::standard_unit_z; + this->phasing = 0.0f; +} + +Plane::Plane( const Float3 &n, const Float &p ) : ICollideable(Type_plane) +{ + this->normal = n; + this->phasing = p; +} + Plane::~Plane( ) {} Plane & Plane::operator = ( const Plane &plane ) @@ -22,32 +32,32 @@ Plane & Plane::operator = ( const Plane &plane ) ::Utility::DynamicMemory::UniquePointer Plane::Clone( ) const { return ::Utility::DynamicMemory::UniquePointer( new Plane(*this) ); } -bool Plane::Intersects( const ICollideable *target ) const +bool Plane::Intersects( const ICollideable &target ) const { - switch( target->type ) + switch( target.type ) { case Type_universe: return true; - case Type_point: return Utility::Intersect( *this, *(Point*)target ); - case Type_ray: return Utility::Intersect( *this, *(Ray*)target, ((Ray*)target)->collisionDistance ); - case Type_sphere: return Utility::Intersect( *this, *(Sphere*)target ); - case Type_plane: return Utility::Intersect( *this, *(Plane*)target ); - case Type_triangle: return false; // TODO: - case Type_box_axis_aligned: return Utility::Intersect( *(BoxAxisAligned*)target, *this ); - case Type_box: return Utility::Intersect( *(Box*)target, *this ); + case Type_point: return Utility::Intersect( *this, *(Point*)&target ); + case Type_ray: return Utility::Intersect( *this, *(Ray*)&target, ((Ray*)&target)->collisionDistance ); + case Type_sphere: return Utility::Intersect( *this, *(Sphere*)&target ); + case Type_plane: return Utility::Intersect( *this, *(Plane*)&target ); + // case Type_triangle: return false; // TODO: + case Type_box_axis_aligned: return Utility::Intersect( *(BoxAxisAligned*)&target, *this ); + case Type_box: return Utility::Intersect( *(Box*)&target, *this ); case Type_frustrum: return false; // TODO: case Type_line: return false; // TODO: default: return false; } } -bool Plane::Contains( const ICollideable *target ) const +bool Plane::Contains( const ICollideable &target ) const { - switch( target->type ) + switch( target.type ) { - case Type_point: return Utility::Intersect( *this, *(Point*)target ); - case Type_ray: return Utility::Contains( *this, *(Ray*)target ); - case Type_plane: return Utility::Contains( *this, *(Plane*)target ); - case Type_triangle: return false; // TODO: + case Type_point: return Utility::Intersect( *this, *(Point*)&target ); + case Type_ray: return Utility::Contains( *this, *(Ray*)&target ); + case Type_plane: return Utility::Contains( *this, *(Plane*)&target ); + // case Type_triangle: return false; // TODO: default: return false; } } \ No newline at end of file diff --git a/Code/OysterPhysics3D/Plane.h b/Code/OysterPhysics3D/Plane.h index d44c92bd..b69c5c9f 100644 --- a/Code/OysterPhysics3D/Plane.h +++ b/Code/OysterPhysics3D/Plane.h @@ -28,8 +28,8 @@ namespace Oyster { namespace Collision3D Plane & operator = ( const Plane &plane ); virtual ::Utility::DynamicMemory::UniquePointer Clone( ) const; - bool Intersects( const ICollideable *target ) const; - bool Contains( const ICollideable *target ) const; + bool Intersects( const ICollideable &target ) const; + bool Contains( const ICollideable &target ) const; }; } } diff --git a/Code/OysterPhysics3D/Point.cpp b/Code/OysterPhysics3D/Point.cpp index 39cc93af..cf1186c9 100644 --- a/Code/OysterPhysics3D/Point.cpp +++ b/Code/OysterPhysics3D/Point.cpp @@ -8,8 +8,16 @@ using namespace ::Oyster::Collision3D; using namespace ::Oyster::Math3D; -Point::Point( ) : ICollideable(Type_point), center() {} -Point::Point( const Float3 &pos ) : ICollideable(Type_point), center(pos) {} +Point::Point( ) : ICollideable(Type_point) +{ + this->center = Float3::null; +} + +Point::Point( const Float3 &pos ) : ICollideable(Type_point) +{ + this->center = pos; +} + Point::~Point( ) {} Point & Point::operator = ( const Point &point ) @@ -19,30 +27,32 @@ Point & Point::operator = ( const Point &point ) } ::Utility::DynamicMemory::UniquePointer Point::Clone( ) const -{ return ::Utility::DynamicMemory::UniquePointer( new Point(*this) ); } - -bool Point::Intersects( const ICollideable *target ) const { - switch( target->type ) + return ::Utility::DynamicMemory::UniquePointer( new Point(*this) ); +} + +bool Point::Intersects( const ICollideable &target ) const +{ + switch( target.type ) { case Type_universe: return true; - case Type_point: return Utility::Intersect( *this, *(Point*)target ); - case Type_ray: return Utility::Intersect( *(Ray*)target, *this, ((Ray*)target)->collisionDistance ); - case Type_sphere: Utility::Intersect( *(Sphere*)target, *this ); - case Type_plane: return Utility::Intersect( *(Plane*)target, *this ); - case Type_triangle: return false; // TODO: - case Type_box_axis_aligned: return Utility::Intersect( *(BoxAxisAligned*)target, *this ); - case Type_box: return Utility::Intersect( *(Box*)target, *this ); + case Type_point: return Utility::Intersect( *this, *(Point*)&target ); + case Type_ray: return Utility::Intersect( *(Ray*)&target, *this, ((Ray*)&target)->collisionDistance ); + case Type_sphere: Utility::Intersect( *(Sphere*)&target, *this ); + case Type_plane: return Utility::Intersect( *(Plane*)&target, *this ); + //case Type_triangle: return false; // TODO: + case Type_box_axis_aligned: return Utility::Intersect( *(BoxAxisAligned*)&target, *this ); + case Type_box: return Utility::Intersect( *(Box*)&target, *this ); case Type_frustrum: return false; // TODO: default: return false; } } -bool Point::Contains( const ICollideable *target ) const +bool Point::Contains( const ICollideable &target ) const { - switch( target->type ) + switch( target.type ) { - case Type_point: return Utility::Intersect( *this, *(Point*)target ); + case Type_point: return Utility::Intersect( *this, *(Point*)&target ); default: return false; } } \ No newline at end of file diff --git a/Code/OysterPhysics3D/Point.h b/Code/OysterPhysics3D/Point.h index 2529ae0c..42561909 100644 --- a/Code/OysterPhysics3D/Point.h +++ b/Code/OysterPhysics3D/Point.h @@ -27,8 +27,8 @@ namespace Oyster { namespace Collision3D Point & operator = ( const Point &point ); virtual ::Utility::DynamicMemory::UniquePointer Clone( ) const; - bool Intersects( const ICollideable *target ) const; - bool Contains( const ICollideable *target ) const; + bool Intersects( const ICollideable &target ) const; + bool Contains( const ICollideable &target ) const; }; } } diff --git a/Code/OysterPhysics3D/Ray.cpp b/Code/OysterPhysics3D/Ray.cpp index f7873437..09fb13ec 100644 --- a/Code/OysterPhysics3D/Ray.cpp +++ b/Code/OysterPhysics3D/Ray.cpp @@ -8,8 +8,20 @@ using namespace ::Oyster::Collision3D; using namespace ::Oyster::Math3D; -Ray::Ray( ) : ICollideable(Type_ray), origin(), direction(), collisionDistance(0.0f) {} -Ray::Ray( const Float3 &o, const ::Oyster::Math::Float3 &d ) : ICollideable(Type_ray), origin(o), direction(d), collisionDistance(0.0f) {} +Ray::Ray( ) : ICollideable(Type_ray) +{ + this->origin = Float3::null; + this->direction = Float3::standard_unit_z; + this->collisionDistance = 0.0f; +} + +Ray::Ray( const Float3 &o, const ::Oyster::Math::Float3 &d ) : ICollideable(Type_ray) +{ + this->origin = o; + this->direction = d; + this->collisionDistance = 0.0f; +} + Ray::~Ray( ) {} Ray & Ray::operator = ( const Ray &ray ) @@ -20,33 +32,35 @@ Ray & Ray::operator = ( const Ray &ray ) } ::Utility::DynamicMemory::UniquePointer Ray::Clone( ) const -{ return ::Utility::DynamicMemory::UniquePointer( new Ray(*this) ); } - -bool Ray::Intersects( const ICollideable *target ) const { - switch( target->type ) + return ::Utility::DynamicMemory::UniquePointer( new Ray(*this) ); +} + +bool Ray::Intersects( const ICollideable &target ) const +{ + switch( target.type ) { case Type_universe: this->collisionDistance = 0.0f; return true; - case Type_point: return Utility::Intersect( *this, *(Point*)target, this->collisionDistance ); - case Type_ray: return Utility::Intersect( *this, *(Ray*)target, this->collisionDistance, ((Ray*)target)->collisionDistance ); - case Type_sphere: return Utility::Intersect( *(Sphere*)target, *this, this->collisionDistance ); - case Type_plane: return Utility::Intersect( *(Plane*)target, *this, this->collisionDistance ); - case Type_triangle: return false; // TODO: - case Type_box_axis_aligned: return Utility::Intersect( *(BoxAxisAligned*)target, *this, this->collisionDistance ); - case Type_box: return Utility::Intersect( *(Box*)target, *this, this->collisionDistance ); + case Type_point: return Utility::Intersect( *this, *(Point*)&target, this->collisionDistance ); + case Type_ray: return Utility::Intersect( *this, *(Ray*)&target, this->collisionDistance, ((Ray*)&target)->collisionDistance ); + case Type_sphere: return Utility::Intersect( *(Sphere*)&target, *this, this->collisionDistance ); + case Type_plane: return Utility::Intersect( *(Plane*)&target, *this, this->collisionDistance ); + // case Type_triangle: return false; // TODO: + case Type_box_axis_aligned: return Utility::Intersect( *(BoxAxisAligned*)&target, *this, this->collisionDistance ); + case Type_box: return Utility::Intersect( *(Box*)&target, *this, this->collisionDistance ); case Type_frustrum: return false; // TODO: default: return false; } } -bool Ray::Contains( const ICollideable *target ) const +bool Ray::Contains( const ICollideable &target ) const { - switch( target->type ) + switch( target.type ) { - case Type_point: return Utility::Intersect( *this, *(Point*)target, this->collisionDistance ); - case Type_ray: Utility::Contains( *this, *(Ray*)target ); + case Type_point: return Utility::Intersect( *this, *(Point*)&target, this->collisionDistance ); + case Type_ray: Utility::Contains( *this, *(Ray*)&target ); default: return false; } } \ No newline at end of file diff --git a/Code/OysterPhysics3D/Ray.h b/Code/OysterPhysics3D/Ray.h index 4132c0b8..5f24ea81 100644 --- a/Code/OysterPhysics3D/Ray.h +++ b/Code/OysterPhysics3D/Ray.h @@ -36,8 +36,8 @@ namespace Oyster { namespace Collision3D Ray & operator = ( const Ray &ray ); virtual ::Utility::DynamicMemory::UniquePointer Clone( ) const; - bool Intersects( const ICollideable *target ) const; - bool Contains( const ICollideable *target ) const; + bool Intersects( const ICollideable &target ) const; + bool Contains( const ICollideable &target ) const; }; } } diff --git a/Code/OysterPhysics3D/RigidBody.cpp b/Code/OysterPhysics3D/RigidBody.cpp index 214a1aee..182a5a17 100644 --- a/Code/OysterPhysics3D/RigidBody.cpp +++ b/Code/OysterPhysics3D/RigidBody.cpp @@ -9,9 +9,14 @@ using namespace ::Oyster::Collision3D; using namespace ::Oyster::Physics3D; using namespace ::Oyster::Math3D; -RigidBody::RigidBody( const Box &b, Float m ) - : box(b), angularMomentum(0.0f), linearMomentum(0.0f), impulseTorqueSum(0.0f), impulseForceSum(0.0f) +RigidBody::RigidBody( const Box &b, Float m, const Float4x4 &inertiaTensor ) { // by Dan Andersson + this->box = b; + this->angularMomentum = Float3::null; + this->linearMomentum = Float3::null; + this->impulseTorqueSum = Float3::null; + this->impulseForceSum = Float3::null; + if( m != 0.0f ) { this->mass = m; @@ -21,7 +26,14 @@ RigidBody::RigidBody( const Box &b, Float m ) this->mass = ::Utility::Value::numeric_limits::epsilon(); } - this->momentOfInertiaTensor = Float4x4::identity; + if( inertiaTensor.GetDeterminant() != 0.0f ) + { + this->momentOfInertiaTensor = inertiaTensor; + } + else + { + this->momentOfInertiaTensor = Float4x4::identity; + } } RigidBody & RigidBody::operator = ( const RigidBody &body ) @@ -36,6 +48,51 @@ RigidBody & RigidBody::operator = ( const RigidBody &body ) return *this; } +bool RigidBody::operator == ( const RigidBody &body ) +{ + if( this->box.center != body.box.center ) + { + return false; + } + + if( this->box.rotation != body.box.rotation ) + { + return false; + } + + if( this->box.boundingOffset != body.box.boundingOffset ) + { + return false; + } + + if( this->angularMomentum != body.angularMomentum ) + { + return false; + } + + if( this->linearMomentum != body.linearMomentum ) + { + return false; + } + + if( this->impulseTorqueSum != body.impulseTorqueSum ) + { + return false; + } + + if( this->impulseForceSum != body.impulseForceSum ) + { + return false; + } + + return true; +} + +bool RigidBody::operator != ( const RigidBody &body ) +{ + return !this->operator==( body ); +} + void RigidBody::Update_LeapFrog( Float deltaTime ) { // by Dan Andersson: Euler leap frog update when Runga Kutta is not needed @@ -225,7 +282,7 @@ Float3 RigidBody::GetLinearVelocity() const } void RigidBody::GetMomentumAt( const Float3 &worldPos, const Float3 &surfaceNormal, Float3 &normalMomentum, Float3 &tangentialMomentum ) const -{ +{ // by Dan Andersson Float3 worldOffset = worldPos - this->box.center; Float3 momentum = Formula::TangentialLinearMomentum( this->angularMomentum, worldOffset ); momentum += this->linearMomentum; @@ -234,7 +291,18 @@ void RigidBody::GetMomentumAt( const Float3 &worldPos, const Float3 &surfaceNorm tangentialMomentum = momentum - normalMomentum; } -void RigidBody::SetMomentOfInertia( const Float4x4 &localI ) +void RigidBody::SetMomentOfInertia_KeepVelocity( const ::Oyster::Math::Float4x4 &localI ) +{ // by Dan Andersson + if( localI.GetDeterminant() != 0.0f ) // insanitycheck! momentOfInertiaTensor must be invertable + { + Float3 w = Formula::AngularVelocity( (this->box.rotation * this->momentOfInertiaTensor).GetInverse(), + this->angularMomentum ); + this->momentOfInertiaTensor = localI; + this->angularMomentum = Formula::AngularMomentum( this->box.rotation*localI, w ); + } +} + +void RigidBody::SetMomentOfInertia_KeepMomentum( const Float4x4 &localI ) { // by Dan Andersson if( localI.GetDeterminant() != 0.0f ) // insanitycheck! momentOfInertiaTensor must be invertable { @@ -246,9 +314,9 @@ void RigidBody::SetMass_KeepVelocity( const Float &m ) { // by Dan Andersson if( m != 0.0f ) // insanitycheck! mass must be invertable { - Float3 velocity = Formula::LinearVelocity( this->mass, this->linearMomentum ); + Float3 v = Formula::LinearVelocity( this->mass, this->linearMomentum ); this->mass = m; - this->linearMomentum = Formula::LinearMomentum( this->mass, velocity ); + this->linearMomentum = Formula::LinearMomentum( this->mass, v ); } } @@ -276,6 +344,11 @@ void RigidBody::SetCenter( const Float3 &worldPos ) this->box.center = worldPos; } +void RigidBody::SetRotation( const Float4x4 &r ) +{ // by Dan Andersson + this->box.rotation = r; +} + void RigidBody::SetImpulseTorque( const Float3 &worldT ) { // by Dan Andersson this->impulseTorqueSum = worldT; diff --git a/Code/OysterPhysics3D/RigidBody.h b/Code/OysterPhysics3D/RigidBody.h index 19ce6bb2..81c92ae0 100644 --- a/Code/OysterPhysics3D/RigidBody.h +++ b/Code/OysterPhysics3D/RigidBody.h @@ -20,10 +20,15 @@ namespace Oyster { namespace Physics3D impulseTorqueSum, /** The impulse torque T (Nm) that will be consumed each update. (worldValue) */ impulseForceSum; /** The impulse force F (N) that will be consumed each update. (worldValue) */ - RigidBody( const ::Oyster::Collision3D::Box &box = ::Oyster::Collision3D::Box(), ::Oyster::Math::Float mass = 1.0f ); + RigidBody( const ::Oyster::Collision3D::Box &box = ::Oyster::Collision3D::Box(), + ::Oyster::Math::Float mass = 12.0f, + const ::Oyster::Math::Float4x4 &inertiaTensor = ::Oyster::Math::Float4x4::identity ); RigidBody & operator = ( const RigidBody &body ); + bool operator == ( const RigidBody &body ); + bool operator != ( const RigidBody &body ); + void Update_LeapFrog( ::Oyster::Math::Float deltaTime ); void ApplyImpulseForce( const ::Oyster::Math::Float3 &worldF ); void ApplyImpulseForceAt( const ::Oyster::Math::Float3 &worldF, const ::Oyster::Math::Float3 &worldPos ); @@ -68,13 +73,15 @@ namespace Oyster { namespace Physics3D // SET METHODS //////////////////////////////// - void SetMomentOfInertia( const ::Oyster::Math::Float4x4 &localI ); + void SetMomentOfInertia_KeepVelocity( const ::Oyster::Math::Float4x4 &localI ); + void SetMomentOfInertia_KeepMomentum( const ::Oyster::Math::Float4x4 &localI ); void SetMass_KeepVelocity( const ::Oyster::Math::Float &m ); void SetMass_KeepMomentum( const ::Oyster::Math::Float &m ); void SetOrientation( const ::Oyster::Math::Float4x4 &o ); void SetSize( const ::Oyster::Math::Float3 &widthHeight ); void SetCenter( const ::Oyster::Math::Float3 &worldPos ); + void SetRotation( const ::Oyster::Math::Float4x4 &r ); void SetImpulseTorque( const ::Oyster::Math::Float3 &worldT ); void SetAngularMomentum( const ::Oyster::Math::Float3 &worldH ); diff --git a/Code/OysterPhysics3D/Sphere.cpp b/Code/OysterPhysics3D/Sphere.cpp index f138208c..0cc8bc3b 100644 --- a/Code/OysterPhysics3D/Sphere.cpp +++ b/Code/OysterPhysics3D/Sphere.cpp @@ -4,8 +4,18 @@ using namespace ::Oyster::Collision3D; using namespace ::Oyster::Math; -Sphere::Sphere( ) : ICollideable(Type_sphere), center(), radius(0.0f) { } -Sphere::Sphere( const Float3 &_position, const Float &_radius ) : ICollideable(Type_sphere), center(_position), radius(_radius) {} +Sphere::Sphere( ) : ICollideable(Type_sphere) +{ + this->center = Float3::null; + this->radius = 0.0f; +} + +Sphere::Sphere( const Float3 &_position, const Float &_radius ) : ICollideable(Type_sphere) +{ + this->center = _position; + this->radius = _radius; +} + Sphere::~Sphere( ) {} Sphere & Sphere::operator = ( const Sphere &sphere ) @@ -18,30 +28,30 @@ Sphere & Sphere::operator = ( const Sphere &sphere ) ::Utility::DynamicMemory::UniquePointer Sphere::Clone( ) const { return ::Utility::DynamicMemory::UniquePointer( new Sphere(*this) ); } -bool Sphere::Intersects( const ICollideable *target ) const +bool Sphere::Intersects( const ICollideable &target ) const { - switch( target->type ) + switch( target.type ) { case Type_universe: return true; - case Type_point: return Utility::Intersect( *this, *(Point*)target ); - case Type_ray: return Utility::Intersect( *this, *(Ray*)target, ((Ray*)target)->collisionDistance ); - case Type_sphere: Utility::Intersect( *this, *(Sphere*)target ); - case Type_plane: return Utility::Intersect( *(Plane*)target, *this ); - case Type_triangle: return false; // TODO: - case Type_box_axis_aligned: return Utility::Intersect( *(BoxAxisAligned*)target, *this ); - case Type_box: return Utility::Intersect( *(Box*)target, *this ); + case Type_point: return Utility::Intersect( *this, *(Point*)&target ); + case Type_ray: return Utility::Intersect( *this, *(Ray*)&target, ((Ray*)&target)->collisionDistance ); + case Type_sphere: Utility::Intersect( *this, *(Sphere*)&target ); + case Type_plane: return Utility::Intersect( *(Plane*)&target, *this ); + // case Type_triangle: return false; // TODO: + case Type_box_axis_aligned: return Utility::Intersect( *(BoxAxisAligned*)&target, *this ); + case Type_box: return Utility::Intersect( *(Box*)&target, *this ); case Type_frustrum: return false; // TODO: default: return false; } } -bool Sphere::Contains( const ICollideable *target ) const +bool Sphere::Contains( const ICollideable &target ) const { - switch( target->type ) + switch( target.type ) { - case Type_point: return Utility::Intersect( *this, *(Point*)target ); - case Type_sphere: return Utility::Contains( *this, *(Sphere*)target ); - case Type_triangle: return false; // TODO: + case Type_point: return Utility::Intersect( *this, *(Point*)&target ); + case Type_sphere: return Utility::Contains( *this, *(Sphere*)&target ); + // case Type_triangle: return false; // TODO: case Type_box_axis_aligned: return false; // TODO: case Type_box: return false; // TODO: case Type_frustrum: return false; // TODO: diff --git a/Code/OysterPhysics3D/Sphere.h b/Code/OysterPhysics3D/Sphere.h index 881c8928..8e73de0b 100644 --- a/Code/OysterPhysics3D/Sphere.h +++ b/Code/OysterPhysics3D/Sphere.h @@ -27,8 +27,8 @@ namespace Oyster { namespace Collision3D Sphere & operator = ( const Sphere &sphere ); virtual ::Utility::DynamicMemory::UniquePointer Clone( ) const; - bool Intersects( const ICollideable *target ) const; - bool Contains( const ICollideable *target ) const; + bool Intersects( const ICollideable &target ) const; + bool Contains( const ICollideable &target ) const; }; } } diff --git a/Code/OysterPhysics3D/Universe.cpp b/Code/OysterPhysics3D/Universe.cpp index f473ff2c..725e2839 100644 --- a/Code/OysterPhysics3D/Universe.cpp +++ b/Code/OysterPhysics3D/Universe.cpp @@ -13,15 +13,15 @@ Universe & Universe::operator = ( const Universe &universe ) UniquePointer Universe::Clone( ) const { return UniquePointer( new Universe(*this) ); } -bool Universe::Intersects( const ICollideable *target ) const +bool Universe::Intersects( const ICollideable &target ) const { // universe touches everything - switch( target->type ) + switch( target.type ) { case Type_ray: - ((Ray*)target)->collisionDistance = 0.0f; + ((Ray*)&target)->collisionDistance = 0.0f; break; case Type_line: - ((Line*)target)->ray.collisionDistance = 0.0f; + ((Line*)&target)->ray.collisionDistance = 0.0f; break; default: break; } @@ -29,6 +29,6 @@ bool Universe::Intersects( const ICollideable *target ) const return true; } -bool Universe::Contains( const ICollideable *target ) const +bool Universe::Contains( const ICollideable &target ) const { return true; } // universe contains everything diff --git a/Code/OysterPhysics3D/Universe.h b/Code/OysterPhysics3D/Universe.h index fd06a454..ff8366be 100644 --- a/Code/OysterPhysics3D/Universe.h +++ b/Code/OysterPhysics3D/Universe.h @@ -19,8 +19,8 @@ namespace Oyster { namespace Collision3D Universe & operator = ( const Universe &universe ); virtual ::Utility::DynamicMemory::UniquePointer Clone( ) const; - bool Intersects( const ICollideable *target ) const; - bool Contains( const ICollideable *target ) const; + bool Intersects( const ICollideable &target ) const; + bool Contains( const ICollideable &target ) const; }; } } diff --git a/Code/Tester/MainTest.cpp b/Code/Tester/MainTest.cpp index ad7d4774..607ba3b4 100644 --- a/Code/Tester/MainTest.cpp +++ b/Code/Tester/MainTest.cpp @@ -7,19 +7,16 @@ //-------------------------------------------------------------------------------------- #define NOMINMAX #include -#include "Core/Core.h" -#include "Render\Preparations\Preparations.h" -#include "Render\Resources\Resources.h" -#include "Render\Rendering\Render.h" -#include "FileLoader\ObjReader.h" -#include "Definitions\GraphicalDefinition.h" +#include "DllInterfaces\GFXAPI.h" + + //-------------------------------------------------------------------------------------- // Global Variables //-------------------------------------------------------------------------------------- HINSTANCE g_hInst = NULL; HWND g_hWnd = NULL; -Oyster::Graphics::Render::Model* m = new Oyster::Graphics::Render::Model(); +Oyster::Graphics::Model::Model* m = new Oyster::Graphics::Model::Model(); Oyster::Math::Float4x4 V; Oyster::Math::Float4x4 P; @@ -42,6 +39,22 @@ HRESULT InitDirect3D(); //-------------------------------------------------------------------------------------- int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) { + + BOOL b = SetDllDirectoryW(L"..\\..\\DLL"); + typedef struct tagLOADPARMS32 + { + LPSTR lpEnvAddress; // address of environment strings + LPSTR lpCmdLine; // address of command line + LPSTR lpCmdShow; // how to show new program + DWORD dwReserved; // must be zero + } LOADPARMS32; + LOADPARMS32 params; + params.dwReserved=NULL; + params.lpCmdLine=""; + params.lpCmdShow=""; + params.lpEnvAddress=""; + LoadModule("OysterGraphics_x86D.dll",¶ms); + if( FAILED( InitWindow( hInstance, nCmdShow ) ) ) return 0; @@ -138,15 +151,10 @@ HRESULT InitDirect3D() { HRESULT hr = S_OK;; - Oyster::Graphics::Core::resolution = Oyster::Math::Float2( 1024, 768 ); - - if(Oyster::Graphics::Core::Init::FullInit(g_hWnd,false,false)==Oyster::Graphics::Core::Init::Fail) + if(Oyster::Graphics::API::Init(g_hWnd,false,false, Oyster::Math::Float2( 1024, 768 )) == Oyster::Graphics::API::Fail) + { return E_FAIL; - - //Init shaders - Oyster::Graphics::Render::Resources::Init(); - - Oyster::Graphics::Render::Preparations::Basic::SetViewPort(); + } #pragma region Triangle //Oyster::Graphics::Definitions::ObjVertex mesh[] = @@ -176,14 +184,13 @@ HRESULT InitDirect3D() #pragma endregion #pragma region Obj - OBJReader or; - or.readOBJFile(L"bth.obj"); - m->info = or.toModel(); + m = Oyster::Graphics::API::CreateModel(L"bth.obj"); + m->WorldMatrix *= 0.1f; + m->WorldMatrix.m44 = 1; #pragma endregion - m->World = Oyster::Math::Matrix::identity; - P = Oyster::Math3D::ProjectionMatrix_Perspective(PI/2,16.0f/9.0f,.1f,100); + P = Oyster::Math3D::ProjectionMatrix_Perspective(Oyster::Math::pi/2,1024.0f/768.0f,.1f,100); V = Oyster::Math3D::OrientationMatrix_LookAtDirection(Oyster::Math::Float3(0,0,-1),Oyster::Math::Float3(0,1,0),Oyster::Math::Float3(0,-1.5f,10.4f)); V = Oyster::Math3D::InverseOrientationMatrix(V); @@ -199,18 +206,11 @@ HRESULT Update(float deltaTime) HRESULT Render(float deltaTime) { - Oyster::Graphics::Render::Rendering::Basic::NewFrame(V,P); - //Oyster::Graphics::Render::Preparations::Basic::ClearBackBuffer(Oyster::Math::Float4(0,0,1,1)); + Oyster::Graphics::API::NewFrame(V,P); - //m->info->Vertices->Apply(0); + Oyster::Graphics::API::RenderScene(m,1); - //Oyster::Graphics::Core::deviceContext->Draw(3,0); - - //Oyster::Graphics::Core::swapChain->Present(0,0); - - Oyster::Graphics::Render::Rendering::Basic::RenderScene(m,1); - - Oyster::Graphics::Render::Rendering::Basic::EndFrame(); + Oyster::Graphics::API::EndFrame(); return S_OK; } diff --git a/Code/Tester/Tester.vcxproj b/Code/Tester/Tester.vcxproj index a810a51a..528c805c 100644 --- a/Code/Tester/Tester.vcxproj +++ b/Code/Tester/Tester.vcxproj @@ -103,7 +103,14 @@ Windows true + OysterGraphics_$(PlatformShortName)D.lib;%(AdditionalDependencies) + $(SolutionDir)..\Bin\DLL;%(AdditionalLibraryDirectories) + OysterGraphics_x86D.dll;%(DelayLoadDLLs) + + + + @@ -118,6 +125,9 @@ Windows true + OysterGraphics_$(PlatformShortName)D.lib;%(AdditionalDependencies) + $(SolutionDir)..\Bin\DLL;%(AdditionalLibraryDirectories) + true @@ -130,12 +140,16 @@ true WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) true + ..\OysterGraphics;..\OysterMath;..\Misc;%(AdditionalIncludeDirectories) Windows true true true + OysterGraphics_$(PlatformShortName).lib;%(AdditionalDependencies) + $(SolutionDir)..\Bin\DLL;%(AdditionalLibraryDirectories) + true @@ -148,12 +162,16 @@ true WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) true + ..\OysterGraphics;..\OysterMath;..\Misc;%(AdditionalIncludeDirectories) Windows true true true + OysterGraphics_$(PlatformShortName).lib;%(AdditionalDependencies) + $(SolutionDir)..\Bin\DLL;%(AdditionalLibraryDirectories) + true @@ -165,6 +183,11 @@ {0ec83e64-230e-48ef-b08c-6ac9651b4f82} + false + true + false + false + false {f10cbc03-9809-4cba-95d8-327c287b18ee}