diff --git a/Bin/DLL/DebugCameraVertex.cso b/Bin/DLL/DebugCameraVertex.cso deleted file mode 100644 index a7193b0b..00000000 Binary files a/Bin/DLL/DebugCameraVertex.cso and /dev/null differ diff --git a/Bin/DLL/DebugPixel.cso b/Bin/DLL/DebugPixel.cso deleted file mode 100644 index 85c09751..00000000 Binary files a/Bin/DLL/DebugPixel.cso and /dev/null differ diff --git a/Bin/DLL/DebugVertex.cso b/Bin/DLL/DebugVertex.cso deleted file mode 100644 index 409bf6f3..00000000 Binary files a/Bin/DLL/DebugVertex.cso and /dev/null differ diff --git a/Bin/DLL/GamePhysics_x86D.dll b/Bin/DLL/GamePhysics_x86D.dll deleted file mode 100644 index e0cde94c..00000000 Binary files a/Bin/DLL/GamePhysics_x86D.dll and /dev/null differ diff --git a/Bin/DLL/GamePhysics_x86D.exp b/Bin/DLL/GamePhysics_x86D.exp deleted file mode 100644 index 8f629462..00000000 Binary files a/Bin/DLL/GamePhysics_x86D.exp and /dev/null differ diff --git a/Bin/DLL/GamePhysics_x86D.ilk b/Bin/DLL/GamePhysics_x86D.ilk deleted file mode 100644 index be8bdf09..00000000 Binary files a/Bin/DLL/GamePhysics_x86D.ilk and /dev/null differ diff --git a/Bin/DLL/GamePhysics_x86D.pdb b/Bin/DLL/GamePhysics_x86D.pdb deleted file mode 100644 index b303fcd0..00000000 Binary files a/Bin/DLL/GamePhysics_x86D.pdb and /dev/null differ diff --git a/Bin/DLL/OysterGraphics_x86D.dll b/Bin/DLL/OysterGraphics_x86D.dll deleted file mode 100644 index 6dce6c5d..00000000 Binary files a/Bin/DLL/OysterGraphics_x86D.dll and /dev/null differ diff --git a/Bin/DLL/OysterGraphics_x86D.exp b/Bin/DLL/OysterGraphics_x86D.exp deleted file mode 100644 index 47ea6535..00000000 Binary files a/Bin/DLL/OysterGraphics_x86D.exp and /dev/null differ diff --git a/Bin/DLL/OysterGraphics_x86D.ilk b/Bin/DLL/OysterGraphics_x86D.ilk deleted file mode 100644 index 4916683f..00000000 Binary files a/Bin/DLL/OysterGraphics_x86D.ilk and /dev/null differ diff --git a/Bin/DLL/OysterGraphics_x86D.pdb b/Bin/DLL/OysterGraphics_x86D.pdb deleted file mode 100644 index baf503ea..00000000 Binary files a/Bin/DLL/OysterGraphics_x86D.pdb and /dev/null differ diff --git a/Bin/DLL/PixelGatherData.cso b/Bin/DLL/PixelGatherData.cso deleted file mode 100644 index 1b5ca385..00000000 Binary files a/Bin/DLL/PixelGatherData.cso and /dev/null differ diff --git a/Bin/DLL/TextureDebug.cso b/Bin/DLL/TextureDebug.cso deleted file mode 100644 index bce054c2..00000000 Binary files a/Bin/DLL/TextureDebug.cso and /dev/null differ diff --git a/Bin/DLL/VertexGatherData.cso b/Bin/DLL/VertexGatherData.cso deleted file mode 100644 index 50f8cf52..00000000 Binary files a/Bin/DLL/VertexGatherData.cso and /dev/null differ 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..23c1a119 --- /dev/null +++ b/Code/DanBiasGame/DanBiasMaincpp.cpp @@ -0,0 +1,316 @@ +//-------------------------------------------------------------------------------------- +// 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 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 ) +{ + // for dynamic .dll loading + // path is relative to the .exe and .dll pos + // also change the VC directories - working dir is set to $(SolutionDir)..\Bin\Executable\Tester + // to fit with where the .obj files is + // linker/ input/ delayed load .dll - specify the .dll that should be loaded + + BOOL success = SetDllDirectory(L"..\\..\\DLL"); + if (success == 0) + { + return 0; + } + + 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); + + //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; +} + +//-------------------------------------------------------------------------------------- +// Create Direct3D with Oyster Graphics +//-------------------------------------------------------------------------------------- +HRESULT InitDirect3D() +{ + if(Oyster::Graphics::API::Init(g_hWnd, false, false, Oyster::Math::Float2( 1024, 768)) != Oyster::Graphics::API::Sucsess) + return E_FAIL; + return S_OK; +} + +//-------------------------------------------------------------------------------------- +// Init the input and the game +//------------------------------------------------------------------------------------- +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; + } + 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; + } + + float pitch = 0; + float yaw = 0; + + //if(inputObj->IsMousePressed()) + //{ + pitch = inputObj->GetPitch(); + yaw = inputObj->GetYaw(); + //} + + game->Update(key, pitch, yaw); + + + return S_OK; +} + +HRESULT Render(float deltaTime) +{ + int isPressed = 0; + if(inputObj->IsKeyPressed(DIK_A)) + { + isPressed = 1; + //std::cout<<"test"; + } + + 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/Camera.cpp b/Code/GameLogic/Camera.cpp new file mode 100644 index 00000000..a969ced5 --- /dev/null +++ b/Code/GameLogic/Camera.cpp @@ -0,0 +1,185 @@ +#include "Camera.h" + +Camera::Camera() +{ + this->m_position = Oyster::Math::Float3(0, 50, 0); + this->mRight = Oyster::Math::Float3(1, 0, 0); + this->mUp = Oyster::Math::Float3(0, 1, 0); + this->mLook = Oyster::Math::Float3(0, 0, 1); +} + +Camera::~Camera() +{ +} + +void Camera::SetPosition(const Oyster::Math::Float3& v) +{ + this->m_position = v; +} + +Oyster::Math::Float3 Camera::GetPosition()const +{ + return this->m_position; +} + +Oyster::Math::Float3 Camera::GetRight()const +{ + return this->mRight; +} + +Oyster::Math::Float3 Camera::GetUp()const +{ + return this->mUp; +} + +Oyster::Math::Float3 Camera::GetLook()const +{ + return this->mLook; +} + +float Camera::GetNearZ()const +{ + return this->mNearZ; +} + +float Camera::GetFarZ()const +{ + return this->mFarZ; +} + +float Camera::GetAspect()const +{ + return this->mAspect; +} + +Oyster::Math::Float3 Camera::CrossMatrix(const Oyster::Math::Float3& vector, const Oyster::Math::Float4x4& matrix) +{ + Oyster::Math::Float3 vec; + vec.x = matrix.m11*vector.x + matrix.m12*vector.y + matrix.m13*vector.z; + vec.y = matrix.m21*vector.x + matrix.m22*vector.y + matrix.m23*vector.z; + vec.z = matrix.m31*vector.x + matrix.m32*vector.y + matrix.m33*vector.z; + return vec; +} + +void Camera::SetLens(float fovY, float aspect, float zn, float zf) +{ + this->mFovY = fovY; + this->mAspect = aspect; + this->mNearZ = zn; + this->mFarZ = zf; + + float yScale = tan((Oyster::Math::pi*0.5f) - (mFovY*0.5f)); + float xScale = yScale/this->mAspect; + + mProj = Oyster::Math::Float4x4(xScale, 0, 0, 0, + 0, yScale, 0, 0, + 0, 0, zf/(zf-zn), 1, + 0, 0, -zn*zf/(zf-zn), 0); + mProj.Transpose(); +} + +void Camera::LookAt(Oyster::Math::Float3 pos, Oyster::Math::Float3 target, Oyster::Math::Float3 worldUp) +{ + Oyster::Math::Float3 L; + + L = target - pos; + L.Normalize(); + + Oyster::Math::Float3 R; + R = worldUp.Cross(L); + R.Normalize(); + + Oyster::Math::Float3 U; + U = L.Cross(R); + + this->m_position = pos; + this->mLook = L; + this->mRight = R; + this->mUp = U; +} + +Oyster::Math::Float4x4 Camera::View()const +{ + return this->mView; +} + +Oyster::Math::Float4x4 Camera::Proj()const +{ + return this->mProj; +} + +Oyster::Math::Float4x4 Camera::ViewsProj()const +{ + Oyster::Math::Float4x4 M; + M = mView * mProj; + return M; +} + +void Camera::Walk(float dist) +{ + this->m_position += dist*this->mLook; +} + +void Camera::Strafe(float dist) +{ + this->m_position += dist*this->mRight; +} + +void Camera::Pitch(float angle) +{ + float radians = angle * 0.0174532925f; + + Oyster::Math::Float4x4 R; + + Oyster::Math3D::RotationMatrix(radians,-mRight,R); + this->mUp = CrossMatrix(this->mUp, R); + this->mLook = CrossMatrix(this->mLook, R); +} + +void Camera::Yaw(float angle) +{ + float radians = angle * 0.0174532925f; + + Oyster::Math::Float4x4 R; + + Oyster::Math::Float3 up(0,1,0); + Oyster::Math3D::RotationMatrix(radians,-up,R); + + this->mRight = CrossMatrix(this->mRight, R); + this->mUp = CrossMatrix(mUp, R); + this->mLook = CrossMatrix(this->mLook, R); +} + +void Camera::UpdateViewMatrix() +{ + mLook.Normalize(); + mUp = mLook.Cross(mRight); + mUp.Normalize(); + mRight = mUp.Cross(mLook); + + float x = -m_position.Dot(mRight); + float y = -m_position.Dot(mUp); + float z = -m_position.Dot(mLook); + + mView.m11 = mRight.x; + mView.m21 = mRight.y; + mView.m31 = mRight.z; + mView.m41 = x; + + mView.m12 = mUp.x; + mView.m22 = mUp.y; + mView.m32 = mUp.z; + mView.m42 = y; + + mView.m13 = mLook.x; + mView.m23 = mLook.y; + mView.m33 = mLook.z; + mView.m43 = z; + + mView.m14 = 0.0f; + mView.m24 = 0.0f; + mView.m34 = 0.0f; + mView.m44 = 1.0f; + + mView.Transpose(); +} \ No newline at end of file diff --git a/Code/GameLogic/Camera.h b/Code/GameLogic/Camera.h new file mode 100644 index 00000000..deb9df62 --- /dev/null +++ b/Code/GameLogic/Camera.h @@ -0,0 +1,63 @@ +#ifndef CAMERA__H +#define CAMERA__H + +#include "OysterMath.h" + +class Camera +{ +private: + + Oyster::Math::Float3 m_position; + Oyster::Math::Float3 mRight; + Oyster::Math::Float3 mUp; + Oyster::Math::Float3 mLook; + + + + float mNearZ; + float mFarZ; + float mAspect; + float mFovY; + + Oyster::Math::Float4x4 mView; + Oyster::Math::Float4x4 mProj; + +public: + Camera(); + virtual ~Camera(); + + void SetPosition(const Oyster::Math::Float3& v); + + Oyster::Math::Float3 GetPosition()const; + + Oyster::Math::Float3 GetRight()const; + Oyster::Math::Float3 GetUp()const; + Oyster::Math::Float3 GetLook()const; + + float GetNearZ()const; + float GetFarZ()const; + float GetAspect()const; + + Oyster::Math::Float3 CrossMatrix(const Oyster::Math::Float3& v, const Oyster::Math::Float4x4& m); + + void SetLens(float fovY, float aspect, float zn, float zf); + + void LookAt(Oyster::Math::Float3 pos, Oyster::Math::Float3 target, Oyster::Math::Float3 worldUp); + + void setLook(Oyster::Math::Float3 look) { mLook = look; } + void setUp(Oyster::Math::Float3 up) { mUp = up; } + void setRight(Oyster::Math::Float3 right) { mRight = right; } + + Oyster::Math::Float4x4 View()const; + Oyster::Math::Float4x4 Proj()const; + Oyster::Math::Float4x4 ViewsProj()const; + + void Walk(float dist); + void Strafe(float dist); + + void Pitch(float angle); + void Yaw(float angle); + + void UpdateViewMatrix(); +}; +#endif \ No newline at end of file diff --git a/Code/GameLogic/CollisionManager.cpp b/Code/GameLogic/CollisionManager.cpp new file mode 100644 index 00000000..f7868b79 --- /dev/null +++ b/Code/GameLogic/CollisionManager.cpp @@ -0,0 +1,50 @@ +#include "CollisionManager.h" + + + +namespace GameLogic +{ + + namespace CollisionManager + { + + 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..a650f595 --- /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 + { + //these are the main collision functions + void PlayerCollision(Oyster::Physics::ICustomBody &rigidBodyPlayer,Oyster::Physics::ICustomBody &obj); + void BoxCollision(Oyster::Physics::ICustomBody &rigidBodyBox, Oyster::Physics::ICustomBody &obj); + + //these are the specific collision case functions + 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..14e0518d --- /dev/null +++ b/Code/GameLogic/DynamicObject.cpp @@ -0,0 +1,20 @@ +#include "DynamicObject.h" + +using namespace GameLogic; +using namespace Oyster::Physics; +using namespace Utility::DynamicMemory; + +DynamicObject::DynamicObject(void) + :Object() +{ +} + + +DynamicObject::~DynamicObject(void) +{ +} + +void DynamicObject::Update() +{ + //update object +} \ 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..b4095130 --- /dev/null +++ b/Code/GameLogic/Game.cpp @@ -0,0 +1,68 @@ +#include "Game.h" +using namespace GameLogic; + +Game::Game(void) +{ + player = NULL; + level = NULL; + camera = NULL; +} + + +Game::~Game(void) +{ + //SAFE_DELETE(player); + if(player) + { + delete player; + player = NULL; + } + if(camera) + { + delete camera; + camera = NULL; + } +} + +void Game::Init() +{ + player = new Player(); + camera = new Camera(); +} +void Game::StartGame() +{ + 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); + + camera->LookAt(pos, dir, up); + camera->SetLens(3.14f/2, 1024/768, 1, 1000); +} +void Game::Update(keyInput keyPressed, float pitch, float yaw) +{ + //player->Update(keyPressed); + camera->Yaw(yaw); + camera->Pitch(pitch); + if(keyPressed == keyInput_A) + { + camera->Strafe(-0.1); + } + if(keyPressed == keyInput_D) + { + camera->Strafe(0.1); + } + if(keyPressed == keyInput_S) + { + camera->Walk(-0.1); + } + if(keyPressed == keyInput_W) + { + camera->Walk(0.1); + } + camera->UpdateViewMatrix(); +} +void Game::Render() +{ + Oyster::Graphics::API::NewFrame(camera->View(), camera->Proj()); + 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..0a8a031a --- /dev/null +++ b/Code/GameLogic/Game.h @@ -0,0 +1,28 @@ +#ifndef GAME_H +#define GAME_H + +#include "Level.h" +#include "Player.h" +#include "IGame.h" +#include "Camera.h" + +namespace GameLogic +{ + class Game + { + public: + Game(); + ~Game(); + + void Init(); + void StartGame(); + void Update(keyInput keyPressed, float pitch, float yaw); + void Render(); + + private: + Level* level; + Player* player; + Camera* camera; + }; +} +#endif \ No newline at end of file diff --git a/Code/GameLogic/GameLogic.vcxproj b/Code/GameLogic/GameLogic.vcxproj index 900f0834..236258d2 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,35 @@ {4285bd3f-3c6c-4670-b7af-a29afef5f6a8} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Code/GameLogic/GameLogic.vcxproj.filters b/Code/GameLogic/GameLogic.vcxproj.filters index d7ef6a1a..f2c5e978 100644 --- a/Code/GameLogic/GameLogic.vcxproj.filters +++ b/Code/GameLogic/GameLogic.vcxproj.filters @@ -14,4 +14,83 @@ 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 + + + 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 + + + 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..dd07c9f8 --- /dev/null +++ b/Code/GameLogic/IGame.cpp @@ -0,0 +1,43 @@ +#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, float pitch, float yaw) +{ + gameModule->Update(keyPressed, pitch, yaw); +} +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..41b2e0d5 --- /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, float pitch, float yaw); + 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..965af90e --- /dev/null +++ b/Code/GameLogic/Object.cpp @@ -0,0 +1,47 @@ +#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"); + + API::SimpleBodyDescription sbDesc; + //sbDesc.centerPosition = + + ICustomBody* temp = rigidBody = API::Instance().CreateRigidBody(sbDesc).Release(); + + 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..767edb1f --- /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: + + enum OBJECT_TYPE + { + OBJECT_TYPE_PLAYER, + OBJECT_TYPE_BOX, + }; + Object(void); + virtual ~Object(void); + + 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..93a83506 --- /dev/null +++ b/Code/GameLogic/Player.cpp @@ -0,0 +1,55 @@ +#include "Player.h" +#include "OysterMath.h" + +using namespace GameLogic; +using namespace Oyster::Physics; + +Player::Player(void) + :Object() +{ + life = 100; +} +Player::~Player(void) +{ + delete this->rigidBody; +} + +void Player::Update(keyInput keyPressed) +{ + if(keyPressed != keyInput_none) + { + Move(keyPressed); + } +} + +void Player::Move(keyInput keyPressed) +{ + 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); + } + if(keyPressed == keyInput_S) + { + Oyster::Math::Float3 pos = this->rigidBody->GetCenter(); + pos.y -= 0.1; + rigidBody->SetCenter(pos); + } + if(keyPressed == keyInput_W) + { + Oyster::Math::Float3 pos = this->rigidBody->GetCenter(); + pos.y += 0.1; + rigidBody->SetCenter(pos); + } +} +void Player::Shoot() +{ + +} diff --git a/Code/GameLogic/Player.h b/Code/GameLogic/Player.h new file mode 100644 index 00000000..7c4045e3 --- /dev/null +++ b/Code/GameLogic/Player.h @@ -0,0 +1,37 @@ +////////////////////////////////////////////////// +//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); + + /******************************************************** + * Update the position of the rigid body + * This will be done with physics later + ********************************************************/ + void Update(keyInput keyPressed); + + void Move(keyInput keyPressed); + 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..57392224 --- /dev/null +++ b/Code/GameLogic/TestGLMain.cpp @@ -0,0 +1,304 @@ +//-------------------------------------------------------------------------------------- +// File: TemplateMain.cpp +// +// BTH-D3D-Template +// +// Copyright (c) Stefan Petersson 2011. All rights reserved. +//-------------------------------------------------------------------------------------- + +////////////////////////////////////////////////////////////////////////// +// Test main function for game logic when .exe +// Doesn't run when Game logic is compiled as a .dll +////////////////////////////////////////////////////////////////////////// + +#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); + + //Init 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; +} + +//-------------------------------------------------------------------------------------- +// Create Direct3D with Oyster Graphics +//-------------------------------------------------------------------------------------- +HRESULT InitDirect3D() +{ + if(Oyster::Graphics::API::Init(g_hWnd, false, false, Oyster::Math::Float2( 1024, 768)) != Oyster::Graphics::API::Sucsess) + return E_FAIL; + return S_OK; +} + +//-------------------------------------------------------------------------------------- +// Init the input and the game +//------------------------------------------------------------------------------------- +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; + } + 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; + } + + float pitch = 0; + float yaw = 0; + + // move only when mouse is pressed + //if(inputObj->IsMousePressed()) + //{ + pitch = inputObj->GetPitch(); + yaw = inputObj->GetYaw(); + //} + + game->Update(key, pitch, yaw); + return S_OK; +} + +HRESULT Render(float deltaTime) +{ + int isPressed = 0; + if(inputObj->IsKeyPressed(DIK_A)) + { + isPressed = 1; + //std::cout<<"test"; + } + + 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 232bc3ed..540002a1 100644 --- a/Code/GamePhysics/GamePhysics.vcxproj +++ b/Code/GamePhysics/GamePhysics.vcxproj @@ -156,6 +156,7 @@ + diff --git a/Code/GamePhysics/GamePhysics.vcxproj.filters b/Code/GamePhysics/GamePhysics.vcxproj.filters index 4c0fd5f3..694a8ec7 100644 --- a/Code/GamePhysics/GamePhysics.vcxproj.filters +++ b/Code/GamePhysics/GamePhysics.vcxproj.filters @@ -33,6 +33,9 @@ Header Files\Implementation + + Header Files\Implementation + @@ -47,5 +50,8 @@ Source Files + + Source Files + \ 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..1da6045b --- /dev/null +++ b/Code/GamePhysics/Implementation/Octree.cpp @@ -0,0 +1,193 @@ +#include "Octree.h" + +using namespace Oyster; +using namespace Physics; +using namespace ::Utility::DynamicMemory; + +const unsigned int Octree::invalid_ref = ::Utility::Value::numeric_limits::max(); + +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(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(UniquePointer< ICustomBody > customBodyRef) +{ + /*this->leafData[this->mapReferences[customBodyRef]].queueRef = this->updateQueue.size(); + this->updateQueue.push_back(&this->leafData[this->mapReferences[customBodyRef]]);*/ +} + +void Octree::DestroyObject(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& updateList) +{ + auto object = this->mapReferences.find(customBodyRef); + + if(object == this->mapReferences.end()) + { + return updateList; + } + + 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)) + { + updateList.push_back(this->leafData[i].customBodyRef); + } + } + + return updateList; +} + +std::vector& Octree::Sample(const Oyster::Collision3D::ICollideable& collideable, std::vector& updateList) +{ + for(unsigned int i = 0; ileafData.size(); i++) + { + if(this->leafData[i].container.Intersects(collideable)) + { + updateList.push_back(this->leafData[i].customBodyRef); + } + } + + return updateList; +} + +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); + } + } +} + +void Octree::Visit(const Oyster::Collision3D::ICollideable& collideable, VistorAction hitAction) +{ + for(unsigned int i = 0; ileafData.size(); i++) + { + if(this->leafData[i].container.Intersects(collideable)) + { + //hitAction(*this, tempRef, i); // @todo TODO: Add typedef to handle function calls with ICollideable + } + } +} + +ICustomBody* Octree::GetCustomBody(const unsigned int tempRef) +{ + return this->leafData[tempRef].customBodyRef; +} + +UniquePointer Octree::Extract( const ICustomBody* objRef ) +{ // Dan Andersson + auto iter = this->mapReferences.find( objRef ); + if( iter != this->mapReferences.end() ) + { + return this->Extract( iter->second ); + } + else + { + return NULL; + } +} + +UniquePointer Octree::Extract( unsigned int tempRef ) +{ + if( tempRef != Octree::invalid_ref ) + { + //! @todo TODO: implement stub + return NULL; + } + else + { + return NULL; + } +} + +unsigned int Octree::GetTemporaryReferenceOf( const ICustomBody* objRef ) const +{ // Dan Andersson + auto iter = this->mapReferences.find( objRef ); + if( iter != this->mapReferences.end() ) + { + return iter->second; + } + else + { + return Octree::invalid_ref; + } +} + +void Octree::SetAsAltered( unsigned int tempRef ) +{ + //! @todo TODO: implement stub +} + +void Octree::EvaluatePosition( unsigned int tempRef ) +{ + //! @todo TODO: implement stub +} \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/Octree.h b/Code/GamePhysics/Implementation/Octree.h index 22385dc6..96631605 100644 --- a/Code/GamePhysics/Implementation/Octree.h +++ b/Code/GamePhysics/Implementation/Octree.h @@ -15,6 +15,10 @@ namespace Oyster class Octree { public: + static const unsigned int invalid_ref; + + typedef void(*VistorAction)(Octree&, unsigned int, unsigned int); + struct Data { Data* prev; @@ -22,33 +26,49 @@ namespace Oyster Collision3D::Sphere container; - Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef; + ::Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef; unsigned int queueRef; }; struct OctreeNode { - + OctreeNode* children[8]; + Data* dataPtr; + Collision3D::BoxAxisAligned container; }; - Octree(unsigned int bufferSize, unsigned char numLayers, Math::Float3 worldSize); + Octree(unsigned int bufferSize = 0, unsigned char numLayers = 0, Math::Float3 worldSize = Math::Float3::null); virtual ~Octree(); - void AddObject(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); + Octree& operator=(const Octree& orig); - void MoveToUpdateQueue(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); + void AddObject(::Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); - void Update(); + void MoveToUpdateQueue(::Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); - void DestroyObject(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); + void DestroyObject(::Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); + + std::vector& Sample(ICustomBody* customBodyRef, std::vector& updateList); + std::vector& Sample(const Oyster::Collision3D::ICollideable& collideable, std::vector& updateList); + void Visit(ICustomBody* customBodyRef, VistorAction hitAction ); + void Visit(const Oyster::Collision3D::ICollideable& collideable, VistorAction hitAction ); + + ICustomBody* GetCustomBody(const unsigned int tempRef); + + ::Utility::DynamicMemory::UniquePointer Extract( const ICustomBody* objRef ); + ::Utility::DynamicMemory::UniquePointer Extract( unsigned int tempRef ); // Dan vill ha + unsigned int GetTemporaryReferenceOf( const ICustomBody* objRef ) const; // Dan vill ha + void SetAsAltered( unsigned int tempRef ); // Dan vill ha + void EvaluatePosition( unsigned int tempRef ); // Dan vill ha - void Sample(Collision3D::ICollideable& collideable); private: std::vector < Data > leafData; + std::vector < Data* > updateQueue; - std::map< ICustomBody*, unsigned int > mapReferences; + std::map< const ICustomBody*, unsigned int > mapReferences; + OctreeNode worldNode; }; } diff --git a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp index 6c3e4a27..3d3080da 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp @@ -1,6 +1,7 @@ #include "PhysicsAPI_Impl.h" -#include "SimpleRigidBody.h" #include "OysterPhysics3D.h" +#include "SimpleRigidBody.h" +#include "SphericalRigidBody.h" using namespace ::Oyster::Physics; using namespace ::Oyster::Physics3D; @@ -10,13 +11,21 @@ using namespace ::Utility::DynamicMemory; API_Impl API_instance; -// default API::EventAction_Collision -void defaultCollisionAction( const ICustomBody *proto, const ICustomBody *deuter ) -{ /* do nothing */ } +namespace +{ + void OnPossibleCollision( Octree& worldScene, unsigned int protoTempRef, unsigned int deuterTempRef ) + { /** @todo TODO: OnPossibleCollision is a temporary solution .*/ + auto proto = worldScene.GetCustomBody( protoTempRef ); + auto deuter = worldScene.GetCustomBody( deuterTempRef ); -// default API::EventAction_Destruction -void defaultDestructionAction( UniquePointer proto ) -{ /* do nothing besides proto auto deleting itself. */ } + float deltaWhen; + Float3 worldWhere; + if( deuter->Intersects(*deuter, 1.0f, deltaWhen, worldWhere) ) + { + proto->CallSubscription( proto, deuter ); + } + } +} Float4x4 & MomentOfInertia::CreateSphereMatrix( const Float mass, const Float radius) { @@ -49,39 +58,63 @@ API & API::Instance() } API_Impl::API_Impl() - : gravityConstant( Constant::gravity_constant ), - updateFrameLength( 1.0f / 120.0f ), - collisionAction( defaultCollisionAction ), - destructionAction( defaultDestructionAction ) -{} +{ + this->gravityConstant = Constant::gravity_constant; + this->updateFrameLength = 1.0f / 120.0f; + this->destructionAction = Default::EventAction_Destruction; + this->worldScene = Octree(); +} API_Impl::~API_Impl() {} void API_Impl::Init( unsigned int numObjects, unsigned int numGravityWells , const Float3 &worldSize ) { - //! @todo TODO: implement stub + unsigned char numLayers = 4; //!< @todo TODO: calc numLayers from worldSize + this->worldScene = Octree( numObjects, numLayers, worldSize ); } -void API_Impl::SetDeltaTime( float deltaTime ) +void API_Impl::SetFrameTimeLength( float deltaTime ) { - updateFrameLength = deltaTime; + this->updateFrameLength = deltaTime; } + void API_Impl::SetGravityConstant( float g ) { this->gravityConstant = g; } -void API_Impl::SetAction( API::EventAction_Collision functionPointer ) + +void API_Impl::SetSubscription( API::EventAction_Destruction functionPointer ) { - this->collisionAction = functionPointer; -} -void API_Impl::SetAction( API::EventAction_Destruction functionPointer ) -{ - this->destructionAction = functionPointer; + if( functionPointer ) + { + this->destructionAction = functionPointer; + } + else + { + this->destructionAction = Default::EventAction_Destruction; + } } void API_Impl::Update() -{ - /** @todo TODO: Fix this function.*/ +{ /** @todo TODO: Update is a temporary solution .*/ + ::std::vector updateList; + auto proto = this->worldScene.Sample( Universe(), updateList ).begin(); + for( ; proto != updateList.end(); ++proto ) + { + this->worldScene.Visit( *proto, OnPossibleCollision ); + } + + proto = updateList.begin(); + for( ; proto != updateList.end(); ++proto ) + { + switch( (*proto)->Update(this->updateFrameLength) ) + { + case UpdateState_altered: + this->worldScene.SetAsAltered( this->worldScene.GetTemporaryReferenceOf(*proto) ); + case UpdateState_resting: default: + break; + } + } } bool API_Impl::IsInLimbo( const ICustomBody* objRef ) @@ -101,71 +134,139 @@ void API_Impl::ReleaseFromLimbo( const ICustomBody* objRef ) void API_Impl::AddObject( ::Utility::DynamicMemory::UniquePointer handle ) { - /** @todo TODO: Fix this function.*/ + this->worldScene.AddObject( handle ); } -::Utility::DynamicMemory::UniquePointer API_Impl::ExtractObject( const ICustomBody* objRef ) +UniquePointer API_Impl::ExtractObject( const ICustomBody* objRef ) { - //! @todo TODO: implement stub - return NULL; + return this->worldScene.Extract( objRef ); } void API_Impl::DestroyObject( const ICustomBody* objRef ) { - /** @todo TODO: Fix this function.*/ + UniquePointer object = this->worldScene.Extract( objRef ); + if( object ) + { + this->destructionAction( object ); + } } void API_Impl::ApplyForceAt( const ICustomBody* objRef, const Float3 &worldPos, const Float3 &worldF ) { - //! @todo TODO: implement stub + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + //this->worldScene.GetCustomBody( tempRef )->Apply //!< @todo TODO: need function + this->worldScene.SetAsAltered( tempRef ); + } } void API_Impl::ApplyCollisionResponse( const ICustomBody* objRefA, const ICustomBody* objRefB, Float &deltaWhen, Float3 &worldPointOfContact ) { - //! @todo TODO: implement stub + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRefA ); + if( tempRef != this->worldScene.invalid_ref ) + { + //! @todo TODO: implement stub + this->worldScene.SetAsAltered( tempRef ); + } } void API_Impl::SetMomentOfInertiaTensor_KeepVelocity( const ICustomBody* objRef, const Float4x4 &localI ) -{ - //! @todo TODO: implement stub +{ // deprecated + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + this->worldScene.GetCustomBody( tempRef )->SetMomentOfInertiaTensor_KeepVelocity( localI ); + } } void API_Impl::SetMomentOfInertiaTensor_KeepMomentum( const ICustomBody* objRef, const Float4x4 &localI ) -{ - //! @todo TODO: implement stub +{ // deprecated + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + this->worldScene.GetCustomBody( tempRef )->SetMomentOfInertiaTensor_KeepMomentum( localI ); + } } void API_Impl::SetMass_KeepVelocity( const ICustomBody* objRef, Float m ) -{ - //! @todo TODO: implement stub +{ // deprecated + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + this->worldScene.GetCustomBody( tempRef )->SetMass_KeepVelocity( m ); + } } void API_Impl::SetMass_KeepMomentum( const ICustomBody* objRef, Float m ) -{ - //! @todo TODO: implement stub +{ // deprecated + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + this->worldScene.GetCustomBody( tempRef )->SetMass_KeepMomentum( m ); + } } void API_Impl::SetCenter( const ICustomBody* objRef, const Float3 &worldPos ) { - //! @todo TODO: implement stub + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + //this->worldScene.GetCustomBody( tempRef )->Set //!< @todo TODO: need function + this->worldScene.EvaluatePosition( tempRef ); + } } void API_Impl::SetRotation( const ICustomBody* objRef, const Float4x4 &rotation ) { - //! @todo TODO: implement stub + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + this->worldScene.GetCustomBody( tempRef )->SetRotation( rotation ); + this->worldScene.EvaluatePosition( tempRef ); + } } void API_Impl::SetOrientation( const ICustomBody* objRef, const Float4x4 &orientation ) { - //! @todo TODO: implement stub + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + this->worldScene.GetCustomBody( tempRef )->SetOrientation( orientation ); + this->worldScene.EvaluatePosition( tempRef ); + } } void API_Impl::SetSize( const ICustomBody* objRef, const Float3 &size ) { - //! @todo TODO: implement stub + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + this->worldScene.GetCustomBody( tempRef )->SetSize( size ); + this->worldScene.EvaluatePosition( tempRef ); + } } -UniquePointer API_Impl::CreateSimpleRigidBody() const +UniquePointer API_Impl::CreateRigidBody( const API::SimpleBodyDescription &desc ) const { - return new SimpleRigidBody(); -} \ No newline at end of file + 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 5a2e3ef6..5de9c05a 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h @@ -2,6 +2,7 @@ #define PHYSICS_API_IMPL_H #include "../PhysicsAPI.h" +#include "Octree.h" namespace Oyster { @@ -15,10 +16,9 @@ namespace Oyster void Init( unsigned int numObjects, unsigned int numGravityWells , const ::Oyster::Math::Float3 &worldSize ); - void SetDeltaTime( float deltaTime ); + void SetFrameTimeLength( float deltaTime ); void SetGravityConstant( float g ); - void SetAction( EventAction_Collision functionPointer ); - void SetAction( EventAction_Destruction functionPointer ); + void SetSubscription( EventAction_Destruction functionPointer ); void Update(); @@ -42,14 +42,21 @@ namespace Oyster void SetOrientation( const ICustomBody* objRef, const ::Oyster::Math::Float4x4 &orientation ); void SetSize( const ICustomBody* objRef, const ::Oyster::Math::Float3 &size ); - ::Utility::DynamicMemory::UniquePointer CreateSimpleRigidBody() const; + ::Utility::DynamicMemory::UniquePointer CreateRigidBody( const SimpleBodyDescription &desc ) const; + ::Utility::DynamicMemory::UniquePointer CreateRigidBody( const SphericalBodyDescription &desc ) const; + private: ::Oyster::Math::Float gravityConstant, updateFrameLength; - EventAction_Collision collisionAction; EventAction_Destruction destructionAction; + Octree worldScene; }; - } + 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 index cc1f847b..70bc6938 100644 --- a/Code/GamePhysics/Implementation/SimpleRigidBody.cpp +++ b/Code/GamePhysics/Implementation/SimpleRigidBody.cpp @@ -2,16 +2,38 @@ #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() - : previous(), current(), - gravityNormal(0.0f), - subscribeCollision(true), - ignoreGravity(false) {} +{ + 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() {} @@ -20,9 +42,9 @@ UniquePointer SimpleRigidBody::Clone() const return new SimpleRigidBody( *this ); } -bool SimpleRigidBody::IsSubscribingCollisions() const -{ // Assumption - return this->subscribeCollision; +void SimpleRigidBody::CallSubscription( const ICustomBody *proto, const ICustomBody *deuter ) +{ + this->collisionAction( proto, deuter ); } bool SimpleRigidBody::IsAffectedByGravity() const @@ -32,10 +54,10 @@ bool SimpleRigidBody::IsAffectedByGravity() const bool SimpleRigidBody::Intersects( const ICustomBody &object, Float timeStepLength, Float &deltaWhen, Float3 &worldPointOfContact ) const { - if( object.Intersects(this->current.box) ) + if( object.Intersects(this->rigid.box) ) { //! @todo TODO: better implementation needed deltaWhen = timeStepLength; - worldPointOfContact = Average( this->current.box.center, object.GetCenter() ); + worldPointOfContact = Average( this->rigid.box.center, object.GetCenter() ); return true; } else @@ -46,18 +68,18 @@ bool SimpleRigidBody::Intersects( const ICustomBody &object, Float timeStepLengt bool SimpleRigidBody::Intersects( const ICollideable &shape ) const { - return this->current.box.Intersects( shape ); + return this->rigid.box.Intersects( shape ); } Sphere & SimpleRigidBody::GetBoundingSphere( Sphere &targetMem ) const { - return targetMem = Sphere( this->current.box.center, this->current.box.boundingOffset.GetMagnitude() ); + 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->current.box.center).GetNormalized(); + return targetMem = (worldPos - this->rigid.box.center).GetNormalized(); } Float3 & SimpleRigidBody::GetGravityNormal( Float3 &targetMem ) const @@ -67,32 +89,43 @@ Float3 & SimpleRigidBody::GetGravityNormal( Float3 &targetMem ) const Float3 & SimpleRigidBody::GetCenter( Float3 &targetMem ) const { - return targetMem = this->current.box.center; + return targetMem = this->rigid.box.center; } Float4x4 & SimpleRigidBody::GetRotation( Float4x4 &targetMem ) const { - return targetMem = this->current.box.rotation; + return targetMem = this->rigid.box.rotation; } Float4x4 & SimpleRigidBody::GetOrientation( Float4x4 &targetMem ) const { - return targetMem = this->current.GetOrientation(); + return targetMem = this->rigid.GetOrientation(); } Float4x4 & SimpleRigidBody::GetView( Float4x4 &targetMem ) const { - return targetMem = this->current.GetView(); + return targetMem = this->rigid.GetView(); } UpdateState SimpleRigidBody::Update( Float timeStepLength ) { - this->previous = this->current; // memorizing the old state - - this->current.Update_LeapFrog( timeStepLength ); + this->rigid.Update_LeapFrog( timeStepLength ); // compare previous and new state and return result - return this->current == this->previous ? resting : altered; + //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) @@ -106,47 +139,42 @@ void SimpleRigidBody::SetGravityNormal( const Float3 &normalizedVector ) this->gravityNormal = normalizedVector; } -void SimpleRigidBody::SetSubscription( bool subscribeCollision ) -{ - this->subscribeCollision = subscribeCollision; -} - void SimpleRigidBody::SetMomentOfInertiaTensor_KeepVelocity( const Float4x4 &localI ) { - this->current.SetMomentOfInertia_KeepVelocity( localI ); + this->rigid.SetMomentOfInertia_KeepVelocity( localI ); } void SimpleRigidBody::SetMomentOfInertiaTensor_KeepMomentum( const Float4x4 &localI ) { - this->current.SetMomentOfInertia_KeepMomentum( localI ); + this->rigid.SetMomentOfInertia_KeepMomentum( localI ); } void SimpleRigidBody::SetMass_KeepVelocity( Float m ) { - this->current.SetMass_KeepVelocity( m ); + this->rigid.SetMass_KeepVelocity( m ); } void SimpleRigidBody::SetMass_KeepMomentum( Float m ) { - this->current.SetMass_KeepMomentum( m ); + this->rigid.SetMass_KeepMomentum( m ); } void SimpleRigidBody::SetCenter( const Float3 &worldPos ) { - this->current.SetCenter( worldPos ); + this->rigid.SetCenter( worldPos ); } void SimpleRigidBody::SetRotation( const Float4x4 &rotation ) { - this->current.SetRotation( rotation ); + this->rigid.SetRotation( rotation ); } void SimpleRigidBody::SetOrientation( const Float4x4 &orientation ) { - this->current.SetOrientation( orientation ); + this->rigid.SetOrientation( orientation ); } void SimpleRigidBody::SetSize( const Float3 &size ) { - this->current.SetSize( 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 index 41be919b..a674a20d 100644 --- a/Code/GamePhysics/Implementation/SimpleRigidBody.h +++ b/Code/GamePhysics/Implementation/SimpleRigidBody.h @@ -10,11 +10,12 @@ namespace Oyster { namespace Physics { public: SimpleRigidBody(); + SimpleRigidBody( const API::SimpleBodyDescription &desc ); virtual ~SimpleRigidBody(); ::Utility::DynamicMemory::UniquePointer Clone() const; - bool IsSubscribingCollisions() const; + void CallSubscription( const ICustomBody *proto, const ICustomBody *deuter ); 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; @@ -29,9 +30,9 @@ namespace Oyster { namespace Physics UpdateState Update( ::Oyster::Math::Float timeStepLength ); + void SetSubscription( EventAction_Collision functionPointer ); void SetGravity( bool ignore); void SetGravityNormal( const ::Oyster::Math::Float3 &normalizedVector ); - void SetSubscription( bool subscribeCollision ); void SetMomentOfInertiaTensor_KeepVelocity( const ::Oyster::Math::Float4x4 &localI ); void SetMomentOfInertiaTensor_KeepMomentum( const ::Oyster::Math::Float4x4 &localI ); void SetMass_KeepVelocity( ::Oyster::Math::Float m ); @@ -42,9 +43,10 @@ namespace Oyster { namespace Physics void SetSize( const ::Oyster::Math::Float3 &size ); private: - ::Oyster::Physics3D::RigidBody previous, current; + ::Oyster::Physics3D::RigidBody rigid; ::Oyster::Math::Float3 gravityNormal; - bool subscribeCollision, ignoreGravity; + EventAction_Collision collisionAction; + bool ignoreGravity; }; } } diff --git a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp index 20d806c9..c741a68a 100644 --- a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp +++ b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp @@ -2,17 +2,40 @@ #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() - : previous(), current( Box(Float4x4::identity, Float3::null, Float3(1.0f)) ), - gravityNormal( 0.0f ), - subscribeCollision( true ), - ignoreGravity( false ), - body( Float3::null, 0.5f ) {} +{ + 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() {} @@ -21,9 +44,9 @@ UniquePointer SphericalRigidBody::Clone() const return new SphericalRigidBody( *this ); } -bool SphericalRigidBody::IsSubscribingCollisions() const -{ // Assumption - return this->subscribeCollision; +void SphericalRigidBody::CallSubscription( const ICustomBody *proto, const ICustomBody *deuter ) +{ + this->collisionAction( proto, deuter ); } bool SphericalRigidBody::IsAffectedByGravity() const @@ -47,7 +70,7 @@ bool SphericalRigidBody::Intersects( const ICustomBody &object, Float timeStepLe bool SphericalRigidBody::Intersects( const ICollideable &shape ) const { - return this->current.box.Intersects( shape ); + return this->rigid.box.Intersects( shape ); } Sphere & SphericalRigidBody::GetBoundingSphere( Sphere &targetMem ) const @@ -58,7 +81,7 @@ Sphere & SphericalRigidBody::GetBoundingSphere( Sphere &targetMem ) const Float3 & SphericalRigidBody::GetNormalAt( const Float3 &worldPos, Float3 &targetMem ) const { //! @todo TODO: better implementation needed - return targetMem = (worldPos - this->current.box.center).GetNormalized(); + return targetMem = (worldPos - this->rigid.box.center).GetNormalized(); } Float3 & SphericalRigidBody::GetGravityNormal( Float3 &targetMem ) const @@ -68,33 +91,44 @@ Float3 & SphericalRigidBody::GetGravityNormal( Float3 &targetMem ) const Float3 & SphericalRigidBody::GetCenter( Float3 &targetMem ) const { - return targetMem = this->current.box.center; + return targetMem = this->rigid.box.center; } Float4x4 & SphericalRigidBody::GetRotation( Float4x4 &targetMem ) const { - return targetMem = this->current.box.rotation; + return targetMem = this->rigid.box.rotation; } Float4x4 & SphericalRigidBody::GetOrientation( Float4x4 &targetMem ) const { - return targetMem = this->current.GetOrientation(); + return targetMem = this->rigid.GetOrientation(); } Float4x4 & SphericalRigidBody::GetView( Float4x4 &targetMem ) const { - return targetMem = this->current.GetView(); + return targetMem = this->rigid.GetView(); } UpdateState SphericalRigidBody::Update( Float timeStepLength ) { - this->previous = this->current; // memorizing the old state - - this->current.Update_LeapFrog( timeStepLength ); - this->body.center = this->current.GetCenter(); + this->rigid.Update_LeapFrog( timeStepLength ); + this->body.center = this->rigid.GetCenter(); // compare previous and new state and return result - return this->current == this->previous ? resting : altered; + //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) @@ -108,50 +142,45 @@ void SphericalRigidBody::SetGravityNormal( const Float3 &normalizedVector ) this->gravityNormal = normalizedVector; } -void SphericalRigidBody::SetSubscription( bool subscribeCollision ) -{ - this->subscribeCollision = subscribeCollision; -} - void SphericalRigidBody::SetMomentOfInertiaTensor_KeepVelocity( const Float4x4 &localI ) { - this->current.SetMomentOfInertia_KeepVelocity( localI ); + this->rigid.SetMomentOfInertia_KeepVelocity( localI ); } void SphericalRigidBody::SetMomentOfInertiaTensor_KeepMomentum( const Float4x4 &localI ) { - this->current.SetMomentOfInertia_KeepMomentum( localI ); + this->rigid.SetMomentOfInertia_KeepMomentum( localI ); } void SphericalRigidBody::SetMass_KeepVelocity( Float m ) { - this->current.SetMass_KeepVelocity( m ); + this->rigid.SetMass_KeepVelocity( m ); } void SphericalRigidBody::SetMass_KeepMomentum( Float m ) { - this->current.SetMass_KeepMomentum( m ); + this->rigid.SetMass_KeepMomentum( m ); } void SphericalRigidBody::SetCenter( const Float3 &worldPos ) { - this->current.SetCenter( worldPos ); + this->rigid.SetCenter( worldPos ); this->body.center = worldPos; } void SphericalRigidBody::SetRotation( const Float4x4 &rotation ) { - this->current.SetRotation( rotation ); + this->rigid.SetRotation( rotation ); } void SphericalRigidBody::SetOrientation( const Float4x4 &orientation ) { - this->current.SetOrientation( orientation ); + this->rigid.SetOrientation( orientation ); this->body.center = orientation.v[3].xyz; } void SphericalRigidBody::SetSize( const Float3 &size ) { - this->current.SetSize( 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 index 7a727ee8..37263e91 100644 --- a/Code/GamePhysics/Implementation/SphericalRigidBody.h +++ b/Code/GamePhysics/Implementation/SphericalRigidBody.h @@ -11,11 +11,12 @@ namespace Oyster { namespace Physics { public: SphericalRigidBody(); + SphericalRigidBody( const API::SphericalBodyDescription &desc ); virtual ~SphericalRigidBody(); ::Utility::DynamicMemory::UniquePointer Clone() const; - bool IsSubscribingCollisions() const; + void CallSubscription( const ICustomBody *proto, const ICustomBody *deuter ); 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; @@ -30,9 +31,9 @@ namespace Oyster { namespace Physics UpdateState Update( ::Oyster::Math::Float timeStepLength ); + void SetSubscription( EventAction_Collision functionPointer ); void SetGravity( bool ignore); void SetGravityNormal( const ::Oyster::Math::Float3 &normalizedVector ); - void SetSubscription( bool subscribeCollision ); void SetMomentOfInertiaTensor_KeepVelocity( const ::Oyster::Math::Float4x4 &localI ); void SetMomentOfInertiaTensor_KeepMomentum( const ::Oyster::Math::Float4x4 &localI ); void SetMass_KeepVelocity( ::Oyster::Math::Float m ); @@ -43,9 +44,10 @@ namespace Oyster { namespace Physics void SetSize( const ::Oyster::Math::Float3 &size ); private: - ::Oyster::Physics3D::RigidBody previous, current; + ::Oyster::Physics3D::RigidBody rigid; ::Oyster::Math::Float3 gravityNormal; - bool subscribeCollision, ignoreGravity; + EventAction_Collision collisionAction; + bool ignoreGravity; ::Oyster::Collision3D::Sphere body; }; } } diff --git a/Code/GamePhysics/PhysicsAPI.h b/Code/GamePhysics/PhysicsAPI.h index bf80e6fa..29014214 100644 --- a/Code/GamePhysics/PhysicsAPI.h +++ b/Code/GamePhysics/PhysicsAPI.h @@ -19,8 +19,8 @@ namespace Oyster enum UpdateState { - resting, - altered + UpdateState_resting, + UpdateState_altered }; namespace Constant @@ -45,7 +45,9 @@ namespace Oyster class PHYSICS_DLL_USAGE API { public: - typedef void (*EventAction_Collision)( const ICustomBody *proto, const ICustomBody *deuter ); + struct SimpleBodyDescription; + struct SphericalBodyDescription; + typedef void (*EventAction_Destruction)( ::Utility::DynamicMemory::UniquePointer proto ); /** Gets the Physics instance. */ @@ -62,7 +64,7 @@ namespace Oyster /******************************************************** * Sets the time length of each physics update frame. ********************************************************/ - virtual void SetDeltaTime( float seconds ) = 0; + virtual void SetFrameTimeLength( float seconds ) = 0; /******************************************************** * Sets the Gravityconstant in the physics that will be @@ -70,20 +72,15 @@ namespace Oyster * @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 a subscribed collision occurs. - ********************************************************/ - virtual void SetAction( EventAction_Collision functionPointer ) = 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 SetAction( EventAction_Destruction functionPointer ) = 0; + virtual void SetSubscription( EventAction_Destruction functionPointer ) = 0; /******************************************************** * Triggers the engine to run next update frame. @@ -213,10 +210,18 @@ namespace Oyster /******************************************************** * 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 CreateSimpleRigidBody() const = 0; - + 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() {} }; @@ -225,6 +230,14 @@ namespace Oyster class PHYSICS_DLL_USAGE ICustomBody { public: + enum SubscriptMessage + { + SubscriptMessage_none, + SubscriptMessage_ignore_collision_response + }; + + typedef SubscriptMessage (*EventAction_Collision)( const ICustomBody *proto, const ICustomBody *deuter ); + virtual ~ICustomBody() {}; /******************************************************** @@ -232,11 +245,11 @@ namespace Oyster * @return An ICustomBody pointer along with the responsibility to delete. ********************************************************/ virtual ::Utility::DynamicMemory::UniquePointer Clone() const = 0; - + /******************************************************** - * @return true if Engine should call the EventAction_Collision function. + * @todo TODO: need doc ********************************************************/ - virtual bool IsSubscribingCollisions() const = 0; + virtual void CallSubscription( const ICustomBody *proto, const ICustomBody *deuter ) = 0; /******************************************************** * @return true if Engine should apply gravity on this object. @@ -312,6 +325,13 @@ namespace Oyster ********************************************************/ 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. ********************************************************/ @@ -323,11 +343,6 @@ namespace Oyster ********************************************************/ virtual void SetGravityNormal( const ::Oyster::Math::Float3 &normalizedVector ) = 0; - /******************************************************** - * @param subscribeCollision: If is true, engine will call EventAction_Collision when this collides. - ********************************************************/ - virtual void SetSubscription( bool subscribeCollision ) = 0; - /******************************************************** * To not be called if is in Engine * Use API::SetMomentOfInertiaTensor_KeepVelocity(...) instead @@ -376,6 +391,48 @@ namespace Oyster ********************************************************/ virtual void SetSize( const ::Oyster::Math::Float3 &size ) = 0; }; + + struct API::SimpleBodyDescription + { + ::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; + } + }; } } #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..5fd15a54 --- /dev/null +++ b/Code/Input/L_inputClass.cpp @@ -0,0 +1,200 @@ +#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; +} + +float InputClass::GetPitch( ) +{ + float dy = (static_cast( m_mouseState.lY)/5); + return -dy; +} +float InputClass::GetYaw( ) +{ + float dX = (static_cast( m_mouseState.lX)/5); + return -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..129024c2 --- /dev/null +++ b/Code/Input/L_inputClass.h @@ -0,0 +1,54 @@ +////////////////////////////////////////////////////////////////////////// +// Temp input handler, not stable! +// When starting the program, don't click anywhere until the program starts +// because that breaks the input.. +////////////////////////////////////////////////////////////////////////// + +#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(); + + // Call if mouse is pressed + float GetYaw(); + float GetPitch(); + +}; + +#endif \ No newline at end of file diff --git a/Code/Misc/IQueue.h b/Code/Misc/IQueue.h new file mode 100644 index 00000000..fc85800e --- /dev/null +++ b/Code/Misc/IQueue.h @@ -0,0 +1,35 @@ +#ifndef I_QUEUE_H +#define I_QUEUE_H + +///////////////////////////////// +// Created by Sam Svensson 2013// +///////////////////////////////// + +namespace Oyster +{ + namespace Queue + { + template + class IQueue + { + public: + + //--------------------------------------------- + //standard operations of the std::queue + //--------------------------------------------- + virtual ~IQueue() {}; + virtual void Push( Type item ) = 0; + virtual Type Pop() = 0; + + virtual Type Front() = 0; + virtual Type Back() = 0; + + virtual int Size() = 0; + virtual bool IsEmpty() = 0; + + virtual void Swap( IQueue &queue ) = 0; + }; + } +} + +#endif \ No newline at end of file diff --git a/Code/Misc/Misc.vcxproj b/Code/Misc/Misc.vcxproj index ca39cada..8cb234da 100644 --- a/Code/Misc/Misc.vcxproj +++ b/Code/Misc/Misc.vcxproj @@ -156,12 +156,14 @@ + + - + diff --git a/Code/Misc/Misc.vcxproj.filters b/Code/Misc/Misc.vcxproj.filters index 6eae993b..7151e26a 100644 --- a/Code/Misc/Misc.vcxproj.filters +++ b/Code/Misc/Misc.vcxproj.filters @@ -27,12 +27,24 @@ Source Files + + Source Files + + + Source Files + Source Files Source Files + + Source Files + + + Source Files + @@ -41,14 +53,38 @@ Header Files - - Header Files - - + Header 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/Misc/Misc.vcxproj.filters.orig b/Code/Misc/Misc.vcxproj.filters.orig deleted file mode 100644 index f3327ce5..00000000 --- a/Code/Misc/Misc.vcxproj.filters.orig +++ /dev/null @@ -1,72 +0,0 @@ - - - - - {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 - -<<<<<<< HEAD -======= - - Source Files - - - Source Files - ->>>>>>> 48c812b0338b859aa6c00c8504dd2f16a4bb44f9 - - - - 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/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/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/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/Thread/OysterMutex.cpp b/Code/Misc/Thread/OysterMutex.cpp index b02ef344..089323ce 100644 --- a/Code/Misc/Thread/OysterMutex.cpp +++ b/Code/Misc/Thread/OysterMutex.cpp @@ -8,7 +8,6 @@ #include #include -using namespace Oyster::Thread; OysterMutex::OysterMutex() diff --git a/Code/Misc/Thread/OysterMutex.h b/Code/Misc/Thread/OysterMutex.h index d9f29d95..18282499 100644 --- a/Code/Misc/Thread/OysterMutex.h +++ b/Code/Misc/Thread/OysterMutex.h @@ -9,29 +9,23 @@ #include #include -namespace Oyster +class OysterMutex { - 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(); +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; +private: + std::mutex mutex; + std::thread::id id; - OysterMutex(const OysterMutex&); - }; - } -} + OysterMutex(const OysterMutex&); +}; #endif // !MISC_OYSTER_MUTEX_H diff --git a/Code/Misc/Thread/OysterThread_Impl.cpp b/Code/Misc/Thread/OysterThread_Impl.cpp index 46b889fe..9605dd78 100644 --- a/Code/Misc/Thread/OysterThread_Impl.cpp +++ b/Code/Misc/Thread/OysterThread_Impl.cpp @@ -10,14 +10,14 @@ #include using namespace Oyster::Thread; -using namespace Utility::DynamicMemory::SmartPointer; +using namespace Utility::DynamicMemory; #pragma region Declerations struct ThreadData; /** A typical Oyster thread function */ - typedef void (*ThreadFunction)(StdSmartPointer&); + typedef void (*ThreadFunction)(SmartPointer&); enum OYSTER_THREAD_STATE { @@ -32,12 +32,13 @@ using namespace Utility::DynamicMemory::SmartPointer; struct ThreadData { std::atomic state; // workerThread; // workerThread; // msec; // threadData; + SmartPointer threadData; PrivateData() :threadData(new ThreadData()) @@ -76,11 +77,11 @@ using namespace Utility::DynamicMemory::SmartPointer; int tempId = 0; std::vector IDS; -static void ThreadingFunction(StdSmartPointer &origin) +static void ThreadingFunction(SmartPointer &origin) { bool shouldContinue; - StdSmartPointer w = origin; + SmartPointer w = origin; theBegining: diff --git a/Code/Misc/ThreadSafeQueue.h b/Code/Misc/ThreadSafeQueue.h new file mode 100644 index 00000000..d0125f71 --- /dev/null +++ b/Code/Misc/ThreadSafeQueue.h @@ -0,0 +1,218 @@ +#ifndef THREAD_SAFE_QUEUE_H +#define THREAD_SAFE_QUEUE_H + +//////////////////////////////////////////// +// Thread safe queue implemented +// with single linked list and template. +// uses mutex to lock the queue +// otherwise its a standard queue +// Created by Sam Svensson 2013 +///////////////////////////////////////////// + +#include "IQueue.h" +#include "Thread/OysterMutex.h" + +namespace Oyster +{ + namespace Queue + { + template + class ThreadSafeQueue : public IQueue + { + public: + ThreadSafeQueue(); + virtual ~ThreadSafeQueue(); + + virtual void Push( Type item ); + virtual Type Pop(); + + virtual Type Front(); + virtual Type Back(); + + virtual int Size(); + virtual bool IsEmpty(); + virtual void Swap( IQueue &queue ); + + private: + class Node + { + public: + Type item; + Node *next; + Node(Type item){ this->item = item; this->next = NULL; }; + ~Node() {}; + }; + + Node *front; + Node *back; + int nrOfNodes; + OysterMutex mutex; + }; + + + + + //---------------------------------------------- + //implemented template functions + //---------------------------------------------- + + template < typename Type > + ThreadSafeQueue::ThreadSafeQueue() + { + this->front = NULL; + this->back = NULL; + this->nrOfNodes = 0; + + } + + template < typename Type > + ThreadSafeQueue::~ThreadSafeQueue() + { + this->mutex.LockMutex(); + + if(this->front != NULL) + { + Node *destroyer; + Node *walker = this->front; + + for(int i = 0; i < this->nrOfNodes; i++) + { + destroyer = walker; + walker = walker->next; + + delete destroyer; + } + + this->front = NULL; + this->back = NULL; + } + + this->mutex.UnlockMutex(); + } + + + template < typename Type > + void ThreadSafeQueue::Push(Type item) + { + Node *e = new Node(item); + + mutex.LockMutex(); + if(this->front != NULL) + { + this->back->next = e; + this->back = e; + } + + else + { + this->front = e; + this->back = e; + } + + this->nrOfNodes++; + + mutex.UnlockMutex(); + } + + template < typename Type > + Type ThreadSafeQueue::Pop() + { + mutex.LockMutex(); + if(this->front != NULL) + { + Type item = this->front->item; + Node *destroyer = this->front; + this->front = front->next; + + delete destroyer; + this->nrOfNodes--; + + if(nrOfNodes == 0) + { + this->front = NULL; + this->back = NULL; + } + return item; + } + + mutex.UnlockMutex(); + + return NULL; + } + + template < typename Type > + Type ThreadSafeQueue::Front() + { + mutex.LockMutex(); + if(front != NULL) + { + return this->front->item; + } + mutex.UnlockMutex(); + + return NULL; + } + + template < typename Type > + Type ThreadSafeQueue::Back() + { + mutex.LockMutex(); + if(back != NULL) + { + return this->back->item; + } + mutex.UnlockMutex(); + + return NULL; + } + + template < typename Type > + int ThreadSafeQueue::Size() + { + //? behövs denna låsas? + mutex.LockMutex(); + return this->nrOfNodes; + mutex.UnlockMutex(); + } + + template < typename Type > + bool ThreadSafeQueue::IsEmpty() + { + mutex.LockMutex(); + if(nrOfNodes == 0 && this->front == NULL) + { + mutex.UnlockMutex(); + return true; + } + + else + { + mutex.UnlockMutex(); + } + return false; + } + + template < typename Type > + void ThreadSafeQueue::Swap(IQueue &queue ) + { + mutex.LockMutex(); + int prevNrOfNodes = this->nrOfNodes; + int size = queue.Size(); + + for(int i = 0; i < size; i++) + { + this->Push(queue.Pop()); + } + + for(int i = 0; i < prevNrOfNodes; i++) + { + queue.Push(this->Pop()); + } + mutex.UnlockMutex(); + } + + + } +} +#endif + diff --git a/Code/Misc/Utilities-InlineImpl.h b/Code/Misc/Utilities-Impl.h similarity index 52% rename from Code/Misc/Utilities-InlineImpl.h rename to Code/Misc/Utilities-Impl.h index 0cd164d8..cc82c959 100644 --- a/Code/Misc/Utilities-InlineImpl.h +++ b/Code/Misc/Utilities-Impl.h @@ -1,8 +1,11 @@ ///////////////////////////////////////////////////////////////////// // Inline and template implementations for // the Utility Collection of Miscellanious Handy Functions -// © Dan Andersson 2013 -// © Dennis Andersen 2013 TODO: Is this correct? +// +// Created 2013 by Dan Andersson +// Edited 2013 by +// * Dan Andersson +// * Dennis Andersen ///////////////////////////////////////////////////////////////////// #ifndef UTILITIES_INLINE_IMPL_H @@ -32,6 +35,7 @@ namespace Utility } } +#pragma region UnuiqePointer template UniquePointer::UniquePointer( Type *assignedInstance ) { @@ -39,17 +43,17 @@ namespace Utility } template - UniquePointer::~UniquePointer() + UniquePointer::UniquePointer( const UniquePointer &donor ) { - SafeDeleteInstance( this->ownedInstance ); + this->ownedInstance = donor.ownedInstance; + donor.ownedInstance = NULL; + } template - UniquePointer & UniquePointer::operator = ( Type *assignedInstance ) + UniquePointer::~UniquePointer() { SafeDeleteInstance( this->ownedInstance ); - this->ownedInstance = assignedInstance; - return *this; } template @@ -91,6 +95,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() { @@ -112,16 +128,17 @@ namespace Utility } template - UniqueArray::~UniqueArray() + UniqueArray::UniqueArray( const UniqueArray &donor ) { - SafeDeleteArray( this->ownedArray ); + this->ownedArray = donor.ownedArray; + donor.ownedArray = NULL; + } template - UniqueArray & UniqueArray::operator = ( Type assignedArray[] ) + UniqueArray::~UniqueArray() { SafeDeleteArray( this->ownedArray ); - this->ownedArray = assignedArray; } template @@ -150,7 +167,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,110 +192,114 @@ namespace Utility { return this->operator bool(); } +#pragma endregion - namespace SmartPointer +#pragma region SmartPointer + template void SmartPointer::Destroy() { - 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(); + delete this->_rc; + this->_rc = NULL; + + //Use default function for memory deallocation. + SafeDeleteInstance(this->_ptr); + + this->_ptr = NULL; + } + template SmartPointer::SmartPointer() + :_rc(0), _ptr(0) + { } + template SmartPointer::SmartPointer(T* p) + :_ptr(p) + { + this->_rc = new ReferenceCount(); + this->_rc->Incref(); + } + template SmartPointer::SmartPointer(const SmartPointer& d) + :_ptr(d._ptr), _rc(d._rc) + { + if(this->_rc) this->_rc->Incref(); - } - template StdSmartPointer::StdSmartPointer(const StdSmartPointer& d) - :_ptr(d._ptr), _rc(d._rc) + } + template SmartPointer::~SmartPointer() + { + if (this->_rc && this->_rc->Decref() == 0) { - if(this->_rc) - this->_rc->Incref(); + Destroy(); } - template StdSmartPointer::~StdSmartPointer() + } + template SmartPointer& SmartPointer::operator= (const SmartPointer& p) + { + if (this != &p) { - if (this->_rc && this->_rc->Decref() == 0) + //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(); } - template StdSmartPointer& StdSmartPointer::operator= (const StdSmartPointer& p) + return *this; + } + template SmartPointer& SmartPointer::operator= (T* p) + { + if (this->_ptr != p) { - if (this != &p) + //Last to go? + if(this->_rc) { - //Last to go? - if(this->_rc && this->_rc->Decref() == 0) + if(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; + else + this->_rc = new ReferenceCount(); + + this->_ptr = p; + this->_rc->Incref(); } + return *this; } + template inline bool SmartPointer::operator== (const SmartPointer& d) + { + return d._ptr == this->_ptr; + } + template inline bool SmartPointer::operator== (const T& p) + { + return &p == this->_ptr; + } + template inline T& SmartPointer::operator* () + { + return *this->_ptr; + } + template inline T* SmartPointer::operator-> () + { + return this->_ptr; + } + template inline SmartPointer::operator T* () + { + return this->_ptr; + } + template inline SmartPointer::operator bool() + { + return (this->_ptr != 0); + } + template inline T* SmartPointer::Get() + { + return this->_ptr; + } + template inline bool SmartPointer::IsValid() + { + return (this->_ptr != NULL) ? true : false; + } +#pragma endregion + } } diff --git a/Code/Misc/Utilities.h b/Code/Misc/Utilities.h index 33f7f39e..ec8b0229 100644 --- a/Code/Misc/Utilities.h +++ b/Code/Misc/Utilities.h @@ -1,8 +1,11 @@ -//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//! +///////////////////////////////////////////////////////////////////// // Utility Collection of Miscellanious Handy Functions -// © Dan Andersson 2013 -// © Dennis Andersen 2013 - +// +// Created 2013 by Dan Andersson +// Edited 2013 by +// * Dan Andersson +// * Dennis Andersen +///////////////////////////////////////////////////////////////////// #ifndef UTILITIES_H #define UTILITIES_H @@ -18,153 +21,212 @@ 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[] ); - //! 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. - UniquePointer( Type *assignedInstance = NULL ); - - //! 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. - 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. - 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; - - //! 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 equavalent with clearing all responsibilities from this UniqueArray. - UniqueArray( Type assignedArray[] = NULL ); - - //! 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. - 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. - 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; - - //! 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; - }; - + //! A simple reference counter with some extra functionality struct ReferenceCount { private: - std::atomic count; + int count; public: ReferenceCount() :count(0) { } - ReferenceCount(const ReferenceCount& o) { count.store(o.count); } - inline const ReferenceCount& operator=(const ReferenceCount& o) { count.store(o.count); return *this;} + ReferenceCount(const ReferenceCount& o) { count = o.count; } + inline const ReferenceCount& operator=(const ReferenceCount& o) { count = 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 + //! Wrapper to safely transfer dynamic ownership/responsibility + template struct UniquePointer { - //! 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; + 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 ); - /** Destroys the pointer and returns the memory allocated. */ - void Destroy(); + /****************************************************************** + * 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 ); - 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(); + /****************************************************************** + * Will auto delete assigned dynamic instance. + ******************************************************************/ + ~UniquePointer(); - /** - * Returns the connected pointer */ - T* Get(); + /****************************************************************** + * 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 ); - /** Checks if the pointer is valid (not NULL) - Returns true for valid, else false. */ - bool IsValid(); - }; - } + /****************************************************************** + * 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; + /****************************************************************** + * @return true if 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(); + + /****************************************************************** + * @return true if this UniquePointer have a current ownership/responsibility of a dynamic instance. + * inline of @see operator bool () const + ******************************************************************/ + bool HaveOwnership() const; + + private: + mutable Type *ownedInstance; + }; + + //! Wrapper to safely transfer dynamic ownership/responsibility + template struct UniqueArray + { + 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(); + + /****************************************************************** + * 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; + + /****************************************************************** + * @return true if this UniqueArray have a current ownership/responsibility of a dynamic array. + ******************************************************************/ + 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(); + + /****************************************************************** + * @return true if this UniqueArray have a current ownership/responsibility of a dynamic array. + * inline of @see operator bool () const + ******************************************************************/ + bool HaveOwnership() const; + + private: + mutable Type *ownedArray; + }; + + //! Wrapper to manage references on a pointer. + template struct SmartPointer + { + private: + ReferenceCount *_rc; + T *_ptr; + + /** Destroys the pointer and returns the memory allocated. */ + void Destroy(); + + public: + SmartPointer(); + SmartPointer(T* p); + SmartPointer(const SmartPointer& d); + virtual~SmartPointer(); + SmartPointer& operator= (const SmartPointer& p); + SmartPointer& operator= (T* p); + bool operator== (const SmartPointer& 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(); + }; } namespace String @@ -310,8 +372,13 @@ namespace Utility template<> inline unsigned long long AverageWithDelta( const unsigned long long &origin, const unsigned long long &delta ) { return origin + (delta >> 1); } } + + namespace Thread + { + //Utilities for threading + } } -#include "Utilities-InlineImpl.h" +#include "Utilities-Impl.h" #endif \ No newline at end of file diff --git a/Code/Misc/Utilities.h.orig b/Code/Misc/Utilities.h.orig deleted file mode 100644 index 6d3e801b..00000000 --- a/Code/Misc/Utilities.h.orig +++ /dev/null @@ -1,319 +0,0 @@ -//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//! -// Utility Collection of Miscellanious Handy Functions -// © Dan Andersson 2013 -<<<<<<< HEAD -//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//! -======= -// © Dennis Andersen 2013 -///////////////////////////////////////////////////////////////////// ->>>>>>> 48c812b0338b859aa6c00c8504dd2f16a4bb44f9 - -#ifndef UTILITIES_H -#define UTILITIES_H - -#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 equavalent with clearing all responsibilities from this UniquePointer. - UniquePointer( Type *assignedInstance = NULL ); - - //! 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. - 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. - 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; - - //! 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 equavalent with clearing all responsibilities from this UniqueArray. - UniqueArray( Type assignedArray[] = NULL ); - - //! 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. - 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. - 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; - - //! 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 ReferenceCount - { - private: - int count; - - public: - ReferenceCount() :count(0) { } - ReferenceCount(const ReferenceCount& o) { count = o.count; } - inline const ReferenceCount& operator=(const ReferenceCount& o) { count = 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* (); - - /** - * Returns the connected pointer */ - T* Get(); - - /** Checks if the pointer is valid (not NULL) - Returns true for valid, else false. */ - bool IsValid(); - }; - } - - - } - - 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/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp new file mode 100644 index 00000000..3f303542 --- /dev/null +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -0,0 +1,153 @@ +#include "Connection.h" + +#include +#include +#include +#include + +using namespace Oyster::Network; + +Connection::~Connection() +{ + closesocket( this->socket ); +} + +int Connection::Connect(unsigned short port , const char serverName[]) +{ + struct hostent *hostEnt; + if((hostEnt = gethostbyname(serverName)) == NULL) + { + return WSAGetLastError(); + } + + struct sockaddr_in server; + server.sin_family = AF_INET; + server.sin_port = htons(port); + server.sin_addr.s_addr = *(unsigned long*) hostEnt->h_addr; + + if(connect(this->socket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) + { + return WSAGetLastError(); + } + + //connection succesfull! + return 0; +} + +int Connection::InitiateServer(unsigned short port) +{ + int errorCode = 0; + + if((errorCode = InitiateSocket()) != 0) + { + return errorCode; + } + + struct sockaddr_in server; + server.sin_family = AF_INET; + server.sin_port = htons(port); + server.sin_addr.s_addr = INADDR_ANY; + + if(bind(this->socket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) + { + errorCode = WSAGetLastError(); + closesocket(this->socket); + return errorCode; + } + + //not our Listen function! its trying to keep our socket open for connections + if(listen(this->socket, 5) == SOCKET_ERROR) + { + errorCode = WSAGetLastError(); + closesocket(this->socket); + return errorCode; + } + + //Server started! + return 0; +} + +int Connection::InitiateClient() +{ + return InitiateSocket(); +} + +int Connection::Disconnect() +{ + closesocket(this->socket); + + return WSAGetLastError(); +} + +int Connection::Send(OysterByte& bytes) +{ + int nBytes; + + nBytes = send(this->socket, bytes, bytes.GetSize(), 0); + if(nBytes == SOCKET_ERROR) + { + return WSAGetLastError(); + } + + return 0; +} + +int Connection::Recieve(OysterByte& bytes) +{ + int nBytes; + + bytes.Clear(1000); + nBytes = recv(this->socket, bytes, 500, 0); + if(nBytes == SOCKET_ERROR) + { + return WSAGetLastError(); + } + else + { + bytes.SetSize(nBytes); + } + + std::cout << "Size of the recieved data: " << nBytes << " bytes" << std::endl; + + //bytes.byteArray[nBytes] = '\0'; + + return 0; +} + +int Connection::Listen() +{ + int clientSocket; + if((clientSocket = accept(this->socket, NULL, NULL)) == INVALID_SOCKET) + { + return WSAGetLastError(); + } + + return clientSocket; +} + +/////////////////////////////////////// +//Private functions +/////////////////////////////////////// +int Connection::InitiateSocket() +{ + this->socket = ::socket(AF_INET, SOCK_STREAM, 0); + if(this->socket == SOCKET_ERROR) + { + return WSAGetLastError(); + } + + return 0; +} + +void Connection::SetBlockingMode(bool blocking) +{ + //TODO: Implement this function. Setting the socket to blocking or non-blocking. + if(blocking) + { + //fcntl(this->socket, F_SETFL, O_NONBLOCK); + } + else + { + + } +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h new file mode 100644 index 00000000..b46ccb02 --- /dev/null +++ b/Code/Network/NetworkDependencies/Connection.h @@ -0,0 +1,45 @@ +#ifndef NETWORK_DEPENDENCIES_CONNECTION_H +#define NETWORK_DEPENDENCIES_CONNECTION_H + +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + +#include "IConnection.h" +#include "../NetworkDependencies/OysterByte.h" + +namespace Oyster +{ + namespace Network + { + class Connection : public IConnection + { + + public: + Connection() { this->socket = 0; }; + Connection( int socket ) { this->socket = socket; }; + virtual ~Connection(); + + + virtual int InitiateServer( unsigned short port ); + virtual int InitiateClient(); + + virtual int Send( OysterByte& bytes ); + virtual int Recieve( OysterByte& bytes ); + + virtual int Disconnect(); + virtual int Connect( unsigned short port , const char serverName[] ); + + virtual int Listen(); + + private: + int InitiateSocket(); + void SetBlockingMode( bool blocking ); + + int socket; + + }; + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Event.cpp b/Code/Network/NetworkDependencies/Event.cpp deleted file mode 100644 index 33e92bbf..00000000 --- a/Code/Network/NetworkDependencies/Event.cpp +++ /dev/null @@ -1,262 +0,0 @@ -#include "Event.h" -using namespace Event; - - -//---------------------------- -// BulletCreated class definitions -BulletCreated::BulletCreated(int ownerID, Float3 position, Float3 direction) - : - GameEvent() -{ - data.owner=ownerID; - data.head=direction; -} -void BulletCreated::LoadRawData(char* d) -{ - memcpy(&data, d, GetSize()); - /*int offset=0; - memcpy(&data.position, data, sizeof(Float3)); - offset+=sizeof(Float3); - - memcpy(&data.head, d+offset, sizeof(Float3)); - offset+=sizeof(Float3); - memcpy(&data.owner, d+offset, sizeof(int));*/ -} -void BulletCreated::SaveRawData(char* d) -{ - memcpy(d, &data, GetSize()); -} - -//---------------------------- -// BulletHit class definitions -BulletHit::BulletHit(int attacker, int hitPlayer) - : - GameEvent() -{ - data.hitTarget=hitPlayer; - data.attackingTarget=attacker; - //this->hpLeft=hl; - //this->shieldLeft=sl; -} -void BulletHit::LoadRawData(char* d) -{ - memcpy(&data, d, GetSize()); -} -void BulletHit::SaveRawData(char* d) -{ - memcpy(d, &data, GetSize()); -} - -ScoreUpdate::ScoreUpdate(Score* scores) -{ - for (int i=0; iGetSize()); - /*int offset=0; - memcpy(&data.position, data, sizeof(Float3)); - offset+=sizeof(Float3); - - memcpy(&playerID, data+offset, sizeof(int));*/ -} -void ShipSpawned::SaveRawData(char* d) -{ - memcpy(d, &data, GetSize()); -} - - -//---------------------------- -// GameEnded class definitions -GameEnded::GameEnded() - : - GameEvent() -{ -} -GameEnded::GameEnded(int winner) - : - GameEvent() -{ - data.winningTeam=winner; -} -void GameEnded::LoadRawData(char* d) -{ - memcpy(&data, d, GetSize()); - /*int offset=0; - memcpy(&eventPosition, data, sizeof(Float3)); - offset+=sizeof(Float3); - - memcpy(&winningTeam, data+offset, sizeof(int)); - offset+=sizeof(int); - - for (int i=0; i + class IPostBox + { + public: + virtual ~IPostBox() {} + virtual void PostMessage(T& message) = 0; + virtual void FetchMessage(T& message) = 0; + virtual bool IsFull() = 0; + + }; + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/ITranslate.h b/Code/Network/NetworkDependencies/ITranslate.h new file mode 100644 index 00000000..80edc8b1 --- /dev/null +++ b/Code/Network/NetworkDependencies/ITranslate.h @@ -0,0 +1,24 @@ +#ifndef NETWORK_DEPENDENCIES_I_TRANSLATE +#define NETWORK_DEPENDENCIES_I_TRANSLATE + +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + +namespace Oyster +{ + namespace Network + { + class OysterByte; + class ITranslate + { + + public: + //packs and unpacks packages for sending or recieving over the connection + virtual void Pack (Protocols::ProtocolHeader &header, OysterByte& bytes) = 0; + virtual void Unpack (Protocols::ProtocolSet* set, OysterByte& bytes ) = 0; + + }; + } +} +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Listener.cpp b/Code/Network/NetworkDependencies/Listener.cpp new file mode 100644 index 00000000..c441d045 --- /dev/null +++ b/Code/Network/NetworkDependencies/Listener.cpp @@ -0,0 +1,69 @@ +#include "Listener.h" + +using namespace Oyster::Network::Server; + +Listener::Listener() +{ + connection = NULL; +} + +Listener::~Listener() +{ + if(connection) + { + delete connection; + } +} + +bool Listener::Init(unsigned int port) +{ + connection = new Connection(); + + connection->InitiateServer(port); + + thread.Create(this, true); + + return true; +} + +void Listener::Shutdown() +{ + thread.Terminate(); +} + +void Listener::SetPostBox(Oyster::Network::IPostBox* postBox) +{ + mutex.LockMutex(); + this->postBox = postBox; + mutex.UnlockMutex(); +} + +int Listener::Accept() +{ + int clientSocket = 0; + clientSocket = connection->Listen(); + + mutex.LockMutex(); + postBox->PostMessage(clientSocket); + mutex.UnlockMutex(); + + return clientSocket; +} + +bool Listener::DoWork() +{ + Accept(); + + return true; +} + +#include +void Listener::ThreadEntry() +{ + std::cout << "Thread started" << std::endl; +} + +void Listener::ThreadExit() +{ + std::cout << "Thread stopped" << std::endl; +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Listener.h b/Code/Network/NetworkDependencies/Listener.h new file mode 100644 index 00000000..8bb16a0f --- /dev/null +++ b/Code/Network/NetworkDependencies/Listener.h @@ -0,0 +1,54 @@ +#ifndef NETWORK_SERVER_LISTENER_H +#define NETWORK_SERVER_LISTENER_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include "IListener.h" +#include "../NetworkDependencies/Connection.h" +#include "../../Misc/Thread/OysterThread.h" +#include "../../Misc/Thread/OysterMutex.h" +#include "IPostBox.h" + +namespace Oyster +{ + namespace Network + { + namespace Server + { + class Listener : public ::Oyster::Thread::IThreadObject + { + public: + Listener(); + ~Listener(); + + bool Init(unsigned int port); + void Shutdown(); + + void SetPostBox(IPostBox* postBox); + + //Thread functions + bool DoWork(); + void ThreadEntry(); + void ThreadExit(); + + private: + //Function that runs in the thread. + int Accept(); + + + private: + ::Oyster::Network::Connection* connection; + + ::Oyster::Thread::OysterThread thread; + OysterMutex mutex; + + IPostBox* postBox; + + }; + } + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp new file mode 100644 index 00000000..97acf526 --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp @@ -0,0 +1,254 @@ +#include "MessageHeader.h" +#include "../Packing.h" +#include +using namespace std; + +using namespace Oyster::Network; +using namespace Oyster::Network::Messages; +using namespace Oyster::Network::Protocols; + +MessageHeader::MessageHeader() +{ + size = 0; +} + +MessageHeader::~MessageHeader() +{ +} + +void MessageHeader::Pack(ProtocolHeader& header, OysterByte& bytes) +{ + size = 0; + + PackInt(header.size, bytes); + PackInt(header.packageType, bytes); + PackInt(header.clientID, bytes); + SetSize(bytes); +} + +void MessageHeader::Unpack(OysterByte& bytes, ProtocolHeader& header) +{ + size = 0; + + header.size = UnpackInt(bytes); + header.packageType = UnpackInt(bytes); + header.clientID = UnpackInt(bytes); +} + +/************************** + Pack +**************************/ + +void MessageHeader::PackBool(bool i, OysterByte& bytes) +{ + bytes.AddSize(1); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 1; +} + +void MessageHeader::PackChar(char i, OysterByte& bytes) +{ + bytes.AddSize(1); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 1; +} + +void MessageHeader::PackUnsignedChar(unsigned char i, OysterByte& bytes) +{ + bytes.AddSize(1); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 1; +} + +void MessageHeader::PackShort(short i, OysterByte& bytes) +{ + bytes.AddSize(2); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 2; +} + +void MessageHeader::PackUnsignedShort(unsigned short i, OysterByte& bytes) +{ + bytes.AddSize(2); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 2; +} + +void MessageHeader::PackInt(int i, OysterByte& bytes) +{ + bytes.AddSize(4); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 4; +} + +void MessageHeader::PackUnsignedInt(unsigned int i, OysterByte& bytes) +{ + bytes.AddSize(4); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 4; +} + +void MessageHeader::PackInt64(__int64 i, OysterByte& bytes) +{ + bytes.AddSize(8); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 8; +} + +void MessageHeader::PackUnsignedInt64(unsigned __int64 i, OysterByte& bytes) +{ + bytes.AddSize(8); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 8; +} + +void MessageHeader::PackFloat(float i, OysterByte& bytes) +{ + bytes.AddSize(4); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 4; +} + +void MessageHeader::PackFloat(float i[], unsigned int elementCount, OysterByte& bytes) +{ + bytes.AddSize(4); + //Pack number of elements + PackUnsignedInt(elementCount, bytes); + + //Pack all elements + for(int j = 0; j < (int)elementCount; j++) + { + PackFloat(i[j], bytes); + } +} + +void MessageHeader::PackDouble(double i, OysterByte& bytes) +{ + bytes.AddSize(8); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 8; +} + +void MessageHeader::PackStr(char str[], OysterByte& bytes) +{ + int totalSize = 2 + strlen(str); + bytes.AddSize(totalSize); + Packing::Pack(&bytes.GetByteArray()[size], str); + size += totalSize; +} + +void MessageHeader::PackStr(std::string str, OysterByte& bytes) +{ + int totalSize = 2 + str.length(); + bytes.AddSize(totalSize); + Packing::Pack(&bytes.GetByteArray()[size], str); + size += totalSize; +} + +/************************** + Unpack +**************************/ + +bool MessageHeader::UnpackBool(OysterByte& bytes) +{ + bool i = Packing::Unpackb(&bytes.GetByteArray()[size]); + size += 1; + return i; +} + +char MessageHeader::UnpackChar(OysterByte& bytes) +{ + char i = Packing::Unpackc(&bytes.GetByteArray()[size]); + size += 1; + return i; +} + +unsigned char MessageHeader::UnpackUnsignedChar(OysterByte& bytes) +{ + unsigned char i = Packing::UnpackC(&bytes.GetByteArray()[size]); + size += 1; + return i; +} + +short MessageHeader::UnpackShort(OysterByte& bytes) +{ + short i = Packing::Unpacks(&bytes.GetByteArray()[size]); + size += 2; + return i; +} + +unsigned short MessageHeader::UnpackUnsignedShort(OysterByte& bytes) +{ + unsigned short i = Packing::UnpackS(&bytes.GetByteArray()[size]); + size += 2; + return i; +} + +int MessageHeader::UnpackInt(OysterByte& bytes) +{ + int i = Packing::Unpacki(&bytes.GetByteArray()[size]); + size += 4; + return i; +} + +unsigned int MessageHeader::UnpackUnsignedInt(OysterByte& bytes) +{ + unsigned int i = Packing::UnpackI(&bytes.GetByteArray()[size]); + size += 4; + return i; +} + +__int64 MessageHeader::UnpackInt64(OysterByte& bytes) +{ + __int64 i = Packing::Unpacki64(&bytes.GetByteArray()[size]); + size += 8; + return i; +} + +unsigned __int64 MessageHeader::UnpackUnsignedInt64(OysterByte& bytes) +{ + unsigned __int64 i = Packing::UnpackI64(&bytes.GetByteArray()[size]); + size += 8; + return i; +} + +float MessageHeader::UnpackFloat(OysterByte& bytes) +{ + float i = Packing::Unpackf(&bytes.GetByteArray()[size]); + size += 4; + return i; +} + +float* MessageHeader::UnpackFloat(unsigned int& elementCount, OysterByte& bytes) +{ + float* i; + + elementCount = UnpackUnsignedInt(bytes); + + i = new float[elementCount]; + for(int j = 0; j < (int)elementCount; j++) + { + i[j] = UnpackFloat(bytes); + } + + return i; +} + +double MessageHeader::UnpackDouble(OysterByte& bytes) +{ + double i = Packing::Unpackd(&bytes.GetByteArray()[size]); + size += 8; + return i; +} + +std::string MessageHeader::UnpackStr(OysterByte& bytes) +{ + std::string str = Packing::UnpackStr(&bytes.GetByteArray()[size]); + size += 2 + str.length(); + return str; +} + +void MessageHeader::SetSize(OysterByte& bytes) +{ + Packing::Pack(bytes, size); +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.h b/Code/Network/NetworkDependencies/Messages/MessageHeader.h new file mode 100644 index 00000000..095ebc1e --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.h @@ -0,0 +1,88 @@ +#ifndef NETWORK_DEPENDENCIES_MESSAGE_HEADER_H +#define NETWORK_DEPENDENCIES_MESSAGE_HEADER_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include +#include "../Protocols.h" +#include "../OysterByte.h" + +namespace Oyster +{ + namespace Network + { + namespace Messages + { + class MessageHeader + { + public: + MessageHeader(); + virtual ~MessageHeader(); + + virtual void Pack(Protocols::ProtocolHeader& header, OysterByte& bytes ); + virtual void Unpack(OysterByte& bytes, Protocols::ProtocolHeader& header); + + protected: + //Pack variables to messages + void PackBool(bool i, OysterByte& bytes); + + void PackChar(char i, OysterByte& bytes); + void PackUnsignedChar(unsigned char i, OysterByte& bytes); + + void PackShort(short i, OysterByte& bytes); + void PackUnsignedShort(unsigned short i, OysterByte& bytes); + + void PackInt(int i, OysterByte& bytes); + void PackUnsignedInt(unsigned int i, OysterByte& bytes); + + void PackInt64(__int64 i, OysterByte& bytes); + void PackUnsignedInt64(unsigned __int64 i, OysterByte& bytes); + + void PackFloat(float i, OysterByte& bytes); + void PackFloat(float i[], unsigned int elementCount, OysterByte& bytes); + void PackDouble(double i, OysterByte& bytes); + + void PackStr(char str[], OysterByte& bytes); + void PackStr(std::string str, OysterByte& bytes); + + //TODO: Add Pack functions for Vec2, 3, 4 and maybe Matrix. Etc. + + + //Unpack variables from message + bool UnpackBool(OysterByte& bytes); + + char UnpackChar(OysterByte& bytes); + unsigned char UnpackUnsignedChar(OysterByte& bytes); + + short UnpackShort(OysterByte& bytes); + unsigned short UnpackUnsignedShort(OysterByte& bytes); + + int UnpackInt(OysterByte& bytes); + unsigned int UnpackUnsignedInt(OysterByte& bytes); + + __int64 UnpackInt64(OysterByte& bytes); + unsigned __int64 UnpackUnsignedInt64(OysterByte& bytes); + + float UnpackFloat(OysterByte& bytes); + float* UnpackFloat(unsigned int& elementCount, OysterByte& bytes); + double UnpackDouble(OysterByte& bytes); + + std::string UnpackStr(OysterByte& bytes); + + //TODO: Add Unpack functions for Vec2, 3, 4 and maybe Matrix. Etc. + + + //Sets the this->size to the first position in msg + void SetSize(OysterByte& bytes); + + private: + unsigned int size; + + }; + } + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageTest.cpp b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp new file mode 100644 index 00000000..7fcb1a71 --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp @@ -0,0 +1,30 @@ +#include "MessageTest.h" + +using namespace Oyster::Network; +using namespace Oyster::Network::Messages; +using namespace Oyster::Network::Protocols; + +MessageTest::MessageTest() +{ +} + +MessageTest::~MessageTest() +{ +} + +void MessageTest::Pack(ProtocolHeader& header, OysterByte& bytes) +{ + MessageHeader::Pack(header, bytes); + + PackStr(static_cast(&header)->textMessage, bytes); + PackFloat(static_cast(&header)->f, static_cast(&header)->numOfFloats, bytes); + SetSize(bytes); +} + +void MessageTest::Unpack(OysterByte& bytes, ProtocolHeader& header) +{ + MessageHeader::Unpack(bytes, header); + + static_cast(&header)->textMessage = UnpackStr(bytes); + static_cast(&header)->f = UnpackFloat(static_cast(&header)->numOfFloats, bytes); +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageTest.h b/Code/Network/NetworkDependencies/Messages/MessageTest.h new file mode 100644 index 00000000..ff636e56 --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.h @@ -0,0 +1,31 @@ +#ifndef NETWORK_DEPENDENCIES_MESSAGE_TEST_H +#define NETWORK_DEPENDENCIES_MESSAGE_TEST_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include "MessageHeader.h" + +namespace Oyster +{ + namespace Network + { + namespace Messages + { + class MessageTest : public MessageHeader + { + public: + MessageTest(); + virtual ~MessageTest(); + + virtual void Pack(Protocols::ProtocolHeader& header, OysterByte& bytes); + virtual void Unpack(OysterByte& bytes, Protocols::ProtocolHeader& header); + + private: + }; + } + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessagesInclude.h b/Code/Network/NetworkDependencies/Messages/MessagesInclude.h new file mode 100644 index 00000000..8f4d41e3 --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessagesInclude.h @@ -0,0 +1,11 @@ +#ifndef NETWORK_DEPENDENCIES_MESSAGES_INCLUDE_H +#define NETWORK_DEPENDENCIES_MESSAGES_INCLUDE_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include "MessageHeader.h" +#include "MessageTest.h" + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Network.h b/Code/Network/NetworkDependencies/Network.h deleted file mode 100644 index 2aa95b45..00000000 --- a/Code/Network/NetworkDependencies/Network.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef NETWORK_H -#define NETWORK_H -#include "NetworkIncludes.h" -#include "EventStructs.h" -#include "NetworkUpdateStructs.h" -#include "NetworkInitStructs.h" -#include "EventStructs.h" -#include "Event.h" -#include "NetworkMiscFunctions.h" -#include "NetworkTimer.h" -#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkConstants.h b/Code/Network/NetworkDependencies/NetworkConstants.h deleted file mode 100644 index c0b23037..00000000 --- a/Code/Network/NetworkDependencies/NetworkConstants.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once -#ifndef NET_CONST_H -#define NET_CONST_H -//const int PLAYER_WAIT_COUNT = 1; -const int PLAYER_MAX_COUNT = 8; -const float LOBBY_WAIT_TIME = 4; -/*namespace Network -{ - void LoadData(){} -}*/ -#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj index d75cedab..dfabbcba 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj @@ -27,7 +27,7 @@ StaticLibrary true v110 - MultiByte + Unicode StaticLibrary @@ -69,28 +69,36 @@ $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(SolutionDir)..\External\Lib\$(ProjectName)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(SolutionDir)..\External\Lib\$(ProjectName)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) Level3 Disabled true - ..\..\Misc;..\..\OysterMath;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -101,7 +109,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -114,7 +122,7 @@ true true true - ..\..\Misc;..\..\OysterMath;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -129,7 +137,7 @@ true true true - ..\..\Misc;..\..\OysterMath;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -137,35 +145,38 @@ true - - - - - - - - - - - - - - - - - {2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee} - - {f10cbc03-9809-4cba-95d8-327c287b18ee} - true - true - true - false - false - + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters index 55401224..74cb9a56 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters @@ -1,60 +1,31 @@  - - {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 - + + + + + + + + + - - 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 - + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkIncludes.h b/Code/Network/NetworkDependencies/NetworkIncludes.h deleted file mode 100644 index 89902672..00000000 --- a/Code/Network/NetworkDependencies/NetworkIncludes.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef NET_INCL_H -#define NET_INCL_H -#ifndef UNICODE -#define UNICODE -#endif - -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include -#include -#include -#include -#include -#include -#include -#include - -#include "OysterMath.h" -using namespace Oyster::Math; - -//ws2_32.lib is a lib file the linker requires for winsock compilation -#pragma comment(lib, "Ws2_32.lib") -#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkInitStructs.h b/Code/Network/NetworkDependencies/NetworkInitStructs.h deleted file mode 100644 index 7ef04ed1..00000000 --- a/Code/Network/NetworkDependencies/NetworkInitStructs.h +++ /dev/null @@ -1,70 +0,0 @@ -#ifndef NET_INIT_STRUCTS_H -#define NET_INIT_STRUCTS_H -#include "NetworkIncludes.h" -#include "NetworkConstants.h" -struct PlayerInitStruct -{ - INT8 pid; - int teamid; - Oyster::Math::Float4x4 position; - PlayerInitStruct() - { - pid=0; - //position=Oyster::Math::Float4x4::identity; - } -}; - -struct GameInitData -{ - INT8 pid; - //std::string playerNames[PLAYER_MAX_COUNT]; - PlayerInitStruct player[PLAYER_MAX_COUNT]; -}; - -struct LobbyUserStruct -{ - INT8 pid; - INT8 shipID; - char usrName[15]; - LobbyUserStruct() - { - pid=0; - shipID=0; - usrName[0]='\0'; - } - void setName(const char* n) - { - strcpy_s(usrName, n); - } - int size() - { - int sz=sizeof(pid); - sz+=sizeof(shipID); - int tmp=(int)strlen(usrName); - sz+=(int)strlen(usrName); - return sz; - } -}; -struct LobbyInitData -{ - INT8 pid; - INT8 playerCount; - int timer; - LobbyUserStruct players[PLAYER_MAX_COUNT]; - LobbyInitData() - { - pid=0; - for (int i=0; i splitString(const char* p_inStr, char p_delim) -{ - std::stringstream ss(p_inStr); - std::vector elems; - std::string item; - while(std::getline(ss, item, p_delim)) - { - elems.push_back(item); - } - return elems; -} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkMiscFunctions.h b/Code/Network/NetworkDependencies/NetworkMiscFunctions.h deleted file mode 100644 index a6959020..00000000 --- a/Code/Network/NetworkDependencies/NetworkMiscFunctions.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef NET_MISC_FNC_H -#define NET_MISC_FNC_H -#include -#include -#include -std::vector splitString(const char* p_inStr, char p_delim); -#define SSTR( x ) dynamic_cast< std::ostringstream & >( \ - ( std::ostringstream() << std::dec << x ) ).str() -#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkTimer.cpp b/Code/Network/NetworkDependencies/NetworkTimer.cpp deleted file mode 100644 index 42b8a143..00000000 --- a/Code/Network/NetworkDependencies/NetworkTimer.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#include "NetworkTimer.h" -NetworkTimer::NetworkTimer() - : - c_SecondsPerCount(0.0), - c_DeltaTime(-1.0), - c_BaseTime(0), - c_PausedTime(0), - c_PrevTime(0), - c_CurrTime(0), - c_Stopped(false) -{ - __int64 countsPerSec; - QueryPerformanceFrequency((LARGE_INTEGER*)&countsPerSec); - c_SecondsPerCount =1.0 / (double)countsPerSec; - - QueryPerformanceCounter((LARGE_INTEGER*)&c_PrevTime); -} - -void NetworkTimer::start() -{ - __int64 p_StartTime; - QueryPerformanceCounter((LARGE_INTEGER*)&p_StartTime); - if(c_Stopped) - { - c_PausedTime += (p_StartTime-c_StopTime); - c_PrevTime = p_StartTime; - c_StopTime = 0; - c_Stopped = false; - } -} -__int64 NetworkTimer::getTime() -{ - __int64 testInt; - return QueryPerformanceCounter((LARGE_INTEGER*)&testInt); - return testInt; -} - -void NetworkTimer::stop() -{ - if(!c_Stopped) - { - __int64 p_CurrTime; - QueryPerformanceCounter((LARGE_INTEGER*)&p_CurrTime); - c_StopTime = p_CurrTime; - c_Stopped = true; - } -} -void NetworkTimer::reset() -{ - __int64 p_CurrTime; - QueryPerformanceCounter((LARGE_INTEGER*)&p_CurrTime); - c_BaseTime = p_CurrTime; - c_PrevTime = p_CurrTime; - c_StopTime = 0; - c_Stopped = false; -} -void NetworkTimer::tick() -{ - if (c_Stopped) - { - c_DeltaTime= 0.0; - return; - } - __int64 p_CurrTime; - QueryPerformanceCounter((LARGE_INTEGER*)&p_CurrTime); - c_CurrTime=p_CurrTime; - - c_DeltaTime=(c_CurrTime-c_PrevTime)*c_SecondsPerCount; - c_PrevTime=c_CurrTime; - if(c_DeltaTime<0.0) c_DeltaTime=0.0; -} -float NetworkTimer::getGameTime() const -{ - if(c_Stopped) - { - return (float)((c_StopTime-c_BaseTime)*c_SecondsPerCount); - } else - { - return (float)(((c_CurrTime-c_PausedTime)-c_BaseTime)*c_SecondsPerCount); - } -} -float NetworkTimer::getDeltaTime() const -{ - return (float)c_DeltaTime; -} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkTimer.h b/Code/Network/NetworkDependencies/NetworkTimer.h deleted file mode 100644 index c4581c50..00000000 --- a/Code/Network/NetworkDependencies/NetworkTimer.h +++ /dev/null @@ -1,25 +0,0 @@ -#include "NetworkIncludes.h" -#ifndef _NET_TIMER_H -#define _NET_TIMER_H -class NetworkTimer -{ -private: - double c_SecondsPerCount; - double c_DeltaTime; - __int64 c_BaseTime; - __int64 c_PausedTime; - __int64 c_StopTime; - __int64 c_PrevTime; - __int64 c_CurrTime; - bool c_Stopped; -public: - NetworkTimer(); - __int64 getTime(); - void start(); - void stop(); - void reset(); - void tick(); - float getGameTime() const; - float getDeltaTime() const; -}; -#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkUpdateStructs.h b/Code/Network/NetworkDependencies/NetworkUpdateStructs.h deleted file mode 100644 index 97f2037d..00000000 --- a/Code/Network/NetworkDependencies/NetworkUpdateStructs.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef NET_UPD_STRUCTS_H -#define NET_UPD_STRUCTS_H -#include "NetworkIncludes.h" -namespace Network -{ - struct EffectData - { - int identifier; - Float3 head; - Float3 tail; - }; - struct ServerToClientUpdateData - { - int pid; - Oyster::Math::Float4x4 position; - float dirVecLen; - int hp; - int shield; - long updateCount; - ServerToClientUpdateData() - { - pid=0; - updateCount=0; - hp=0; - shield=0; - } - }; - const int SERVER_PLAYER_DATA_SIZE = 84; - struct ClientToServerUpdateData - { - __int8 pid; - //Oyster::Math::Float4x4 position; - __int8 forward; - __int8 roll; - __int8 straferight; - __int8 strafeup; - bool firePrim; - bool fireSecond; - bool fireSpecial; - long updateCount; - bool braking; - float TurnHor; - float TurnVer; - ClientToServerUpdateData() - { - pid=0; - forward=0; - roll=0; - straferight=0; - strafeup=0; - firePrim=false; - fireSecond=false; - fireSpecial=false; - updateCount=0; - braking=false; - TurnHor= 0.0f; - TurnVer= 0.0f; - } - }; - const int CLIENT_PLAYER_DATA_SIZE = sizeof(ClientToServerUpdateData); -} -#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/OysterByte.cpp b/Code/Network/NetworkDependencies/OysterByte.cpp new file mode 100644 index 00000000..ef7aa434 --- /dev/null +++ b/Code/Network/NetworkDependencies/OysterByte.cpp @@ -0,0 +1,94 @@ +#include "OysterByte.h" + +using namespace Oyster::Network; + +OysterByte::OysterByte() +{ + size = 0; + capacity = 10; + byteArray = new unsigned char[capacity]; +} + +OysterByte::OysterByte(int cap) +{ + size = 0; + capacity = cap; + byteArray = new unsigned char[capacity]; +} + +OysterByte::~OysterByte() +{ + delete[] byteArray; +} + +void OysterByte::Clear(unsigned int cap) +{ + delete[] byteArray; + byteArray = new unsigned char[cap]; + size = 0; +} + +int OysterByte::GetSize() +{ + return size; +} + +unsigned char* OysterByte::GetByteArray() +{ + return byteArray; +} + +void OysterByte::AddSize(unsigned int size) +{ + int oldSize = this->size; + this->size += size; + + if(this->size >= capacity) + { + IncreaseCapacity(oldSize); + } +} + +void OysterByte::SetBytes(unsigned char* bytes) +{ + delete[] byteArray; + byteArray = bytes; +} + +void OysterByte::SetSize(unsigned int size) +{ + this->size = size; +} + +OysterByte::operator char*() +{ + return (char*)byteArray; +} + +OysterByte::operator const char*() +{ + return (const char*)byteArray; +} + +OysterByte::operator unsigned char*() +{ + return byteArray; +} + +///////////// +// Private // +///////////// + +void OysterByte::IncreaseCapacity(unsigned int oldSize) +{ + capacity = size * 2; + unsigned char* temp = new unsigned char[capacity]; + + for(int i = 0; i < (int)oldSize; i++) + { + temp[i] = byteArray[i]; + } + + delete[] byteArray; + byteArray = temp; +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/OysterByte.h b/Code/Network/NetworkDependencies/OysterByte.h new file mode 100644 index 00000000..87a0103c --- /dev/null +++ b/Code/Network/NetworkDependencies/OysterByte.h @@ -0,0 +1,47 @@ +#ifndef NETWORK_DEPENDENCIES_OYSTER_BYTE_H +#define NETWORK_DEPENDENCIES_OYSTER_BYTE_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include + +namespace Oyster +{ + namespace Network + { + class OysterByte + { + public: + OysterByte(); + OysterByte(int cap); + virtual ~OysterByte(); + + void Clear(unsigned int cap); + + int GetSize(); + unsigned char* GetByteArray(); + + void AddSize(unsigned int size); + void SetBytes(unsigned char* bytes); + void SetSize(unsigned int size); //Only sets the private variable 'size' + + operator char*(); + operator const char*(); + operator unsigned char*(); + + private: + void IncreaseCapacity(unsigned int cap); //Expands the byteArray + + + private: + unsigned char* byteArray; + unsigned int size; + unsigned int capacity; + + }; + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Packing.cpp b/Code/Network/NetworkDependencies/Packing.cpp new file mode 100644 index 00000000..7adc395c --- /dev/null +++ b/Code/Network/NetworkDependencies/Packing.cpp @@ -0,0 +1,470 @@ +#include "Packing.h" + +/*************************** + Packing +***************************/ + +#include + +namespace Oyster +{ + namespace Network + { + namespace Packing + { + //bool (1-bit) + void Pack(unsigned char buffer[], bool i) + { + *buffer++ = i; + } + + //char (8-bit) + void Pack(unsigned char buffer[], char i) + { + *buffer++ = i; + } + + void Pack(unsigned char buffer[], unsigned char i) + { + *buffer++ = i; + } + + //short (16-bit) + void Pack(unsigned char buffer[], short i) + { + *buffer++ = i >> 8; + *buffer++ = (char)i; + } + + void Pack(unsigned char buffer[], unsigned short i) + { + *buffer++ = i >> 8; + *buffer++ = (char)i; + } + + //int (32-bit) + void Pack(unsigned char buffer[], int i) + { + *buffer++ = i >> 24; + *buffer++ = i >> 16; + *buffer++ = i >> 8; + *buffer++ = i; + } + + void Pack(unsigned char buffer[], unsigned int i) + { + *buffer++ = i >> 24; + *buffer++ = i >> 16; + *buffer++ = i >> 8; + *buffer++ = i; + } + + //__int64 (64-bit) + void Pack(unsigned char buffer[], __int64 i) + { + *buffer++ = (char)(i >> 56); + *buffer++ = (char)(i >> 48); + *buffer++ = (char)(i >> 40); + *buffer++ = (char)(i >> 32); + *buffer++ = (char)(i >> 24); + *buffer++ = (char)(i >> 16); + *buffer++ = (char)(i >> 8); + *buffer++ = (char)i; + } + + void Pack(unsigned char buffer[], unsigned __int64 i) + { + *buffer++ = (char)(i >> 56); + *buffer++ = (char)(i >> 48); + *buffer++ = (char)(i >> 40); + *buffer++ = (char)(i >> 32); + *buffer++ = (char)(i >> 24); + *buffer++ = (char)(i >> 16); + *buffer++ = (char)(i >> 8); + *buffer++ = (char)i; + } + + //floating point (32, 64-bit) + void Pack(unsigned char buffer[], float i) + { + int tempFloat = Pack754(i, 32, 8); + Pack(buffer, tempFloat); + } + + void Pack(unsigned char buffer[], double i) + { + __int64 tempDouble = Pack754(i, 64, 11); + Pack(buffer, tempDouble); + } + + //string + void Pack(unsigned char buffer[], char str[]) + { + short len = strlen(str); + Pack(buffer, len); + buffer += 2; + memcpy(buffer, str, len); + } + + void Pack(unsigned char buffer[], std::string& str) + { + short len = str.length(); + Pack(buffer, len); + buffer += 2; + memcpy(buffer, str.c_str(), len); + } + + unsigned __int64 Pack754(long double f, unsigned bits, unsigned expbits) + { + long double fnorm; + int shift; + long long sign, exp, significand; + unsigned significandbits = bits - expbits - 1; // -1 for sign bit + + if (f == 0.0) + return 0; // get this special case out of the way + + // check sign and begin normalization + if (f < 0) + { + sign = 1; + fnorm = -f; + } + else + { + sign = 0; + fnorm = f; + } + + // get the normalized form of f and track the exponent + shift = 0; + while(fnorm >= 2.0) + { + fnorm /= 2.0; + shift++; + } + + while(fnorm < 1.0) + { + fnorm *= 2.0; + shift--; + } + + fnorm = fnorm - 1.0; + + // calculate the binary form (non-float) of the significand data + significand = fnorm * ((1LL << significandbits) + 0.5f); + + // get the biased exponent + exp = shift + ((1 << (expbits - 1)) - 1); // shift + bias + + // return the final answer + return (sign << (bits - 1)) | (exp << (bits - expbits - 1)) | significand; + } + + /****************************** + Unpacking + ******************************/ + + //bool (1-bit) + bool Unpackb(unsigned char buffer[]) + { + return (bool)buffer; + } + + //char (8-bit) + char Unpackc(unsigned char buffer[]) + { + if(*buffer <= 0x7f) + { + return *buffer; + } + else + { + return (-1 - (unsigned char)(0xffu - *buffer)); + } + } + + unsigned char UnpackC(unsigned char buffer[]) + { + return *buffer; + } + + //short (16-bit) + short Unpacks(unsigned char buffer[]) + { + short i = ((short)buffer[0] << 8) | buffer[1]; + + if(i > 0x7fffu) + { + i = -1 - (unsigned short)(0xffffu - i); + } + + return i; + } + + unsigned short UnpackS(unsigned char buffer[]) + { + return ((unsigned int)buffer[0] << 8) | buffer[1]; + } + + //int (32-bit) + int Unpacki(unsigned char buffer[]) + { + int i = ((int)buffer[0] << 24) | + ((int)buffer[1] << 16) | + ((int)buffer[2] << 8) | + ((int)buffer[3]); + + if(i > 0x7fffffffu) + { + i = -1 - (int)(0xffffffffu - i); + } + + return i; + } + + unsigned int UnpackI(unsigned char buffer[]) + { + return ((unsigned int)buffer[0] << 24) | + ((unsigned int)buffer[1] << 16) | + ((unsigned int)buffer[2] << 8) | + ((unsigned int)buffer[3]); + } + + //__int64 (64-bit) + __int64 Unpacki64(unsigned char buffer[]) + { + __int64 i = ((__int64)buffer[0] << 56) | + ((__int64)buffer[1] << 48) | + ((__int64)buffer[2] << 40) | + ((__int64)buffer[3] << 32) | + ((__int64)buffer[4] << 24) | + ((__int64)buffer[5] << 16) | + ((__int64)buffer[6] << 8) | + (buffer[7]); + + if(i > 0x7fffffffffffffffu) + { + i = -1 - (__int64)(0xffffffffffffffffu - i); + } + + return i; + } + + unsigned __int64 UnpackI64(unsigned char buffer[]) + { + + return ((__int64)buffer[0] << 56) | + ((__int64)buffer[1] << 48) | + ((__int64)buffer[2] << 40) | + ((__int64)buffer[3] << 32) | + ((__int64)buffer[4] << 24) | + ((__int64)buffer[5] << 16) | + ((__int64)buffer[6] << 8) | + ((__int64)buffer[7]); + } + + //floating point (32, 64-bit) + float Unpackf(unsigned char buffer[]) + { + int tempFloat = Unpacki(buffer); + return (float)Unpack754(tempFloat, 32, 8); + } + + double Unpackd(unsigned char buffer[]) + { + __int64 tempDouble = Unpacki64(buffer); + return Unpack754(tempDouble, 64, 11); + } + + //string + std::string UnpackStr(unsigned char buffer[]) + { + short len = UnpackS(buffer); + std::string temp; + temp.resize(len); + + buffer += 2; + for(int i = 0; i < len; i++) + { + temp[i] = buffer[i]; + } + + return temp; + } + + long double Unpack754(unsigned __int64 i, unsigned bits, unsigned expbits) + { + long double result; + long long shift; + unsigned bias; + unsigned significandbits = bits - expbits - 1; // -1 for sign bit + + if (i == 0) + return 0.0; + + // pull the significand + result = (i&((1LL << significandbits) - 1)); // mask + result /= (1LL << significandbits); // convert back to float + result += 1.0f; // add the one back on + + // deal with the exponent + bias = (1 << (expbits - 1)) - 1; + shift = ((i >> significandbits) & ((1LL << expbits) - 1)) - bias; + while(shift > 0) + { + result *= 2.0; + shift--; + } + while(shift < 0) + { + result /= 2.0; + shift++; + } + + // sign it + result *= (i >> (bits - 1)) & 1 ? -1.0 : 1.0; + + return result; + } + } + } +} + +/* +int32_t pack(unsigned char* buffer, char* format, ...) +{ + va_list ap; + int16_t h; + int32_t l; + int8_t c; + float f; + double d; + char* s; + int32_t size = 0, len; + + va_start(ap, format); + + for(; *format != '\0'; format++) + { + switch(*format) + { + case 'h': // 16-bit + size += 2; + h = (int16_t)va_arg(ap, int); + packi16(buffer, h); + buffer += 2; + break; + case 'l': // 32-bit + size += 4; + l = va_arg(ap, int32_t); + packi32(buffer, l); + buffer += 4; + break; + case 'c': // 8-bit + size += 1; + c = (int8_t)va_arg(ap, int); + *buffer++ = (c >> 0)&0xff; + break; + case 'f': // float (32-bit) + size += 4; + f = (float)va_arg(ap, double); + //l = pack754(f, 32, 8); + packi32(buffer, l); + buffer += 4; + break; + case 'd': // double (64-bit) + size += 8; + d = (float)va_arg(ap, double); + //l = pack754(f, 64, 11); + packi32(buffer, l); + buffer += 4; + break; + case 's': // string + s = va_arg(ap, char*); + len = strlen(s); + size += len + 2; + packi16(buffer, len); + buffer += 2; + memcpy(buffer, s, len); + buffer += len; + break; + } + } + + va_end(ap); + + return size; +} +*/ + +/* +void unpack(unsigned char* buffer, char* format, ...) +{ + va_list ap; + int16_t* h; + int32_t* l; + int32_t pf; + int64_t pd; + int8_t* c; + float* f; + double* d; + char* s; + int32_t len, count, maxstrlen = 0; + + va_start(ap, format); + + for(; *format != '\0'; format++) + { + switch(*format) + { + case 'h': // 16-bit + h = va_arg(ap, int16_t*); + *h = unpacki16(buffer); + buffer += 2; + break; + case 'l': // 32-bit + l = va_arg(ap, int32_t*); + *l = unpacki32(buffer); + buffer += 4; + break; + case 'c': // 8-bit + c = va_arg(ap, int8_t*); + *c = *buffer++; + break; + case 'f': // float + f = va_arg(ap, float*); + pf = unpacki32(buffer); + buffer += 4; + //*f = unpack754(pf, 32, 8); + break; + case 'd': // double (64-bit) + d = va_arg(ap, double*); + pd = unpacki64(buffer); + buffer += 8; + //*d = unpack754(pf, 64, 11); + break; + case 's': // string + s = va_arg(ap, char*); + len = unpacki16(buffer); + buffer += 2; + if (maxstrlen > 0 && len > maxstrlen) count = maxstrlen - 1; + else count = len; + memcpy(s, buffer, count); + s[count] = '\0'; + buffer += len; + break; + default: + if (isdigit(*format)) // track max str len + { + maxstrlen = maxstrlen * 10 + (*format-'0'); + } + } + + if(!isdigit(*format)) + maxstrlen = 0; + } + + va_end(ap); +}*/ \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Packing.h b/Code/Network/NetworkDependencies/Packing.h new file mode 100644 index 00000000..7a52c644 --- /dev/null +++ b/Code/Network/NetworkDependencies/Packing.h @@ -0,0 +1,106 @@ +#ifndef PACKING_H +#define PACKING_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include + +/****************************** + Packing +******************************/ +namespace Oyster +{ + namespace Network + { + namespace Packing + { + //bool (1-bit) + void Pack(unsigned char buffer[], bool i); + + //char (8-bit) + void Pack(unsigned char buffer[], char i); + void Pack(unsigned char buffer[], unsigned char i); // unsigned + + //short (16-bit) + void Pack(unsigned char buffer[], short i); + void Pack(unsigned char buffer[], unsigned short i); // unsigned + + //int (32-bit) + void Pack(unsigned char buffer[], int i); + void Pack(unsigned char buffer[], unsigned int i); // unsigned + + //__int64 (64-bit) + void Pack(unsigned char buffer[], __int64 i); + void Pack(unsigned char buffer[], unsigned __int64 i); // unsigned + + //floating point (32, 64-bit) + void Pack(unsigned char buffer[], float i); + void Pack(unsigned char buffer[], double i); + + //string + void Pack(unsigned char buffer[], char str[]); + void Pack(unsigned char buffer[], std::string& str); + + unsigned __int64 Pack754(long double f, unsigned bits, unsigned expbits); + + /****************************** + Unpacking + ******************************/ + + //bool (1-bit) + bool Unpackb(unsigned char buffer[]); + + //char (8-bit) + char Unpackc(unsigned char buffer[]); + unsigned char UnpackC(unsigned char buffer[]); // unsigned + + //short (16-bit) + short Unpacks(unsigned char buffer[]); + unsigned short UnpackS(unsigned char buffer[]); // unsigned + + //int (32-bit) + int Unpacki(unsigned char buffer[]); + unsigned int UnpackI(unsigned char buffer[]); // unsigned + + //__int64 (64-bit) + __int64 Unpacki64(unsigned char buffer[]); + unsigned __int64 UnpackI64(unsigned char buffer[]); // unsigned + + //floating point (32, 64-bit) + float Unpackf(unsigned char buffer[]); + double Unpackd(unsigned char buffer[]); + + //string + std::string UnpackStr(unsigned char buffer[]); + + long double Unpack754(unsigned __int64 i, unsigned bits, unsigned expbits); + } + } +} + + +//int32_t pack(unsigned char* buffer, char* format, ...); + +//void unpack(unsigned char* buffer, char* format, ...); + + +/*********************************************** +* This table is used for naming pack/unpack functions. +* It's also used to identify types in the 'format' string in function pack()/unpack() +* +* bits |signed unsigned float string +* -----+---------------------------------- +* 1 | b +* 8 | c C +* 16 | s S f +* 32 | i I d +* 64 | q Q g +* - | str +* +* (16-bit unsigned length is automatically added in front of strings) +* +*/ + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/PostBox.h b/Code/Network/NetworkDependencies/PostBox.h new file mode 100644 index 00000000..b2e553f8 --- /dev/null +++ b/Code/Network/NetworkDependencies/PostBox.h @@ -0,0 +1,69 @@ +#ifndef NETWORK_DEPENDENCIES_POST_BOX_H +#define NETWORK_DEPENDENCIES_POST_BOX_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include "IPostBox.h" +#include "../../Misc/Thread/OysterMutex.h" +#include "../../Misc/ThreadSafeQueue.h" + +namespace Oyster +{ + namespace Network + { + //With this class you can post items to it and then fetch them somewhere else. + //It is thread safe beacause of the ThreadSafeQueue. + template + class PostBox : public IPostBox + { + public: + PostBox(); + virtual ~PostBox(); + + virtual void PostMessage(T& message); + virtual void FetchMessage(T& message); + virtual bool IsFull(); + + private: + Oyster::Queue::ThreadSafeQueue messages; + + }; + + //Implementation of PostBox + template + PostBox::PostBox() + { + } + + template + PostBox::~PostBox() + { + } + + template + void PostBox::PostMessage(T& message) + { + messages.Push(message); + } + + template + void PostBox::FetchMessage(T& message) + { + if(IsFull()) + { + message = messages.Front(); + messages.Pop(); + } + } + + template + bool PostBox::IsFull() + { + return !messages.IsEmpty(); + } + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Protocols.h b/Code/Network/NetworkDependencies/Protocols.h new file mode 100644 index 00000000..8defcfb3 --- /dev/null +++ b/Code/Network/NetworkDependencies/Protocols.h @@ -0,0 +1,85 @@ +#ifndef NETWORK_DEPENDENCIES_PROTOCOLS_H +#define NETWORK_DEPENDENCIES_PROTOCOLS_H + +////////////////////////////////////// +// Created by Sam Svensson 2013 +// Holder structs for our protocols +// with the use of union. +// each packagetyp +// is linked to a protocol +////////////////////////////////////// + +#include + +namespace Oyster +{ + namespace Network + { + namespace Protocols + { + enum PackageType + { + PackageType_header, + PackageType_test, + PackageType_input, + PackageType_update_position + }; + + struct ProtocolHeader + { + int size; + int packageType; + int clientID; + + ProtocolHeader() { this->packageType = PackageType_header; } + virtual ~ProtocolHeader() { } + }; + + struct ProtocolTest : public ProtocolHeader + { + std::string textMessage; + unsigned int numOfFloats; + float *f; + + ProtocolTest() { this->packageType = PackageType_test; } + virtual ~ProtocolTest() { delete[] f; } + }; + + + //Holding every protocol in an union. + //Used because we now don't have to type case our protocol when we recieve them. + class ProtocolSet + { + public: + PackageType type; + union + { + ProtocolHeader* pHeader; + ProtocolTest *pTest; + + }Protocol; + + void Release() + { + switch(type) + { + case PackageType_header: + if(Protocol.pHeader) + { + delete Protocol.pHeader; + } + break; + case PackageType_test: + if(Protocol.pTest) + { + delete Protocol.pTest; + } + break; + } + } + }; + } + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Translator.cpp b/Code/Network/NetworkDependencies/Translator.cpp new file mode 100644 index 00000000..4bb739ca --- /dev/null +++ b/Code/Network/NetworkDependencies/Translator.cpp @@ -0,0 +1,64 @@ +#include "Translator.h" + +using namespace Oyster::Network; +using namespace ::Protocols; +using namespace ::Messages; + +void Translator::Pack( ProtocolHeader &header, OysterByte& bytes ) +{ + MessageHeader *message = NULL; + + switch(header.packageType) + { + case PackageType_header: + message = new MessageHeader(); + break; + + case PackageType_test: + message = new MessageTest(); + break; + } + + if(message != NULL) + { + message->Pack(header, bytes); + + delete message; + message = NULL; + } +} + +void Translator::Unpack(ProtocolSet* set, OysterByte& bytes ) +{ + ProtocolHeader *header = new ProtocolHeader(); + MessageHeader *message = new MessageHeader(); + + message->Unpack(bytes, *header); + delete message; + message = NULL; + + //Switch to the correct package. + set->type = (PackageType)header->packageType; + switch(set->type) + { + case PackageType_header: + message = new MessageHeader(); + set->Protocol.pHeader = new ProtocolHeader; + message->Unpack(bytes, *set->Protocol.pHeader); + break; + + case PackageType_test: + message = new MessageTest(); + set->Protocol.pTest = new ProtocolTest; + message->Unpack(bytes, *set->Protocol.pTest); + break; + } + + if(message) + { + delete message; + } + delete header; + + //return set; +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Translator.h b/Code/Network/NetworkDependencies/Translator.h new file mode 100644 index 00000000..56459f72 --- /dev/null +++ b/Code/Network/NetworkDependencies/Translator.h @@ -0,0 +1,32 @@ +#ifndef NETWORK_DEPENDENCIES_TRANSLATOR_H +#define NETWORK_DEPENDENCIES_TRANSLATOR_H + +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + +#include "Messages/MessagesInclude.h" +#include "Protocols.h" +#include "ITranslate.h" +#include "OysterByte.h" + +namespace Oyster +{ + namespace Network + { + class Translator : public ITranslate + { + public: + Translator () { }; + ~Translator() { }; + + void Pack (Protocols::ProtocolHeader &header, OysterByte& bytes ); + void Unpack (Protocols::ProtocolSet* set, OysterByte& bytes ); + + private: + + }; + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/UpdateStructs.cpp b/Code/Network/NetworkDependencies/UpdateStructs.cpp deleted file mode 100644 index 05209a9c..00000000 --- a/Code/Network/NetworkDependencies/UpdateStructs.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "NetworkUpdateStructs.h" \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/WinsockFunctions.cpp b/Code/Network/NetworkDependencies/WinsockFunctions.cpp new file mode 100644 index 00000000..ea3c3b00 --- /dev/null +++ b/Code/Network/NetworkDependencies/WinsockFunctions.cpp @@ -0,0 +1,39 @@ +#include "WinsockFunctions.h" +#include + +bool InitWinSock() +{ + WSADATA wsaData; + return WSAStartup(MAKEWORD(2, 2), &wsaData) == NO_ERROR; +} + +void ShutdownWinSock() +{ + WSACleanup(); +} + +std::wstring GetErrorMessage(int errorCode) +{ + LPWSTR lpMessage; + std::wstring retVal(L"Succesful"); + + DWORD bufLen = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS , + NULL, + errorCode , + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) , + (LPWSTR)&lpMessage, + 0 , + NULL ); + + if(bufLen) + { + retVal = lpMessage; + + LocalFree(lpMessage); + + return retVal; + } + + //Added this if bufLen is 0 + return retVal; +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/WinsockFunctions.h b/Code/Network/NetworkDependencies/WinsockFunctions.h new file mode 100644 index 00000000..a4edf38d --- /dev/null +++ b/Code/Network/NetworkDependencies/WinsockFunctions.h @@ -0,0 +1,15 @@ +#ifndef NETWORK_DEPENDENCIES_WINSOCK_FUNCTIONS_H +#define NETWORK_DEPENDENCIES_WINSOCK_FUNCTIONS_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include + +void ShutdownWinSock(); +bool InitWinSock(); + +std::wstring GetErrorMessage(int errorCode); + +#endif \ No newline at end of file diff --git a/Bin/DLL/PLACEHOLDER b/Code/Network/NetworkDependencies/main.cpp similarity index 100% rename from Bin/DLL/PLACEHOLDER rename to Code/Network/NetworkDependencies/main.cpp diff --git a/Code/Network/OysterNetworkClient/Client.cpp b/Code/Network/OysterNetworkClient/Client.cpp new file mode 100644 index 00000000..daffe9b6 --- /dev/null +++ b/Code/Network/OysterNetworkClient/Client.cpp @@ -0,0 +1,41 @@ +#include "Client.h" + +using namespace Oyster::Network::Client; + +Client::Client() +{ + connection = new Connection(); +} + +Client::~Client() +{ + delete this->connection; + connection = 0; +} + +int Client::Connect(unsigned int port, char filename[]) +{ + int errorCode; + + if((errorCode = connection->InitiateClient()) != 0) + { + return errorCode; + } + + if((errorCode = connection->Connect(port, filename)) != 0) + { + return errorCode; + } + + return 0; +} + +void Client::Send(Oyster::Network::OysterByte& bytes) +{ + connection->Send(bytes); +} + +void Client::Recv(Oyster::Network::OysterByte& bytes) +{ + connection->Recieve(bytes); +} \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/Client.h b/Code/Network/OysterNetworkClient/Client.h new file mode 100644 index 00000000..6e69e657 --- /dev/null +++ b/Code/Network/OysterNetworkClient/Client.h @@ -0,0 +1,35 @@ +#ifndef NETWORK_CLIENT_CLIENT_H +#define NETWORK_CLIENT_CLIENT_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include "../NetworkDependencies/Connection.h" +#include "../NetworkDependencies/OysterByte.h" + +namespace Oyster +{ + namespace Network + { + namespace Client + { + class Client + { + public: + Client(); + ~Client(); + + int Connect(unsigned int port, char filename[]); + + void Send(OysterByte& bytes); + void Recv(OysterByte& bytes); + + private: + ::Oyster::Network::Connection* connection; + }; + } + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/ClientDataHandler.cpp b/Code/Network/OysterNetworkClient/ClientDataHandler.cpp deleted file mode 100644 index 52d0f2ff..00000000 --- a/Code/Network/OysterNetworkClient/ClientDataHandler.cpp +++ /dev/null @@ -1,112 +0,0 @@ -#include "SocketClient.h" - -#pragma once -#ifndef SOCKET_DATA_CPP -#define SOCKET_DATA_CPP - -/*std::vector splitString(char* p_inStr, char p_delim) -{ -std::stringstream ss(p_inStr); -std::vector elems; -std::string item; -while(std::getline(ss, item, p_delim)) -{ -elems.push_back(item); -} -return elems; -}*/ - -void SocketClient::parseReceivedData(/*char* data, int size*/) -{ - switch (recvBuffer[0]) // TODO: runtime error occured here when shutting down client. recvBuffer invalid pointer. ~Dan 2013-05-14 - { - case 1://It's data - parseData(); - break; - case 2://For the moment, this is only for init data - parseGameInitData(); - break; - case 3://It's a chat message - parseMessage(); - break; - case 4://It's a server message - parseServermessage(); - break; - case 5://Player has been connected to a game lobby - parseLobbyInitData(); - break; - case 6://It's an event - parseReceivedEvent(); - break; - case 7: - parseReceivedEffect(); - break; - case 8: - parseRenderData(); - break; - default: - int a=0; - - } -} -void SocketClient::parseRenderData() -{ - receiveRenderData(recvBuffer+1, recvBufLen-1); -} -void SocketClient::parseReceivedEffect() -{ - receiveEffectData(recvBuffer+1, recvBufLen-1); -} -void SocketClient::parseReceivedEvent() -{ - receiveEvent(recvBuffer+1); -} -void SocketClient::parseGameInitData() -{ - receiveGameInitData(recvBuffer+1); - connectStatus=true; -} - -void SocketClient::parseLobbyInitData() -{ - receiveLobbyInitData(recvBuffer+1, recvBufLen-1); - connectStatus=true; -} - -void SocketClient::parseServermessage() -{ - recvBuffer[recvBufLen]='\0'; - if(!strcmp(recvBuffer+1, "connected")) - { - connectStatus=true; - connStatus=ONLINE_MAINMENU; - receiveConnStatus(ONLINE_MAINMENU); - } - else if(!strcmp(recvBuffer+1, "qst")) - { - connStatus=ONLINE_QUEUEING; - receiveConnStatus(ONLINE_QUEUEING); - } - else if(!strcmp(recvBuffer+1, "qed")) - { - connStatus=ONLINE_MAINMENU; - receiveConnStatus(ONLINE_MAINMENU); - } - //Server message of some sort -} - -void SocketClient::parseData() -{ - //memcpy(&tmpPlayer,buffer+1,playerDataSize); - //playerContPtr->setPlayerStruct(tmpPlayer); - receivePlayerUpdate(recvBuffer+1, recvBufLen-1); -} - -void SocketClient::parseMessage() -{ - //std::string message; - //message="[Chat] "+users[pid].getUsername()+": "+(buffer+1); - printf("%s\n",recvBuffer+1); -} - -#endif diff --git a/Code/Network/OysterNetworkClient/ClientInitFunctions.cpp b/Code/Network/OysterNetworkClient/ClientInitFunctions.cpp deleted file mode 100644 index e2c4b920..00000000 --- a/Code/Network/OysterNetworkClient/ClientInitFunctions.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include "SocketClient.h" - -#pragma once -#ifndef SOCKET_INIT_CPP -#define SOCKET_INIT_CPP - -bool SocketClient::startReceiveThread() -{ - threadhandle[0]=CreateThread( - NULL, - 0, - (LPTHREAD_START_ROUTINE)&receiveDataThreadV, - (LPVOID) this, - 0, - NULL); - return true; -} - -bool SocketClient::startSendDataThread() -{ - threadhandle[1]=CreateThread( - NULL, - 0, - (LPTHREAD_START_ROUTINE)&receiveDataThreadV, - (LPVOID) this, - 0, - NULL); - return true; -} -bool SocketClient::init(int listenPort) -{ - return initUDPSocket(listenPort); -} -bool SocketClient::connectToIP(const char* ip, int listenPort, char* initData, int initDataSize) -{ - init(listenPort); - //--------------------------------------------- - // Set up the port and IP of the server - //Port starts up as a different one from when connected, it changes once the server has exchanged some info with the client - - UDPsendAddr.sin_family = AF_INET; - UDPsendAddr.sin_port = htons(UDPSendPort); - UDPsendAddr.sin_addr.s_addr = inet_addr(ip); - - TCPsendAddr.sin_family = AF_INET; - TCPsendAddr.sin_port = htons(TCPSendPort); - TCPsendAddr.sin_addr.s_addr = inet_addr(ip); - /*iResult=connect(connTCP, (SOCKADDR *) &TCPsendAddr, addrSize); - if (iResult == SOCKET_ERROR) { - int test=WSAGetLastError(); - wprintf(L"connect failed with error: %d\n", WSAGetLastError()); - //closesocket(connTCP); - //WSACleanup(); - return false; - }/* - iResult=send(connTCP, initData, initDataSize, 0); - if (iResult == SOCKET_ERROR) { - int test=WSAGetLastError(); - wprintf(L"connect failed with error: %d\n", WSAGetLastError()); - //closesocket(connTCP); - //WSACleanup(); - return false; - }*/ - - iResult = sendto(connUDP, - initData, initDataSize, 0, (SOCKADDR *) & UDPsendAddr, addrSize); - if (iResult == SOCKET_ERROR) { - wprintf(L"Client UDP sendto failed with error: %d\n", WSAGetLastError()); - //closesocket(connUDP); - //WSACleanup(); - return false; - } - //connectStatus=true; - connectStatus=false; - return true; -} - - -#endif diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index 5c297686..b8f1057f 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -1,79 +1,121 @@ -#include "SocketClient.h" -const int maxThreadCount=2; -bool validateIpAddress(const std::string ipAddress) -{ - struct sockaddr_in sa; - int result = inet_pton(AF_INET, ipAddress.c_str(), &(sa.sin_addr)); - return result != 0; -} -/*int main(int argc, char *argv[]) -{ - std::string tst; - bool test=true; - //Multithreading variables - //int nThreads = 0; - //DWORD dwThreadId[maxThreadCount]; - //HANDLE threadhandle; +#include +#include +#include +#include "../NetworkDependencies/WinsockFunctions.h" +#include "..\NetworkDependencies\Translator.h" +#include "..\NetworkDependencies\Protocols.h" +#include "../NetworkDependencies/OysterByte.h" +#include "../../Misc/ThreadSafeQueue.h" +#include "Client.h" - GameClass game; - SocketClient client; - //Sets up the link to the GameClass class. - client.setPlayerContPtr(&game); - //This is the loop which makes the user enter the server address. - while (!client.isReady()); - do - { - if (!test) - { - printf("Could not connect to server. Try another IP.\n"); - } - else - { - printf("Enter the server ip. \n"); - } - getline(std::cin, tst); - if (tst.length()==0) - { - tst="127.0.0.1"; - } - if (validateIpAddress(tst)) - { - //Tmp init connection message: set username - char* tmp=new char[30]; - printf("What is your desired username?\n"); - std::cin.getline(tmp,30); - if (strlen(tmp)==0) - { - tmp="Anonymous"; - } - printf("Username set to %s\n", tmp); +#pragma comment(lib, "ws2_32.lib") - test=client.connectToIP(tst.c_str(), tmp, strlen(tmp)); - } - else - { - printf("Invalid IPaddress. Please enter a new IPaddress.\n"); - test=false; - } - } while (!test); - while (!client.isConnected()); - Sleep(1000); - //Starts the receive loop - //threadhandle=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&client.receiveDataThreadV,(LPVOID) &client,0,&dwThreadId[0]); - client.startReceiveThread(); - //GetExitCodeThread(threadhandle, eCode); - //This is just a loop to receive user input which creates a natural delay for sendUserData. - printf("Write what you want to send\n"); - tst="tmp init message"; - while (tst.length()>0) +using namespace std; +using namespace Oyster::Network::Protocols; +using namespace Oyster::Network::Client; + +void chat(Client &client); + +int main() +{ + int errorCode; + + char msgRecv[255] = "\0"; + + InitWinSock(); + + cout << "Client" << endl; + + //Create Client + Client client; + + //Connect to server + errorCode = client.Connect(9876, "localhost"); + + if(errorCode != 0) { - client.sendMessage(tst); - client.sendUserData(); - getline(std::cin, tst); + wstring errorTest = GetErrorMessage(errorCode); + wcout << "errorMessage: " << errorTest << endl; } - //Kills off the thread and connection - //DWORD eCode=0; - //TerminateThread(threadhandle, eCode); - client.closeConnection(); + + chat(client); + + ShutdownWinSock(); + + system("pause"); return 0; -}*/ \ No newline at end of file +} + +void chat(Client &client) +{ + Oyster::Network::Translator *t = new Oyster::Network::Translator(); + + Oyster::Network::OysterByte msgRecv; + string msgSend = ""; + + ProtocolSet* set = new ProtocolSet; + ProtocolTest test; + test.numOfFloats = 5; + test.f = new float[test.numOfFloats]; + float temp = 12345.5654f; + for(int i = 0; i < 5; i++) + { + test.f[i] = temp; + temp++; + } + + bool chatDone = false; + + while(!chatDone) + { + client.Recv(msgRecv); + + t->Unpack(set, msgRecv); + + switch(set->type) + { + case PackageType_header: + break; + case PackageType_test: + cout <<"Client 2: " << set->Protocol.pTest->textMessage <Protocol.pTest->numOfFloats; i++) + { + cout << set->Protocol.pTest->f[i] << ' ' ; + } + cout << endl; + break; + } + + set->Release(); + msgRecv.Clear(1000); + + /*std::getline(std::cin, msgSend); + + + + if( msgSend != "exit") + { + if(msgSend.length() < 1) + { + msgSend = "ERROR!"; + } + + test.textMessage = msgSend; + + t->Pack(test, msgRecv); + + client.Send(msgRecv); + } + + else + { + chatDone = true; + } + + cin.clear();*/ + + } + + delete t; + delete set; +} \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/ClientTCPSpecific.cpp b/Code/Network/OysterNetworkClient/ClientTCPSpecific.cpp deleted file mode 100644 index 1e8b7216..00000000 --- a/Code/Network/OysterNetworkClient/ClientTCPSpecific.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include "SocketClient.h" - -bool SocketClient::initTCPSocket(int listenPort) -{ - TCPrecvAddr.sin_family = AF_INET; - TCPrecvAddr.sin_addr.s_addr = htonl(INADDR_ANY); - TCPrecvAddr.sin_port = htons(/*TCPRecvPort*/listenPort); - - connTCP = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (connTCP == INVALID_SOCKET) - { - wprintf(L"socket function failed with error: %ld\n", WSAGetLastError()); - WSACleanup(); - return false; - } - - iResult = bind(connTCP, (SOCKADDR *) & TCPrecvAddr, addrSize); - if (iResult == SOCKET_ERROR) - { - int tst=WSAGetLastError(); - wprintf(L"bind function failed with error %d\n", WSAGetLastError()); - iResult = closesocket(connTCP); - if (iResult == SOCKET_ERROR) - wprintf(L"closesocket function failed with error %d\n", WSAGetLastError()); - //WSACleanup(); - return false; - } - return true; -} -bool SocketClient::sendDataTCP(const char* data, int size) -{ - iResult = sendto(connTCP, - data, size, 0, (SOCKADDR *) & TCPsendAddr, addrSize); - if (iResult == SOCKET_ERROR) { - wprintf(L"TCP sendto failed with error: %d\n", WSAGetLastError()); - return false; - } - return true; -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/ClientUDPSpecific.cpp b/Code/Network/OysterNetworkClient/ClientUDPSpecific.cpp deleted file mode 100644 index 9cab63ae..00000000 --- a/Code/Network/OysterNetworkClient/ClientUDPSpecific.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include "SocketClient.h" -bool SocketClient::initUDPSocket(int listenPort) -{ - UDPrecvAddr.sin_family = AF_INET; - UDPrecvAddr.sin_addr.s_addr = htonl(INADDR_ANY); - UDPrecvAddr.sin_port = htons(listenPort); - //--------------------------------------------- - // Create a socket for sending data - connUDP = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (connUDP == INVALID_SOCKET) - { - wprintf(L"socket failed with error: %ld\n", WSAGetLastError()); - WSACleanup(); - return false; - } - iResult = bind(connUDP, (SOCKADDR *) & UDPrecvAddr, addrSize); - if (iResult == SOCKET_ERROR) - { - wprintf(L"bind function failed with error %d\n", WSAGetLastError()); - iResult = closesocket(connUDP); - if (iResult == SOCKET_ERROR) - wprintf(L"closesocket function failed with error %d\n", WSAGetLastError()); - WSACleanup(); - return false; - } - return true; -} -bool SocketClient::sendDataUDP(const char* data, int size) -{ - iResult = sendto(connUDP, - data, size, 0, (SOCKADDR *) & UDPsendAddr, addrSize); - if (iResult == SOCKET_ERROR) { - wprintf(L"sendto failed with error: %d\n", WSAGetLastError()); - //closesocket(connUDP); - //WSACleanup(); - return false; - } - return true; -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj index e51f38e2..f4e13099 100644 --- a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj +++ b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj @@ -24,26 +24,26 @@ - StaticLibrary + Application true v110 MultiByte - StaticLibrary + Application true v110 MultiByte - StaticLibrary + Application false v110 true MultiByte - StaticLibrary + Application false v110 true @@ -69,28 +69,36 @@ $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -101,7 +109,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -114,7 +122,7 @@ true true true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -129,7 +137,7 @@ true true true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -137,28 +145,21 @@ true - - - - - - - - - - - {2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee} - - {f10cbc03-9809-4cba-95d8-327c287b18ee} - {c5aa09d0-6594-4cd3-bd92-1d380c7b3b50} + + + + + + + diff --git a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters index 4327b3ae..2e5e9ef6 100644 --- a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters +++ b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters @@ -15,27 +15,15 @@ - - Source Files - - - Source Files - Source Files - - Source Files - - - Source Files - - + Source Files - + Header Files diff --git a/Code/Network/OysterNetworkClient/SocketClient.cpp b/Code/Network/OysterNetworkClient/SocketClient.cpp deleted file mode 100644 index cde039cf..00000000 --- a/Code/Network/OysterNetworkClient/SocketClient.cpp +++ /dev/null @@ -1,133 +0,0 @@ -#include "SocketClient.h" -#pragma once -#ifndef SOCKET_CLIENT_CPP -#define SOCKET_CLIENT_CPP - -SocketClient::SocketClient() -{ - playerDataSize=Network::CLIENT_PLAYER_DATA_SIZE; - sendDelayMS=10; - connUDP = INVALID_SOCKET; - connTCP = INVALID_SOCKET; - //sendBuffer=new char[BUFFER_MAX_SIZE]; - //sendBufLen=BUFFER_MAX_SIZE; - //ZeroMemory(sendBuffer,sendBufLen); - recvBuffer=new char[BUFFER_MAX_SIZE]; - recvBufLen=BUFFER_MAX_SIZE; - ZeroMemory(recvBuffer,recvBufLen); - - dataBuf=new char[playerDataSize+1]; - dataBuf[0]=1; - //ZeroMemory(b,sizeof(buffer)); - //---------------------- - // Initialize Winsock - iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); - if (iResult != NO_ERROR) { - printf("WSAStartup failed with error: %d\n", iResult); - } - - - - addrSize=sizeof(sockaddr_in); - connectStatus=false; -} - - - -bool SocketClient::sendUserData() -{ - //memcpy(dataBuf+1,&playerContPtr->getPlayerData(),playerDataSize); - //return sendData(dataBuf, playerDataSize+1); - printf("NOT YET IMPLEMENTED"); - return false; -} - -bool SocketClient::sendUserData(char* data, int size) -{ - memcpy(dataBuf+1,data,size); - return sendDataUDP(dataBuf, size+1); -} - -bool SocketClient::sendMessage(std::string msg) -{ - if (msg[0]=='/') - { - //Server command - msg[0]=2; - - } - else - { - //Chat message - msg='1'+msg; - msg[0]=3; - } - return sendDataUDP(msg.c_str(), (int)msg.size()); -} - -bool SocketClient::closeConnection() -{ - connectStatus=false; - Sleep(5); - //Give the threads 5 ms to quit themselves before terminating them - DWORD eCode=0; - TerminateThread(threadhandle[0], eCode); - TerminateThread(threadhandle[1], eCode); - //--------------------------------------------- - // When the application is finished sending, close the socket. - setupStatus=false; - printf("Finished sending. Closing socket.\n"); - iResult = closesocket(connUDP); - if (iResult == SOCKET_ERROR) - { - wprintf(L"closesocket failed with error: %d\n", WSAGetLastError()); - WSACleanup(); - return false; - } - //--------------------------------------------- - // Clean up and quit. - printf("Exiting.\n"); - WSACleanup(); - return true; -} - -void SocketClient::receiveDataThreadV(SocketClient* ptr) -{ - while(true) - { - ptr->recvBufLen=recvfrom(ptr->connUDP, ptr->recvBuffer, BUFFER_MAX_SIZE, 0, (SOCKADDR *) & ptr->UDPsendAddr, &ptr->addrSize); - if (ptr->recvBufLen == SOCKET_ERROR) - { - wprintf(L"recv failed with error %d\n", WSAGetLastError()); - } - //ptr->buffer[ptr->iResult]='\0'; - else - ptr->parseReceivedData(); - } -} - - -void SocketClient::receiveDataWaitOnResponse() -{ - recvBufLen=recvfrom(connUDP, recvBuffer, BUFFER_MAX_SIZE, 0, (SOCKADDR *) & UDPsendAddr, &addrSize); - if (recvBufLen == SOCKET_ERROR) - { - wprintf(L"recv failed with error %d\n", WSAGetLastError()); - } - //buffer[iResult]='\0'; - else - parseReceivedData(); -} - -void SocketClient::sendDataThreadV(SocketClient* ptr) -{ - printf("NOT YET IMPLEMENTED"); - /*while(ptr->connectStatus) - { - memcpy(ptr->dataBuf+1,&ptr->playerContPtr->getPlayerData(),playerDataSize); - ptr->sendData(ptr->dataBuf, playerDataSize+1); - Sleep(ptr->sendDelayMS); - }*/ -} - -#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/SocketClient.h b/Code/Network/OysterNetworkClient/SocketClient.h deleted file mode 100644 index 46c57d8d..00000000 --- a/Code/Network/OysterNetworkClient/SocketClient.h +++ /dev/null @@ -1,147 +0,0 @@ -#pragma once -//Start by defining unicode -//#ifndef UNICODE -//#define UNICODE -//#endif -//defining WIN32_LEAN_AND_MEAN this early is REQUIRED if you want to avoid a certain winsock error. -//#define WIN32_LEAN_AND_MEAN -//#define NOMINMAX -//#include -//#include "GameClassExample.h" -//These includes are required for winsock -#include "Network.h" -//#include -//#include -//#include -//#include -//#include "OysterMath.h" -//These are optional includes for various useful features -#include -#include -#include -#include - -//ws2_32.lib is a lib file the linker requires for winsock compilation -#pragma comment(lib, "Ws2_32.lib") - -//constants used by the socket client to avoid hard coding and/or mass variable declaration -const short TCPSendPort = 11110; -const short TCPRecvPort = 11111; -const short UDPSendPort = 11000; -const short UDPRecvPort = 11001; -const int BUFFER_MAX_SIZE = 4096; - -enum ConnectionStatus -{ - OFFLINE, - ONLINE_MAINMENU, - ONLINE_QUEUEING, - ONLINE_INLOBBY, - ONLINE_INGAME -}; -class SocketClient -{ -private: - HANDLE threadhandle[2]; - int sendDelayMS; - - //2 bools used to verify the activation of the client so threads can't start too early - ConnectionStatus connStatus; - bool setupStatus; - bool connectStatus; - - //iResult is used to check error codes - int iResult; - //wsaData records error messages and errors which winsock might encounter - WSADATA wsaData; - - //Main socket - SOCKET connUDP; - SOCKET connTCP; - - //Addresses used for data transfer - sockaddr_in TCPrecvAddr; - sockaddr_in TCPsendAddr; - //UDPrecvAddr marks the port and IP adress the server is supposed to return data to. - sockaddr_in UDPrecvAddr; - //UDPsendAddr marks which IP and port the client is supposed to send data to. - sockaddr_in UDPsendAddr; - //size of a sockaddr_in. This might as well be a constant, but i'm keeping it in the class for performance reasons. - int addrSize; - - //buffer which is filled when data receive happens. - char* recvBuffer; - //this variable tracks the buffer length. - int recvBufLen; - - //dataBuf is a buffer solely for sending your own user data. It never changes size in order to increase performance. - //char* sendBuffer; - //int sendBufLen; - //PlayerStruct tmpPlayer; - char* dataBuf; - int playerDataSize; -public: - void setPlayerDataSize(int pds){playerDataSize=pds;} - //Constructor - SocketClient(); - - //Initiation for sockets. - bool init(int listenPort); - bool initTCPSocket(int listenPort); - bool initUDPSocket(int listenPort); - //Connects to a server of a user-defined IP. Can only be called after an initXSocket has gone through. - //The 2 remaining variables are init data and size of said data. Currently username. - bool connectToIP(const char* ip, int listenPort, char* initData, int initDataSize); - //sends an undefined data type of (variable#2) size to the server. - bool sendDataUDP(const char*, int); - bool sendDataTCP(const char*, int); - //sends a text string to the server. - bool sendMessage(std::string str); - bool sendServerMessage(std::string str); - //sends user data to the server - bool sendUserData(); - bool sendUserData(char* data, int size); - - //Closes connection, kills off the socket. - bool closeConnection(); - - //Simple ifBoolIsTrue checks - bool isReady() const {return setupStatus;} - bool isConnected() const {return connectStatus;} - void receiveDataWaitOnResponse(); - //Sends data periodically - static void sendDataThreadV(SocketClient* ptr); - //Receive loop. This is event-based and is on its own thread. - static void receiveDataThreadV(SocketClient* ptr); - //Once data is received, it calls on the parseReceivedData function. - void parseReceivedData(); - //void parseReceivedKeyframe(); - //If an event is called from the server, this function will be called. - void parseReceivedEvent(); - void parseReceivedEffect(); - //It is then sent to one of the following functions based on the first byte of the buffer. - - //Servermessage - void parseServermessage(); - //single user data - void parseData(); - //string (character data) - void parseMessage(); - //init data which sets the start position etc of all characters. - void parseLobbyInitData(); - void parseGameInitData(); - void parseRenderData(); - - bool startReceiveThread(); - bool startSendDataThread(); - void setSendDelay(int ms){sendDelayMS=ms;} - - //virtual functions - virtual void receiveGameInitData(char*)=0; - virtual void receiveLobbyInitData(char*, int)=0; - virtual void receivePlayerUpdate(char*, int)=0; - virtual void receiveRenderData(char*, int)=0; - virtual void receiveEffectData(char*, int)=0; - virtual void receiveConnStatus(ConnectionStatus)=0; - virtual void receiveEvent(char*)=0; -}; \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Client.cpp b/Code/Network/OysterNetworkServer/Client.cpp new file mode 100644 index 00000000..5cc15eec --- /dev/null +++ b/Code/Network/OysterNetworkServer/Client.cpp @@ -0,0 +1,24 @@ +#include "Client.h" + +using namespace Oyster::Network; +using namespace Oyster::Network::Server; + +Client::Client(unsigned int socket) +{ + connection = new Connection(socket); +} + +Client::~Client() +{ + delete connection; +} + +void Client::Send(OysterByte& bytes) +{ + connection->Send(bytes); +} + +void Client::Recv(OysterByte& bytes) +{ + connection->Recieve(bytes); +} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Client.h b/Code/Network/OysterNetworkServer/Client.h new file mode 100644 index 00000000..2c5ba35f --- /dev/null +++ b/Code/Network/OysterNetworkServer/Client.h @@ -0,0 +1,34 @@ +#ifndef NETWORK_SERVER_CLIENT_H +#define NETWORK_SERVER_CLIENT_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include "../NetworkDependencies/Connection.h" +#include "../NetworkDependencies/OysterByte.h" + +namespace Oyster +{ + namespace Network + { + namespace Server + { + class Client + { + public: + Client(unsigned int socket); + ~Client(); + + void Send(OysterByte& bytes); + void Recv(OysterByte& bytes); + + private: + ::Oyster::Network::Connection* connection; + + }; + } + } +}; + +#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Game.cpp b/Code/Network/OysterNetworkServer/Game.cpp deleted file mode 100644 index 7948603d..00000000 --- a/Code/Network/OysterNetworkServer/Game.cpp +++ /dev/null @@ -1,113 +0,0 @@ -#include "Game.h" -Game::Game() -{ - playerCount=0; - started=false; - for (int i=0; i usr, int nrOfPlayers) -{ - /*for (int i=0; isetGame(2); - //init.players[i]=players[i]; - } - return init; -} -void Game::addUser(int uid) -{ - userID[playerCount++]=uid; -} -bool Game::startGame() -{ - started=true; - return started; -} -void Game::update(float dt) -{ - -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Game.h b/Code/Network/OysterNetworkServer/Game.h deleted file mode 100644 index d162a322..00000000 --- a/Code/Network/OysterNetworkServer/Game.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once -#ifndef GAME_H -#define GAME_H -#include "User.h" -#include "ServerInclude.h" -const int MUTEX_COUNT =2; -//Mutex #0=playerPos setGet -//Mutex #1= - -//#include "Session.h" - -class Game -{ -private: - bool started; - //ClientToServerUpdateData players[PLAYER_MAX_COUNT]; - User* users[PLAYER_MAX_COUNT]; - int userID[PLAYER_MAX_COUNT]; - bool ready[PLAYER_MAX_COUNT]; - int playerCount; - - //Tracks which ship each user has - int shipID[PLAYER_MAX_COUNT]; - HANDLE mutex[MUTEX_COUNT]; - //::Game::Session *session; - int sessionID; -public: - //Will reset all data - //playerIDs is an array of int which points toward each users connection. - void setReady(int pid, bool rdy){ready[pid]=rdy;} - bool allReady(){for (int i=0; i players, int nrOfPlayers); - GameInitData getInitData(); - bool startGame(); - bool isStarted(){return started;} - Game(); - //Float4x4 getPlayerPos(int id); - //void setPlayerPos(int id, Float4x4 pos); - //bool checkMoveValidity(ClientToServerUpdateData plr); - //ClientToServerUpdateData getPlayerData(int id); - //void setPlayerData(int id, ClientToServerUpdateData ps); - - int getPlayerCount() {return playerCount;} - int getUserID(int i) {return userID[i];} - - void initLUA(char* file); - void update(float dt); - void addUser(int uid); - void removeUser(int uid){playerCount--;} -}; -#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Lobby.cpp b/Code/Network/OysterNetworkServer/Lobby.cpp deleted file mode 100644 index ade4b120..00000000 --- a/Code/Network/OysterNetworkServer/Lobby.cpp +++ /dev/null @@ -1,73 +0,0 @@ -#include "Lobby.h" - -Lobby::Lobby() -{ - timerStarted=false; - nrUsers=0; - timerMutex = CreateMutex( - NULL, // default security attributes - FALSE, // initially not owned - NULL); // unnamed mutex - - if (timerMutex == NULL) - { - printf("CreateMutex error: %d\n", GetLastError()); - } - for(int i=0; i0) - return timeLeft; - else - return 0; - } - ReleaseMutex(timerMutex); -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Lobby.h b/Code/Network/OysterNetworkServer/Lobby.h deleted file mode 100644 index a17e771c..00000000 --- a/Code/Network/OysterNetworkServer/Lobby.h +++ /dev/null @@ -1,27 +0,0 @@ -#include "ServerInclude.h" -#include "User.h" -#ifndef LOBBY_H -#define LOBBY_H -class Lobby -{ -private: - int nrUsers; - int userID[PLAYER_MAX_COUNT]; - ServerTimer countdownTimer; - float countdownLimit; - LobbyUserStruct userData[PLAYER_MAX_COUNT]; - bool timerStarted; - HANDLE timerMutex; -public: - Lobby(); - void addUser(User usr, int i); - int getUserID(int i) const {return userID[i];} - int getNrPlayers() const {return nrUsers;} - void removeUser(); - void updateUserData(LobbyUserStruct); - LobbyInitData getLobbyInitData(); - void startLobbyCountdown(float seconds); - float timeLeft(); - -}; -#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj index 6be7bc04..65136729 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj @@ -24,26 +24,26 @@ - StaticLibrary + Application true v110 MultiByte - StaticLibrary + Application true v110 MultiByte - StaticLibrary + Application false v110 true MultiByte - StaticLibrary + Application false v110 true @@ -69,28 +69,36 @@ $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -101,7 +109,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -114,7 +122,7 @@ true true true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -129,7 +137,7 @@ true true true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -137,37 +145,21 @@ true - - - - - - - - - - - - - - - - - - - - {2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee} - - {f10cbc03-9809-4cba-95d8-327c287b18ee} - {c5aa09d0-6594-4cd3-bd92-1d380c7b3b50} + + + + + + + diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters index 15a52647..3cb5827c 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters @@ -15,54 +15,15 @@ - - Source Files - - - Source Files - - - 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 diff --git a/Code/Network/OysterNetworkServer/ServerDataHandler.cpp b/Code/Network/OysterNetworkServer/ServerDataHandler.cpp deleted file mode 100644 index 55c36a02..00000000 --- a/Code/Network/OysterNetworkServer/ServerDataHandler.cpp +++ /dev/null @@ -1,219 +0,0 @@ -#include "SocketServer.h" - - - -void SocketServer::parseReceivedData(int threadID/*char* data, int size*/) -{ - bool test=false; - for(unsigned int i=0; isrcAddr); - data->buffer[data->dataSize]='\0'; - usr.setUsername(data->buffer); - users.push_back(usr); - sendData(((int)users.size())-1, "\4connected",10); - std::string asd=users[users.size()-1].getUsername(); - printf("Username:%s, IP:%s\n",users[users.size()-1].getUsername().c_str(), inet_ntoa(users[users.size()-1].getAddr().sin_addr)); -} -void SocketServer::removeUser(int id) -{ - games[users[id].getGame()].removeUser(id); - users.erase(users.begin()+id); -} -void SocketServer::parseServercommand(int pid, int threadID) -{ - connData[threadID].buffer[connData[threadID].dataSize]='\0'; - wprintf(L"User %d sent a server command.\n", pid); - printf("The command is the following:%s.\n", connData[threadID].buffer+1); - std::vector list=splitString(connData[threadID].buffer+1, ' '); - bool validcommand=false; - if(list.size()==0) - { - //Ignore case 1, to avoid vector subscript out of range errors - } - //First variable: Command - else if(!list[0].compare(" ")) - { - //Add rest ignore cases here - } - else if(!list[0].compare("help")) - { - validcommand=true; - } - //else if(!list[0].compare("startgame")) - //{ - //validcommand=true; - //Do more than just sending init data here - //sendInitData(); - //} - else if (!list[0].compare("exit")) - { - validcommand=true; - //User #pid needs to be removed here, and data needs to be sorted accordingly. - } - else if (!list[0].compare("qst")) - { - validcommand=true; - if (users[pid].getState()==ONLINE) - { - sendData(pid, "\4qst",4); - users[pid].setState(ONLINE_QUEUEING); - } - } - else if (!list[0].compare("qed")) - { - validcommand=true; - if (users[pid].getState()==ONLINE_QUEUEING) - { - sendData(pid, "\4qed",4); - users[pid].setState(ONLINE); - } - } - else if (!list[0].compare("rdy")) - { - if (users[pid].getState()==ONLINE_INGAME) - { - games[users[pid].getGame()].setReady(pid, true); - } - } - else if (!list[0].compare("dc")) - { - validcommand=true; - printf("User %s (ID:%d) has disconnected.",users[pid].getUsername().c_str(), pid); - users[pid].setState(OFFLINE); - removeUser(pid); - //Tell games that he might be in here taht he's down - //users.erase(users.begin() - } - else if((!list[0].compare("w")||!list[0].compare("whisper")||!list[0].compare("msg")) && list.size()>2) - { - validcommand=true; - for(unsigned int i=0; i1) - { - users[pid].setUsername(list[1]); - //list[1]="\3Your username has been changed to "+list[1]; - //sendData(pid,list[1].c_str(), list[1].length()); - validcommand=true; - } - } - if(!validcommand) - { - int a=0; - //sendData(pid, "\3Invalid server command.", 24); - //Tell user that the server command was invalid - } -} -void SocketServer::parseData(int pid, int gid, int threadID) -{ - memcpy(&connData[threadID].tmpdata,connData[threadID].buffer+1,CLIENT_PLAYER_DATA_SIZE); - //No old packets - if (users[pid].getLastUpdate()accessPlayer(pid),connData[threadID].tmpdata); - } -} -void SocketServer::parseMessage(int pid, int threadID) -{ - std::string message; - message="\3[Chat] "+users[pid].getUsername()+": "+(connData[threadID].buffer+1); - sendData(-1,message.c_str(), (int)message.length()); -} -void SocketServer::sendInitData(int gid) -{ - GameInitData init=games[gid].getInitData(); - //int test=session->getNumPlayers(); // getNumPlayers is removed - for (int i=0; iaccessPlayer(i).getOrientation(); - } - char* gd=new char[sizeof(init)+1]; - gd[0]=2; - for (int i=0; i -#define DEBUG_NEW new(_NORMAL_BLOCK ,__FILE__, __LINE__) -#else -#define DEBUG_NEW new -#endif - -#include -#include -#include -#include -#include "OysterMath.h" -//#include "Session.h" -#include "ServerTimer.h" -using namespace Network; - -const float GAME_UPDATEDELAY=1.0f/120.0f; diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index 6c3d7f56..9dd0a0c1 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -1,47 +1,128 @@ -#include -#include "SocketServer.h" -#include "ServerTimer.h" #include -#include -#include -//#ifdef WINDOWS -#include -#include "ServerInclude.h" -#define GetCurrentDir _getcwd -//#else - //For other OS than windows; can't be found on - //all windows setups so it's commented for now - //#include - //#define GetCurrentDir getcwd - //#endif +#include +#include +#include +#include "../NetworkDependencies/WinsockFunctions.h" +#include "../NetworkDependencies/Listener.h" +#include "../NetworkDependencies/Translator.h" +#include "Client.h" +#include "../NetworkDependencies/OysterByte.h" +#include "../NetworkDependencies/PostBox.h" +#include "../../Misc/WinTimer.h" -char* getCurDir() -{ - char* cCurrentPath; - cCurrentPath=new char[FILENAME_MAX]; - int test=sizeof(cCurrentPath); - if (!GetCurrentDir(cCurrentPath, FILENAME_MAX)) - { - return "ERROR"; - } - cCurrentPath[FILENAME_MAX - 1] = '\0'; - return cCurrentPath; -} -int main(int argc, char *argv[]) -{ - srand((unsigned int)time(0)); - ::Oyster::Game::MoveAble::setDiscreteTimeSlice( GAME_UPDATEDELAY ); +#pragma comment(lib, "ws2_32.lib") - SocketServer server; - server.loadMapList("..\\Content\\Maplist.txt"); - while (!server.isReady()); - server.startThreads(); - GameLogic::Object::init("NOT_IMPLEMENTED"); - server.startGameCreateLoop(50); - while(true) +using namespace std; +using namespace Oyster::Network::Server; +using namespace Oyster::Network; +using namespace ::Protocols; +using namespace Utility; + +int main() +{ + OysterByte recvBuffer; + IPostBox* postBox = new PostBox(); + + cout << "Server" << endl; + Translator t; + int errorCode; + + if(!InitWinSock()) { - server.updateServers(); + cout << "errorMessage: unable to start winsock" << endl; } - server.closeConnection(); + + //Create socket + Listener listener; + listener.Init(9876); + listener.SetPostBox(postBox); + Sleep(1000); + + //Start listening + //Accept a client + ProtocolTest test; + test.clientID = 0; + test.size = 2; + test.textMessage = "hej"; + test.numOfFloats = 0; + test.f = new float[test.numOfFloats]; + float temp = 395.456f; + for(int i = 0; i < (int)test.numOfFloats; i++) + { + test.f[i] = temp; + temp--; + } + + t.Pack(test, recvBuffer); + + WinTimer timer; + + vector clients; + int client = -1; + while(1) + { + client = -1; + postBox->FetchMessage(client); + if(client != -1) + { + cout << "Client connected: " << client << endl; + clients.push_back(new Client(client)); + + clients.at(clients.size()-1)->Send(recvBuffer); + } + + //Send a message every 1 secounds to all clients. + if(timer.getElapsedSeconds() > 1) + { + cout << "Sending to " << clients.size() << " clients." << endl; + timer.reset(); + for(int i = 0; i < (int)clients.size(); i++) + { + clients.at(i)->Send(recvBuffer); + } + } + Sleep(100); + } + listener.Shutdown(); + + /* + ProtocolSet* set = new ProtocolSet; + + client1.Send(recvBuffer); + + while(1) + { + client1.Recv(recvBuffer); + + t.Unpack(set, recvBuffer); + cout << set->Protocol.pTest->clientID << ' ' << set->Protocol.pTest->packageType << ' ' << set->Protocol.pTest->size << endl; + cout << "Client1: " << set->Protocol.pTest->textMessage << endl; + for(int i = 0; i < (int)set->Protocol.pTest->numOfFloats; i++) + { + cout << set->Protocol.pTest->f[i] << ' '; + } + cout << endl; + set->Release(); + client2.Send(recvBuffer); + + client2.Recv(recvBuffer); + + t.Unpack(set, recvBuffer); + cout << set->Protocol.pTest->clientID << ' ' << set->Protocol.pTest->packageType << ' ' << set->Protocol.pTest->size << endl; + cout << "Client2: " << set->Protocol.pTest->textMessage << endl; + for(int i = 0; i < (int)set->Protocol.pTest->numOfFloats; i++) + { + cout << set->Protocol.pTest->f[i] << ' '; + } + cout << endl; + set->Release(); + client1.Send(recvBuffer); + } + + + ShutdownWinSock(); + delete set; + */ + system("pause"); return 0; -} \ No newline at end of file +} diff --git a/Code/Network/OysterNetworkServer/ServerTCPSpecific.cpp b/Code/Network/OysterNetworkServer/ServerTCPSpecific.cpp deleted file mode 100644 index eb6987c9..00000000 --- a/Code/Network/OysterNetworkServer/ServerTCPSpecific.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include "SocketServer.h" -bool SocketServer::initTCPSocket() -{ - //---------------------- - // Create a SOCKET for listening for incoming connection requests. - TCPSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (TCPSocket == INVALID_SOCKET) { - wprintf(L"TCP socket function failed with error: %ld\n", WSAGetLastError()); - WSACleanup(); - return false; - } - - iResult = bind(TCPSocket, (SOCKADDR *) & TCPRecvAddr, addrSize); - if (iResult == SOCKET_ERROR) { - wprintf(L"TCP bind function failed with error %d\n", WSAGetLastError()); - iResult = closesocket(TCPSocket); - if (iResult == SOCKET_ERROR) - wprintf(L"TCP closesocket function failed with error %d\n", WSAGetLastError()); - WSACleanup(); - return false; - } - return true; -} -DWORD SocketServer::activateTCPConnectLoop(ThreadArguments* tra) -{ - while (true) - { - (tra->ptr)->receiveConnection(tra->threadID); - } -} -void SocketServer::receiveConnection(int threadID) -{ - User tmp; - //---------------------- - // Listen for incoming connection requests - // on the created socket - if (listen(TCPSocket, SOMAXCONN) == SOCKET_ERROR) - { - wprintf(L"listen function failed with error: %d\n", WSAGetLastError()); - return; - } - - printf("Starting TCP connection loop.\n"); - int a=0; - while(a==0) - { - a=1; - tmp.connection=accept(TCPSocket, (struct sockaddr*)&TCPRecvAddr, &addrSize); - printf("Accepted a TCP connection from IP %s.\n", inet_ntoa(TCPRecvAddr.sin_addr)); - tcpData[threadID].dataSize=recv( - tmp.connection, - tcpData[threadID].buffer, - tcpData[threadID].bufLen, - 0); - connData[threadID].buffer[connData[threadID].dataSize]='\0'; - tmp.setUsername(tcpData[threadID].buffer); - if (tcpData[threadID].dataSize == SOCKET_ERROR) - { - wprintf(L"TCP recv failed with error %d\n", WSAGetLastError()); - } - printf("TCP Thread #%d received connData from %s\n", threadID, inet_ntoa(tcpData[threadID].srcAddr.sin_addr)); - //connData[threadID].buffer[connData[threadID].dataSize]='\0'; - //AddUser(&tcpData[threadID]); - //parseReceivedData(threadID); - } -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/ServerTimer.cpp b/Code/Network/OysterNetworkServer/ServerTimer.cpp deleted file mode 100644 index 4dc3d286..00000000 --- a/Code/Network/OysterNetworkServer/ServerTimer.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#include "ServerTimer.h" -ServerTimer::ServerTimer() - : - c_SecondsPerCount(0.0), - c_DeltaTime(-1.0), - c_BaseTime(0), - c_PausedTime(0), - c_PrevTime(0), - c_CurrTime(0), - c_Stopped(false) -{ - __int64 countsPerSec; - QueryPerformanceFrequency((LARGE_INTEGER*)&countsPerSec); - c_SecondsPerCount =1.0 / (double)countsPerSec; - - QueryPerformanceCounter((LARGE_INTEGER*)&c_PrevTime); -} - -void ServerTimer::start() -{ - __int64 p_StartTime; - QueryPerformanceCounter((LARGE_INTEGER*)&p_StartTime); - if(c_Stopped) - { - c_PausedTime += (p_StartTime-c_StopTime); - c_PrevTime = p_StartTime; - c_StopTime = 0; - c_Stopped = false; - } -} -__int64 ServerTimer::getTime() -{ - __int64 testInt; - return QueryPerformanceCounter((LARGE_INTEGER*)&testInt); - return testInt; -} - -void ServerTimer::stop() -{ - if(!c_Stopped) - { - __int64 p_CurrTime; - QueryPerformanceCounter((LARGE_INTEGER*)&p_CurrTime); - c_StopTime = p_CurrTime; - c_Stopped = true; - } -} -void ServerTimer::reset() -{ - __int64 p_CurrTime; - QueryPerformanceCounter((LARGE_INTEGER*)&p_CurrTime); - c_BaseTime = p_CurrTime; - c_PrevTime = p_CurrTime; - c_StopTime = 0; - c_Stopped = false; -} -void ServerTimer::tick() -{ - if (c_Stopped) - { - c_DeltaTime= 0.0; - return; - } - __int64 p_CurrTime; - QueryPerformanceCounter((LARGE_INTEGER*)&p_CurrTime); - c_CurrTime=p_CurrTime; - - c_DeltaTime=(c_CurrTime-c_PrevTime)*c_SecondsPerCount; - c_PrevTime=c_CurrTime; - if(c_DeltaTime<0.0) c_DeltaTime=0.0; -} -float ServerTimer::getGameTime() const -{ - if(c_Stopped) - { - return (float)((c_StopTime-c_BaseTime)*c_SecondsPerCount); - } else - { - return (float)(((c_CurrTime-c_PausedTime)-c_BaseTime)*c_SecondsPerCount); - } -} -float ServerTimer::getDeltaTime() const -{ - return (float)c_DeltaTime; -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/ServerTimer.h b/Code/Network/OysterNetworkServer/ServerTimer.h deleted file mode 100644 index 660c1799..00000000 --- a/Code/Network/OysterNetworkServer/ServerTimer.h +++ /dev/null @@ -1,25 +0,0 @@ -#include "ServerInclude.h" -#ifndef _GAME_TIMER_H -#define _GAME_TIMER_H -class ServerTimer -{ -private: - double c_SecondsPerCount; - double c_DeltaTime; - __int64 c_BaseTime; - __int64 c_PausedTime; - __int64 c_StopTime; - __int64 c_PrevTime; - __int64 c_CurrTime; - bool c_Stopped; -public: - ServerTimer(); - __int64 getTime(); - void start(); - void stop(); - void reset(); - void tick(); - float getGameTime() const; - float getDeltaTime() const; -}; -#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/ServerUDPSpecific.cpp b/Code/Network/OysterNetworkServer/ServerUDPSpecific.cpp deleted file mode 100644 index 1ffdf624..00000000 --- a/Code/Network/OysterNetworkServer/ServerUDPSpecific.cpp +++ /dev/null @@ -1,55 +0,0 @@ -#include "SocketServer.h" -bool SocketServer::initUDPSocket() -{ - //--------------------------------------------- - // Create a socket for sending data - UDPSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (UDPSocket == INVALID_SOCKET) { - wprintf(L"UDP socket failed with error: %ld\n", WSAGetLastError()); - WSACleanup(); - return false; - } - //--------------------------------------------- - // Bind socket to IP - iResult = bind(UDPSocket, (SOCKADDR *) & UDPRecvAddr, addrSize); - if (iResult == SOCKET_ERROR) { - wprintf(L"UDP bind failed with error: %d\n", WSAGetLastError()); - closesocket(UDPSocket); - WSACleanup(); - return false; - } - return true; -} -DWORD SocketServer::activateUDPReceiveLoop(ThreadArguments* tra) -{ - (tra->ptr)->serverUDPReceiveLoopActive=true;//weird crash //PAR - (tra->ptr)->receiveDataUDP(tra->threadID); - return 0; -} -void SocketServer::stopUDPReceiveLoops() -{ - serverUDPReceiveLoopActive=false; - WaitForMultipleObjects(NR_CONNECTTHREADS, udpDataHandle, true, INFINITE); - printf("All UDP data recv threads stopped.\n"); -} -void SocketServer::receiveDataUDP(int threadID) -{ - while(serverUDPReceiveLoopActive) - { - connData[threadID].dataSize=recvfrom( - UDPSocket, - connData[threadID].buffer, - connData[threadID].bufLen, - 0, - (SOCKADDR *)&connData[threadID].srcAddr, - &addrSize); - if (connData[threadID].dataSize == SOCKET_ERROR) - { - wprintf(L"recvfrom failed with error %d\n", WSAGetLastError()); - } - //printf("Thread #%d received data from %s\n", threadID, inet_ntoa(connData[threadID].srcAddr.sin_addr)); - //connData[threadID].buffer[connData[threadID].dataSize]='\0'; - else - parseReceivedData(threadID); - } -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Servercore.cpp b/Code/Network/OysterNetworkServer/Servercore.cpp deleted file mode 100644 index 6dd855fd..00000000 --- a/Code/Network/OysterNetworkServer/Servercore.cpp +++ /dev/null @@ -1,420 +0,0 @@ -#include "SocketServer.h" -#include -bool SocketServer::loadMapList(char* maploc) -{ - ::std::string workDir; - ::Utility::String::extractDirPath( workDir, maploc, '\\' ); - - //maploc is the filename of the list which contains all maps - //load all map file names into the server, but don't load the maps themselves. - std::ifstream file; - file.open(maploc); - if (!file.is_open()) - return false; - ::std::string str; - while(!file.eof()) - { - ::std::getline( file, str ); - maps.push_back( workDir + str ); - } - - /* - maps.push_back("map1test.map"); - maps.push_back("map2 test.map"); - */ - return true; -} -bool SocketServer::LoadInitData(char* maploc) -{ - std::vector cont; - char* in=new char[100]; - std::ifstream ifs; - ifs.open(maploc); - if(!ifs.is_open()) - { - return false; - } - while(!ifs.eof()) - { - ifs.getline(in, 100); - cont=splitString(in, '='); - if (cont.size()==2) - { - if(!strcmp("nr_players_per_session", cont[0].c_str())) - { - playersPerSessionCount=atoi(cont[1].c_str()); - } - else if(!strcmp("nr_kills_to_win", cont[0].c_str())) - { - killsRequiredPerSession=atoi(cont[1].c_str()); - } - else if(!strcmp("match_type", cont[0].c_str())) - { - //Isn't used - } - } - - } - ifs.close(); -} -SocketServer::~SocketServer() -{ - serverTCPConnectionLoopActive=false; - serverUDPReceiveLoopActive=false; - serverTCPReceiveLoopActive=false; - for (int i=0; iptr)->serverGameCreationLoop(tra->threadID); - return 0; -} -bool SocketServer::serverGameCreationLoop(int delay) -{ // TODO: Mem access Violoation Crash 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ... delay = -858993460 - //Mem access violation in a thread can also be caused by failure from something else instead of it, - //it still breaks at header even if, for example, server->load or lobby.startLobbyCountdown breaks it - //If you get an error here, make sure that isn't the problem. - int count; - while(serverGameCreationActive) - { - if (nrActiveSessions==0) - { - count=0; - for (unsigned int i=0; i=playersPerSessionCount) - { - games.resize(1); - //lobby.resize(games.size()+1); - session =new GameLogic::Session(); - lobby = Lobby(); - timer.resize(1); - timeTillUpdate.resize(1); - timeTillUpdate[0]=GAME_UPDATEDELAY; - updateCount.resize(1); - updateCount[0]=0; - int curID=(int)games.size()-1; - int mapid=rand()%maps.size(); - session->setNrPlayers(playersPerSessionCount); - session->setKillsRequired(killsRequiredPerSession); - session->load(maps[mapid]); - printf("Map nr %d loaded, name %s.\n",mapid, maps[mapid].c_str()); - count=0; - for (unsigned int i=0; countaccessPlayer(i).spawn(); - count++; - } - } - lobbyActive=true; - sendLobbyInitData(curID); - lobby.startLobbyCountdown(LOBBY_WAIT_TIME); - sendRenderData(curID); - //return true; - } - if(lobbyActive) - { - for (int i=0; i<1; i++) - { - float ttimer=lobby.timeLeft(); - if (ttimer==0) - { - printf("Starting game.\n"); - games[i].initGame(users,playersPerSessionCount); - sendInitData(i); - nrActiveSessions++; - lobbyActive=false; - //serverGameCreationActive=false; - } - } - } - } - Sleep(delay); - } - printf("Maximum server count reached, shutting down the sever creation thread.\n"); - return false; -} -SocketServer::SocketServer() -{ - UDPSocket = INVALID_SOCKET; - nrActiveSessions=0; - serverGameCreationActive=false; - serverTCPConnectionLoopActive=false; - serverTCPReceiveLoopActive=false; - serverUDPReceiveLoopActive=false; - killsRequiredPerSession=10; - playersPerSessionCount=1; - LoadInitData("../ServerData.dat"); - //--------------------------------------------- - // Set up the port and IP of the server - //Port starts up as a different one from when UDPSocketected, it changes once the server has exchanged some info with the client - UDPRecvAddr.sin_family = AF_INET; - UDPRecvAddr.sin_port = htons(UDPRecvPort); - UDPRecvAddr.sin_addr.s_addr = htonl(INADDR_ANY); - - sessionEvents=std::vector(0); - sessionEffects=std::vector(0); - TCPRecvAddr.sin_family = AF_INET; - TCPRecvAddr.sin_port = htons(TCPRecvPort); - TCPRecvAddr.sin_addr.s_addr = htonl(INADDR_ANY); - - addrSize=sizeof(sockaddr_in); - for (int i=0; i=users.size()) - { - //User doesn't exist - printf("UDP sendData(%d) sendto failed because the specified user does not exist\n", uid); - } - else - { - iResult = sendto(UDPSocket, data, size, 0, (SOCKADDR *) & users[uid].getAddr(), addrSize); - if (iResult == SOCKET_ERROR) - { - wprintf(L"UDP sendData(%d) sendto failed with error: %d\n", uid, WSAGetLastError()); - closesocket(UDPSocket); - WSACleanup(); - return false; - } - } - } - return true; -} -bool SocketServer::sendKeyFrameData(int size, const char* data) -{ - for (int i=0; i -#include -namespace Benchmark -{ - struct - { - double averageTime, totalTime, minTime, maxTime; unsigned int numSamples; - } timerData[10] = { 0.0f, 0.0f, ::std::numeric_limits::max(), -::std::numeric_limits::max(), 0 }; - - void sampleTime( const ::Utility::WinTimer &timer, unsigned char ref ) - { - double elapsedTime = timer.getElapsedSeconds(); - timerData[ref].totalTime += elapsedTime; - timerData[ref].minTime = ::Utility::Value::min( timerData[ref].minTime, elapsedTime ); - timerData[ref].maxTime = ::Utility::Value::max( timerData[ref].maxTime, elapsedTime ); - ++timerData[ref].numSamples; - timerData[ref].averageTime = timerData[ref].totalTime / (double) timerData[ref].numSamples; - } - - void print( ) - { - ::std::ofstream file; - file.open( "BenchMarkData.txt", ::std::ios_base::app | ::std::ios_base::out ); - - if( file.is_open() ) - { - file << "minTime\t\t: maxTime\t: averageTime\t\ttotalTime\tnumSamples\n"; - for( unsigned char i = 0; i < 1; ++i ) - file << timerData[i].minTime << (timerData[i].minTime == 0.0f ? "\t\t: " : "\t: ") << timerData[i].maxTime << "\t: " << timerData[i].averageTime << "\t\t" << timerData[i].totalTime << '\t' << timerData[i].numSamples <<'\n'; - file << ::std::endl; - file.close(); - ::std::cout << "Benchmark data saved." << ::std::endl; - } - } -} -// END BENCHMARK BLOCK/**/ - -void SocketServer::updateServers() -{ - for(int i=0; iupdate( timer[i].getDeltaTime() ) ) - { - case ::GameLogic::Session::Updated: - // BENCHMARK BLOCK - //processTimer.reset(); - // END BENCHMARK BLOCK - - processSessionPlayerData(i); - processAllSessionEvents(i); - processAllSessionEffects(i); - - // BENCHMARK BLOCK - //Benchmark::sampleTime( processTimer, 0 ); - // END BENCHMARK BLOCK - - DEBUGCTR=0; - updateCount[i]++; - default: - break; - case ::GameLogic::Session::Over: - processAllSessionEvents(i); - nrActiveSessions=0; - if(users.size()==0) - { - printf("Game with id %d done, shutting down the game.\n", 0); - Sleep(10); - - } - break; - } - - // BENCHMARK BLOCK - //if( Benchmark::timerData[0].numSamples % 1000 == 1 ) - // Benchmark::print(); - // END BENCHMARK BLOCK - } - } - if(nrActiveSessions==0) - { - Sleep(50); - } -} -void SocketServer::processSessionPlayerData(int serverID) -{ - sendGameDataStruct.updateCount=updateCount[serverID]; - int offset=1; - for (int i=0; iaccessPlayer(i).getOrientation(); - sendGameDataStruct.hp=session->accessPlayer(i).getHullPoints(); - sendGameDataStruct.shield=session->accessPlayer(i).getShieldPoints(); - sendGameDataStruct.dirVecLen=session->accessPlayer(i).getMovement().length(); - sendGameDataStruct.pid=i; - memcpy(sendGameDataBuffer+offset, &sendGameDataStruct, SERVER_PLAYER_DATA_SIZE); - offset+=SERVER_PLAYER_DATA_SIZE; - } - sendData(-1,sendGameDataBuffer, sendGameDataBufferSize); -} -void SocketServer::processAllSessionEvents(int serverID) -{ - session->fetchEvents(sessionEvents); - for (int i=0; i<(int)sessionEvents.size(); i++) - { - sendEventData(serverID, i); - delete sessionEvents[i]; - } - sessionEvents.resize(0); -} -bool SocketServer::sendGameData(int serverID) -{ - //data[0]=1; - for (int i=0; iGetSize(); - int size1=sizeof(Event::BulletCreated); - int tst=sizeof(Event::Type); - char* ed=new char[size+1+tst]; - ed[0]=6; - sessionEvents[sid]->SaveRawData(ed+(1+tst)); - - Event::Type eTest=Event::getEventType(sessionEvents[sid]); - memcpy(ed+1, &eTest, sizeof(Event::Type)); - - sendData(-1, ed, size+1+tst); - delete ed; -} -void SocketServer::sendRenderData(int gid) -{ - Protocol::RenderData data; - session->writeToRenderResourceData(data); - int size=data.getRequiredBufferSize()+1; - char* sendChar=new char[size]; - data.fillBuffer(sendChar+1); - sendChar[0]=8; - sendData(-1, sendChar, size); - delete sendChar; -} -void SocketServer::processAllSessionEffects(int gid) -{ - session->fetchEffectData(sessionEffects); - - if (sessionEffects.size()>0) - { - int size=(int)sessionEffects.size()*sizeof(Network::EffectData) + 1; - delete sendEffectDataBuffer; - sendEffectDataBuffer=new char[size]; - for (size_t i=0; i0) - p.thrustForward(); - if(update.forward<0) - p.thrustBackward(); - - if(update.straferight>0) - p.strafeRight(); - if(update.straferight<0) - p.strafeLeft(); - - if(update.strafeup>0) - p.climb(); - if(update.strafeup<0) - p.dive(); - - if(update.roll>0) - { - ::Oyster::Math::Float baseAcceleration = p.rotationProperty.acceleration.roll; - p.rotationProperty.acceleration.roll /= ::Oyster::Game::MoveAble::getDiscreteTimeSlice(); - - p.rollLeft(); - p.rotationProperty.acceleration.roll = baseAcceleration; - } - if(update.roll<0) - { - ::Oyster::Math::Float baseAcceleration = p.rotationProperty.acceleration.roll; - p.rotationProperty.acceleration.roll /= ::Oyster::Game::MoveAble::getDiscreteTimeSlice(); - p.rollRight(); - p.rotationProperty.acceleration.roll = baseAcceleration; - } - if(update.roll==0) - { - p.stopRotation(); - } - - if(update.TurnVer!=0.0f) - { - ::Oyster::Math::Float baseAcceleration = p.rotationProperty.acceleration.pitch; - p.rotationProperty.acceleration.pitch *= -update.TurnVer / ::Oyster::Game::MoveAble::getDiscreteTimeSlice(); - p.pitchUp( ); - p.disableRotationReduction(); - p.rotationProperty.acceleration.pitch = baseAcceleration; - } - - if(update.TurnHor!=0.0f) - { - ::Oyster::Math::Float baseAcceleration = p.rotationProperty.acceleration.yaw; - p.rotationProperty.acceleration.yaw *= -update.TurnHor / ::Oyster::Game::MoveAble::getDiscreteTimeSlice(); - p.yawLeft( ); - p.disableRotationReduction(); - p.rotationProperty.acceleration.yaw = baseAcceleration; - } - if(update.firePrim) - p.firePrimaryWeapon(); -} - diff --git a/Code/Network/OysterNetworkServer/SocketServer.h b/Code/Network/OysterNetworkServer/SocketServer.h deleted file mode 100644 index 67eac381..00000000 --- a/Code/Network/OysterNetworkServer/SocketServer.h +++ /dev/null @@ -1,126 +0,0 @@ -#include "Game.h" -#include "Lobby.h" -//void ControlPlayer( GameLogic::Player& p,const ClientToServerUpdateData &update); -const int NR_CONNECTTHREADS=1; -const int NR_SIMULTCPCONNECTS=1; -//threads can only take 1 argument -struct ThreadArguments; -struct ConnThreadData -{ - sockaddr_in srcAddr; - - ClientToServerUpdateData tmpdata; - char* buffer; - int bufLen; - int dataSize; -}; -// Link with ws2_32.lib -#pragma comment(lib, "Ws2_32.lib") -const short TCPSendPort = 11111; -const short TCPRecvPort = 11110; -const short UDPSendPort = 11001; -const short UDPRecvPort = 11000; - -class SocketServer -{ -private: - bool serverGameCreationActive; - HANDLE gameCreateHandle; - bool serverTCPConnectionLoopActive; - bool serverUDPReceiveLoopActive; - bool serverTCPReceiveLoopActive; - bool setupStatus; - int iResult; - WSADATA wsaData; - - SOCKET UDPSocket; - SOCKET TCPSocket; - - sockaddr_in TCPRecvAddr; - sockaddr_in UDPRecvAddr; - - int addrSize; - - HANDLE tcpDataHandle[NR_SIMULTCPCONNECTS]; - ConnThreadData tcpData[NR_SIMULTCPCONNECTS]; - - HANDLE udpDataHandle[NR_CONNECTTHREADS]; - ConnThreadData connData[NR_CONNECTTHREADS]; - - int dataSize; - - - char* sendEffectDataBuffer; - char* sendGameDataBuffer; - int sendGameDataBufferSize; - ServerToClientUpdateData sendGameDataStruct; - std::vector users; - std::vector games; - Lobby lobby; - int nrActiveSessions; - std::vector sessionEvents; - std::vector sessionEffects; - //GameLogic::Session* session; - std::vector timer; - int DEBUGCTR; - std::vector updateCount; - std::vector timeTillUpdate; - std::vector<::std::string> maps; - std::string text; - int playersPerSessionCount; - int killsRequiredPerSession; - bool lobbyActive; -public: - virtual ~SocketServer(); - //Debug force modify functions - void processAllSessionEvents(int serverID); - void processAllSessionEffects(int gid); - void processSessionPlayerData(int serverID); - //End of debug items - void updateServers(); - SocketServer(); - bool checkConnection(int userID); - bool initUDPSocket(); - bool initTCPSocket(); - //void firstTimeConnect(); - bool loadMapList(char* map); - bool serverGameCreationLoop(int delay); - bool startThreads(); - static DWORD activateUDPReceiveLoop(ThreadArguments* tra); - void stopUDPReceiveLoops(); - //TCP functions - static DWORD activateTCPConnectLoop(ThreadArguments* tra); - void receiveConnection(int threadID); - //End of TCP functions - bool sendData(int uid, const char*, int); - bool sendGameData(int serverID); - bool sendKeyFrameData(int size, const char* data); - void sendInitData(int gid); - void sendRenderData(int gid); - void sendEventData(int gid, int size); - void sendLobbyInitData(int lid); - bool closeConnection(); - void receiveDataUDP(int threadID); - - static DWORD activateServerGameLoop(ThreadArguments* tra); - void startGameCreateLoop(int delay); - void stopGameCreateLoop(); - void parseReceivedData(int threadID/*char*, int*/);//char and int required if i don't want to use the class buffer - void ParseReceivedData(ConnThreadData* data); - - void parseServercommand(int pid, int threadID); - void parseData(int pid, int gid, int threadID); - void parseMessage(int pid, int threadID); - - void addUser(int threadID); - void AddUser(ConnThreadData* data); - void removeUser(int id); - - bool isReady() const {return setupStatus;} - bool LoadInitData(char* maploc); -}; -struct ThreadArguments -{ - SocketServer* ptr; - int threadID; -}; \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/User.cpp b/Code/Network/OysterNetworkServer/User.cpp deleted file mode 100644 index 5dcbdf8d..00000000 --- a/Code/Network/OysterNetworkServer/User.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include "User.h" -User::User(int i, sockaddr_in add, std::string usr) -{ - addr=add; - username=usr; - curGame=-1; - connection=NULL; - state=ONLINE; - lastUpdate=-1; - updMutex = CreateMutex( - NULL, // default security attributes - FALSE, // initially not owned - NULL); // unnamed mutex - - if (updMutex == NULL) - { - printf("CreateMutex error: %d\n", GetLastError()); - } -} -User::User() -{ - username=""; - curGame=-1; - connection=NULL; - state=ONLINE; - lastUpdate=-1; - updMutex = CreateMutex( - NULL, // default security attributes - FALSE, // initially not owned - NULL); // unnamed mutex - - if (updMutex == NULL) - { - printf("CreateMutex error: %d\n", GetLastError()); - } - lastUpdateData.pid=-1; -} -void User::setLastUpdateData(Network::ClientToServerUpdateData data) -{ - WaitForSingleObject(updMutex, INFINITE); - lastUpdateData=data; - ReleaseMutex(updMutex); -} -Network::ClientToServerUpdateData User::getLastUpdateData() -{ - WaitForSingleObject(updMutex, INFINITE); - Network::ClientToServerUpdateData data=lastUpdateData; - ReleaseMutex(updMutex); - return data; -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/User.h b/Code/Network/OysterNetworkServer/User.h deleted file mode 100644 index 1a68b950..00000000 --- a/Code/Network/OysterNetworkServer/User.h +++ /dev/null @@ -1,42 +0,0 @@ -#include "ServerInclude.h" -#ifndef USER_H -#define USER_H -enum UserState -{ - OFFLINE, - OFFLINE_INGAME, - ONLINE, - ONLINE_QUEUEING, - ONLINE_INLOBBY, - ONLINE_INGAME -}; -class User -{ -private: - std::string username; - int curGame; - sockaddr_in addr; - UserState state; - long lastUpdate; - HANDLE updMutex; - Network::ClientToServerUpdateData lastUpdateData; -public: - void setLastUpdateData(Network::ClientToServerUpdateData data); - Network::ClientToServerUpdateData getLastUpdateData(); - void setLastUpdate(long upd){lastUpdate=upd;} - long getLastUpdate() {return lastUpdate;} - HANDLE threadHandle; - SOCKET connection; - User(); - User(int id, sockaddr_in addr, std::string usr="Unknown"); - //SOCKET getTCPSocket() const {return connection;} - sockaddr_in getAddr() const {return addr;} - std::string getUsername() const {return username;} - void setUsername(std::string usr){username=usr;} - void setState(UserState st){state=st;} - UserState getState(){return state;} - void setGame(int gid){curGame=gid;} - bool isIngame() {return state==ONLINE_INGAME;} - int getGame(){return curGame;} -}; -#endif \ No newline at end of file diff --git a/Code/OysterGraphics/Core/Core.h b/Code/OysterGraphics/Core/Core.h index 30fee4be..42343c11 100644 --- a/Code/OysterGraphics/Core/Core.h +++ b/Code/OysterGraphics/Core/Core.h @@ -164,7 +164,7 @@ namespace Oyster char* data; }; - static void SetShaderEffect(ShaderEffect&); + static void SetShaderEffect(ShaderEffect); static void CreateInputLayout(const D3D11_INPUT_ELEMENT_DESC *desc, int ElementCount,int VertexIndex,ID3D11InputLayout *&Layout); diff --git a/Code/OysterGraphics/Core/ShaderManager.cpp b/Code/OysterGraphics/Core/ShaderManager.cpp index f001f25e..94f7fd57 100644 --- a/Code/OysterGraphics/Core/ShaderManager.cpp +++ b/Code/OysterGraphics/Core/ShaderManager.cpp @@ -256,7 +256,7 @@ namespace Oyster /// \todo smart Set ie. not resetting the shader /// \todo research states /// \todo smart buffer set - void Core::ShaderManager::SetShaderEffect(ShaderEffect& se) + void Core::ShaderManager::SetShaderEffect(ShaderEffect se) { Set::Pixel(se.Shaders.Pixel); Set::Vertex(se.Shaders.Vertex); diff --git a/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/GBufferHeader.hlsli b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/GBufferHeader.hlsli index 3aaed031..d39f6ae5 100644 --- a/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/GBufferHeader.hlsli +++ b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/GBufferHeader.hlsli @@ -28,8 +28,6 @@ struct PixelOut Texture2D Diffuse : register(t0); Texture2D Specular : register(t1); -SamplerState Sampler : register(s0); - cbuffer PerFrame : register(b0) { matrix View; diff --git a/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/PixelGatherData.hlsl b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/PixelGatherData.hlsl index b43db0c1..61f0e20f 100644 --- a/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/PixelGatherData.hlsl +++ b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GatherGBuffer/PixelGatherData.hlsl @@ -3,7 +3,7 @@ PixelOut main(VertexOut input) { PixelOut output; - output.DiffuseGlow = Diffuse.Sample(Sampler, input.UV); + 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/SimpleDebug/DebugCameraVertex.hlsl b/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugCameraVertex.hlsl index 6095911d..1b015976 100644 --- a/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugCameraVertex.hlsl +++ b/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugCameraVertex.hlsl @@ -1,13 +1,28 @@ #include "Debug.hlsl" - -VertexOut main( VertexIn input ) { - VertexOut outp; - outp.Wpos = mul( World, float4(input.pos,1) ); + matrix View; + float4x4 Projection; +} +cbuffer PerModel : register(b1) +{ + matrix World; +} + +struct VertexIn +{ + float3 pos : POSITION; + float2 UV : TEXCOORD; + float3 normal : NORMAL; +}; + +float4 main( VertexIn input ) : SV_POSITION +{ + 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); - outp.Pos = mul(VP, outp.Wpos ); - outp.UV = input.UV; - outp.Normal = input.normal; + //matrix WVP = mul(World, VP); + return mul(VP, postTransform ); - return outp; } \ No newline at end of file diff --git a/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugVertex.hlsl b/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugVertex.hlsl index 9908555c..94efe039 100644 --- a/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugVertex.hlsl +++ b/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugVertex.hlsl @@ -1,4 +1,4 @@ float4 main( float4 pos : POSITION ) : SV_POSITION { - return pos*0.1f; + return pos; } \ No newline at end of file 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/OysterPhysics3D/Box.cpp b/Code/OysterPhysics3D/Box.cpp index e9f04b04..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( ) {} diff --git a/Code/OysterPhysics3D/BoxAxisAligned.cpp b/Code/OysterPhysics3D/BoxAxisAligned.cpp index bdd9d0a9..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,7 +36,9 @@ BoxAxisAligned & BoxAxisAligned::operator = ( const BoxAxisAligned &box ) } ::Utility::DynamicMemory::UniquePointer BoxAxisAligned::Clone( ) const -{ return ::Utility::DynamicMemory::UniquePointer( new BoxAxisAligned(*this) ); } +{ + return ::Utility::DynamicMemory::UniquePointer( new BoxAxisAligned(*this) ); +} bool BoxAxisAligned::Intersects( const ICollideable &target ) const { diff --git a/Code/OysterPhysics3D/Frustrum.cpp b/Code/OysterPhysics3D/Frustrum.cpp index a826a4e0..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() {} 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/Line.cpp b/Code/OysterPhysics3D/Line.cpp index 6258c9d9..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 ) diff --git a/Code/OysterPhysics3D/Plane.cpp b/Code/OysterPhysics3D/Plane.cpp index 48a76883..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 ) diff --git a/Code/OysterPhysics3D/Point.cpp b/Code/OysterPhysics3D/Point.cpp index a100359b..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,7 +27,9 @@ Point & Point::operator = ( const Point &point ) } ::Utility::DynamicMemory::UniquePointer Point::Clone( ) const -{ return ::Utility::DynamicMemory::UniquePointer( new Point(*this) ); } +{ + return ::Utility::DynamicMemory::UniquePointer( new Point(*this) ); +} bool Point::Intersects( const ICollideable &target ) const { diff --git a/Code/OysterPhysics3D/Ray.cpp b/Code/OysterPhysics3D/Ray.cpp index 6d501335..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,7 +32,9 @@ Ray & Ray::operator = ( const Ray &ray ) } ::Utility::DynamicMemory::UniquePointer Ray::Clone( ) const -{ return ::Utility::DynamicMemory::UniquePointer( new Ray(*this) ); } +{ + return ::Utility::DynamicMemory::UniquePointer( new Ray(*this) ); +} bool Ray::Intersects( const ICollideable &target ) const { diff --git a/Code/OysterPhysics3D/RigidBody.cpp b/Code/OysterPhysics3D/RigidBody.cpp index 24648999..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 ) diff --git a/Code/OysterPhysics3D/RigidBody.h b/Code/OysterPhysics3D/RigidBody.h index bff6acde..81c92ae0 100644 --- a/Code/OysterPhysics3D/RigidBody.h +++ b/Code/OysterPhysics3D/RigidBody.h @@ -20,7 +20,9 @@ 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 ); diff --git a/Code/OysterPhysics3D/Sphere.cpp b/Code/OysterPhysics3D/Sphere.cpp index e30ad384..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 ) diff --git a/Code/Tester/Tester.vcxproj b/Code/Tester/Tester.vcxproj index c6694156..27fc7682 100644 --- a/Code/Tester/Tester.vcxproj +++ b/Code/Tester/Tester.vcxproj @@ -148,6 +148,7 @@ true WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) true + ..\OysterGraphics;..\OysterMath;..\Misc;%(AdditionalIncludeDirectories) Windows @@ -169,6 +170,7 @@ true WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) true + ..\OysterGraphics;..\OysterMath;..\Misc;%(AdditionalIncludeDirectories) Windows