diff --git a/Bin/Level.txt b/Bin/Level.txt new file mode 100644 index 00000000..d86dd3db Binary files /dev/null and b/Bin/Level.txt differ diff --git a/Bin/Script/PLACEHOLDER b/Bin/Script/PLACEHOLDER deleted file mode 100644 index e69de29b..00000000 diff --git a/Bin/Settings/ServerInit.ini b/Bin/Settings/ServerInit.ini deleted file mode 100644 index a3b8f420..00000000 --- a/Bin/Settings/ServerInit.ini +++ /dev/null @@ -1,2 +0,0 @@ -port 15151 -clients 200 \ No newline at end of file diff --git a/Bin/Settings/serversearchpath.ini b/Bin/Settings/serversearchpath.ini deleted file mode 100644 index 6dc44cff..00000000 --- a/Bin/Settings/serversearchpath.ini +++ /dev/null @@ -1,4 +0,0 @@ -ServerInit ..\Settings\ServerInit.ini -More a -more b -more c \ No newline at end of file diff --git a/Bin/map b/Bin/map new file mode 100644 index 00000000..a578cc32 Binary files /dev/null and b/Bin/map differ diff --git a/Bin/map.txt b/Bin/map.txt new file mode 100644 index 00000000..e5c751fb Binary files /dev/null and b/Bin/map.txt differ diff --git a/Code/Dokumentation/GameServer.uxf b/Code/Dokumentation/GameServer.uxf index 9b416e02..735a2592 100644 --- a/Code/Dokumentation/GameServer.uxf +++ b/Code/Dokumentation/GameServer.uxf @@ -1,11 +1,11 @@ - + 10 UMLClass - 530 - 320 + 610 + 340 100 30 @@ -16,20 +16,8 @@ UMLClass - 530 - 250 - 100 - 30 - - MainLobby - - - - - UMLClass - - 510 - 500 + 580 + 480 160 80 @@ -41,89 +29,34 @@ - UMLClass + com.umlet.element.Relation + + 620 + 340 + 60 + 160 + + lt=->>>> + 30;140;40;30 + + + com.umlet.element.Relation 710 - 320 + 480 100 - 30 - - LobbyClient - - - - com.umlet.element.Relation - - 550 - 250 - 50 - 90 - - lt=->>>> - 30;70;30;30 - - - com.umlet.element.Relation - - 550 - 420 - 50 - 100 - - lt=->>>> - 30;80;30;30 - - - com.umlet.element.Relation - - 600 - 300 - 130 50 - lt=>>>- - 110;30;30;30 - - - com.umlet.element.Relation - - 600 - 230 - 180 - 110 - - lt=>>>- - 160;90;160;30;30;30 - - - com.umlet.element.Relation - - 640 - 410 - 140 - 140 - - lt=>>>- - 120;30;120;120;30;120 - - - com.umlet.element.Relation - - 610 - 140 - 400 - 150 - - lt=<<. - 380;130;170;130;170;30;30;30 + lt=>>>>- + 80;30;30;30 UMLClass - 520 - 160 + 600 + 180 120 - 30 + 120 GameServer @@ -131,42 +64,19 @@ com.umlet.element.Relation - 550 - 160 + 630 + 270 50 - 110 + 90 lt=>>>>- - 30;90;30;30 - - - com.umlet.element.Relation - - 750 - 260 - 260 - 80 - - lt=<<. - 240;30;30;30;30;60 - - - com.umlet.element.Package - - 990 - 250 - 120 - 50 - - NetworkAPI -bg=#a21aff - + 30;70;30;30 UMLClass - 510 - 20 + 590 + 100 130 40 @@ -177,22 +87,22 @@ DanBiasServerAPI com.umlet.element.Relation - 550 - 30 + 630 + 110 50 - 150 + 90 lt=>>>>- - 30;130;30;30 + 30;70;30;30 UMLClass - 300 - 320 + 1060 + 330 120 - 30 + 50 NetworkSession @@ -200,41 +110,41 @@ DanBiasServerAPI com.umlet.element.Relation - 330 - 230 - 220 - 110 + 690 + 220 + 390 + 50 - lt=->>>>> - 200;30;30;30;30;90 + lt=-<<<< + 30;30;370;30 com.umlet.element.Relation - 390 - 300 - 160 + 680 + 320 + 400 50 lt=->>>>> - 140;30;30;30 + 30;30;380;30 com.umlet.element.Relation - 330 - 320 - 200 - 210 + 690 + 340 + 390 + 160 lt=->>>>> - 180;190;30;190;30;30 + 30;140;40;40;370;30 com.umlet.element.Package - 990 - 370 + 460 + 640 120 50 @@ -245,164 +155,19 @@ bg=blue com.umlet.element.Relation - 750 - 320 - 260 - 90 + 370 + 530 + 350 + 290 lt=<<. - 240;70;30;70;30;30 - - - com.umlet.element.Package - - 990 - 310 - 120 - 40 - - PhysicsAPI -bg=blue --- - - - - - com.umlet.element.Relation - - 780 - 300 - 230 - 50 - - lt=.<< - 210;30;30;30 - - - com.umlet.element.Relation - - 640 - 380 - 370 - 190 - - lt=<<. - 350;30;190;30;190;170;30;170 + 90;150;30;270;330;240;240;30 UMLClass - 320 - 120 - 130 - 90 - - ServerInitReader --- -Helper to load ini files to server - -elementstyle=wordwrap - - - - - com.umlet.element.Relation - - 420 - 140 - 120 - 50 - - lt=>>. - - 100;30;30;30 - - - UMLClass - - 510 - 400 - 160 - 50 - - GameSessionManager --- -/Creates game sessions/ - - - - com.umlet.element.Relation - - 550 - 320 - 50 - 100 - - lt=>>- - 30;30;30;80 - - - com.umlet.element.Package - - 990 - 430 - 120 - 40 - - ProtocolManager -bg=#aaaaa - - - - com.umlet.element.Relation - - 310 - 320 - 770 - 300 - - lt=<<. - 750;150;750;280;30;280;30;30 - - - com.umlet.element.Relation - - 1080 - 260 - 70 - 210 - - lt=<<. - 30;190;50;190;50;30;30;30 - - - UMLClass - - 160 - 310 - 120 - 40 - - /<<interface>>/ -INetworkSession - - - - com.umlet.element.Relation - - 250 - 300 - 70 - 50 - - lt=->>>>> - 50;30;30;30 - - - UMLClass - - 710 - 410 + 790 + 500 100 30 @@ -412,28 +177,91 @@ INetworkSession com.umlet.element.Relation - 730 - 320 - 50 - 110 + 670 + 530 + 150 + 180 - lt=>>>- - 30;30;30;90 + lt=<<. + 130;160;30;30 + + + com.umlet.element.Package + + 800 + 670 + 120 + 40 + + GameProtocols +bg=#aaaaa + + + + com.umlet.element.Package + + 1040 + 200 + 160 + 190 + + NetworkAPI +bg=#a21aff + UMLClass - 150 - 420 - 160 - 50 + 1060 + 280 + 120 + 40 - MapManager --- -Manages all map stuff. - -elementstyle=wordwrap - + NetworkClient + + UMLClass + + 1060 + 230 + 120 + 40 + + NetworkServer + + + + com.umlet.element.Relation + + 690 + 240 + 390 + 80 + + lt=-> + 30;30;200;30;200;60;370;60 + + + com.umlet.element.Relation + + 690 + 260 + 390 + 100 + + lt=-<<<< + 30;30;180;30;180;80;370;80 + + + com.umlet.element.Relation + + 860 + 270 + 380 + 260 + + lt=>>>- + 320;30;360;30;360;230;30;240 + diff --git a/Code/Dokumentation/LevelLoader.uxf b/Code/Dokumentation/LevelLoader.uxf new file mode 100644 index 00000000..b5cef8f0 --- /dev/null +++ b/Code/Dokumentation/LevelLoader.uxf @@ -0,0 +1,277 @@ + + + 8 + + com.umlet.element.Relation + + 632 + 232 + 88 + 176 + + lt=. +<Uses + 24;24;24;64;72;64;72;160 + + + com.umlet.element.Relation + + 136 + 232 + 40 + 168 + + lt=<<. + 24;24;24;152 + + + com.umlet.element.Relation + + 448 + 496 + 40 + 88 + + lt=<<<<- + 24;72;24;24 + + + com.umlet.element.Relation + + 432 + 232 + 40 + 168 + + lt=<<. + 24;24;24;152 + + + com.umlet.element.Class + + 608 + 216 + 128 + 40 + + Resource Loader +<<Dennis>><<Singleton> + + + + com.umlet.element.Class + + 232 + 112 + 128 + 40 + + GameLogic +<<Erik>> + + + + com.umlet.element.Class + + 120 + 232 + 80 + 24 + + Defines + + + + com.umlet.element.Class + + 352 + 568 + 232 + 136 + + <<Interface>> +LevelParser +-- +Functions: +vector<struct> Parse(); +- +Privates: +enum headerType; +const int FileHeaderSize; +const int FileVersion; + + + + + com.umlet.element.Relation + + 336 + 88 + 136 + 160 + + lt=lt=->>>> +m1=1..1 +m2=1..1 +Uses> + 24;40;80;40;120;40;120;144 + + + com.umlet.element.Relation + + 560 + 496 + 136 + 104 + + lt=<<<<- + 120;24;120;88;24;88 + + + com.umlet.element.Class + + 352 + 384 + 232 + 136 + + LevelLoader +<<API>><Interface>> +-- +Functions: +vector<struct> LoadLevel(String fileName); +struct LoadLevelHeader(String fileName); +- +Privates: + + + + + + com.umlet.element.Relation + + 560 + 600 + 176 + 56 + + lt=- +m1=1..1 +m2=1..1 +Uses> + 24;40;160;40 + + + com.umlet.element.Package + + 344 + 344 + 584 + 368 + + LevelLoader + + + + com.umlet.element.Relation + + 472 + 200 + 152 + 56 + + lt=- +m1=1..1 +m2=1..1 +Uses> + 24;40;136;40 + + + com.umlet.element.Class + + 416 + 232 + 80 + 24 + + LevelLoader + + + + + com.umlet.element.Class + + 48 + 384 + 232 + 104 + + ObjectDefines.h +<<Header file>> +-- +Enum ObjectType(static, dynamic, specials); +. +Struct static; +Struct dynamic; +Struct specials + + + + com.umlet.element.Class + + 720 + 584 + 200 + 120 + + Collection of functions +<<lots of functions>> +-- +functions for creating the right structs + + + + com.umlet.element.Package + + 40 + 344 + 248 + 160 + + Defines + + + + com.umlet.element.Class + + 592 + 392 + 208 + 128 + + <<Interface>> +Loader +-- +Functions: +wchar* LoadFile(string fileName); +//Model* LoadHitBoxes(string modelName); +//Model* LoadHitBoxes(int modelID); +- +Privates: + + + + com.umlet.element.Relation + + 176 + 200 + 256 + 56 + + lt=->>>> +m1=1..1 +m2=1..1 +<Knows about + 240;40;24;40 + + diff --git a/Code/Dokumentation/Other/Timestep_Impulse_Fix.odt b/Code/Dokumentation/Other/Timestep_Impulse_Fix.odt new file mode 100644 index 00000000..1ad0992a Binary files /dev/null and b/Code/Dokumentation/Other/Timestep_Impulse_Fix.odt differ diff --git a/Code/Dokumentation/Other/Timestep_Impulse_Fix.pdf b/Code/Dokumentation/Other/Timestep_Impulse_Fix.pdf new file mode 100644 index 00000000..4b99c319 Binary files /dev/null and b/Code/Dokumentation/Other/Timestep_Impulse_Fix.pdf differ diff --git a/Code/Dokumentation/Other/angular momentum to angular velocity.odt b/Code/Dokumentation/Other/angular momentum to angular velocity.odt new file mode 100644 index 00000000..d0faa22d Binary files /dev/null and b/Code/Dokumentation/Other/angular momentum to angular velocity.odt differ diff --git a/Code/Dokumentation/Other/angular momentum to angular velocity.pdf b/Code/Dokumentation/Other/angular momentum to angular velocity.pdf new file mode 100644 index 00000000..8c6ef85b Binary files /dev/null and b/Code/Dokumentation/Other/angular momentum to angular velocity.pdf differ diff --git a/Code/Dokumentation/Other/angular_momentum_to_angular_velocity.pdf b/Code/Dokumentation/Other/angular_momentum_to_angular_velocity.pdf new file mode 100644 index 00000000..820bf412 Binary files /dev/null and b/Code/Dokumentation/Other/angular_momentum_to_angular_velocity.pdf differ diff --git a/Code/Dokumentation/Physics_Sprint3.uxf b/Code/Dokumentation/Physics_Sprint3.uxf index 0462e35c..6b74de3e 100644 --- a/Code/Dokumentation/Physics_Sprint3.uxf +++ b/Code/Dokumentation/Physics_Sprint3.uxf @@ -6,7 +6,7 @@ com.umlet.element.Class 357 - 609 + 518 252 406 @@ -34,7 +34,7 @@ Forcefield( .. ) : Float com.umlet.element.Class 364 - 819 + 728 238 189 @@ -60,7 +60,7 @@ Cylinder( .. ) : Matrix com.umlet.element.Class 616 - 609 + 518 210 35 @@ -73,7 +73,7 @@ Update_LeapFrog( deltatime : Float ) : void com.umlet.element.Class 616 - 672 + 581 210 203 @@ -101,7 +101,7 @@ CalculateAngularMomentum( .. ) : Vector com.umlet.element.Class 728 - 938 + 847 98 21 @@ -112,7 +112,7 @@ CalculateAngularMomentum( .. ) : Vector com.umlet.element.Class 728 - 966 + 875 98 21 @@ -123,7 +123,7 @@ CalculateAngularMomentum( .. ) : Vector com.umlet.element.Class 728 - 994 + 903 98 21 @@ -134,7 +134,7 @@ CalculateAngularMomentum( .. ) : Vector com.umlet.element.Relation 644 - 623 + 532 132 62 @@ -146,7 +146,7 @@ CalculateAngularMomentum( .. ) : Vector com.umlet.element.Class 350 - 574 + 483 483 448 @@ -157,31 +157,30 @@ bg=green - - - com.umlet.element.Class - - 560 - 511 - 161 - 49 - - Constant : <<namespace>> + + com.umlet.element.Class + + 560 + 420 + 161 + 49 + + Constant : <<namespace>> <<extern>> -- gravity_constant : const Float - - - - com.umlet.element.Class - - 224 - 476 - 329 - 84 - - Default : <<namespace>> + + + + com.umlet.element.Class + + 224 + 385 + 329 + 84 + + Default : <<namespace>> <<intern>> -- EventAction_Destruction : <<PhysicsAPI::EventAction_Destruction>> @@ -189,45 +188,61 @@ EventAction_Collision : <<ICustomBody::EventAction_Collision>> EventAction_CollisionResponse : <<ICustomBody::EventAction_Collision>> EventAction_Move : <<ICustomBody::EventAction_Collision>> - - - - com.umlet.element.Class - - 224 - 161 - 224 - 35 - - API : <<interface>> + + + + com.umlet.element.Class + + 245 + 63 + 224 + 196 + + API : <<interface>> -- {innerclass EventAction_Destruction : <<FunctionPointer>> -innerclass} - - - - com.umlet.element.Class - - 259 - 217 - 133 - 28 - - API_Impl : <<class>> +innerclass} + +Init( .. ) : void +SetFrameTimeLength( .. ) : void +SetGravityConstant( .. ) : void +SetSubscription( .. ) : void +Update() : void +IsInLimbo( .. ) : bool +MoveToLimbo( .. ) : void +ReleaseFromLimbo( .. ) : void +AddObject( .. ) : void +ExtractObject( .. ) : ICustomBody* +DestroyObject( .. ) : void +AddGravity( .. ) : void +RemoveGravity( .. ) : void +ApplyEffect( .. ) : void +CreateRigidBody( .. ) : ICustomBody* + + + + com.umlet.element.Class + + 273 + 280 + 133 + 28 + + API_Impl : <<class>> -- <<uses>> OctTree : class - - - - com.umlet.element.Class - - 455 - 161 - 280 - 84 - - ICustomBody : <<interface>> + + + + com.umlet.element.Class + + 476 + 63 + 280 + 287 + + ICustomBody : <<interface>> {innerclass SubscriptMessage : Enum @@ -243,58 +258,78 @@ innerclass} {innerclass EventAction_Move : <<Subscription : void>> -innerclass} - - - - com.umlet.element.Class - - 259 - 252 - 175 - 35 - - SimpleRigidBody : <<class>> +innerclass} + +Clone() : ICustomBody* +CallSubscription_Collision( .. ) : SubscriptMessage +CallSubscription_CollisionResponse( .. ) : void +CallSubscription_Move() : void +GetState( .. ) : State +SetState( .. ) : void +IsAffectedByGravity() : bool +Intersects( .. ) : bool +GetBoundingSphere : Sphere +GetNormalAt( .. ) : Vector +GetGravityNormal( .. ) : Vector +GetCustomTag() : void* +Update( .. ) : UpdateState +Predict( .. ) : void +SetScene( .. ) : void +SetSubscription( .. ) : void +SetGravity( .. ) : void +SetGravityNormal( .. ) : void +SetCustomTag( .. ) : void + + + + com.umlet.element.Class + + 273 + 315 + 175 + 28 + + SimpleRigidBody : <<class>> -- <<uses>> Physics3D::RigidBody : struct - - - - com.umlet.element.Class - - 259 - 294 - 175 - 35 - - SphericalRigidBody : <<class>> + + + + com.umlet.element.Class + + 273 + 350 + 175 + 28 + + SphericalRigidBody : <<class>> -- <<uses>> Physics3D::RigidBody : struct - - - - com.umlet.element.Class - - 21 - 364 - 196 - 196 - - Formula : <<namespace>> + + + + com.umlet.element.Class + + 21 + 273 + 196 + 196 + + Formula : <<namespace>> <<intern>> -- - - - - com.umlet.element.Class - - 28 - 399 - 175 - 84 - - MomentOfInertia : <<namespace>> + + + + com.umlet.element.Class + + 28 + 308 + 175 + 84 + + MomentOfInertia : <<namespace>> <<intern>> -- CreateSphereMatrix( .. ) : Matrix @@ -302,138 +337,138 @@ CreateHollowSphereMatrix( .. ) : Matrix CreateCuboidMatrix( .. ) : Matrix CreateCylinderMatrix( .. ) : Matrix CreateRodMatrix( .. ) : Matrix - - - - com.umlet.element.Class - - 28 - 497 - 175 - 56 - - CollisionResponse : <<namespace>> + + + + com.umlet.element.Class + + 28 + 406 + 175 + 56 + + CollisionResponse : <<namespace>> <<intern>> -- Bounce( .. ) : Float Friction( .. ) : Vector - - - - com.umlet.element.Relation - - 294 - 175 - 34 - 55 - - lt=<<. - 21;21;21;42 - - - com.umlet.element.Relation - - 413 - 224 - 90 - 55 - - lt=<<. - 77;21;77;42;21;42 - - - com.umlet.element.Class - - 525 - 350 - 203 - 42 - - OctTree : <<class>> + + + + com.umlet.element.Relation + + 308 + 238 + 34 + 55 + + lt=<<. + 21;21;21;42 + + + com.umlet.element.Relation + + 427 + 308 + 97 + 76 + + lt=<<. + 84;42;84;63;35;63;35;21;21;21 + + + com.umlet.element.Class + + 560 + 371 + 203 + 42 + + OctTree : <<class>> -- <<uses>> Collision3D::Sphere : struct <<uses>> Collision3D::BoxAxisAligned : struct - - - - com.umlet.element.Relation - - 546 - 224 - 118 - 139 - - lt=<- -m2= <<uses>> - 105;21;105;112;28;112;28;126 - - - com.umlet.element.Relation - - 413 - 245 - 90 - 69 - - lt=. - 77;21;77;56;21;56 - - - com.umlet.element.Class - - 21 - 161 - 182 - 196 - - Struct : <<namespace>> + + + + com.umlet.element.Relation + + 518 + 329 + 100 + 55 + + lt=<- + <<uses>> + 56;21;56;42 + + + com.umlet.element.Relation + + 427 + 329 + 97 + 55 + + lt=. + 84;21;84;42;21;42 + + + com.umlet.element.Class + + 21 + 63 + 182 + 196 + + Struct : <<namespace>> <<extern>> -- - - - - com.umlet.element.Class - - 28 - 301 - 168 - 14 - - SimpleBodyDescription : struct - - - - com.umlet.element.Class - - 28 - 329 - 168 - 14 - - SimpleSphericalDescription : struct - - - - com.umlet.element.Class - - 28 - 273 - 168 - 14 - - CustomBodyState : struct - - - - com.umlet.element.Class - - 28 - 189 - 168 - 63 - - Gravity : struct + + + + com.umlet.element.Class + + 28 + 203 + 168 + 14 + + SimpleBodyDescription : struct + + + + com.umlet.element.Class + + 28 + 231 + 168 + 14 + + SimpleSphericalDescription : struct + + + + com.umlet.element.Class + + 28 + 175 + 168 + 14 + + CustomBodyState : struct + + + + com.umlet.element.Class + + 28 + 91 + 168 + 63 + + Gravity : struct {innerclass GravityWell innerclass} @@ -443,98 +478,97 @@ innerclass} {innerclass GravityDirectedField innerclass} - - - - com.umlet.element.Relation - - 182 - 189 - 90 - 49 - - lt=<- + + + + com.umlet.element.Relation + + 182 + 105 + 104 + 195 + + lt=<- + <<uses>> + 21;21;56;21;56;168;91;168;91;182 + + + com.umlet.element.Relation + + 182 + 161 + 104 + 139 + + lt=<- + 21;21;56;21;56;112;91;112;91;126 + + + com.umlet.element.Relation + + 385 + 252 + 104 + 49 + + lt=<- <<uses>> - 21;35;77;35 - - - com.umlet.element.Relation - - 182 - 203 - 90 - 83 - - lt=<- - 21;70;42;70;42;21;77;21 - - - com.umlet.element.Relation - - 371 - 189 - 97 - 49 - - lt=<- -<<uses>> - 84;35;21;35 - - - com.umlet.element.Relation - - 182 - 266 - 90 - 49 - - lt=<- -<<uses>> - 21;35;77;35 - - - com.umlet.element.Relation - - 182 - 280 - 90 - 62 - - lt=<- - 21;49;42;49;42;21;77;21 - - - com.umlet.element.Relation - - 231 - 238 - 41 - 76 - - lt=- - 28;21;21;21;21;63 - - - com.umlet.element.Class - - 14 - 126 - 728 - 441 - - Physics : <<namespace>> + 91;35;21;35 + + + com.umlet.element.Relation + + 182 + 189 + 104 + 181 + + lt=<- + 21;21;42;21;42;168;91;168 + + + com.umlet.element.Relation + + 175 + 217 + 111 + 153 + + lt=<- + <<uses>> + 28;21;49;21;49;140;98;140 + + + com.umlet.element.Relation + + 231 + 301 + 55 + 69 + + lt=- + 42;21;42;21;21;21;21;56 + + + com.umlet.element.Class + + 14 + 35 + 756 + 441 + + Physics : <<namespace>> <<extern>> bg=green -- - - - + + com.umlet.element.Class 0 - 91 + 0 847 945 @@ -551,7 +585,7 @@ bg=orange com.umlet.element.Class 175 - 637 + 546 126 21 @@ -562,7 +596,7 @@ bg=orange com.umlet.element.Class 175 - 609 + 518 126 21 @@ -573,7 +607,7 @@ bg=orange com.umlet.element.Class 175 - 665 + 574 126 21 @@ -584,7 +618,7 @@ bg=orange com.umlet.element.Class 175 - 693 + 602 126 21 @@ -595,7 +629,7 @@ bg=orange com.umlet.element.Class 175 - 721 + 630 126 21 @@ -606,7 +640,7 @@ bg=orange com.umlet.element.Class 175 - 861 + 770 126 21 @@ -617,7 +651,7 @@ bg=orange com.umlet.element.Class 175 - 749 + 658 126 21 @@ -628,7 +662,7 @@ bg=orange com.umlet.element.Class 175 - 791 + 700 126 21 @@ -639,7 +673,7 @@ bg=orange com.umlet.element.Class 175 - 819 + 728 126 21 @@ -650,7 +684,7 @@ bg=orange com.umlet.element.Class 175 - 889 + 798 126 21 @@ -661,7 +695,7 @@ bg=orange com.umlet.element.Class 21 - 609 + 518 126 70 @@ -677,7 +711,7 @@ Contain( .. ) : bool com.umlet.element.Relation 280 - 595 + 504 55 321 @@ -688,7 +722,7 @@ Contain( .. ) : bool com.umlet.element.Relation 280 - 812 + 721 55 34 @@ -699,7 +733,7 @@ Contain( .. ) : bool com.umlet.element.Relation 280 - 784 + 693 55 34 @@ -710,7 +744,7 @@ Contain( .. ) : bool com.umlet.element.Relation 280 - 742 + 651 55 34 @@ -721,7 +755,7 @@ Contain( .. ) : bool com.umlet.element.Relation 280 - 854 + 763 55 34 @@ -732,7 +766,7 @@ Contain( .. ) : bool com.umlet.element.Relation 280 - 714 + 623 55 34 @@ -743,7 +777,7 @@ Contain( .. ) : bool com.umlet.element.Relation 280 - 686 + 595 55 34 @@ -754,7 +788,7 @@ Contain( .. ) : bool com.umlet.element.Relation 280 - 658 + 567 55 34 @@ -765,7 +799,7 @@ Contain( .. ) : bool com.umlet.element.Relation 280 - 630 + 539 55 34 @@ -776,7 +810,7 @@ Contain( .. ) : bool com.umlet.element.Relation 196 - 749 + 658 83 55 @@ -788,7 +822,7 @@ Contain( .. ) : bool com.umlet.element.Relation 35 - 658 + 567 153 84 @@ -800,7 +834,7 @@ Contain( .. ) : bool com.umlet.element.Relation 133 - 595 + 504 55 286 @@ -811,7 +845,7 @@ Contain( .. ) : bool com.umlet.element.Relation 196 - 819 + 728 83 55 @@ -823,7 +857,7 @@ Contain( .. ) : bool com.umlet.element.Relation 133 - 805 + 714 55 34 @@ -834,7 +868,7 @@ Contain( .. ) : bool com.umlet.element.Relation 133 - 735 + 644 55 34 @@ -845,7 +879,7 @@ Contain( .. ) : bool com.umlet.element.Relation 133 - 679 + 588 55 34 @@ -856,7 +890,7 @@ Contain( .. ) : bool com.umlet.element.Relation 133 - 651 + 560 55 34 @@ -867,7 +901,7 @@ Contain( .. ) : bool com.umlet.element.Relation 133 - 623 + 532 55 34 @@ -878,7 +912,7 @@ Contain( .. ) : bool com.umlet.element.Class 14 - 574 + 483 329 343 @@ -894,7 +928,7 @@ bg=green com.umlet.element.Class 938 - 168 + 77 98 28 @@ -907,7 +941,7 @@ bg=green com.umlet.element.Class 896 - 266 + 175 42 21 @@ -919,7 +953,7 @@ bg=green com.umlet.element.Class 952 - 266 + 175 70 21 @@ -931,7 +965,7 @@ bg=green com.umlet.element.Relation 896 - 189 + 98 34 90 @@ -942,9 +976,9 @@ bg=green com.umlet.element.Relation 966 - 189 - 34 - 90 + 98 + 28 + 84 lt=()) 21;77;21;21 @@ -953,7 +987,7 @@ bg=green com.umlet.element.Class 896 - 119 + 28 161 28 @@ -966,7 +1000,7 @@ bg=green com.umlet.element.Relation 896 - 126 + 35 48 97 @@ -977,7 +1011,7 @@ bg=green com.umlet.element.Class 889 - 91 + 0 175 133 @@ -990,7 +1024,7 @@ bg=blue com.umlet.element.Relation 910 - 175 + 84 90 48 @@ -1001,9 +1035,9 @@ bg=blue com.umlet.element.Relation 1036 - 112 - 111 - 34 + 21 + 105 + 28 lt=<() r1=provide @@ -1013,9 +1047,9 @@ r1=provide com.umlet.element.Relation 1015 - 161 - 132 - 34 + 70 + 126 + 28 lt=<() r1=provide diff --git a/Code/Game/DanBiasGame/DanBiasGame.vcxproj b/Code/Game/DanBiasGame/DanBiasGame.vcxproj index 0e856428..f1cbf970 100644 --- a/Code/Game/DanBiasGame/DanBiasGame.vcxproj +++ b/Code/Game/DanBiasGame/DanBiasGame.vcxproj @@ -72,7 +72,7 @@ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D $(SolutionDir)..\External\Lib\;$(SolutionDir)..\Bin\DLL;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) - $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Network/NetworkAPI;$(IncludePath);C:\Program Files %28x86%29\Visual Leak Detector\include + $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Network/NetworkAPI;$(IncludePath);C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)Game\GameServer\ true @@ -80,7 +80,7 @@ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D $(SolutionDir)..\External\Lib\;$(SolutionDir)..\Bin\DLL;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) - $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Network/NetworkAPI;$(IncludePath);C:\Program Files %28x86%29\Visual Leak Detector\include + $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Network/NetworkAPI;$(IncludePath);C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)Game\GameServer\ false @@ -88,7 +88,7 @@ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) $(SolutionDir)..\External\Lib\;$(SolutionDir)..\Bin\DLL;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) - $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Network/NetworkAPI;$(IncludePath);C:\Program Files %28x86%29\Visual Leak Detector\include + $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Network/NetworkAPI;$(IncludePath);C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)Game\GameServer\ false @@ -96,7 +96,7 @@ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) $(SolutionDir)..\External\Lib\;$(SolutionDir)..\Bin\DLL;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) - $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Network/NetworkAPI;$(IncludePath);C:\Program Files %28x86%29\Visual Leak Detector\include + $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Network/NetworkAPI;$(IncludePath);C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)Game\GameServer\ @@ -190,8 +190,12 @@ {f10cbc03-9809-4cba-95d8-327c287b18ee} + + {143bd516-20a1-4890-a3e4-f8bfd02220e7} + + @@ -202,15 +206,18 @@ + + + diff --git a/Code/Game/DanBiasGame/DanBiasGame_Impl.cpp b/Code/Game/DanBiasGame/DanBiasGame_Impl.cpp index 930d4bad..43edd84a 100644 --- a/Code/Game/DanBiasGame/DanBiasGame_Impl.cpp +++ b/Code/Game/DanBiasGame/DanBiasGame_Impl.cpp @@ -5,6 +5,7 @@ #include "GameClientState/GameClientState.h" #include "GameClientState\GameState.h" #include "GameClientState\LobbyState.h" +#include "GameClientState\LoginState.h" #include #include "NetworkClient.h" @@ -51,6 +52,7 @@ namespace DanBias DanBiasClientReturn DanBiasGame::Initiate(DanBiasGameDesc& desc) { + WindowShell::CreateConsoleWindow(); if(! m_data->window->CreateWin(WindowShell::WINDOW_INIT_DESC())) return DanBiasClientReturn_Error; @@ -61,22 +63,20 @@ namespace DanBias return DanBiasClientReturn_Error; m_data->recieverObj = new GameRecieverObject; - - m_data->recieverObj->nwClient = new Oyster::Network::NetworkClient(m_data->recieverObj, Oyster::Network::NetworkProtocolCallbackType_Object); - m_data->recieverObj->nwClient->Connect(desc.port, desc.IP); + /*m_data->recieverObj->Connect(desc.port, desc.IP); - if (!m_data->recieverObj->nwClient->IsConnected()) + if (!m_data->recieverObj->IsConnected()) { // failed to connect return DanBiasClientReturn_Error; - } + }*/ // Start in lobby state - m_data->recieverObj->gameClientState = new Client::LobbyState(); - if(!m_data->recieverObj->gameClientState->Init(m_data->recieverObj->nwClient)) + m_data->recieverObj->gameClientState = new Client::LoginState(); + if(!m_data->recieverObj->gameClientState->Init(m_data->recieverObj)) return DanBiasClientReturn_Error; - m_data->timer = new Utility::WinTimer(); //why dynamic memory? - m_data->timer->reset(); + m_data->timer = new Utility::WinTimer(); //why dynamic memory? + m_data->timer->reset(); return DanBiasClientReturn_Sucess; } @@ -133,9 +133,10 @@ namespace DanBias HRESULT DanBiasGame::Update(float deltaTime) { - + m_data->recieverObj->Update(); m_data->inputObj->Update(); + DanBias::Client::GameClientState::ClientState state = DanBias::Client::GameClientState::ClientState_Same; state = m_data->recieverObj->gameClientState->Update(deltaTime, m_data->inputObj); @@ -157,7 +158,7 @@ namespace DanBias return E_FAIL; break; } - m_data->recieverObj->gameClientState->Init(m_data->recieverObj->nwClient); // send game client + m_data->recieverObj->gameClientState->Init(m_data->recieverObj); // send game client } return S_OK; @@ -184,10 +185,9 @@ namespace DanBias { m_data->recieverObj->gameClientState->Release(); delete m_data->recieverObj->gameClientState; - m_data->recieverObj->nwClient->Disconnect(); - delete m_data->recieverObj->nwClient; - delete m_data->timer; + m_data->recieverObj->Disconnect(); delete m_data->recieverObj; + delete m_data->timer; delete m_data->inputObj; delete m_data; diff --git a/Code/Game/DanBiasGame/DanBiasMaincpp.cpp b/Code/Game/DanBiasGame/DanBiasMaincpp.cpp deleted file mode 100644 index 0b7ea666..00000000 --- a/Code/Game/DanBiasGame/DanBiasMaincpp.cpp +++ /dev/null @@ -1,316 +0,0 @@ -//-------------------------------------------------------------------------------------- -// 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/Game/DanBiasGame/GameClientRecieverFunc.h b/Code/Game/DanBiasGame/GameClientRecieverFunc.h index 68cb19d6..36b831a0 100644 --- a/Code/Game/DanBiasGame/GameClientRecieverFunc.h +++ b/Code/Game/DanBiasGame/GameClientRecieverFunc.h @@ -1,112 +1,143 @@ #ifndef DANBIAS_CLIENTRECIEVEROBJECT_H #define DANBIAS_CLIENTRECIEVEROBJECT_H +//WTF!? No headers included??? + namespace DanBias { -struct GameRecieverObject :public Oyster::Network::ProtocolRecieverObject -{ - Oyster::Network::NetworkClient* nwClient; - Client::GameClientState* gameClientState; - - // receiver function for server messages - // parsing protocols and sending it to the gameState - void NetworkCallback(Oyster::Network::CustomNetProtocol& p) override + + struct GameRecieverObject :public Oyster::Network::NetworkClient { - int pType = p[0].value.netInt; - switch (pType) + Client::GameClientState* gameClientState; + + // receiver function for server messages + // parsing protocols and sending it to the gameState + void NetworkCallback(Oyster::Network::CustomNetProtocol& p) override { - case protocol_General_Status: + int pType = p[0].value.netInt; + switch (pType) { - GameLogic::Protocol_General_Status::States state; - state = (GameLogic::Protocol_General_Status::States)p[1].value.netShort; - if( state == GameLogic::Protocol_General_Status::States_disconected) + case protocol_General_Status: { - // server disconnected - DanBiasGame::Release(); + GameLogic::Protocol_General_Status::States state; + state = (GameLogic::Protocol_General_Status::States)p[1].value.netShort; + if( state == GameLogic::Protocol_General_Status::States_disconected) + { + // server disconnected + DanBiasGame::Release(); + } } - } - break; - case protocol_Gameplay_PlayerNavigation: - { - Client::GameClientState::KeyInput* protocolData = new Client::GameClientState::KeyInput; - for(int i = 0; i< 6; i++) + break; + case protocol_Gameplay_PlayerMovement: { - protocolData->key[i] = p[i+1].value.netBool; - } + Client::GameClientState::KeyInput* protocolData = new Client::GameClientState::KeyInput; + for(int i = 0; i< 6; i++) + { + protocolData->key[i] = p[i+1].value.netBool; + } - if(dynamic_cast(gameClientState)) - ((Client::GameState*)gameClientState)->Protocol(protocolData); - delete protocolData; - protocolData = NULL; - } - break; - case protocol_Gameplay_PlayerPosition: - { - Client::GameClientState::PlayerPos* protocolData = new Client::GameClientState::PlayerPos; - for(int i = 0; i< 3; i++) + if(dynamic_cast(gameClientState)) + ((Client::GameState*)gameClientState)->Protocol(protocolData); + delete protocolData; + protocolData = NULL; + } + break; + //case protocol_Gameplay_PlayerPosition: + // { + // Client::GameClientState::PlayerPos* protocolData = new Client::GameClientState::PlayerPos; + // for(int i = 0; i< 3; i++) + // { + // protocolData->playerPos[i] = p[i].value.netFloat; + // } + // if(dynamic_cast(gameClientState)) + // ((Client::GameState*)gameClientState)->Protocol(protocolData); + // delete protocolData; + // protocolData = NULL; + // } + // break; + + case protocol_Gameplay_ObjectCreate: { - protocolData->playerPos[i] = p[i].value.netFloat; - } - if(dynamic_cast(gameClientState)) - ((Client::GameState*)gameClientState)->Protocol(protocolData); - delete protocolData; - protocolData = NULL; - } - break; + Client::GameClientState::NewObj* protocolData = new Client::GameClientState::NewObj; + protocolData->object_ID = p[1].value.netInt; + protocolData->path = p[2].value.netCharPtr; + for(int i = 0; i< 16; i++) + { + protocolData->worldPos[i] = p[i+3].value.netFloat; + } - case protocol_Gameplay_CreateObject: - { - Client::GameClientState::NewObj* protocolData = new Client::GameClientState::NewObj; - protocolData->object_ID = p[1].value.netInt; - protocolData->path = p[2].value.netCharPtr; - for(int i = 0; i< 16; i++) + if(dynamic_cast(gameClientState)) + ((Client::GameState*)gameClientState)->Protocol(protocolData); + + delete p[2].value.netCharPtr; //delete char array + delete protocolData; + protocolData = NULL; + } + break; + case protocol_Gameplay_ObjectDisabled: { - protocolData->worldPos[i] = p[i+3].value.netFloat; + Client::GameClientState::RemoveObj* protocolData = new Client::GameClientState::RemoveObj; + protocolData->object_ID = p[1].value.netInt; + + if(dynamic_cast(gameClientState)) + ((Client::GameState*)gameClientState)->Protocol(protocolData); + + delete protocolData; + protocolData = NULL; } - - if(dynamic_cast(gameClientState)) - ((Client::GameState*)gameClientState)->Protocol(protocolData); - - delete p[2].value.netCharPtr; //delete char array - delete protocolData; - protocolData = NULL; - } - break; - case protocol_Gameplay_RemoveObject: - { - Client::GameClientState::RemoveObj* protocolData = new Client::GameClientState::RemoveObj; - protocolData->object_ID = p[1].value.netInt; - - if(dynamic_cast(gameClientState)) - ((Client::GameState*)gameClientState)->Protocol(protocolData); - - delete protocolData; - protocolData = NULL; - } - break; - case protocol_Gameplay_ObjectPosition: - { - - Client::GameClientState::ObjPos* protocolData = new Client::GameClientState::ObjPos; - protocolData->object_ID = p[1].value.netInt; - for(int i = 0; i< 16; i++) + break; + case protocol_Gameplay_ObjectPosition: { - protocolData->worldPos[i] = p[i+2].value.netFloat; + + Client::GameClientState::ObjPos protocolData; + protocolData.object_ID = p[1].value.netInt; + for(int i = 0; i< 16; i++) + { + protocolData.worldPos[i] = p[i+2].value.netFloat; + } + + if(dynamic_cast(gameClientState)) + ((Client::GameState*)gameClientState)->Protocol(&protocolData); } + break; - if(dynamic_cast(gameClientState)) - ((Client::GameState*)gameClientState)->Protocol(protocolData); + default: + break; + } - delete protocolData; - protocolData = NULL; + if(ProtocolIsLobby(p[0].value.netInt)) ParseLobbyProtocol(p); + } + + void ParseLobbyProtocol(Oyster::Network::CustomNetProtocol& p) + { + switch (p[0].value.netShort) + { + case protocol_General_Status: //this->GeneralStatus (Protocol_General_Status (p), c); + break; + case protocol_General_Text: //this->GeneralText (Protocol_General_Text (p), c); + break; + //case protocol_Lobby_Create: this->LobbyCreateGame (Protocol_LobbyCreateGame (p), c); + //break; + case protocol_Lobby_Start: //this->LobbyStartGame (Protocol_LobbyStartGame (p), c); + break; + //case protocol_Lobby_Join: this->LobbyJoin (Protocol_LobbyJoin (p), c); + //break; + case protocol_Lobby_Login: //this->LobbyLogin (Protocol_LobbyLogin (p), c); + break; + case protocol_Lobby_Refresh: //this->LobbyRefresh (Protocol_LobbyRefresh (p), c); + break; + case protocol_Lobby_GameData: //this->LobbyGameData (Protocol_LobbyGameData (p), c); + { + GameLogic::Protocol_LobbyGameData temp(p); + printf("%s, %i.%i\n", temp.mapName.c_str(), temp.majorVersion, temp.minorVersion); + } + break; + case protocol_Lobby_ClientData: //this->LobbyMainData (Protocol_LobbyClientData (p), c); + break; + //case protocol_Lobby_GameData: this->LobbyGameData (Protocol_LobbyGameData (p), c); + //break; } - break; - - default: - break; - } - - } -}; + } + }; } #endif \ No newline at end of file diff --git a/Code/Game/DanBiasGame/GameClientState/C_obj/C_Player.cpp b/Code/Game/DanBiasGame/GameClientState/C_obj/C_Player.cpp index 4cd6fbd3..49c450b5 100644 --- a/Code/Game/DanBiasGame/GameClientState/C_obj/C_Player.cpp +++ b/Code/Game/DanBiasGame/GameClientState/C_obj/C_Player.cpp @@ -8,6 +8,7 @@ struct C_Player::myData Oyster::Math3D::Float4x4 view; Oyster::Math3D::Float4x4 proj; Oyster::Graphics::Model::Model *model; + Oyster::Math3D::Float4 lookDir; int ID; }privData; @@ -29,7 +30,7 @@ void C_Player::Init(ModelInitData modelInit) privData->model->WorldMatrix = modelInit.world; privData->model->Visible = modelInit.visible; privData->ID = modelInit.id; - + privData->lookDir = Oyster::Math3D::Float4 (0,0,1,0); } void C_Player::setPos(Oyster::Math::Float4x4 world) { diff --git a/Code/Game/DanBiasGame/GameClientState/Camera.cpp b/Code/Game/DanBiasGame/GameClientState/Camera.cpp new file mode 100644 index 00000000..13b5a70f --- /dev/null +++ b/Code/Game/DanBiasGame/GameClientState/Camera.cpp @@ -0,0 +1,192 @@ +#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();*/ + mProj = Oyster::Math3D::ProjectionMatrix_Perspective(fovY,aspect,zn,zf); +} + +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); + mView = Oyster::Math3D::ViewMatrix_LookAtDirection(mLook, mUp, m_position); + /* + 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/Game/DanBiasGame/GameClientState/Camera.h b/Code/Game/DanBiasGame/GameClientState/Camera.h new file mode 100644 index 00000000..56ea5569 --- /dev/null +++ b/Code/Game/DanBiasGame/GameClientState/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/Game/DanBiasGame/GameClientState/GameClientState.h b/Code/Game/DanBiasGame/GameClientState/GameClientState.h index 2ba930b7..28a671ba 100644 --- a/Code/Game/DanBiasGame/GameClientState/GameClientState.h +++ b/Code/Game/DanBiasGame/GameClientState/GameClientState.h @@ -51,6 +51,7 @@ public: }; enum ClientState { + ClientState_Login, ClientState_Lobby, ClientState_Game, ClientState_Same, diff --git a/Code/Game/DanBiasGame/GameClientState/GameState.cpp b/Code/Game/DanBiasGame/GameClientState/GameState.cpp index e0b0054a..2e04959d 100644 --- a/Code/Game/DanBiasGame/GameClientState/GameState.cpp +++ b/Code/Game/DanBiasGame/GameClientState/GameState.cpp @@ -4,7 +4,8 @@ #include "C_obj/C_DynamicObj.h" #include #include "NetworkClient.h" - +#include "Camera.h" +#include using namespace DanBias::Client; @@ -17,7 +18,6 @@ struct GameState::myData int modelCount; Oyster::Network::NetworkClient* nwClient; gameStateState state; - }privData; @@ -38,22 +38,35 @@ GameState::~GameState(void) bool GameState::Init(Oyster::Network::NetworkClient* nwClient) { // load models + camera = new Camera; privData = new myData(); privData->state = gameStateState_loading; privData->nwClient = nwClient; privData->state = LoadGame(); + return true; } GameState::gameStateState GameState::LoadGame() { Oyster::Graphics::Definitions::Pointlight plight; - plight.Pos = Oyster::Math::Float3(0,3,0); + plight.Pos = Oyster::Math::Float3(0,15,5); plight.Color = Oyster::Math::Float3(0,1,0); - plight.Radius = 5; + plight.Radius = 50; plight.Bright = 2; + Oyster::Graphics::API::AddLight(plight); + plight.Pos = Oyster::Math::Float3(10,15,5); + plight.Color = Oyster::Math::Float3(1,0,0); + plight.Radius = 50; + plight.Bright = 2; + Oyster::Graphics::API::AddLight(plight); + plight.Pos = Oyster::Math::Float3(10,-15,5); + plight.Color = Oyster::Math::Float3(0,0,1); + plight.Radius = 50; + plight.Bright = 2; + Oyster::Graphics::API::AddLight(plight); LoadModels(L"map"); - InitCamera(Oyster::Math::Float3(0,0,5.4f)); + InitCamera(Oyster::Math::Float3(0,0,20.0f)); return gameStateState_playing; } bool GameState::LoadModels(std::wstring mapFile) @@ -63,46 +76,67 @@ bool GameState::LoadModels(std::wstring mapFile) // init models privData->modelCount = 2; + // add world model ModelInitData modelData; + Oyster::Math3D::Float4x4 translate; + C_Object* obj; + translate = Oyster::Math3D::TranslationMatrix(Oyster::Math::Float3(0,0,0)); + Oyster::Math3D::Float4x4 scale = Oyster::Math3D::Float4x4::identity; + scale.v[0].x = 8; + scale.v[1].y = 8; + scale.v[2].z = 8; + modelData.world = scale; //modelData.world * translate + modelData.modelPath = L"..\\Content\\Models\\ball.dan"; + modelData.id = 0; + obj = new C_Player(); + privData->object.push_back(obj); + privData->object[privData->object.size() -1 ]->Init(modelData); + + // add box model modelData.world = Oyster::Math3D::Float4x4::identity; - Oyster::Math3D::Float4x4 translate = Oyster::Math3D::TranslationMatrix(Oyster::Math::Float3(-2,-2,-2)); + translate = Oyster::Math3D::TranslationMatrix(Oyster::Math::Float3(-5,15,0)); + modelData.world = modelData.world * translate; + modelData.modelPath = L"..\\Content\\Models\\box.dan"; + modelData.id = 1; + + obj = new C_Player(); + privData->object.push_back(obj); + privData->object[privData->object.size() -1 ]->Init(modelData); + modelData.world = Oyster::Math3D::Float4x4::identity; + + // add player model + modelData.world = Oyster::Math3D::Float4x4::identity; + translate = Oyster::Math3D::TranslationMatrix(Oyster::Math::Float3(0, 15, 0)); + modelData.world = modelData.world * translate; modelData.visible = true; modelData.modelPath = L"..\\Content\\Models\\char_white.dan"; - modelData.id = 0; + modelData.id = 2; // load models - C_Object* obj = new C_Player(); + obj = new C_Player(); privData->object.push_back(obj); privData->object[privData->object.size() -1 ]->Init(modelData); - translate = Oyster::Math3D::TranslationMatrix(Oyster::Math::Float3(-2,2,2)); - modelData.world = modelData.world * translate; - modelData.modelPath = L"..\\Content\\Models\\char_white.dan"; - modelData.id ++; - - obj = new C_DynamicObj(); - privData->object.push_back(obj); - privData->object[privData->object.size() -1 ]->Init(modelData); - - translate = Oyster::Math3D::TranslationMatrix(Oyster::Math::Float3(-2,-2,-2)); - modelData.world = modelData.world * translate; - modelData.modelPath = L"..\\Content\\Models\\char_white.dan"; - modelData.id ++; - - obj = new C_DynamicObj(); - privData->object.push_back(obj); - privData->object[privData->object.size() -1 ]->Init(modelData); return true; } bool GameState::InitCamera(Oyster::Math::Float3 startPos) { + 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, 20); + + camera->LookAt(pos, dir, up); + camera->SetLens(3.14f/2, 1024/768, 1, 1000); + privData->proj = Oyster::Math3D::ProjectionMatrix_Perspective(Oyster::Math::pi/2,1024.0f/768.0f,.1f,1000); //privData->proj = Oyster::Math3D::ProjectionMatrix_Orthographic(1024, 768, 1, 1000); Oyster::Graphics::API::SetProjection(privData->proj); - + camera->UpdateViewMatrix(); + privData->view = camera->View(); + privData->view = Oyster::Math3D::ViewMatrix_LookAtDirection(Oyster::Math::Float3(0,0,-1),Oyster::Math::Float3(0,1,0),startPos); privData->view = Oyster::Math3D::OrientationMatrix_LookAtDirection(Oyster::Math::Float3(0,0,-1),Oyster::Math::Float3(0,1,0),startPos); privData->view = Oyster::Math3D::InverseOrientationMatrix(privData->view); return true; @@ -110,6 +144,7 @@ bool GameState::InitCamera(Oyster::Math::Float3 startPos) GameClientState::ClientState GameState::Update(float deltaTime, InputClass* KeyInput) { + DanBias::GameServerAPI::ServerUpdate(); switch (privData->state) { case gameStateState_loading: @@ -127,83 +162,9 @@ GameClientState::ClientState GameState::Update(float deltaTime, InputClass* KeyI // read server data // update objects { - bool send = false; - GameLogic::Protocol_PlayerMovement movePlayer; - movePlayer.bForward = false; - movePlayer.bBackward = false; - movePlayer.bStrafeLeft = false; - movePlayer.bStrafeRight = false; - movePlayer.bTurnLeft = false; - movePlayer.bTurnRight = false; + readKeyInput(KeyInput); + camera->UpdateViewMatrix(); - if(KeyInput->IsKeyPressed(DIK_W)) - { - - if(!key_forward) - { - movePlayer.bForward = true; - send = true; - key_forward = true; - } - } - else - key_forward = false; - - if(KeyInput->IsKeyPressed(DIK_S)) - { - if(!key_backward) - { - movePlayer.bBackward = true; - send = true; - key_backward = true; - } - } - else - key_backward = false; - - if(KeyInput->IsKeyPressed(DIK_A)) - { - if(!key_strafeLeft) - { - movePlayer.bStrafeLeft = true; - send = true; - key_strafeLeft = true; - } - } - else - key_strafeLeft = false; - - if(KeyInput->IsKeyPressed(DIK_D)) - { - if(!key_strafeRight) - { - movePlayer.bStrafeRight = true; - send = true; - key_strafeRight = true; - } - } - else - key_strafeRight = false; - - - if (privData->nwClient->IsConnected() && send) - { - privData->nwClient->Send(movePlayer); - } - - //send delta mouse movement - if (KeyInput->IsMousePressed()) - { - GameLogic::Protocol_PlayerMouse deltaMouseMove; - deltaMouseMove.dxMouse = KeyInput->GetYaw(); - deltaMouseMove.dyMouse = KeyInput->GetPitch(); - //privData->nwClient->Send(deltaMouseMove); - } - - // send event data - // - if(KeyInput->IsKeyPressed(DIK_L)) - privData->state = GameState::gameStateState_end; } break; case gameStateState_end: @@ -218,10 +179,12 @@ GameClientState::ClientState GameState::Update(float deltaTime, InputClass* KeyI } bool GameState::Render() { - Oyster::Graphics::API::SetView(privData->view); + Oyster::Graphics::API::SetView(camera->View()); + //Oyster::Graphics::API::SetProjection(camera->Proj()); + //Oyster::Graphics::API::SetView(privData->view); Oyster::Graphics::API::SetProjection(privData->proj); Oyster::Graphics::API::NewFrame(); - for (int i = 0; i < privData->object.size(); i++) + for (unsigned int i = 0; i < privData->object.size(); i++) { privData->object[i]->Render(); } @@ -230,7 +193,7 @@ bool GameState::Render() } bool GameState::Release() { - for (int i = 0; i < privData->object.size(); i++) + for (unsigned int i = 0; i < privData->object.size(); i++) { privData->object[i]->Release(); delete privData->object[i]; @@ -241,6 +204,118 @@ bool GameState::Release() privData = NULL; return true; } +void GameState::readKeyInput(InputClass* KeyInput) +{ + + bool send = false; + GameLogic::Protocol_PlayerMovement movePlayer; + movePlayer.bForward = false; + movePlayer.bBackward = false; + movePlayer.bLeft = false; + movePlayer.bRight = false; + + if(KeyInput->IsKeyPressed(DIK_W)) + { + + if(!key_forward) + { + movePlayer.bForward = true; + send = true; + key_forward = true; + } + } + else + key_forward = false; + + if(KeyInput->IsKeyPressed(DIK_S)) + { + if(!key_backward) + { + movePlayer.bBackward = true; + send = true; + key_backward = true; + } + } + else + key_backward = false; + + if(KeyInput->IsKeyPressed(DIK_A)) + { + if(!key_strafeLeft) + { + movePlayer.bLeft = true; + send = true; + key_strafeLeft = true; + } + } + else + key_strafeLeft = false; + + if(KeyInput->IsKeyPressed(DIK_D)) + { + if(!key_strafeRight) + { + movePlayer.bRight = true; + send = true; + key_strafeRight = true; + } + } + else + key_strafeRight = false; + + + if (privData->nwClient->IsConnected() && send) + { + privData->nwClient->Send(movePlayer); + } + + //send delta mouse movement + if (KeyInput->IsMousePressed()) + { + camera->Yaw(KeyInput->GetYaw()); + camera->Pitch(KeyInput->GetPitch()); + camera->UpdateViewMatrix(); + GameLogic::Protocol_PlayerLook playerLookDir; + Oyster::Math::Float3 look = camera->GetLook(); + playerLookDir.lookDirX = look.x; + playerLookDir.lookDirY = look.y; + playerLookDir.lookDirZ = look.z; + privData->nwClient->Send(playerLookDir); + } + + // shoot + if(KeyInput->IsKeyPressed(DIK_Z)) + { + if(!key_Shoot) + { + GameLogic::Protocol_PlayerShot playerShot; + playerShot.hasShot = true; + privData->nwClient->Send(playerShot); + key_Shoot = true; + } + } + else + key_Shoot = false; + + // jump + if(KeyInput->IsKeyPressed(DIK_X)) + { + if(!key_Jump) + { + GameLogic::Protocol_PlayerJump playerJump; + playerJump.hasJumped = true; + privData->nwClient->Send(playerJump); + key_Jump = true; + } + } + else + key_Jump = false; + + // send event data + // + if(KeyInput->IsKeyPressed(DIK_L)) + privData->state = GameState::gameStateState_end; +} void GameState::Protocol(ProtocolStruct* pos) { @@ -266,15 +341,19 @@ void GameState::Protocol( ObjPos* pos ) world[i] = pos->worldPos[i]; } - for (int i = 0; i < privData->object.size(); i++) + for (unsigned int i = 0; i < privData->object.size(); i++) { if(privData->object[i]->GetId() == pos->object_ID) { privData->object[i]->setPos(world); - - //privData->view = world; - //privData->view = Oyster::Math3D::InverseOrientationMatrix(privData->view); - + //camera->setRight((Oyster::Math::Float3(world[0], world[1], world[2]))); + //camera->setUp((Oyster::Math::Float3(world[4], world[5], world[6]))); + //camera->setLook((Oyster::Math::Float3(world[8], world[9], world[10]))); + if(i == 2) // playerobj + { + camera->SetPosition(Oyster::Math::Float3(world[12], world[13], world[14])); + camera->UpdateViewMatrix(); + } } } } @@ -305,7 +384,7 @@ void GameState::Protocol( NewObj* newObj ) void DanBias::Client::GameState::Protocol( RemoveObj* obj ) { - for (int i = 0; i < privData->object.size(); i++) + for (unsigned int i = 0; i < privData->object.size(); i++) { if(privData->object[i]->GetId() == obj->object_ID) { diff --git a/Code/Game/DanBiasGame/GameClientState/GameState.h b/Code/Game/DanBiasGame/GameClientState/GameState.h index 3942afba..f8f1b67b 100644 --- a/Code/Game/DanBiasGame/GameClientState/GameState.h +++ b/Code/Game/DanBiasGame/GameClientState/GameState.h @@ -3,6 +3,7 @@ #include "GameClientState.h" #include "OysterMath.h" #include +#include "Camera.h" namespace DanBias { namespace Client @@ -21,6 +22,9 @@ private: bool key_backward; bool key_strafeRight; bool key_strafeLeft; + bool key_Shoot; + bool key_Jump; + Camera* camera; struct myData; myData* privData; @@ -33,6 +37,7 @@ public: bool InitCamera(Oyster::Math::Float3 startPos) ; gameStateState LoadGame(); + void readKeyInput(InputClass* KeyInput); bool Render()override; bool Release()override; diff --git a/Code/Game/DanBiasGame/GameClientState/LobbyState.cpp b/Code/Game/DanBiasGame/GameClientState/LobbyState.cpp index 69e3504a..5d6bff79 100644 --- a/Code/Game/DanBiasGame/GameClientState/LobbyState.cpp +++ b/Code/Game/DanBiasGame/GameClientState/LobbyState.cpp @@ -4,6 +4,7 @@ #include "C_obj/C_Player.h" #include "C_obj/C_StaticObj.h" #include "C_obj/C_DynamicObj.h" +#include using namespace DanBias::Client; @@ -31,7 +32,7 @@ LobbyState::~LobbyState(void) bool LobbyState::Init(Oyster::Network::NetworkClient* nwClient) { privData = new myData(); - + this->nwClient = nwClient; // load models LoadModels(L"UImodels.txt"); InitCamera(Oyster::Math::Float3(0,0,5.4f)); @@ -43,7 +44,7 @@ bool LobbyState::LoadModels(std::wstring file) plight.Pos = Oyster::Math::Float3(-2,3,0); plight.Color = Oyster::Math::Float3(0,1,0); plight.Radius = 10; - plight.Bright = 3; + plight.Bright = 1; Oyster::Graphics::API::AddLight(plight); // open file // read file @@ -86,9 +87,15 @@ GameClientState::ClientState LobbyState::Update(float deltaTime, InputClass* Key // update animation // send data to server // check data from server + DanBias::GameServerAPI::ServerUpdate(); if( KeyInput->IsKeyPressed(DIK_G)) - return ClientState_Game; + { + if(!DanBias::GameServerAPI::GameStart()) + return GameClientState::ClientState_Same; + return ClientState_Game; + } + return ClientState_Same; } bool LobbyState::Render() diff --git a/Code/Game/DanBiasGame/GameClientState/LobbyState.h b/Code/Game/DanBiasGame/GameClientState/LobbyState.h index e7cb7b8c..057fc850 100644 --- a/Code/Game/DanBiasGame/GameClientState/LobbyState.h +++ b/Code/Game/DanBiasGame/GameClientState/LobbyState.h @@ -3,6 +3,7 @@ #include "GameClientState.h" #include "OysterMath.h" +#include "NetworkClient.h" #include namespace DanBias { @@ -12,6 +13,7 @@ namespace DanBias class LobbyState : public GameClientState { private: + Oyster::Network::NetworkClient* nwClient; struct myData; myData* privData; public: diff --git a/Code/Game/DanBiasGame/GameClientState/LoginState.cpp b/Code/Game/DanBiasGame/GameClientState/LoginState.cpp new file mode 100644 index 00000000..8fa4936d --- /dev/null +++ b/Code/Game/DanBiasGame/GameClientState/LoginState.cpp @@ -0,0 +1,166 @@ +#include "LoginState.h" +#include "DllInterfaces/GFXAPI.h" +#include "OysterMath.h" +#include "C_obj/C_Player.h" +#include "C_obj/C_StaticObj.h" +#include "C_obj/C_DynamicObj.h" +#include + +using namespace DanBias::Client; + +struct LoginState::myData +{ + myData(){} + Oyster::Math3D::Float4x4 view; + Oyster::Math3D::Float4x4 proj; + C_Object* object[2]; + int modelCount; + // UI object + // game client* +}privData; + +LoginState::LoginState(void) +{ + +} + +LoginState::~LoginState(void) +{ + +} + +bool LoginState::Init(Oyster::Network::NetworkClient* nwClient) +{ + privData = new myData(); + this->nwClient = nwClient; + // load models + LoadModels(L"UImodels.txt"); + InitCamera(Oyster::Math::Float3(0,0,5.4f)); + return true; +} +bool LoginState::LoadModels(std::wstring file) +{ + Oyster::Graphics::Definitions::Pointlight plight; + plight.Pos = Oyster::Math::Float3(-2,3,0); + plight.Color = Oyster::Math::Float3(0,1,0); + plight.Radius = 10; + plight.Bright = 1; + Oyster::Graphics::API::AddLight(plight); + // open file + // read file + // init models + privData->modelCount = 2; + + ModelInitData modelData; + + modelData.world = Oyster::Math3D::Float4x4::identity; + modelData.visible = true; + modelData.modelPath = L"..\\Content\\Models\\box_2.dan"; + // load models + privData->object[0] = new C_StaticObj(); + privData->object[0]->Init(modelData); + + Oyster::Math3D::Float4x4 translate = Oyster::Math3D::TranslationMatrix(Oyster::Math::Float3(-2,-2,-2)); + modelData.world = modelData.world * translate; + + privData->object[1] = new C_DynamicObj(); + privData->object[1]->Init(modelData); + return true; +} + +bool LoginState::InitCamera(Oyster::Math::Float3 startPos) +{ + privData->proj = Oyster::Math3D::ProjectionMatrix_Perspective(Oyster::Math::pi/2,1024.0f/768.0f,.1f,1000); + //privData->proj = Oyster::Math3D::ProjectionMatrix_Orthographic(1024, 768, 1, 1000); + Oyster::Graphics::API::SetProjection(privData->proj); + + privData->view = Oyster::Math3D::OrientationMatrix_LookAtDirection(Oyster::Math::Float3(0,0,-1),Oyster::Math::Float3(0,1,0),startPos); + privData->view = Oyster::Math3D::InverseOrientationMatrix(privData->view); + return true; +} +GameClientState::ClientState LoginState::Update(float deltaTime, InputClass* KeyInput) +{ + // picking + // mouse events + // different menus + // play sounds + // update animation + // send data to server + // check data from server + + // create game + if( KeyInput->IsKeyPressed(DIK_C)) + { + DanBias::GameServerAPI::ServerInitDesc desc; + + DanBias::GameServerAPI::ServerInitiate(desc); + DanBias::GameServerAPI::ServerStart(); + // my ip + nwClient->Connect(15151, "127.0.0.1"); + + if (!nwClient->IsConnected()) + { + // failed to connect + return ClientState_Same; + } + return ClientState_Lobby; + } + // join game + if( KeyInput->IsKeyPressed(DIK_J)) + { + // game ip + nwClient->Connect(15151, "194.47.150.56"); + + if (!nwClient->IsConnected()) + { + // failed to connect + return ClientState_Same; + } + return ClientState_Lobby; + } + return ClientState_Same; +} +bool LoginState::Render() +{ + + Oyster::Graphics::API::SetView(privData->view); + Oyster::Graphics::API::SetProjection( privData->proj); + + + Oyster::Graphics::API::NewFrame(); + // render objects + for (int i = 0; i < privData->modelCount; i++) + { + privData->object[i]->Render(); + } + + // render effects + + // render lights + + Oyster::Graphics::API::EndFrame(); + return true; +} +bool LoginState::Release() +{ + for (int i = 0; i < privData->modelCount; i++) + { + privData->object[i]->Release(); + delete privData->object[i]; + privData->object[i] = NULL; + } + + delete privData; + privData = NULL; + return true; +} +void LoginState::Protocol(ProtocolStruct* protocol) +{ + if((PlayerName*)protocol) + PlayerJoinProtocol((PlayerName*)protocol); + +} +void LoginState::PlayerJoinProtocol(PlayerName* name) +{ + +} \ No newline at end of file diff --git a/Code/Game/DanBiasGame/GameClientState/LoginState.h b/Code/Game/DanBiasGame/GameClientState/LoginState.h new file mode 100644 index 00000000..d426187d --- /dev/null +++ b/Code/Game/DanBiasGame/GameClientState/LoginState.h @@ -0,0 +1,33 @@ +#ifndef DANBIAS_CLIENT_LOGINSTATE_H +#define DANBIAS_CLIENT_LOGINSTATE_H + +#include "GameClientState.h" +#include "OysterMath.h" +#include "NetworkClient.h" +#include +namespace DanBias +{ + namespace Client + { + + class LoginState : public GameClientState + { + private: + Oyster::Network::NetworkClient* nwClient; + struct myData; + myData* privData; + public: + LoginState(void); + ~LoginState(void); + bool Init(Oyster::Network::NetworkClient* nwClient); + bool LoadModels(std::wstring file); + bool InitCamera(Oyster::Math::Float3 startPos); + ClientState Update(float deltaTime, InputClass* KeyInput); + + bool Render(); + bool Release(); + void Protocol(ProtocolStruct* protocol)override; + void PlayerJoinProtocol(PlayerName* name); + + };};}; +#endif // ! DANBIAS_CLIENT_LOGINSTATE_H \ No newline at end of file diff --git a/Code/Game/DanBiasLauncher/Launcher.cpp b/Code/Game/DanBiasLauncher/Launcher.cpp index 38f499eb..95bad91c 100644 --- a/Code/Game/DanBiasLauncher/Launcher.cpp +++ b/Code/Game/DanBiasLauncher/Launcher.cpp @@ -18,7 +18,7 @@ int WINAPI WinMain( HINSTANCE hinst, HINSTANCE prevInst, PSTR cmdLine, int cmdSh DanBias::DanBiasGameDesc gameDesc; gameDesc.port = 15151; //gameDesc.port = 15152; - //gameDesc.IP = "193.11.184.196"; + //gameDesc.IP = "193.11.184.109"; //gameDesc.IP = "193.11.184.31"; //gameDesc.IP = "194.47.150.56"; gameDesc.IP = "127.0.0.1"; diff --git a/Code/Game/DanBiasServer/AdminInterface/AdminInterface.cpp b/Code/Game/DanBiasServer/AdminInterface/AdminInterface.cpp deleted file mode 100644 index 80e2f9fe..00000000 --- a/Code/Game/DanBiasServer/AdminInterface/AdminInterface.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#define NOMINMAX -#include "AdminInterface.h" -#include -#include -#include "..\GameServer.h" -#include "..\GameSession\GameSessionManager.h" -#include "..\GameSession\GameSession.h" -#include "..\Helpers\ServerDataReader.h" -#include "..\LobbySessions\LobbyClient.h" -#include "..\LobbySessions\NetworkSession.h" -#include "..\LobbySessions\GameLobby.h" -#include "..\LobbySessions\MainLobby.h" - -using namespace Oyster::Network; -using namespace Oyster::Thread; -using namespace DanBias; - -struct AdminInstanceData :public IThreadObject -{ - bool isCreated; - Oyster::Network::NetworkServer adminServer; - NetworkClient* admin; - NetworkSession* parentInstance; - OysterThread worker; - - bool DoWork() override - { - //((GameServer*)parentInstance)->serve - return true; - } - -}adminInstanceData; - -void AdminArrived(NetworkClient* adm) -{ - if(adminInstanceData.admin) - { - delete adm; - return; - } - - adminInstanceData.admin = adm; - adminInstanceData.worker.Create(&adminInstanceData, true, true); -} - -void AdminInterface::Toggle(bool toggle, NetworkSession* parent) -{ - if(toggle) - { - if(!parent) return; - - if(adminInstanceData.isCreated) return; - - NetworkServer::INIT_DESC desc; - desc.port = 15152; - desc.callbackType = NetworkClientCallbackType_Function; - desc.recvObj.clientConnectFnc = AdminArrived; - - if(!adminInstanceData.adminServer.Init(desc)) return; - adminInstanceData.parentInstance = parent; - - adminInstanceData.adminServer.Start(); - } - else - { - adminInstanceData.adminServer.Shutdown(); - } -} \ No newline at end of file diff --git a/Code/Game/DanBiasServer/AdminInterface/AdminInterface.h b/Code/Game/DanBiasServer/AdminInterface/AdminInterface.h deleted file mode 100644 index 4acc20a2..00000000 --- a/Code/Game/DanBiasServer/AdminInterface/AdminInterface.h +++ /dev/null @@ -1,20 +0,0 @@ -///////////////////////////////////////// -// Created by [Dennis Andersen] [2013] // -///////////////////////////////////////// -#ifndef DANBIASSERVER_ADMIN_INTERFACE_H -#define DANBIASSERVER_ADMIN_INTERFACE_H - -#include - -namespace DanBias -{ - class NetworkSession; - //Global admin - class AdminInterface - { - public: - static void Toggle(bool toggle, NetworkSession* parent); - - }; -} -#endif // !DANBIASSERVER_ADMIN_INTERFACE_H diff --git a/Code/Game/DanBiasServer/DanBiasServerAPI.cpp b/Code/Game/DanBiasServer/DanBiasServerAPI.cpp deleted file mode 100644 index dfaf0b75..00000000 --- a/Code/Game/DanBiasServer/DanBiasServerAPI.cpp +++ /dev/null @@ -1,28 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// -#include "DanBiasServerAPI.h" -#include "GameServer.h" - -namespace DanBias -{ - -#pragma region Server Data - static GameServer server; -#pragma endregion - - - DanBiasServerReturn DanBiasServerAPI::Initiate() - { - return server.Create(); - } - DanBiasServerReturn DanBiasServerAPI::Run() - { - return server.Run(); - } - DanBiasServerReturn DanBiasServerAPI::Release() - { - return server.Release(); - } - -} //End namspace DanBias \ No newline at end of file diff --git a/Code/Game/DanBiasServer/DanBiasServerAPI.h b/Code/Game/DanBiasServer/DanBiasServerAPI.h deleted file mode 100644 index 1d514053..00000000 --- a/Code/Game/DanBiasServer/DanBiasServerAPI.h +++ /dev/null @@ -1,37 +0,0 @@ -///////////////////////////////////////// -// Created by [Dennis Andersen] [2013] // -///////////////////////////////////////// -#ifndef DANBIAS_SERVER_DANBIAS_SERVER_H -#define DANBIAS_SERVER_DANBIAS_SERVER_H - -#include - -#define DANBIAS_SERVER - -#ifdef DANBIAS_SERVER_DLL_EXPORT - #define DANBIAS_SERVER_DLL __declspec(dllexport) -#else - #define DANBIAS_SERVER_DLL __declspec(dllimport) -#endif - -namespace DanBias -{ - enum DanBiasServerReturn - { - DanBiasServerReturn_Error, - DanBiasServerReturn_Sucess, - }; - - extern "C" - { - class DANBIAS_SERVER_DLL DanBiasServerAPI - { - public: - static DanBiasServerReturn Initiate(); - static DanBiasServerReturn Run(); - static DanBiasServerReturn Release(); - };//End class DanBiasServer - }//End Extern "C" -} //End namspace DanBias - -#endif // !DANBIAS_SERVER_DANBIAS_SERVER_H diff --git a/Code/Game/DanBiasServer/GameServer.cpp b/Code/Game/DanBiasServer/GameServer.cpp deleted file mode 100644 index 1da2b5ba..00000000 --- a/Code/Game/DanBiasServer/GameServer.cpp +++ /dev/null @@ -1,161 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// -#define NOMINMAX -#include -#include -#include - -#include "GameServer.h" -#include "Helpers\ServerDataReader.h" -#include "GameSession\GameSessionManager.h" -#include "LobbySessions\LobbyClient.h" -#include "GameSession\GameSession.h" -#include "AdminInterface\AdminInterface.h" - -#include -#include - -#include - -namespace DanBias -{ - using namespace Oyster::Network; - - GameServer* GameServer::instance = 0; - - void GameServer::NetworkCallback(NetworkClient* client) - { - static bool myTest = false; - static int sessionId = -1; - printf("Client with ID [%i] connected.\n", client->GetID()); - - if(!myTest) - { - Utility::DynamicMemory::SmartPointer c = new LobbyClient(client); - - GameSessionDescription desc; - desc.mapName = L"test"; - desc.clients.Push(c); - desc.exitDestionation = this->mainLobby; - if((sessionId = GameSessionManager::AddSession(desc, true)) == 0) - printf("Failed to create a game session\n"); - myTest = true; - //myTest = new GameSession(); - // - //DanBias::GameSession::GameSessionDescription desc; - //desc.owner = 0; - //desc.clients.Push(c); - // - //if(!myTest->Create(desc)) return; - //myTest->Run(); - } - else - { - Utility::DynamicMemory::SmartPointer c = new LobbyClient(client); - GameSessionManager::JoinSession(sessionId, c); - } - - - //Utility::DynamicMemory::SmartPointer c = new LobbyClient(client); - //this->mainLobby->Attach(c, this->mainLobby->GetPostbox()); - } - - - GameServer::GameServer() - : initiated(0) - , running(0) - , released(0) - , maxClients(0) - , mainLobby(0) - , server(0) - { this->instance = this; } - GameServer::~GameServer() - { - - } - DanBiasServerReturn GameServer::Create() - { - this->server = new NetworkServer(); - this->mainLobby = new MainLobby(); - - InitData data; - if(!LoadIniFile(data)) return DanBiasServerReturn_Error; - - NetworkServer::INIT_DESC serverDesc; - this->maxClients = data.clients; - serverDesc.port = data.port; - serverDesc.recvObj = this; - serverDesc.callbackType = Oyster::Network::NetworkClientCallbackType_Object; - - if(!this->server->Init(serverDesc)) return DanBiasServerReturn_Error; - if(!WindowShell::CreateConsoleWindow()) return DanBiasServerReturn_Error; - - this->initiated = true; - return DanBiasServerReturn_Sucess; - } - DanBiasServerReturn GameServer::Run() - { - if(this->running) return DanBiasServerReturn_Error; - if(this->released) return DanBiasServerReturn_Error; - if(!this->initiated) return DanBiasServerReturn_Error; - - if(!this->server->Start()) return DanBiasServerReturn_Error; - //Oyster::Thread::OysterThread ioThread; - //ioThread.Create(this, true, - - while (true) - { - if(!WindowShell::Frame()) break; - - this->mainLobby->Frame(); - - if(GetAsyncKeyState(0x51)) //Q for exit - break; - } - - return DanBiasServerReturn_Sucess; - } - DanBiasServerReturn GameServer::Release() - { - GameSessionManager::CloseSession(); - this->mainLobby->Release(); - delete this->mainLobby; - this->server->Shutdown(); - delete this->server; - this->released = true; - return DanBiasServerReturn_Sucess; - } - - NetworkSession* GameServer::MainLobbyInstance() - { - return GameServer::instance->mainLobby; - } - - bool GameServer::LoadIniFile(InitData& ini) - { - std::ifstream in; - std::string f = GetInitPath(InitPath_ServerIni); - in.open(f, std::ios::in); - if(!in.is_open()) return false; - - std::string buffer; - while (!in.eof()) - { - in >> buffer; - - if(buffer == "port") - { - in >> ini.port; - } - else if(buffer == "clients") - { - in >> ini.clients; - } - - } - - in.close(); - return true; - } -}//End namespace DanBias diff --git a/Code/Game/DanBiasServer/GameServer.h b/Code/Game/DanBiasServer/GameServer.h deleted file mode 100644 index ccdb6e05..00000000 --- a/Code/Game/DanBiasServer/GameServer.h +++ /dev/null @@ -1,50 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// -#ifndef DANBIASSERVER_GAME_SERVER_H -#define DANBIASSERVER_GAME_SERVER_H - -#include "DanBiasServerAPI.h" -#include "LobbySessions\MainLobby.h" -#include -#include - -namespace DanBias -{ - class GameServer :public Oyster::Network::ClientConnectedObject - { - public: - GameServer(); - virtual~GameServer(); - - DanBiasServerReturn Create(); - DanBiasServerReturn Run(); - DanBiasServerReturn Release(); - - static NetworkSession* MainLobbyInstance(); - - private: - //static void ClientConnectCallbackFunction(Oyster::Network::NetworkClient& connectedClient); - void NetworkCallback(Oyster::Network::NetworkClient* client) override; - - bool initiated; - bool running; - bool released; - int maxClients; - MainLobby *mainLobby; - Oyster::Network::NetworkServer *server; - static GameServer* instance; - - private: - struct InitData - { - int port; - int clients; - }; - bool LoadIniFile(InitData&); - - private: - friend class AdminInterface; - }; -}// End namspace DanBias -#endif // !DANBIASSERVER_DBSERVER_H diff --git a/Code/Game/DanBiasServer/GameSession/GameClient.cpp b/Code/Game/DanBiasServer/GameSession/GameClient.cpp deleted file mode 100644 index 23f0f3e2..00000000 --- a/Code/Game/DanBiasServer/GameSession/GameClient.cpp +++ /dev/null @@ -1,67 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// - -#include "GameClient.h" -#include "..\LobbySessions\NetworkSession.h" -#include - -using namespace Utility::DynamicMemory; -using namespace DanBias; -using namespace GameLogic; - -static int gameClientIDCount = 1; - -GameClient::GameClient(SmartPointer client, IPlayerData* player, Oyster::Callback::OysterCallback value) -{ - this->callbackValue = value; - this->client = client; - this->id = gameClientIDCount++; - this->player = player; - Oyster::Callback::OysterCallback c; - c.callbackType = Oyster::Callback::CallbackType_Object; - c.value = this; - this->client->SetCallback(c); - -} -GameClient::~GameClient() -{ - if(this->client) this->client->Disconnect(); - this->player = 0; - this->id = -1; -} - -void GameClient::SetCallback(Oyster::Callback::OysterCallback value) -{ - this->callbackValue = value; -} - -GameLogic::IPlayerData* GameClient::GetPlayer() -{ - return this->player; -} -GameLogic::IPlayerData* GameClient::ReleasePlayer() -{ - GameLogic::IPlayerData *temp = this->player; - this->player = 0; - return temp; -} -LobbyClient* GameClient::GetClient() const -{ - return this->client; -} -Utility::DynamicMemory::SmartPointer GameClient::ReleaseClient() -{ - SmartPointer temp = this->client; - this->client = 0; - return temp; -} -int GameClient::GetID() const -{ - return this->id; -} -void GameClient::ObjectCallback(NetworkSession::NetEvent e) -{ - e.gameClient = this; - this->callbackValue(e); -} diff --git a/Code/Game/DanBiasServer/GameSession/GameClient.h b/Code/Game/DanBiasServer/GameSession/GameClient.h deleted file mode 100644 index 0a74479a..00000000 --- a/Code/Game/DanBiasServer/GameSession/GameClient.h +++ /dev/null @@ -1,43 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// -#ifndef DANBIASSERVER_CLIENT_OBJECT_H -#define DANBIASSERVER_CLIENT_OBJECT_H - -#include "..\LobbySessions\LobbyClient.h" -#include -#include - -namespace DanBias -{ - class GameClient: Oyster::Callback::CallbackObject - { - public: - GameClient(Utility::DynamicMemory::SmartPointer client, GameLogic::IPlayerData* player, Oyster::Callback::OysterCallback value); - virtual~GameClient(); - - void SetCallback(Oyster::Callback::OysterCallback value); - - /* */ - GameLogic::IPlayerData* GetPlayer(); - - GameLogic::IPlayerData* ReleasePlayer(); - - LobbyClient* GetClient() const; - Utility::DynamicMemory::SmartPointer ReleaseClient(); - int GetID() const; - - private: - //Utility::DynamicMemory::SmartPointer player; - GameLogic::IPlayerData* player; - Utility::DynamicMemory::SmartPointer client; - Oyster::Callback::OysterCallback callbackValue; - int id; - void ObjectCallback(NetworkSession::NetEvent) override; - - private: - friend class AdminInterface; - }; - -}//End namespace DanBias -#endif // !DANBIASSERVER_CLIENT_OBJECT_H diff --git a/Code/Game/DanBiasServer/GameSession/GameSession.h b/Code/Game/DanBiasServer/GameSession/GameSession.h index aee9b29d..b2145c19 100644 --- a/Code/Game/DanBiasServer/GameSession/GameSession.h +++ b/Code/Game/DanBiasServer/GameSession/GameSession.h @@ -30,7 +30,7 @@ namespace DanBias NetworkSession* owner; Utility::DynamicMemory::DynamicArray> clients; }; - + static GameSession* gameSession; public: GameSession(); virtual~GameSession(); diff --git a/Code/Game/DanBiasServer/GameSession/GameSessionManager.cpp b/Code/Game/DanBiasServer/GameSession/GameSessionManager.cpp deleted file mode 100644 index 23dadb65..00000000 --- a/Code/Game/DanBiasServer/GameSession/GameSessionManager.cpp +++ /dev/null @@ -1,123 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// -#include "GameSessionManager.h" - -#include "..\LobbySessions\LobbyClient.h" -#include "GameSession.h" -#include - -using namespace DanBias; -using namespace Utility::DynamicMemory; - -struct GameSessionData -{ - DynamicArray< SmartPointer< GameSession > > sessions; - - int freeSpot; - - int Existst(int session) - { - for (unsigned int i = 0; i < sessions.Size(); i++) - { - if(!sessions[i] && freeSpot == -1) freeSpot = i; - if(sessions[i]->GetID() == session) return i; - } - return -1; - } - int GetFree() - { - for (unsigned int i = 0; i < sessions.Size(); i++) - { - if(!sessions[i]) - { - this->freeSpot = i; - return this->freeSpot; - } - } - - this->freeSpot = -1; - return this->freeSpot; - } - -} gameSessionData; - - -int GameSessionManager::AddSession(GameSessionDescription& instance, bool run) -{ - int k = gameSessionData.GetFree(); - - SmartPointer gs = new GameSession(); - - DanBias::GameSession::GameDescription desc; - desc.owner = instance.exitDestionation; - desc.clients = instance.clients; - desc.mapName = instance.mapName; - - - if(!gs->Create(desc)) return 0; - - if(k == -1) gameSessionData.sessions.Push(gs); - else gameSessionData.sessions[k] = gs; - - if(run) gs->Run(); - - return gs->GetID(); -} - -bool GameSessionManager::StartSession(int session) -{ - int i = -1; - if((i = gameSessionData.Existst(session)) != -1) return false; - - gameSessionData.sessions[i]->Run(); - - return true; -} - -bool GameSessionManager::JoinSession(int session, Utility::DynamicMemory::SmartPointer client) -{ - int i = -1; - if((i = gameSessionData.Existst(session)) == -1) return false; - - gameSessionData.sessions[i]->Join(client); - - return true; -} - -void GameSessionManager::GetSessionInfo(int session, GameSessionInfo& data) -{ - memset(&data, 0, sizeof(GameSessionInfo)); - - int i = -1; - if((i = gameSessionData.Existst(session)) != -1) return; - - //data.gametime = gameSessionData.sessions[i]-> - //data.mapName = gameSessionData.sessions[i]-> - //data.numberOfPlayers = gameSessionData.sessions[i]-> -} - -void GameSessionManager::CloseSession() -{ - for (unsigned int i = 0; i < gameSessionData.sessions.Size(); i++) - { - gameSessionData.sessions[i]->CloseSession(); - } -} -void GameSessionManager::CloseSession(int session) -{ - int i = -1; - if((i = gameSessionData.Existst(session)) != -1) return; - - - gameSessionData.sessions[i]->CloseSession(); -} - -int GameSessionManager::GetSessionSize() -{ - return gameSessionData.sessions.Size(); -} - - - - diff --git a/Code/Game/DanBiasServer/GameSession/GameSessionManager.h b/Code/Game/DanBiasServer/GameSession/GameSessionManager.h deleted file mode 100644 index 75b0e64d..00000000 --- a/Code/Game/DanBiasServer/GameSession/GameSessionManager.h +++ /dev/null @@ -1,82 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// -#ifndef DANBIASSERVER_GAME_SEESION_MANAGER_H -#define DANBIASSERVER_GAME_SEESION_MANAGER_H - -#include -#include -#include - -namespace DanBias -{ - class LobbyClient; - class NetworkSession; - - struct GameSessionDescription - { - std::wstring mapName; - Utility::DynamicMemory::DynamicArray> clients; - NetworkSession* exitDestionation; //The new owner when session dies - }; - struct GameSessionInfo - { - std::wstring mapName; - unsigned int numberOfPlayers; - float gametime; - }; - - class GameSessionManager - { - public: - /** - * Add a new game session. - * On success, the function returns the game instance id number greater than 0. - */ - static int AddSession(GameSessionDescription& instance, bool run); - - /** - * Starts an existing game session - * @param session The session id recieved when created. - * @param run Indicates if the game session should start imidiatly when created. - * @return Returns false if session is not found. - */ - static bool StartSession(int session); - - /** - * Join an exiting session - * @param session The session id recieved when created. - * @param client The client that is to join a game session - * @return Returns false on failure. - */ - static bool JoinSession(int session, Utility::DynamicMemory::SmartPointer client); - - /** - * Gets information about a given session - * @param session The session id recieved when created. - * @param sessionInformation The output parameter that will be filled. - */ - static void GetSessionInfo(int session, GameSessionInfo& sessionInformation); - - /** - * Close a session. - * @param session The session id recieved when created a session. - */ - static void CloseSession(int session); - - /** - * Close all sessions. - */ - static void CloseSession(); - - /** - * Get total sessions running - * @return Returns the total sessions curently running. - */ - static int GetSessionSize(); - - private: - friend class AdminInterface; - }; -} -#endif // !DANBIASSERVER_GAME_SEESION_MANAGER_H diff --git a/Code/Game/DanBiasServer/GameSession/GameSession_Events.cpp b/Code/Game/DanBiasServer/GameSession/GameSession_Events.cpp index 164e5748..8306e138 100644 --- a/Code/Game/DanBiasServer/GameSession/GameSession_Events.cpp +++ b/Code/Game/DanBiasServer/GameSession/GameSession_Events.cpp @@ -11,7 +11,6 @@ #include - using namespace Utility::DynamicMemory; using namespace Oyster; using namespace Oyster::Network; @@ -42,35 +41,41 @@ namespace DanBias { switch (p[protocol_INDEX_ID].value.netShort) { - case protocol_Gameplay_PlayerNavigation: + case protocol_Gameplay_PlayerMovement: { - - //Oyster::Math::Float4x4 world = Oyster::Math::Matrix::identity; if(p[1].value.netBool) //bool bForward; - //world.v[3].x = 2; c->GetPlayer()->Move(GameLogic::PLAYER_MOVEMENT_FORWARD); if(p[2].value.netBool) //bool bBackward; - //world.v[3].x = -2; c->GetPlayer()->Move(GameLogic::PLAYER_MOVEMENT_BACKWARD); - if(p[5].value.netBool) //bool bStrafeRight; - //world.v[3].y = 2; - c->GetPlayer()->Move(GameLogic::PLAYER_MOVEMENT_RIGHT); - if(p[6].value.netBool) //bool bStrafeLeft; - //world.v[3].y = -2; + if(p[3].value.netBool) //bool bStrafeLeft; c->GetPlayer()->Move(GameLogic::PLAYER_MOVEMENT_LEFT); + if(p[4].value.netBool) //bool bStrafeRight; + c->GetPlayer()->Move(GameLogic::PLAYER_MOVEMENT_RIGHT); } break; - case protocol_Gameplay_PlayerMouseMovement: + case protocol_Gameplay_PlayerLookDir: + { + Protocol_PlayerLook m; m = p; + Oyster::Math3D::Float3 lookDir; + lookDir.x = p.Get(1).value.netFloat; + lookDir.y = p.Get(2).value.netFloat; + lookDir.z = p.Get(3).value.netFloat; + c->GetPlayer()->Rotate(lookDir); + } + break; + case protocol_Gameplay_PlayerChangeWeapon: break; - case protocol_Gameplay_PlayerPosition: - - break; - case protocol_Gameplay_CreateObject: - - break; - case protocol_Gameplay_ObjectPosition: - + case protocol_Gameplay_PlayerShot: + if (p[1].value.netBool) + c->GetPlayer()->UseWeapon(GameLogic::WEAPON_USE_PRIMARY_PRESS); + break; + case protocol_Gameplay_PlayerJump: + if (p[1].value.netBool) + c->GetPlayer()->Move(GameLogic::PLAYER_MOVEMENT_JUMP); + break; + case protocol_Gameplay_ObjectDamage: + break; } } @@ -82,10 +87,6 @@ namespace DanBias case protocol_General_Status: switch (p[1].value.netInt) { - case GameLogic::Protocol_General_Status::States_bussy: - - break; - case GameLogic::Protocol_General_Status::States_disconected: printf("Client with ID [%i] dissconnected\n", c->GetClient()->GetID()); this->RemoveClient(c); @@ -98,23 +99,58 @@ namespace DanBias case GameLogic::Protocol_General_Status::States_ready: break; + + case GameLogic::Protocol_General_Status::States_leave: + + break; } break; - case protocol_General_Text: - + { + GameLogic::Protocol_General_Text temp(p); + printf("Message recieved from (%i):\t %s\n", c->GetID(), temp.text.c_str()); + } break; + } } void GameSession::ObjectMove(GameLogic::IObjectData* movedObject) { - //if (movedObject->) - //{ - // - //} - //movedObject->GetOrientation(); + GameLogic::IObjectData* obj = NULL; + if(dynamic_cast(movedObject)) + { + obj =((GameLogic::ILevelData*)movedObject)->GetObjectAt(0); + if(obj) + { + if(obj->GetType() == OBJECT_TYPE_WORLD) + { + obj->GetID(); + Oyster::Math::Float4x4 world =obj->GetOrientation(); + Oyster::Math3D::Float4x4 scale = Oyster::Math3D::Float4x4::identity; + scale.v[0].x = 8; + scale.v[1].y = 8; + scale.v[2].z = 8; + //world = world * scale; + Protocol_ObjectPosition p(world, 0); + GameSession::gameSession->Send(p.GetProtocol()); + } + } + obj = NULL; + obj =((GameLogic::ILevelData*)movedObject)->GetObjectAt(1); + if(obj) + { + if(obj->GetType() == OBJECT_TYPE_BOX) + { + obj->GetID(); + Oyster::Math::Float4x4 world = obj->GetOrientation(); + Protocol_ObjectPosition p(world, 1); + GameSession::gameSession->Send(p.GetProtocol()); + } + } + } + } }//End namespace DanBias diff --git a/Code/Game/DanBiasServer/GameSession/GameSession_Logic.cpp b/Code/Game/DanBiasServer/GameSession/GameSession_Logic.cpp index a0010f1f..6d72ff57 100644 --- a/Code/Game/DanBiasServer/GameSession/GameSession_Logic.cpp +++ b/Code/Game/DanBiasServer/GameSession/GameSession_Logic.cpp @@ -24,24 +24,11 @@ using namespace GameLogic; namespace DanBias { + bool GameSession::DoWork( ) { if(this->isRunning) { - if(GetAsyncKeyState(VK_UP)) - { - Protocol_General_Status p(Protocol_General_Status::States_ready); - Send(p.GetProtocol()); - Sleep(100); - } - if(GetAsyncKeyState(VK_DOWN)) - { - Oyster::Math::Float4x4 world = Oyster::Math::Matrix::identity; - Protocol_CreateObject p(world, 2, "../Content/crate"); - Send(p.GetProtocol()); - Sleep(100); - } - double dt = this->timer.getElapsedSeconds(); gameInstance.SetFrameTimeLength((float)dt); @@ -65,9 +52,8 @@ namespace DanBias if(clients.Size() >= 1 && clients[0]) { Oyster::Math::Float4x4 world = this->clients[0]->GetPlayer()->GetOrientation(); - Protocol_ObjectPosition p(world, 1); + Protocol_ObjectPosition p(world, 2); Send(p.GetProtocol()); - //Sleep(100); } } diff --git a/Code/Game/DanBiasServer/GameSession/GameSession_Network.cpp b/Code/Game/DanBiasServer/GameSession/GameSession_Network.cpp deleted file mode 100644 index 729ef417..00000000 --- a/Code/Game/DanBiasServer/GameSession/GameSession_Network.cpp +++ /dev/null @@ -1,29 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// -#include "GameSession.h" -#include "GameClient.h" - -#include -#include -#include -#include - -using namespace Utility::DynamicMemory; -using namespace Oyster; -using namespace Oyster::Network; -using namespace Oyster::Thread; -using namespace GameLogic; - -namespace DanBias -{ - void GameSession::Send(Oyster::Network::CustomNetProtocol* p) - { - for (unsigned int i = 0; i < this->clients.Size(); i++) - { - if(this->clients[i] && this->clients[i]->GetClient()) - this->clients[i]->GetClient()->Send(p); - } - } -}//End namespace DanBias - diff --git a/Code/Game/DanBiasServer/Helpers/MapManager.h b/Code/Game/DanBiasServer/Helpers/MapManager.h deleted file mode 100644 index 49342a56..00000000 --- a/Code/Game/DanBiasServer/Helpers/MapManager.h +++ /dev/null @@ -1,30 +0,0 @@ -///////////////////////////////////////// -// Created by [Dennis Andersen] [2013] // -///////////////////////////////////////// -#ifndef DANBIASSERVER_LEVELMANAGER_H -#define DANBIASSERVER_LEVELMANAGER_H - -#include "ServerDataReader.h" -#include "..\LobbySessions\LobbyClient.h" -#include "..\LobbySessions\NetworkSession.h" -#include "..\LobbySessions\GameLobby.h" -#include - -namespace DanBias -{ - class MapManager - { - public: - struct MapInitDesc - { - const wchar_t* map; - Utility::DynamicMemory::DynamicArray> clients; - }; - - public: - static bool InitiateMapPack(const MapInitDesc& desc); - - }; -} - -#endif // !DANBIASSERVER_LEVELMANAGER_H diff --git a/Code/Game/DanBiasServer/Helpers/ServerDataReader.h b/Code/Game/DanBiasServer/Helpers/ServerDataReader.h deleted file mode 100644 index 73048bd7..00000000 --- a/Code/Game/DanBiasServer/Helpers/ServerDataReader.h +++ /dev/null @@ -1,44 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// -#ifndef DANBIASSERVER_SERVER_INIT_READER_H -#define DANBIASSERVER_SERVER_INIT_READER_H - -#include -#include - -namespace DanBias -{ - enum InitPath - { - InitPath_ServerIni, - }; - static std::string GetInitPath(InitPath file) - { - std::string type = ""; - std::string path = ""; - std::string flag = ""; - - switch (file) - { - case DanBias::InitPath_ServerIni: - flag = "ServerInit"; - break; - } - - std::fstream in; - in.open("..\\Settings\\serversearchpath.ini", std::ios::in); - if(!in.is_open()) return ""; - - while (!in.eof() && type != flag) - { - in >> type; - in >> path; - } - - in.close(); - return path; - } -} - -#endif // !DANBIASSERVER_SERVER_INIT_READER_H diff --git a/Code/Game/DanBiasServer/LobbySessions/GameLobby.cpp b/Code/Game/DanBiasServer/LobbySessions/GameLobby.cpp deleted file mode 100644 index fc770db8..00000000 --- a/Code/Game/DanBiasServer/LobbySessions/GameLobby.cpp +++ /dev/null @@ -1,21 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// -#include "GameLobby.h" - - -namespace DanBias -{ - GameLobby::GameLobby(Utility::DynamicMemory::SmartPointer owner) - { - - } - GameLobby::~GameLobby() - { - - } - void GameLobby::Release() - { - - } -}//End namespace DanBias \ No newline at end of file diff --git a/Code/Game/DanBiasServer/LobbySessions/GameLobby.h b/Code/Game/DanBiasServer/LobbySessions/GameLobby.h deleted file mode 100644 index b6c6d4f9..00000000 --- a/Code/Game/DanBiasServer/LobbySessions/GameLobby.h +++ /dev/null @@ -1,24 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// -#ifndef DANBIASSERVER_GAMELOBBY_H -#define DANBIASSERVER_GAMELOBBY_H - -#include "NetworkSession.h" - -namespace DanBias -{ - class GameLobby :public NetworkSession - { - public: - GameLobby(Utility::DynamicMemory::SmartPointer owner); - virtual~GameLobby(); - - void Release(); - - private: - friend class AdminInterface; - }; -}//End namespace DanBias - -#endif // !DANBIASSERVER_GAME_LOBBY_H \ No newline at end of file diff --git a/Code/Game/DanBiasServer/LobbySessions/INetworkSession.cpp b/Code/Game/DanBiasServer/LobbySessions/INetworkSession.cpp deleted file mode 100644 index 899e1d53..00000000 --- a/Code/Game/DanBiasServer/LobbySessions/INetworkSession.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "INetworkSession.h" -#include - -INetworkSession::INetworkSession() - :id(GID()) -{} -INetworkSession::INetworkSession(const INetworkSession& orig) -{ - id = orig.id; -} -const INetworkSession& INetworkSession::operator=(const INetworkSession& orig) -{ - id = orig.id; - return *this; -} -INetworkSession::~INetworkSession() -{} - diff --git a/Code/Game/DanBiasServer/LobbySessions/INetworkSession.h b/Code/Game/DanBiasServer/LobbySessions/INetworkSession.h deleted file mode 100644 index dfad66ae..00000000 --- a/Code/Game/DanBiasServer/LobbySessions/INetworkSession.h +++ /dev/null @@ -1,22 +0,0 @@ -///////////////////////////////////////// -// Created by [Dennis Andersen] [2013] // -///////////////////////////////////////// -#ifndef DANBIASSERVER_INETWORKSESSION_H -#define DANBIASSERVER_INETWORKSESSION_H - -class INetworkSession -{ -public: - INetworkSession(); - INetworkSession(const INetworkSession& orig); - const INetworkSession& operator=(const INetworkSession& orig); - virtual~INetworkSession(); - - inline int GetID() const { return this->id; } - -private: - int id; - -}; - -#endif // !DANBIASSERVER_INETWORKSESSION_H diff --git a/Code/Game/DanBiasServer/LobbySessions/LobbyClient.cpp b/Code/Game/DanBiasServer/LobbySessions/LobbyClient.cpp deleted file mode 100644 index 95f18e68..00000000 --- a/Code/Game/DanBiasServer/LobbySessions/LobbyClient.cpp +++ /dev/null @@ -1,51 +0,0 @@ -#include "LobbyClient.h" -#include - -using namespace Utility::DynamicMemory; -using namespace Oyster::Network; -using namespace Oyster::Callback; -using namespace GameLogic; - -namespace DanBias -{ - LobbyClient::LobbyClient(SmartPointer client) - { - this->client = client; - this->client->SetRecieverObject(this, NetworkProtocolCallbackType_Object); - } - LobbyClient::~LobbyClient() - { - this->callbackValue.callbackType = CallbackType_Unknown; - } - - void LobbyClient::Disconnect() - { - this->client->Disconnect(); - } - void LobbyClient::SetCallback(OysterCallback value) - { - this->callbackValue = value; - } - - /** This method is NOT threadsafe. */ - void LobbyClient::NetworkCallback(CustomNetProtocol& protocol) - { - if(this->callbackValue.callbackType == CallbackType_Unknown) return; - - NetworkSession::NetEvent e; - e.sender = this; - e.protocol = protocol; - - this->callbackValue(e); - } - void LobbyClient::Disconnected() - { - if(this->callbackValue.callbackType == CallbackType_Unknown) return; - - NetworkSession::NetEvent e; - e.sender = this; - e.protocol = *GameLogic::Protocol_General_Status(Protocol_General_Status::States_disconected).GetProtocol(); - - this->callbackValue(e); - } -}//End namsapce DanBias \ No newline at end of file diff --git a/Code/Game/DanBiasServer/LobbySessions/LobbyClient.h b/Code/Game/DanBiasServer/LobbySessions/LobbyClient.h deleted file mode 100644 index 33b99d78..00000000 --- a/Code/Game/DanBiasServer/LobbySessions/LobbyClient.h +++ /dev/null @@ -1,38 +0,0 @@ -///////////////////////////////////////// -// Created by [Dennis Andersen] [2013] // -///////////////////////////////////////// -#ifndef DANBIASSERVER_LOBBYCLIENT_H -#define DANBIASSERVER_LOBBYCLIENT_H - -#include "NetworkSession.h" -#include -#include - -namespace DanBias -{ - class LobbyClient :public Oyster::Network::NetClientEvent - { - public: - LobbyClient(Utility::DynamicMemory::SmartPointer client); - virtual~LobbyClient(); - - void Disconnect(); - void SetCallback(Oyster::Callback::OysterCallback value); - - inline void Send(Oyster::Network::CustomProtocolObject& protocol) { this->client->Send(protocol); } - inline void Send(Oyster::Network::CustomNetProtocol* protocol) { this->client->Send(protocol); } - inline int GetID() const { return this->client->GetID(); } - - private: - Utility::DynamicMemory::SmartPointer client; - Oyster::Callback::OysterCallback callbackValue; - - private: - void NetworkCallback(Oyster::Network::CustomNetProtocol& protocol) override; - void Disconnected() override; - - private: - friend class AdminInterface; - }; -}//End namspace DanBias -#endif // !DANBIASSERVER_LOBBYCLIENT_H diff --git a/Code/Game/DanBiasServer/LobbySessions/MainLobby.cpp b/Code/Game/DanBiasServer/LobbySessions/MainLobby.cpp deleted file mode 100644 index 9b8899ca..00000000 --- a/Code/Game/DanBiasServer/LobbySessions/MainLobby.cpp +++ /dev/null @@ -1,110 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// -#include "MainLobby.h" -#include "LobbyClient.h" -#include -#include - -using namespace Utility::DynamicMemory; -using namespace Oyster::Network; -using namespace Oyster; - -namespace DanBias -{ - MainLobby::MainLobby() - :gameLobby(5) - { - this->box = new PostBox(); - } - MainLobby::~MainLobby() - { - - } - void MainLobby::Release() - { - delete this->box; - this->box = 0; - this->CloseSession(true); - } - - void MainLobby::Frame() - { - ParseEvents(); - } - IPostBox* MainLobby::GetPostbox() - { - return this->box; - } - -//////// Private - void MainLobby::ParseEvents() - { - if(this->box && !this->box->IsEmpty()) - { - NetEvent &e = this->box->Fetch(); - - ParseProtocol(e.protocol, e.sender); - - } - } - void MainLobby::ParseProtocol(Oyster::Network::CustomNetProtocol& p, DanBias::LobbyClient* c) - { - bool update = false; - switch (p[0].value.netShort) - { - case protocol_Lobby_CreateGame: - { - GameLogic::Protocol_LobbyCreateGame val(p); - CreateGame(val, c); - update = true; - } - break; - case protocol_Lobby_JoinLobby: - { - GameLogic::Protocol_LobbyJoinLobby val(p); - JoinLobby(val, c); - } - break; - case protocol_Lobby_LeaveLobby: - { - Detach(c)->Disconnect(); - } - break; - } - - if(update) SendUpdate(); - } - - void MainLobby::CreateGame(GameLogic::Protocol_LobbyCreateGame& p, DanBias::LobbyClient* c) - { - for (unsigned int i = 0; i < this->gameLobby.Size(); i++) - { - if(!gameLobby[i]) - { - gameLobby[i] = new GameLobby(NetworkSession::Detach(c)); - return; - } - } - - this->gameLobby.Push(new GameLobby(NetworkSession::Detach(c))); - } - void MainLobby::JoinLobby(GameLogic::Protocol_LobbyJoinLobby& p, DanBias::LobbyClient* c) - { - for (unsigned int i = 0; i < this->gameLobby.Size(); i++) - { - if (this->gameLobby[i]->GetID() == p.LobbyID) - { - this->gameLobby[i]->Attach(Detach(c)); - return; - } - } - } - - void MainLobby::SendUpdate() - { - //Send Lobbys - GameLogic::Protocol_LobbyUpdate(); - } - -}//End namespace DanBias \ No newline at end of file diff --git a/Code/Game/DanBiasServer/LobbySessions/MainLobby.h b/Code/Game/DanBiasServer/LobbySessions/MainLobby.h deleted file mode 100644 index a28d90e9..00000000 --- a/Code/Game/DanBiasServer/LobbySessions/MainLobby.h +++ /dev/null @@ -1,42 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// -#ifndef DANBIASSERVER_MAINLOBBY_H -#define DANBIASSERVER_MAINLOBBY_H - -#include "NetworkSession.h" -#include "GameLobby.h" -#include -#include - -namespace DanBias -{ - class MainLobby :public NetworkSession - { - public: - MainLobby(); - virtual~MainLobby(); - void Release(); - - void Frame(); - - Oyster::IPostBox* GetPostbox(); - - private: - void ParseEvents(); - void ParseProtocol(Oyster::Network::CustomNetProtocol& p, DanBias::LobbyClient* c); - - void CreateGame(GameLogic::Protocol_LobbyCreateGame& p, DanBias::LobbyClient* c); - void JoinLobby(GameLogic::Protocol_LobbyJoinLobby& p, DanBias::LobbyClient* c); - - void SendUpdate(); - - private: - Oyster::IPostBox *box; - Utility::DynamicMemory::DynamicArray> gameLobby; - - private: - friend class AdminInterface; - }; -}//End namespace DanBias -#endif // !DANBIASGAME_GAMELOBBY_H diff --git a/Code/Game/DanBiasServer/LobbySessions/NetworkSession.cpp b/Code/Game/DanBiasServer/LobbySessions/NetworkSession.cpp deleted file mode 100644 index 0eecf59a..00000000 --- a/Code/Game/DanBiasServer/LobbySessions/NetworkSession.cpp +++ /dev/null @@ -1,219 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// -#include "LobbyClient.h" -#include "NetworkSession.h" -#include - - - -namespace DanBias -{ - NetworkSession::NetworkSession() - : owner(0) - , clientCount(0) - {} - NetworkSession::NetworkSession(const NetworkSession& orig) - { - this->clients = orig.clients; - this->owner = orig.owner; - this->clientCount = orig.clientCount; - } - const NetworkSession& NetworkSession::operator=(const NetworkSession& orig) - { - this->clients = orig.clients; - this->owner = orig.owner; - this->clientCount = orig.clientCount; - return *this; - } - NetworkSession::~NetworkSession() - { - this->clients.Clear(); - this->clientCount = 0; - } - - bool NetworkSession::Attach(Utility::DynamicMemory::SmartPointer client) - { - clientListLock.lock(); - - int k = -1; - for (unsigned int i = 0; (k == -1) && i < this->clients.Size(); i++) - { - if(!this->clients[i]) - k = i; - } - - if(k == -1) - { - this->clients.Push(client); - } - else - { - this->clients[k] = client; - } - this->clientCount++; - clientListLock.unlock(); - - return true; - } - - Utility::DynamicMemory::SmartPointer NetworkSession::Detach(Oyster::Network::NetworkClient* client) - { - Utility::DynamicMemory::SmartPointer val; - - clientListLock.lock(); - - for (unsigned int i = 0; i < this->clients.Size(); i++) - { - if(this->clients[0]->GetID() == client->GetID()) - { - val = this->clients[i]; - this->clients[i] = 0; - this->clientCount--; - } - } - - clientListLock.unlock(); - - return val; - } - Utility::DynamicMemory::SmartPointer NetworkSession::Detach(const LobbyClient* client) - { - Utility::DynamicMemory::SmartPointer val; - - clientListLock.lock(); - - for (unsigned int i = 0; i < this->clients.Size(); i++) - { - if(this->clients[0]->GetID() == client->GetID()) - { - val = this->clients[i]; - this->clients[i] = 0; - this->clientCount--; - } - } - - clientListLock.unlock(); - - return val; - } - Utility::DynamicMemory::SmartPointer NetworkSession::Detach(const LobbyClient& client) - { - Utility::DynamicMemory::SmartPointer val; - - clientListLock.lock(); - - for (unsigned int i = 0; i < this->clients.Size(); i++) - { - if(this->clients[0]->GetID() == client.GetID()) - { - val = this->clients[i]; - this->clients[i] = 0; - this->clientCount--; - } - } - - clientListLock.unlock(); - - return val; - } - Utility::DynamicMemory::SmartPointer NetworkSession::Detach(short ID) - { - Utility::DynamicMemory::SmartPointer val; - - clientListLock.lock(); - - for (unsigned int i = 0; i < this->clients.Size(); i++) - { - if(this->clients[0]->GetID() == ID) - { - val = this->clients[i]; - this->clients[i] = 0; - this->clientCount--; - } - } - - clientListLock.unlock(); - - return val; - } - - bool NetworkSession::Send(Oyster::Network::CustomNetProtocol& protocol) - { - bool returnValue = false; - for (unsigned int i = 0; i < this->clients.Size(); i++) - { - if(this->clients[i]) - { - this->clients[i]->Send(&protocol); - returnValue = true; - } - } - - return returnValue; - } - bool NetworkSession::Send(Oyster::Network::CustomNetProtocol& protocol, int ID) - { - for (unsigned int i = 0; i < this->clients.Size(); i++) - { - if(this->clients[i] && this->clients[i]->GetID() == ID) - { - this->clients[i]->Send(&protocol); - return true; - } - } - return false; - } - - void NetworkSession::SetCallback(Oyster::Callback::OysterCallback value) - { - for (unsigned int i = 0; i < this->clients.Size(); i++) - { - this->clients[i]->SetCallback(value); - } - } - - void NetworkSession::CloseSession(bool dissconnectClients) - { - clientListLock.lock(); - - for (unsigned int i = 0; i < this->clients.Size(); i++) - { - if(dissconnectClients) this->clients[i]->Disconnect(); - else if(this->owner) this->owner->Attach(this->clients[i]); - } - - this->clients.Clear(); - - clientListLock.unlock(); - } - Utility::DynamicMemory::SmartPointer NetworkSession::FindClient(int ID) - { - for (unsigned int i = 0; i < this->clients.Size(); i++) - { - if(this->clients[i]->GetID() == ID) - return this->clients[i]; - } - return Utility::DynamicMemory::SmartPointer(); - } - Utility::DynamicMemory::SmartPointer NetworkSession::FindClient(LobbyClient& obj) - { - for (unsigned int i = 0; i < this->clients.Size(); i++) - { - if(this->clients[i]->GetID() == obj.GetID()) - return this->clients[i]; - } - return Utility::DynamicMemory::SmartPointer(); - } - Utility::DynamicMemory::SmartPointer NetworkSession::FindClient(LobbyClient* obj) - { - for (unsigned int i = 0; i < this->clients.Size(); i++) - { - if(this->clients[i]->GetID() == obj->GetID()) - return this->clients[i]; - } - return Utility::DynamicMemory::SmartPointer(); - } - - -}//End namespace DanBias \ No newline at end of file diff --git a/Code/Game/DanBiasServer/LobbySessions/NetworkSession.h b/Code/Game/DanBiasServer/LobbySessions/NetworkSession.h deleted file mode 100644 index 41fb0a59..00000000 --- a/Code/Game/DanBiasServer/LobbySessions/NetworkSession.h +++ /dev/null @@ -1,91 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// -#ifndef DANBIASSERVER_NETWORK_SESSION_H -#define DANBIASSERVER_NETWORK_SESSION_H - -//warning C4150: deletion of pointer to incomplete type, no destructor called -#pragma warning(disable : 4150) - -#define NOMINMAX - -#include "INetworkSession.h" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace DanBias -{ - class LobbyClient; - class GameClient; - - class NetworkSession :public INetworkSession - { - public: - struct NetEvent - { - LobbyClient* sender; - GameClient* gameClient; - Oyster::Network::CustomNetProtocol protocol; - NetEvent():sender(0), gameClient(0){} - }; - - public: - NetworkSession(); - NetworkSession(const NetworkSession& orig); - const NetworkSession& operator=(const NetworkSession& orig); - virtual~NetworkSession(); - - virtual bool Attach(Utility::DynamicMemory::SmartPointer client); - - virtual Utility::DynamicMemory::SmartPointer Detach(Oyster::Network::NetworkClient* client); - virtual Utility::DynamicMemory::SmartPointer Detach(const LobbyClient* client); - virtual Utility::DynamicMemory::SmartPointer Detach(const LobbyClient& client); - virtual Utility::DynamicMemory::SmartPointer Detach(short ID); - - Utility::DynamicMemory::SmartPointer FindClient(LobbyClient& obj); - Utility::DynamicMemory::SmartPointer FindClient(LobbyClient* obj); - Utility::DynamicMemory::SmartPointer FindClient(int ID); - - /** - * Sends a message to all clients in this session. - */ - virtual bool Send(Oyster::Network::CustomNetProtocol& message); - /** - * Sends a message to a specific client in this session. - */ - virtual bool Send(Oyster::Network::CustomNetProtocol& protocol, int ID); - - /** - * Set the callback to all clients to where a messages is recieved. - */ - virtual void SetCallback(Oyster::Callback::OysterCallback value); - - /** - * Closes the session and sends the clients to given owner session if any. - * If session is null, clients is assumed to already be elsewhere and only releases a reference. - */ - virtual void CloseSession(bool dissconnectClients = false); - - - /** Set where the clients is returned on closed session. */ - inline void SetOwner(NetworkSession* owner) { this->owner = owner; } - - protected: - Utility::DynamicMemory::DynamicArray> clients; - NetworkSession* owner; //Where clients end up when session is closed. - - private: - std::mutex clientListLock; - int clientCount; - - private: - friend class AdminInterface; - }; -}//End namespace DanBias -#endif // !DANBIASSERVER_NETWORK_SESSION_H diff --git a/Code/Game/DanBiasServerLauncher/DanBiasServerLauncher.vcxproj b/Code/Game/DanBiasServerLauncher/DanBiasServerLauncher.vcxproj index ec88a915..dde29257 100644 --- a/Code/Game/DanBiasServerLauncher/DanBiasServerLauncher.vcxproj +++ b/Code/Game/DanBiasServerLauncher/DanBiasServerLauncher.vcxproj @@ -71,7 +71,7 @@ $(SolutionDir)..\Bin\Executable\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D - $(SolutionDir)Game\DanBiasServer;C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + $(SolutionDir)Game\GameServer;C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)WindowManager\;$(IncludePath) $(OutDir)..\DLL\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) @@ -79,7 +79,7 @@ $(SolutionDir)..\Bin\Executable\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D - $(SolutionDir)Game\DanBiasServer;C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + $(SolutionDir)Game\GameServer;C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)WindowManager\;$(IncludePath) $(OutDir)..\DLL\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) @@ -87,7 +87,7 @@ $(SolutionDir)..\Bin\Executable\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) - $(SolutionDir)Game\DanBiasServer;C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + $(SolutionDir)Game\GameServer;C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)WindowManager\;$(IncludePath) $(OutDir)..\DLL\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) @@ -95,7 +95,7 @@ $(SolutionDir)..\Bin\Executable\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) - $(SolutionDir)Game\DanBiasServer;C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + $(SolutionDir)Game\GameServer;C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)WindowManager\;$(IncludePath) $(OutDir)..\DLL\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) @@ -111,8 +111,8 @@ Windows true - DanBiasGame_$(PlatformShortName)D.dll;DanBiasServer_$(PlatformShortName)D.dll;%(DelayLoadDLLs) - DanBiasGame_$(PlatformShortName)D.lib;DanBiasServer_$(PlatformShortName)D.lib;%(AdditionalDependencies) + DanBiasGame_$(PlatformShortName)D.dll;GameServer_$(PlatformShortName)D.dll + GameServer_$(PlatformShortName)D.lib;DanBiasGame_$(PlatformShortName)D.lib;%(AdditionalDependencies) @@ -128,8 +128,8 @@ Windows true - DanBiasServer_$(PlatformShortName)D.dll;DanBiasGame_$(PlatformShortName)D.dll;%(DelayLoadDLLs) - DanBiasGame_$(PlatformShortName)D.lib;DanBiasServer_$(PlatformShortName)D.lib;%(AdditionalDependencies) + DanBiasGame_$(PlatformShortName)D.dll;GameServer_$(PlatformShortName)D.dll + GameServer_$(PlatformShortName)D.lib;DanBiasGame_$(PlatformShortName)D.lib;%(AdditionalDependencies) @@ -149,8 +149,8 @@ true true true - DanBiasServer_$(PlatformShortName).dll;DanBiasGame_$(PlatformShortName).dll;%(DelayLoadDLLs) - DanBiasServer_$(PlatformShortName).lib;DanBiasGame_$(PlatformShortName).lib;%(AdditionalDependencies) + DanBiasGame_$(PlatformShortName).dll;GameServer_$(PlatformShortName).dll;%(DelayLoadDLLs) + GameServer_$(PlatformShortName).lib;DanBiasGame_$(PlatformShortName).lib;%(AdditionalDependencies) @@ -170,13 +170,18 @@ true true true - DanBiasServer_$(PlatformShortName).dll;DanBiasGame_$(PlatformShortName).dll;%(DelayLoadDLLs) - DanBiasServer_$(PlatformShortName).lib;DanBiasGame_$(PlatformShortName).lib;%(AdditionalDependencies) + DanBiasGame_$(PlatformShortName).dll;GameServer_$(PlatformShortName).dll;%(DelayLoadDLLs) + GameServer_$(PlatformShortName).lib;DanBiasGame_$(PlatformShortName).lib;%(AdditionalDependencies) + + + {35aea3c0-e0a7-4e1e-88cd-514aa5a442b1} + + diff --git a/Code/Game/DanBiasServerLauncher/ServerLauncher.cpp b/Code/Game/DanBiasServerLauncher/ServerLauncher.cpp index 17d1a045..a27ab406 100644 --- a/Code/Game/DanBiasServerLauncher/ServerLauncher.cpp +++ b/Code/Game/DanBiasServerLauncher/ServerLauncher.cpp @@ -2,12 +2,13 @@ // Launcher to launch Danbias server // // Created by [Dennis Andersen] [2013] // ////////////////////////////////////////////////// -#define NOMINMAX //Blame it on windows +#define NOMINMAX //Blame it on microsoft #include #include +#include +#include - -#include +#include int WINAPI WinMain( HINSTANCE hinst, HINSTANCE prevInst, PSTR cmdLine, int cmdShow) { @@ -15,10 +16,22 @@ int WINAPI WinMain( HINSTANCE hinst, HINSTANCE prevInst, PSTR cmdLine, int cmdSh { return cmdShow; } - if( DanBias::DanBiasServerAPI::Initiate() == DanBias::DanBiasServerReturn_Sucess) + + WindowShell::CreateConsoleWindow(); + + DanBias::GameServerAPI::ServerInitDesc desc; + desc.listenPort = 15151; + if(DanBias::GameServerAPI::ServerInitiate(desc) == DanBias::DanBiasServerReturn_Sucess) { - DanBias::DanBiasServerAPI::Run(); - DanBias::DanBiasServerAPI::Release(); + + DanBias::GameServerAPI::ServerStart(); + //DanBias::GameServerAPI::GameStart(); + while (!(GetAsyncKeyState(0x51))) //Q for exit + { + DanBias::GameServerAPI::ServerUpdate(); + Sleep(1); + } + DanBias::GameServerAPI::ServerStop(); } return cmdShow; } \ No newline at end of file diff --git a/Code/Game/GameLogic/AttatchmentMassDriver.cpp b/Code/Game/GameLogic/AttatchmentMassDriver.cpp index 6ec70e1b..7554c879 100644 --- a/Code/Game/GameLogic/AttatchmentMassDriver.cpp +++ b/Code/Game/GameLogic/AttatchmentMassDriver.cpp @@ -3,71 +3,68 @@ using namespace GameLogic; -struct AttatchmentMassDriver::PrivateData -{ - PrivateData() - { - - } - - ~PrivateData() - { - - } - -}myData; AttatchmentMassDriver::AttatchmentMassDriver(void) { - myData = new PrivateData(); this->owner = 0; } AttatchmentMassDriver::AttatchmentMassDriver(Player &owner) { - myData = new PrivateData(); + this->owner = &owner; } AttatchmentMassDriver::~AttatchmentMassDriver(void) { - delete myData; + } /******************************************************** * Uses the attatchment and will from here switch case the different WEAPON_FIRE's that are to be used ********************************************************/ -void AttatchmentMassDriver::UseAttatchment(const GameLogic::WEAPON_FIRE &usage) +void AttatchmentMassDriver::UseAttatchment(const GameLogic::WEAPON_FIRE &usage, float dt) { //switch case to determin what functionallity to use in the attatchment switch (usage) { case WEAPON_FIRE::WEAPON_USE_PRIMARY_PRESS: - ForcePush(usage); + ForcePush(usage,dt); break; case WEAPON_FIRE::WEAPON_USE_SECONDARY_PRESS: - ForcePull(usage); + ForcePull(usage,dt); break; } - + } /******************************************************** * Pushes objects in a cone in front of the weapon when fired ********************************************************/ -void AttatchmentMassDriver::ForcePush(const GameLogic::WEAPON_FIRE &usage) +void AttatchmentMassDriver::ForcePush(const GameLogic::WEAPON_FIRE &usage, float dt) { - //create coneRigidBody that will then collide with object and push them in the aimed direction + //Oyster::Math::Float4 pushForce = Oyster::Math::Float4(this->owner->GetLookDir()) * (500 * dt); + Oyster::Math::Float4x4 aim = Oyster::Math3D::ViewMatrix_LookAtDirection(owner->GetLookDir(), owner->GetRigidBody()->GetGravityNormal(), owner->GetPosition()); + Oyster::Math::Float4x4 hitSpace = Oyster::Math3D::ProjectionMatrix_Perspective(Oyster::Math::pi/4,1,1,20); + Oyster::Collision3D::Frustrum hitFrustum = Oyster::Collision3D::Frustrum(Oyster::Math3D::ViewProjectionMatrix(aim,hitSpace)); + int arg = 0; + + Oyster::Physics::API::Instance().ApplyEffect(hitFrustum,&arg,ForcePushAction); } /******************************************************** * Pulls the player in the direction he is looking, used for fast movement(kinda like a jetpack) ********************************************************/ -void AttatchmentMassDriver::ForcePull(const WEAPON_FIRE &usage) +void AttatchmentMassDriver::ForcePull(const WEAPON_FIRE &usage, float dt) { - //Oyster::Physics::API::Instance().ApplyForceAt(owner->GetRigidBody(), owner->GetRigidBody()->GetCenter(), owner->GetLookDir() * 100); + Oyster::Physics::Struct::CustomBodyState state = this->owner->GetRigidBody()->GetState(); + + //do something with state + state.ApplyLinearImpulse(Oyster::Math::Float3(this->owner->GetLookDir()) * (500 * dt)); + + this->owner->GetRigidBody()->SetState(state); } diff --git a/Code/Game/GameLogic/AttatchmentMassDriver.h b/Code/Game/GameLogic/AttatchmentMassDriver.h index a1ededd0..594ea4fd 100644 --- a/Code/Game/GameLogic/AttatchmentMassDriver.h +++ b/Code/Game/GameLogic/AttatchmentMassDriver.h @@ -15,30 +15,31 @@ namespace GameLogic ~AttatchmentMassDriver(void); - void UseAttatchment(const WEAPON_FIRE &usage); + void UseAttatchment(const WEAPON_FIRE &usage, float dt); private: /******************************************************** * Pushes objects and players in a cone in front of the player * @param fireInput: allows switching on different functionality in this specific function ********************************************************/ - void ForcePush(const WEAPON_FIRE &usage); + void ForcePush(const WEAPON_FIRE &usage, float dt); /******************************************************** * Pulls the player forward, this is a movement tool * @param fireInput: allows switching on different functionality in this specific function ********************************************************/ - void ForcePull(const WEAPON_FIRE &usage); + void ForcePull(const WEAPON_FIRE &usage, float dt); /******************************************************** * Sucks objects towards the player, the player can then pick up an object and throw it as a projectile * @param fireInput: allows switching on different functionality in this specific function ********************************************************/ - void ForceSuck(const WEAPON_FIRE &usage); + void ForceSuck(const WEAPON_FIRE &usage, float dt); + + static void ForcePushAction(Oyster::Physics::ICustomBody *obj, void* args); private: - struct PrivateData; - PrivateData *myData; + }; } #endif diff --git a/Code/Game/GameLogic/AttatchmentSocket.cpp b/Code/Game/GameLogic/AttatchmentSocket.cpp index a3d9097c..4a663bef 100644 --- a/Code/Game/GameLogic/AttatchmentSocket.cpp +++ b/Code/Game/GameLogic/AttatchmentSocket.cpp @@ -5,25 +5,10 @@ using namespace GameLogic; using namespace Utility::DynamicMemory; -struct AttatchmentSocket::PrivateData -{ - PrivateData() - { - - } - - ~PrivateData() - { - - } - - SmartPointer attatchment; - - -}myData; AttatchmentSocket::AttatchmentSocket(void) { + this->attatchment = 0; } @@ -34,17 +19,17 @@ AttatchmentSocket::~AttatchmentSocket(void) IAttatchment* AttatchmentSocket::GetAttatchment() { - return myData->attatchment; + return this->attatchment; } void AttatchmentSocket::SetAttatchment(IAttatchment *attatchment) { - myData->attatchment = attatchment; + this->attatchment = attatchment; } void AttatchmentSocket::RemoveAttatchment() { - myData->attatchment = 0; + this->attatchment = 0; } diff --git a/Code/Game/GameLogic/AttatchmentSocket.h b/Code/Game/GameLogic/AttatchmentSocket.h index 2257dd7a..8c5745c5 100644 --- a/Code/Game/GameLogic/AttatchmentSocket.h +++ b/Code/Game/GameLogic/AttatchmentSocket.h @@ -19,8 +19,7 @@ namespace GameLogic void RemoveAttatchment(); private: - struct PrivateData; - PrivateData *myData; + IAttatchment *attatchment; }; } #endif \ No newline at end of file diff --git a/Code/Game/GameLogic/CollisionManager.cpp b/Code/Game/GameLogic/CollisionManager.cpp index 4cdb3689..116c9082 100644 --- a/Code/Game/GameLogic/CollisionManager.cpp +++ b/Code/Game/GameLogic/CollisionManager.cpp @@ -1,62 +1,90 @@ -#include "CollisionManager.h" #include "PhysicsAPI.h" #include "Object.h" #include "DynamicObject.h" #include "Player.h" +#include "Level.h" +#include "AttatchmentMassDriver.h" +#include "Game.h" using namespace Oyster; using namespace GameLogic; - void PlayerVBox(Player &player, DynamicObject &box); + void PlayerVBox(Player &player, DynamicObject &box, Oyster::Math::Float kineticEnergyLoss); + void PlayerVObject(Player &player, Object &obj, Oyster::Math::Float kineticEnergyLoss); - - Physics::ICustomBody::SubscriptMessage CollisionManager::PlayerCollision(const Oyster::Physics::ICustomBody *rigidBodyPlayer, const Oyster::Physics::ICustomBody *obj) + //Physics::ICustomBody::SubscriptMessage + void Player::PlayerCollision(Oyster::Physics::ICustomBody *rigidBodyPlayer, Oyster::Physics::ICustomBody *obj, Oyster::Math::Float kineticEnergyLoss) { - //Player *player = ((Player*)(rigidBodyPlayer->gameObjectRef)); - //Object *realObj = (Object*)obj->gameObjectRef; + + Player *player = ((Game::PlayerData*)(rigidBodyPlayer->GetCustomTag()))->player; + Object *realObj = (Object*)obj->GetCustomTag(); //needs to be changed? - //switch (realObj->GetType()) - //{ - //case OBJECT_TYPE::OBJECT_TYPE_BOX: - // PlayerVBox(*player,(*(DynamicObject*) realObj)); - // break; - //case OBJECT_TYPE::OBJECT_TYPE_PLAYER: - // - // break; - //} + return; + switch (realObj->GetObjectType()) + { + case OBJECT_TYPE::OBJECT_TYPE_GENERIC: + PlayerVObject(*player,*realObj, kineticEnergyLoss); + //return Physics::ICustomBody::SubscriptMessage_none; + break; + + case OBJECT_TYPE::OBJECT_TYPE_BOX: + PlayerVBox(*player,(*(DynamicObject*) realObj), kineticEnergyLoss); + //return Physics::ICustomBody::SubscriptMessage_none; + break; + case OBJECT_TYPE::OBJECT_TYPE_PLAYER: + //return Physics::ICustomBody::SubscriptMessage_none; + break; + case OBJECT_TYPE::OBJECT_TYPE_WORLD: + int test = 5; + break; + } - return Physics::ICustomBody::SubscriptMessage_none; + //return Physics::ICustomBody::SubscriptMessage_none; } - void PlayerVBox(Player &player, DynamicObject &box) + void PlayerVBox(Player &player, DynamicObject &box, Oyster::Math::Float kineticEnergyLoss) { + //use kinetic energyloss of the collision in order too determin how much damage to take + //use as part of the damage algorithm player.DamageLife(20); } - - Physics::ICustomBody::SubscriptMessage CollisionManager::BoxCollision(const Oyster::Physics::ICustomBody *rigidBodyBox, const Oyster::Physics::ICustomBody *obj) + + void PlayerVObject(Player &player, Object &obj, Oyster::Math::Float kineticEnergyLoss) { - if(rigidBodyBox == 0) + //Collision between a player and a general static or dynamic object + //use kinetic energyloss of the collision in order too determin how much damage to take + //use as part of the damage algorithm + int damageDone = 0; + int forceThreashHold = 200; + + if(kineticEnergyLoss > forceThreashHold) //should only take damage if the force is high enough { - return Physics::ICustomBody::SubscriptMessage::SubscriptMessage_none; + damageDone = kineticEnergyLoss * 0.10f; + player.DamageLife(damageDone); } - //DynamicObject *box = (DynamicObject*)rigidBodyBox->gameObjectRef; - //Object *realObj = (Object*)obj->gameObjectRef; - - //switch (realObj->GetType()) - //{ - //case OBJECT_TYPE::OBJECT_TYPE_BOX: - // - // break; - //case OBJECT_TYPE::OBJECT_TYPE_PLAYER: - // //PlayerVBox(*(Player*)realObj,*box); - // break; - //} - + + } + Oyster::Physics::ICustomBody::SubscriptMessage Object::DefaultCollisionBefore(Oyster::Physics::ICustomBody *rigidBodyLevel, Oyster::Physics::ICustomBody *obj) + { return Physics::ICustomBody::SubscriptMessage_none; } - - Oyster::Physics::ICustomBody::SubscriptMessage CollisionManager::LevelCollision(const Oyster::Physics::ICustomBody *rigidBodyLevel, const Oyster::Physics::ICustomBody *obj) + //Oyster::Physics::ICustomBody::SubscriptMessage + Oyster::Physics::ICustomBody::SubscriptMessage Level::LevelCollisionBefore(Oyster::Physics::ICustomBody *rigidBodyLevel, Oyster::Physics::ICustomBody *obj) { return Physics::ICustomBody::SubscriptMessage_ignore_collision_response; } + Oyster::Physics::ICustomBody::SubscriptMessage Level::LevelCollisionAfter(Oyster::Physics::ICustomBody *rigidBodyLevel, Oyster::Physics::ICustomBody *obj, Oyster::Math::Float kineticEnergyLoss) + { + return Physics::ICustomBody::SubscriptMessage_ignore_collision_response; + } + + void AttatchmentMassDriver::ForcePushAction(Oyster::Physics::ICustomBody *obj, void *args) + { + Oyster::Math::Float3 pushForce = Oyster::Math::Float4(1,0,0) * (1); + Oyster::Physics::ICustomBody::State state; + state = obj->GetState(); + state.ApplyLinearImpulse(pushForce); + obj->SetState(state); + //((Object*)obj->GetCustomTag())->ApplyLinearImpulse(pushForce); + } \ No newline at end of file diff --git a/Code/Game/GameLogic/CollisionManager.h b/Code/Game/GameLogic/CollisionManager.h index 21723885..6179333f 100644 --- a/Code/Game/GameLogic/CollisionManager.h +++ b/Code/Game/GameLogic/CollisionManager.h @@ -10,14 +10,7 @@ namespace GameLogic class CollisionManager { public: - //these are the main collision functions - //typedef SubscriptMessage (*EventAction_Collision)( const ICustomBody *proto, const ICustomBody *deuter ); - static Oyster::Physics::ICustomBody::SubscriptMessage PlayerCollision(const Oyster::Physics::ICustomBody *rigidBodyPlayer, const Oyster::Physics::ICustomBody *obj); - static Oyster::Physics::ICustomBody::SubscriptMessage BoxCollision(const Oyster::Physics::ICustomBody *rigidBodyBox, const Oyster::Physics::ICustomBody *obj); - static Oyster::Physics::ICustomBody::SubscriptMessage LevelCollision(const Oyster::Physics::ICustomBody *rigidBodyLevel, const Oyster::Physics::ICustomBody *obj); - //these are the specific collision case functions - //void PlayerVBox(Player &player, DynamicObject &box); - //void BoxVBox(DynamicObject &box1, DynamicObject &box2); + //put general collision functions here that are not part of a specific object }; diff --git a/Code/Game/GameLogic/DynamicObject.cpp b/Code/Game/GameLogic/DynamicObject.cpp index a8ea1ab4..437dca2c 100644 --- a/Code/Game/GameLogic/DynamicObject.cpp +++ b/Code/Game/GameLogic/DynamicObject.cpp @@ -7,15 +7,34 @@ using namespace GameLogic; DynamicObject::DynamicObject() :Object() { - -} -DynamicObject::DynamicObject(void* collisionFunc, OBJECT_TYPE type) - :Object(collisionFunc, type) +} +DynamicObject::DynamicObject(OBJECT_TYPE type) + :Object(type) +{ + +} +DynamicObject::DynamicObject(Oyster::Physics::ICustomBody *rigidBody, OBJECT_TYPE type) + :Object(rigidBody,type) { } +DynamicObject::DynamicObject(void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type) + :Object(collisionFuncBefore,collisionFuncAfter,type) +{ + +} +DynamicObject::DynamicObject(Oyster::Physics::ICustomBody *rigidBody ,void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type) + :Object(rigidBody, collisionFuncBefore, collisionFuncAfter, type) +{ + +} +DynamicObject::DynamicObject(Oyster::Physics::ICustomBody *rigidBody ,Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncBefore)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter), Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncAfter)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter,Oyster::Math::Float kineticEnergyLoss), OBJECT_TYPE type) + :Object(rigidBody, collisionFuncBefore, collisionFuncAfter, type) +{ + +} DynamicObject::~DynamicObject(void) { diff --git a/Code/Game/GameLogic/DynamicObject.h b/Code/Game/GameLogic/DynamicObject.h index 70b5efe7..3fcdae39 100644 --- a/Code/Game/GameLogic/DynamicObject.h +++ b/Code/Game/GameLogic/DynamicObject.h @@ -14,7 +14,12 @@ namespace GameLogic public: DynamicObject(); - DynamicObject(void* collisionFunc, OBJECT_TYPE type); + DynamicObject(OBJECT_TYPE type); + DynamicObject(Oyster::Physics::ICustomBody *rigidBody, OBJECT_TYPE type); + DynamicObject(void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type); + DynamicObject(Oyster::Physics::ICustomBody *rigidBody ,void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type); + DynamicObject(Oyster::Physics::ICustomBody *rigidBody ,Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncBefore)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter), Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncAfter)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter,Oyster::Math::Float kineticEnergyLoss), OBJECT_TYPE type); + ~DynamicObject(void); private: diff --git a/Code/Game/GameLogic/Game.cpp b/Code/Game/GameLogic/Game.cpp index 5ab72dcc..12ca7237 100644 --- a/Code/Game/GameLogic/Game.cpp +++ b/Code/Game/GameLogic/Game.cpp @@ -93,6 +93,7 @@ void Game::CreateTeam() bool Game::NewFrame() { + for (unsigned int i = 0; i < this->players.Size(); i++) { if(this->players[i]->player) this->players[i]->player->BeginFrame(); @@ -104,6 +105,30 @@ bool Game::NewFrame() { if(this->players[i]->player) this->players[i]->player->EndFrame(); } + for (unsigned int i = 0; i < this->players.Size(); i++) + { + if(this->players[i]->player) this->players[i]->player->BeginFrame(); + } + + API::Instance().Update(); + + for (unsigned int i = 0; i < this->players.Size(); i++) + { + if(this->players[i]->player) this->players[i]->player->EndFrame(); + } + for (unsigned int i = 0; i < this->players.Size(); i++) + { + if(this->players[i]->player) this->players[i]->player->BeginFrame(); + } + + API::Instance().Update(); + + for (unsigned int i = 0; i < this->players.Size(); i++) + { + if(this->players[i]->player) this->players[i]->player->EndFrame(); + } + + gameInstance.onMoveFnc(this->level); return true; } @@ -151,9 +176,9 @@ float Game::GetFrameTime() const void Game::PhysicsOnMove(const ICustomBody *object) { - IObjectData* temp = 0; - //IObjectData* temp = ((IObjectData*)object->GetDataTag()); - if(gameInstance.onMoveFnc) gameInstance.onMoveFnc(temp); + IObjectData* temp = (IObjectData*)object->GetCustomTag(); + + if(gameInstance.onMoveFnc && temp) gameInstance.onMoveFnc(temp); } void Game::PhysicsOnDestroy(::Utility::DynamicMemory::UniquePointer proto) { diff --git a/Code/Game/GameLogic/Game.h b/Code/Game/GameLogic/Game.h index b6f19eb8..3ea76b61 100644 --- a/Code/Game/GameLogic/Game.h +++ b/Code/Game/GameLogic/Game.h @@ -39,6 +39,8 @@ namespace GameLogic Oyster::Math::Float4x4 GetOrientation() override; int GetID() const override; OBJECT_TYPE GetObjectType() const override; + void Rotate(const Oyster::Math3D::Float3 lookDir) override; + Player *player; }; @@ -51,7 +53,7 @@ namespace GameLogic Oyster::Math::Float4x4 GetOrientation() override; int GetID() const override; OBJECT_TYPE GetObjectType() const override; - + IObjectData* GetObjectAt(int ID) const override; Level *level; }; diff --git a/Code/Game/GameLogic/GameAPI.h b/Code/Game/GameLogic/GameAPI.h index 8e05c8cd..ee4bad83 100644 --- a/Code/Game/GameLogic/GameAPI.h +++ b/Code/Game/GameLogic/GameAPI.h @@ -75,6 +75,12 @@ namespace GameLogic ********************************************************/ virtual void Move(const PLAYER_MOVEMENT &movement) = 0; + /** Relative rotation around given axis + * @param x: The relative x axis + * @param y: The relative y axis + **/ + virtual void Rotate(const Oyster::Math3D::Float3 lookDir) = 0; + /******************************************************** * Uses the chosen players weapon based on input * @param Usage: enum value on what kind of action is to be taken @@ -94,7 +100,7 @@ namespace GameLogic class ILevelData :public IObjectData { public: - + virtual IObjectData* GetObjectAt(int ID) const = 0; }; class DANBIAS_GAMELOGIC_DLL GameAPI diff --git a/Code/Game/GameLogic/GameLogic.vcxproj b/Code/Game/GameLogic/GameLogic.vcxproj index 6b66a9d5..809c82b5 100644 --- a/Code/Game/GameLogic/GameLogic.vcxproj +++ b/Code/Game/GameLogic/GameLogic.vcxproj @@ -184,7 +184,12 @@ + + + + + @@ -202,7 +207,11 @@ + + + + diff --git a/Code/Game/GameLogic/GameLogicStates.h b/Code/Game/GameLogic/GameLogicStates.h index 4c7c4197..2b0d0b8b 100644 --- a/Code/Game/GameLogic/GameLogicStates.h +++ b/Code/Game/GameLogic/GameLogicStates.h @@ -24,7 +24,8 @@ namespace GameLogic { OBJECT_TYPE_PLAYER = 0, OBJECT_TYPE_BOX = 1, - OBJECT_TYPE_WORLD = 2, + OBJECT_TYPE_WORLD = 2, + OBJECT_TYPE_GENERIC = 4, OBJECT_TYPE_UNKNOWN = -1, }; diff --git a/Code/Game/GameLogic/Game_LevelData.cpp b/Code/Game/GameLogic/Game_LevelData.cpp index a9434f69..1a5973e6 100644 --- a/Code/Game/GameLogic/Game_LevelData.cpp +++ b/Code/Game/GameLogic/Game_LevelData.cpp @@ -25,13 +25,18 @@ Oyster::Math::Float4x4 Game::LevelData::GetOrientation() //return this->level->GetOrientation(); return Oyster::Math::Float4x4(); } + int Game::LevelData::GetID() const { - //this->level->GetID(); - return -1; + return ((IObjectData*)this->level)->GetID(); } OBJECT_TYPE Game::LevelData::GetObjectType() const { - //return this->level->GetType(); - return OBJECT_TYPE_UNKNOWN; + return ((IObjectData*)this->level)->GetObjectType(); + //return OBJECT_TYPE_UNKNOWN; } + +IObjectData* Game::LevelData::GetObjectAt(int ID) const +{ + return this->level->GetObj(ID); +} \ No newline at end of file diff --git a/Code/Game/GameLogic/Game_PlayerData.cpp b/Code/Game/GameLogic/Game_PlayerData.cpp index 58fe6616..f2ae7c19 100644 --- a/Code/Game/GameLogic/Game_PlayerData.cpp +++ b/Code/Game/GameLogic/Game_PlayerData.cpp @@ -4,8 +4,19 @@ using namespace GameLogic; Game::PlayerData::PlayerData() -{ - this->player = new Player(); +{ + //set some stats that are appropriate to a player + Oyster::Physics::API::SimpleBodyDescription sbDesc; + sbDesc.centerPosition = Oyster::Math::Float3(0,165,0); + sbDesc.size = Oyster::Math::Float3(4,7,4); + + //create rigid body + Oyster::Physics::ICustomBody *rigidBody = Oyster::Physics::API::Instance().CreateRigidBody(sbDesc).Release(); + + //create player with this rigid body + this->player = new Player(rigidBody,Object::DefaultCollisionBefore, Player::PlayerCollision, OBJECT_TYPE::OBJECT_TYPE_PLAYER); + this->player->GetRigidBody()->SetCustomTag(this); + } Game::PlayerData::PlayerData(int playerID,int teamID) { @@ -44,7 +55,12 @@ int Game::PlayerData::GetTeamID() const { return this->player->GetTeamID(); } + OBJECT_TYPE Game::PlayerData::GetObjectType() const { - return this->player->GetType(); + return this->player->GetObjectType(); +} +void Game::PlayerData::Rotate(const Oyster::Math3D::Float3 lookDir) +{ + this->player->Rotate(lookDir); } \ No newline at end of file diff --git a/Code/Game/GameLogic/IAttatchment.h b/Code/Game/GameLogic/IAttatchment.h index 5bc400e6..e458fdbf 100644 --- a/Code/Game/GameLogic/IAttatchment.h +++ b/Code/Game/GameLogic/IAttatchment.h @@ -19,7 +19,7 @@ namespace GameLogic IAttatchment(void); ~IAttatchment(void); - virtual void UseAttatchment(const WEAPON_FIRE &usage) = 0; + virtual void UseAttatchment(const WEAPON_FIRE &usage, float dt) = 0; private: diff --git a/Code/Game/GameLogic/Level.cpp b/Code/Game/GameLogic/Level.cpp index 90dc1865..f631979d 100644 --- a/Code/Game/GameLogic/Level.cpp +++ b/Code/Game/GameLogic/Level.cpp @@ -8,6 +8,7 @@ using namespace Oyster::Physics; Level::Level(void) { + } Level::~Level(void) { @@ -19,25 +20,48 @@ void Level::InitiateLevel(std::string levelPath) } void Level::InitiateLevel(float radius) { - //API::SphericalBodyDescription sbDesc; - //sbDesc.centerPosition = Oyster::Math::Float4(0,0,0,1); - //sbDesc.ignoreGravity = true; - //sbDesc.radius = radius; - //sbDesc.mass = 1e16f; //10^16 - //sbDesc.mass = 0; //10^16 - //sbDesc.subscription_onCollision = CollisionManager::LevelCollision; - // - //ICustomBody* rigidBody = API::Instance().CreateRigidBody(sbDesc).Release(); - //API::Instance().AddObject(rigidBody); + + // add level sphere + API::SphericalBodyDescription sbDesc; + sbDesc.centerPosition = Oyster::Math::Float4(0,0,0,1); + sbDesc.ignoreGravity = true; + sbDesc.radius = 150; + sbDesc.mass = 10e12f; - //API::Gravity gravityWell; - // - //gravityWell.gravityType = API::Gravity::GravityType_Well; - //gravityWell.well.mass = 1e16f; - //gravityWell.well.position = Oyster::Math::Float4(0,0,0,1); - // - //API::Instance().AddGravity(gravityWell); + ICustomBody* rigidBody = API::Instance().CreateRigidBody(sbDesc).Release(); + ICustomBody::State state; + rigidBody->GetState(state); + state.SetRestitutionCoeff(0.01); + rigidBody->SetState(state); + + levelObj = new StaticObject(rigidBody, LevelCollisionBefore, LevelCollisionAfter, OBJECT_TYPE::OBJECT_TYPE_WORLD); + rigidBody->SetCustomTag(levelObj); + + + // add box + API::SimpleBodyDescription sbDesc_TestBox; + sbDesc_TestBox.centerPosition = Oyster::Math::Float4(-5,15,0,0); + sbDesc_TestBox.ignoreGravity = false; + sbDesc_TestBox.mass = 10; + sbDesc_TestBox.size = Oyster::Math::Float4(0.5f,0.5f,0.5f,0); + + ICustomBody* rigidBody_TestBox = API::Instance().CreateRigidBody(sbDesc_TestBox).Release(); + rigidBody_TestBox->SetSubscription(Level::PhysicsOnMoveLevel); + + testBox = new DynamicObject(rigidBody_TestBox, OBJECT_TYPE::OBJECT_TYPE_BOX); + rigidBody_TestBox->SetCustomTag(testBox); + rigidBody_TestBox->GetState(state); + state.ApplyLinearImpulse(Oyster::Math::Float3(0,0,4)); + rigidBody_TestBox->SetState(state); + + + // add gravitation + API::Gravity gravityWell; + gravityWell.gravityType = API::Gravity::GravityType_Well; + gravityWell.well.mass = 10e16f; + gravityWell.well.position = Oyster::Math::Float4(0,0,0,1); + API::Instance().AddGravity(gravityWell); } void Level::AddPlayerToTeam(Player *player, int teamID) @@ -55,4 +79,15 @@ void Level::RespawnPlayer(Player *player) this->teamManager.RespawnPlayerRandom(player); } - +Object* Level::GetObj( int ID) const +{ + if( ID == 0 ) + return (Object*)levelObj; + else + return (Object*)testBox; +} +void Level::PhysicsOnMoveLevel(const ICustomBody *object) +{ + // function call from physics update when object was moved + Object* temp = (Object*)object->GetCustomTag(); +} diff --git a/Code/Game/GameLogic/Level.h b/Code/Game/GameLogic/Level.h index 2242a8b2..60f7a932 100644 --- a/Code/Game/GameLogic/Level.h +++ b/Code/Game/GameLogic/Level.h @@ -51,12 +51,27 @@ namespace GameLogic ********************************************************/ void RespawnPlayer(Player *player); + /******************************************************** + * Collision function for level, this is to be sent to physics through the subscribe function with the rigidbody + * Will be called when the physics detect a collision + * @param rigidBodyLevel: physics object of the level + * @param obj: physics object for the object that collided with the level + ********************************************************/ + static Oyster::Physics::ICustomBody::SubscriptMessage LevelCollisionBefore(Oyster::Physics::ICustomBody *rigidBodyLevel, Oyster::Physics::ICustomBody *obj); + static Oyster::Physics::ICustomBody::SubscriptMessage LevelCollisionAfter(Oyster::Physics::ICustomBody *rigidBodyLevel, Oyster::Physics::ICustomBody *obj, Oyster::Math::Float kineticEnergyLoss); + + Object* GetObj( int ID ) const; + static void PhysicsOnMoveLevel(const Oyster::Physics::ICustomBody *object); + + private: TeamManager teamManager; Utility::DynamicMemory::DynamicArray> staticObjects; Utility::DynamicMemory::DynamicArray> dynamicObjects; GameMode gameMode; Utility::DynamicMemory::SmartPointer rigidBodyLevel; + StaticObject *levelObj; + DynamicObject *testBox; }; diff --git a/Code/Game/GameLogic/LevelLoader/LevelLoader.cpp b/Code/Game/GameLogic/LevelLoader/LevelLoader.cpp new file mode 100644 index 00000000..d60aac66 --- /dev/null +++ b/Code/Game/GameLogic/LevelLoader/LevelLoader.cpp @@ -0,0 +1,18 @@ +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + +#include "LevelLoader.h" +using namespace GameLogic; +using namespace GameLogic::LevelFileLoader; + + +std::vector LevelLoader::LoadLevel(std::string fileName) +{ + return parser.Parse(fileName); +} + +LevelMetaData LevelLoader::LoadLevelHeader(std::string fileName) +{ + return parser.ParseHeader(fileName); +} \ No newline at end of file diff --git a/Code/Game/GameLogic/LevelLoader/LevelLoader.h b/Code/Game/GameLogic/LevelLoader/LevelLoader.h new file mode 100644 index 00000000..4ac7a950 --- /dev/null +++ b/Code/Game/GameLogic/LevelLoader/LevelLoader.h @@ -0,0 +1,42 @@ +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + +#ifndef LEVELLOADER_H +#define LEVELLOADER_H + +#include +#include +#include +#include "ObjectDefines.h" +#include "LevelParser.h" + +namespace GameLogic +{ + class LevelLoader + { + + public: + LevelLoader(){this->parser = GameLogic::LevelFileLoader::LevelParser(); } + ~LevelLoader(){} + + /******************************************************** + * Loads the level and objects from file. + * @param fileName: Path to the level-file that you want to load. + * @return: Returns all structs with objects and information about the level. + ********************************************************/ + std::vector LoadLevel(std::string fileName); + + /******************************************************** + * Just for fast access for the meta information about the level. + * @param fileName: Path to the level-file that you want to load. + * @return: Returns the meta information about the level. + ********************************************************/ + LevelMetaData LoadLevelHeader(std::string fileName); //. + + private: + GameLogic::LevelFileLoader::LevelParser parser; + }; +} + +#endif \ No newline at end of file diff --git a/Code/Game/GameLogic/LevelLoader/LevelParser.cpp b/Code/Game/GameLogic/LevelLoader/LevelParser.cpp new file mode 100644 index 00000000..3ab3c203 --- /dev/null +++ b/Code/Game/GameLogic/LevelLoader/LevelParser.cpp @@ -0,0 +1,117 @@ +#include "LevelParser.h" + +#include "Loader.h" +#include "ParseFunctions.h" + +using namespace GameLogic; +using namespace ::LevelFileLoader; + +LevelParser::LevelParser() +{ + formatVersion.formatVersionMajor = 1; + formatVersion.formatVersionMinor = 0; +} + +LevelParser::~LevelParser() +{ +} + +std::vector LevelParser::Parse(std::string filename) +{ + int bufferSize = 0; + int counter = 0; + + std::vector objects; + + //Read entire level file. + Loader loader; + char* buffer = (char*)loader.LoadFile(filename.c_str(), bufferSize); + + //Read format version + FormatVersion levelFormatVersion; + //ParseObject(&buffer[counter], &levelFormatVersion, sizeof(formatVersion)); + if(this->formatVersion != levelFormatVersion) + { + //Do something if it's not the same version + } + + while(counter < bufferSize) + { + //Get typeID + ObjectTypeHeader typeID; + ParseObject(&buffer[counter], &typeID, sizeof(typeID)); + switch((int)typeID.typeID) + { + case ObjectType_LevelMetaData: + { + LevelMetaData header; + ParseLevelMetaData(&buffer[counter], header, counter); + objects.push_back(header); + break; + } + + case ObjectType_Dynamic: + { + ObjectHeader header; + ParseObject(&buffer[counter], &header, sizeof(header)); + objects.push_back(header); + counter += sizeof(header); + break; + } + + default: + //Couldn't find typeID. FAIL!!!!!! + break; + } + } + + return objects; +} + +//för meta information om leveln. +LevelMetaData LevelParser::ParseHeader(std::string filename) +{ + int bufferSize = 0; + int counter = 0; + + LevelMetaData levelHeader; + levelHeader.typeID = ObjectType::ObjectType_Unknown; + + //Read entire level file. + Loader loader; + char* buffer = (char*)loader.LoadFile(filename.c_str(), bufferSize); + + //Read format version + FormatVersion levelFormatVersion; + //ParseObject(&buffer[counter], &levelFormatVersion, sizeof(formatVersion)); + if(this->formatVersion != levelFormatVersion) + { + //Do something if it's not the same version + } + + //Find the header in the returned string. + while(counter < bufferSize) + { + ObjectTypeHeader typeID; + ParseObject(&buffer[counter], &typeID, sizeof(typeID)); + + switch(typeID.typeID) + { + case ObjectType_LevelMetaData: + ParseLevelMetaData(&buffer[counter], levelHeader, counter); + return levelHeader; + break; + case ObjectType_Dynamic: + //Do not call parse this object, since we are only interested in the LevelMetaData + //Only increase the counter size + counter += sizeof(ObjectHeader); + break; + + default: + //Couldn't find typeID. FAIL!!!!!! + break; + } + } + + return levelHeader; +} \ No newline at end of file diff --git a/Code/Game/GameLogic/LevelLoader/LevelParser.h b/Code/Game/GameLogic/LevelLoader/LevelParser.h new file mode 100644 index 00000000..6dce25f8 --- /dev/null +++ b/Code/Game/GameLogic/LevelLoader/LevelParser.h @@ -0,0 +1,30 @@ +#ifndef LEVEL_PARSER_H +#define LEVEL_PARSER_H + +#include +#include +#include "ObjectDefines.h" + +namespace GameLogic +{ + namespace LevelFileLoader + { + class LevelParser + { + public: + LevelParser(); + ~LevelParser(); + + // + std::vector Parse(std::string filename); + + // + LevelMetaData ParseHeader(std::string filename); + + private: + FormatVersion formatVersion; + + }; + } +} +#endif \ No newline at end of file diff --git a/Code/Game/GameLogic/LevelLoader/Loader.cpp b/Code/Game/GameLogic/LevelLoader/Loader.cpp new file mode 100644 index 00000000..3e15315c --- /dev/null +++ b/Code/Game/GameLogic/LevelLoader/Loader.cpp @@ -0,0 +1,22 @@ +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + +#include "Loader.h" +#include + +using namespace GameLogic::LevelFileLoader; +using namespace Oyster::Resource; +using namespace std; + +char* Loader::LoadFile(std::string fileName, int &size) +{ + //convert from string to wstring + std::wstring temp(fileName.begin(), fileName.end()); + + //convert from wstring to wchar then loads the file + char* buffer = (char*)OysterResource::LoadResource(temp.c_str(), Oyster::Resource::ResourceType::ResourceType_Byte_Raw, -1 , false); + + size = OysterResource::GetResourceSize(buffer); + return buffer; +} \ No newline at end of file diff --git a/Code/Game/GameLogic/LevelLoader/Loader.h b/Code/Game/GameLogic/LevelLoader/Loader.h new file mode 100644 index 00000000..198c2a87 --- /dev/null +++ b/Code/Game/GameLogic/LevelLoader/Loader.h @@ -0,0 +1,28 @@ +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + +#ifndef LOADER_H +#define LOADER_H + +#include "..\Misc\Resource\OysterResource.h" +#include + +namespace GameLogic +{ + namespace LevelFileLoader + { + class Loader + { + public: + Loader (){}; + ~Loader(){}; + char* LoadFile(std::string fileName, int &size); + + //TODO: + //Add functionality to load physicsObjects (hitboxes) + }; + } +} + +#endif; \ No newline at end of file diff --git a/Code/Game/GameLogic/LevelLoader/ObjectDefines.h b/Code/Game/GameLogic/LevelLoader/ObjectDefines.h new file mode 100644 index 00000000..dcf960a5 --- /dev/null +++ b/Code/Game/GameLogic/LevelLoader/ObjectDefines.h @@ -0,0 +1,109 @@ +#ifndef OBJECT_DEFINES_H +#define OBJECT_DEFINES_H + +#include +#include + +namespace GameLogic +{ + /************************************ + Enums + *************************************/ + + enum ObjectType + { + ObjectType_LevelMetaData, + ObjectType_Static, + ObjectType_Dynamic, + //Etc + + ObjectType_NUM_OF_TYPES, + + ObjectType_Unknown = -1, + }; + + enum UsePhysics + { + UsePhysics_UseFullPhysics, + UsePhysics_IgnoreGravity, + UsePhysics_IgnorePhysics, + + UsePhysics_Count, + UsePhysics_Unknown = -1, + }; + + //Should this be moved somewhere else? + enum GameMode + { + GameMode_FreeForAll, + GameMode_TeamDeathMatch, + //Etc + + GameMode_Count, + GameMode_Unknown = -1, + }; + + + /************************************ + Structs + *************************************/ + + struct FormatVersion + { + int formatVersionMajor; + int formatVersionMinor; + + bool operator ==(const FormatVersion& obj) + { + return (this->formatVersionMajor != obj.formatVersionMajor && this->formatVersionMinor != obj.formatVersionMinor); + } + + bool operator !=(const FormatVersion& obj) + { + return !(*this == obj); + } + }; + + struct ObjectTypeHeader + { + ObjectType typeID; + }; + + struct PhysicsObject + { + float mass; + float elasticity; + float frictionCoeffStatic; + float frictionCoeffDynamic; + float inertiaTensor[16]; + UsePhysics usePhysics; + }; + + struct LevelMetaData : ObjectTypeHeader + { + std::string levelName; + FormatVersion levelVersion; + std::string levelDescription; + std::string levelAuthor; + int maxNumberOfPlayer; + float worldSize; + int overviewPictureID; + std::vector gameModesSupported; + }; + + struct ObjectHeader : public ObjectTypeHeader + { + //Model, + int ModelID; + //Texture + int TextureID; + //Position + float position[3]; + //Rotation + float rotation[3]; + //Scale + float scale[3]; + }; +} + +#endif \ No newline at end of file diff --git a/Code/Game/GameLogic/LevelLoader/ParseFunctions.cpp b/Code/Game/GameLogic/LevelLoader/ParseFunctions.cpp new file mode 100644 index 00000000..f456b2d7 --- /dev/null +++ b/Code/Game/GameLogic/LevelLoader/ParseFunctions.cpp @@ -0,0 +1,80 @@ +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + +#include "ParseFunctions.h" +#include "../../../Misc/Packing/Packing.h" +#include + +using namespace Oyster::Packing; +using namespace GameLogic::LevelFileLoader; +using namespace GameLogic; +using namespace std; + +namespace GameLogic +{ + namespace LevelFileLoader + { + void ParseObject(char* buffer, void *header, int size) + { + memcpy(header, buffer, size); + } + + void ParseLevelMetaData(char* buffer, LevelMetaData &header, int &size) + { + int start = 0; + int tempSize; + char tempName[100]; + + memcpy(&header.typeID, &buffer[start], 4); + start += 4; + + memcpy(&tempSize , &buffer[start], 4); + start += 4; + + memcpy(&tempName, &buffer[start], tempSize); + header.levelName.assign(&tempName[0], &tempName[tempSize]); + start += tempSize; + + memcpy(&header.levelVersion, &buffer[start], 8); + start += 8; + + memcpy(&tempSize, &buffer[start], 4); + start +=4; + + memcpy(&tempName, &buffer[start], tempSize); + header.levelDescription.assign(&tempName[0], &tempName[tempSize]); + start += tempSize; + + memcpy(&tempSize, &buffer[start], 4); + start += 4; + + memcpy(&tempName, &buffer[start], tempSize); + header.levelAuthor.assign(&tempName[0], &tempName[tempSize]); + start += tempSize; + + memcpy(&header.maxNumberOfPlayer, &buffer[start], 4); + start += 4; + + memcpy(&header.worldSize, &buffer[start], 4); + start += 4; + + memcpy(&header.overviewPictureID, &buffer[start], 4); + start += 4; + + memcpy(&tempSize, &buffer[start], 4); + start += 4; + + int temp; + + for(int i = 0; i < tempSize; i++) + { + memcpy(&temp, &buffer[start], 4); + start += 4; + header.gameModesSupported.push_back((GameMode)temp); + } + + size += start; + } + } +} \ No newline at end of file diff --git a/Code/Game/GameLogic/LevelLoader/ParseFunctions.h b/Code/Game/GameLogic/LevelLoader/ParseFunctions.h new file mode 100644 index 00000000..08962b4a --- /dev/null +++ b/Code/Game/GameLogic/LevelLoader/ParseFunctions.h @@ -0,0 +1,19 @@ +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + +#ifndef PARSERFUNCTIONS_H +#define PARSERFUNCTIONS_H +#include "ObjectDefines.h" + +namespace GameLogic +{ + namespace LevelFileLoader + { + void ParseObject(char* buffer, void *header, int size); + void ParseLevelMetaData(char* buffer, LevelMetaData &header, int &size); + } +} + + +#endif \ No newline at end of file diff --git a/Code/Game/GameLogic/Object.cpp b/Code/Game/GameLogic/Object.cpp index 7e137c37..3b8094fb 100644 --- a/Code/Game/GameLogic/Object.cpp +++ b/Code/Game/GameLogic/Object.cpp @@ -16,38 +16,83 @@ const Game *Object::gameInstance = (Game*)(&Game::Instance()); Object::Object() { API::SimpleBodyDescription sbDesc; - //sbDesc.centerPosition = - - //poi - ICustomBody* rigidBody = API::Instance().CreateRigidBody(sbDesc).Release(); - + this->rigidBody = API::Instance().CreateRigidBody(sbDesc).Release(); Oyster::Physics::API::Instance().AddObject(rigidBody); - //rigidBody->gameObjectRef = this; - - this->objectID = GID(); - this->type = OBJECT_TYPE::OBJECT_TYPE_UNKNOWN; + this->objectID = GID(); + this->getState = this->rigidBody->GetState(); + this->setState = this->getState; } -Object::Object(void* collisionFunc, OBJECT_TYPE type) +Object::Object(OBJECT_TYPE type) { API::SimpleBodyDescription sbDesc; - //sbDesc.centerPosition = - //poi this->rigidBody = API::Instance().CreateRigidBody(sbDesc).Release(); + Oyster::Physics::API::Instance().AddObject(rigidBody); + this->type = type; + this->objectID = GID(); + this->getState = this->rigidBody->GetState(); + this->setState = this->getState; +} +Object::Object(Oyster::Physics::ICustomBody *rigidBody, OBJECT_TYPE type) +{ + Oyster::Physics::API::Instance().AddObject(rigidBody); + this->rigidBody = rigidBody; + this->type = type; + this->objectID = GID(); + this->getState = this->rigidBody->GetState(); + this->setState = this->getState; +} + +Object::Object(void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type) +{ + API::SimpleBodyDescription sbDesc; + + this->rigidBody = API::Instance().CreateRigidBody(sbDesc).Release(); Oyster::Physics::API::Instance().AddObject(rigidBody); - rigidBody->SetSubscription((Oyster::Physics::ICustomBody::EventAction_Collision)(collisionFunc)); - - //rigidBody->gameObjectRef = this; - + this->type = type; this->objectID = GID(); + this->getState = this->rigidBody->GetState(); + this->setState = this->getState; +} + +Object::Object(Oyster::Physics::ICustomBody *rigidBody ,void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type) +{ + Oyster::Physics::API::Instance().AddObject(rigidBody); + + this->rigidBody = rigidBody; + this->rigidBody->SetSubscription((Oyster::Physics::ICustomBody::EventAction_BeforeCollisionResponse)(collisionFuncBefore)); + this->rigidBody->SetSubscription((Oyster::Physics::ICustomBody::EventAction_AfterCollisionResponse)(collisionFuncAfter)); this->type = type; + this->objectID = GID(); + this->getState = this->rigidBody->GetState(); + this->setState = this->getState; +} + +Object::Object(Oyster::Physics::ICustomBody *rigidBody ,Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncBefore)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter), Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncAfter)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter,Oyster::Math::Float kineticEnergyLoss), OBJECT_TYPE type) +{ + Oyster::Physics::API::Instance().AddObject(rigidBody); + + this->rigidBody = rigidBody; + this->rigidBody->SetSubscription((Oyster::Physics::ICustomBody::EventAction_BeforeCollisionResponse)(collisionFuncBefore)); + this->rigidBody->SetSubscription((Oyster::Physics::ICustomBody::EventAction_AfterCollisionResponse)(collisionFuncAfter)); + + + this->type = type; + this->objectID = GID(); + this->getState = this->rigidBody->GetState(); + this->setState = this->getState; +} + +void Object::ApplyLinearImpulse(Oyster::Math::Float3 force) +{ + setState.ApplyLinearImpulse(force); } @@ -56,7 +101,7 @@ Object::~Object(void) } -OBJECT_TYPE Object::GetType() const +OBJECT_TYPE Object::GetObjectType() const { return this->type; } @@ -73,10 +118,40 @@ Oyster::Physics::ICustomBody* Object::GetRigidBody() void Object::BeginFrame() { + this->rigidBody->SetState(this->setState); + } +// update physic void Object::EndFrame() { - this->rigidBody->GetState(this->getState); + + Oyster::Math::Float4x4 rotMatrix = setState.GetOrientation(); //Oyster::Math3D::RotationMatrix(rot, axis); + //Oyster::Math3D::SnapAxisYToNormal_UsingNlerp(rotMatrix, -setState.GetGravityNormal()); + //setState.SetOrientation(rotMatrix); + + this->getState = this->rigidBody->GetState(); this->setState = this->getState; +} + +void Object::setBeforeCollisonFunc(Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncBefore)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter)) +{ + this->rigidBody->SetSubscription((Oyster::Physics::ICustomBody::EventAction_BeforeCollisionResponse)(collisionFuncBefore)); +} +void Object::setAfterCollisonFunc(Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncAfter)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter,Oyster::Math::Float kineticEnergyLoss)) +{ + this->rigidBody->SetSubscription((Oyster::Physics::ICustomBody::EventAction_AfterCollisionResponse)(collisionFuncAfter)); +} + +Oyster::Math::Float3 Object::GetPosition() +{ + Oyster::Physics::ICustomBody::State state; + state = this->rigidBody->GetState(); + return state.GetCenterPosition(); +} +Oyster::Math::Float4x4 Object::GetOrientation() +{ + Oyster::Physics::ICustomBody::State state; + state = this->rigidBody->GetState(); + return state.GetOrientation(); } \ No newline at end of file diff --git a/Code/Game/GameLogic/Object.h b/Code/Game/GameLogic/Object.h index 1316b287..44b0ca48 100644 --- a/Code/Game/GameLogic/Object.h +++ b/Code/Game/GameLogic/Object.h @@ -7,26 +7,41 @@ #define OBJECT_H #include "GameLogicStates.h" +#include "GameAPI.h" #include namespace GameLogic { class Game; - class Object + class Object :public IObjectData { public: Object(); - Object(void* collisionFunc, OBJECT_TYPE type); + Object(OBJECT_TYPE type); + Object(Oyster::Physics::ICustomBody *rigidBody, OBJECT_TYPE type); + Object(void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type); + Object(Oyster::Physics::ICustomBody *rigidBody ,void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type); + Object(Oyster::Physics::ICustomBody *rigidBody ,Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncBefore)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter), Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncAfter)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter,Oyster::Math::Float kineticEnergyLoss), OBJECT_TYPE type); ~Object(void); - OBJECT_TYPE GetType() const; + // API overrides + OBJECT_TYPE GetObjectType() const; int GetID() const; + Oyster::Math::Float3 GetPosition(); + Oyster::Math::Float4x4 GetOrientation(); + + Oyster::Physics::ICustomBody* GetRigidBody(); + void ApplyLinearImpulse(Oyster::Math::Float3 force); void BeginFrame(); void EndFrame(); + void setBeforeCollisonFunc(Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncBefore)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter)); + void setAfterCollisonFunc(Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncAfter)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter,Oyster::Math::Float kineticEnergyLoss)); + + static Oyster::Physics::ICustomBody::SubscriptMessage DefaultCollisionBefore(Oyster::Physics::ICustomBody *rigidBodyLevel, Oyster::Physics::ICustomBody *obj); private: OBJECT_TYPE type; int objectID; diff --git a/Code/Game/GameLogic/Player.cpp b/Code/Game/GameLogic/Player.cpp index a7ca4df4..45ae8f65 100644 --- a/Code/Game/GameLogic/Player.cpp +++ b/Code/Game/GameLogic/Player.cpp @@ -8,23 +8,56 @@ using namespace GameLogic; using namespace Oyster::Physics; Player::Player() - :DynamicObject(CollisionManager::PlayerCollision, OBJECT_TYPE::OBJECT_TYPE_PLAYER) + :DynamicObject() { - weapon = new Weapon(); - - life = 100; - teamID = -1; - playerState = PLAYER_STATE::PLAYER_STATE_IDLE; + +} +Player::Player(OBJECT_TYPE type) + :DynamicObject(type) +{ + InitPlayer(); +} +Player::Player(Oyster::Physics::ICustomBody *rigidBody, OBJECT_TYPE type) + :DynamicObject(rigidBody,type) +{ + InitPlayer(); +} + +Player::Player(void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type) + :DynamicObject(collisionFuncBefore,collisionFuncAfter,type) +{ + InitPlayer(); +} +Player::Player(Oyster::Physics::ICustomBody *rigidBody ,void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type) + :DynamicObject(rigidBody, collisionFuncBefore, collisionFuncAfter, type) +{ + InitPlayer(); +} +Player::Player(Oyster::Physics::ICustomBody *rigidBody ,Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncBefore)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter), Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncAfter)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter,Oyster::Math::Float kineticEnergyLoss), OBJECT_TYPE type) + :DynamicObject(rigidBody, collisionFuncBefore, collisionFuncAfter, type) +{ + InitPlayer(); +} + +void Player::InitPlayer() +{ + weapon = new Weapon(2,this); + + this->life = 100; + this->teamID = -1; + this->playerState = PLAYER_STATE_IDLE; lookDir = Oyster::Math::Float4(0,0,-1,0); } Player::~Player(void) { - delete weapon; - weapon = NULL; + if(weapon) + { + delete weapon; + weapon = NULL; + } } - void Player::Move(const PLAYER_MOVEMENT &movement) { switch(movement) @@ -53,31 +86,29 @@ void Player::Move(const PLAYER_MOVEMENT &movement) void Player::MoveForward() { - setState.ApplyLinearImpulse(this->lookDir * (100 * this->gameInstance->GetFrameTime())); + setState.ApplyLinearImpulse(this->lookDir * (20 * this->gameInstance->GetFrameTime())); } void Player::MoveBackwards() { - setState.ApplyLinearImpulse(-this->lookDir * 100 * this->gameInstance->GetFrameTime()); + setState.ApplyLinearImpulse(-this->lookDir * 20 * this->gameInstance->GetFrameTime()); } void Player::MoveRight() { //Do cross product with forward vector and negative gravity vector - Oyster::Math::Float4 r = Oyster::Math::Float4(1, 0, 0, 0 ); - //Oyster::Math::Float4 r = (-rigidBody->GetGravityNormal()).Cross((Oyster::Math::Float3)this->lookDir); - setState.ApplyLinearImpulse(r * 100 * this->gameInstance->GetFrameTime()); + Oyster::Math::Float3 r = (-rigidBody->GetGravityNormal()).Cross((Oyster::Math::Float3)this->lookDir); + setState.ApplyLinearImpulse(r * 20 * this->gameInstance->GetFrameTime()); } void Player::MoveLeft() { //Do cross product with forward vector and negative gravity vector - Oyster::Math::Float4 r = Oyster::Math::Float4(1, 0, 0, 0 ); - //Oyster::Math::Float4 r1 = -(-rigidBody->GetGravityNormal()).Cross((Oyster::Math::Float3)this->lookDir); //Still get zero - setState.ApplyLinearImpulse(-r * 100 * this->gameInstance->GetFrameTime()); + Oyster::Math::Float3 r = -(-rigidBody->GetGravityNormal()).Cross((Oyster::Math::Float3)this->lookDir); //Still get zero + setState.ApplyLinearImpulse(-r * 20 * this->gameInstance->GetFrameTime()); } void Player::UseWeapon(const WEAPON_FIRE &usage) { - this->weapon->Use(usage); + this->weapon->Use(usage,gameInstance->GetFrameTime()); } void Player::Respawn(Oyster::Math::Float3 spawnPoint) @@ -88,6 +119,22 @@ void Player::Respawn(Oyster::Math::Float3 spawnPoint) this->lookDir = Oyster::Math::Float4(1,0,0); } +void Player::Rotate(const Oyster::Math3D::Float3 lookDir) +{ + this->lookDir = lookDir; + + Oyster::Math::Float4 up(0,1,0,0);//-setState.GetGravityNormal(); + Oyster::Math::Float4 pos = setState.GetCenterPosition(); + Oyster::Math::Float4x4 world = Oyster::Math3D::OrientationMatrix_LookAtDirection(lookDir, up.xyz, pos.xyz); + // cant set rotation + //setState.SetOrientation(world); + //this->lookDir = lookDir - up.xyz; + //this->lookDir = lookDir; + + //this->setState.AddRotation(Oyster::Math::Float4(x, y)); + //this->setState.SetRotation(); +} + void Player::Jump() { @@ -116,7 +163,7 @@ Oyster::Math::Float4x4 Player::GetOrientation() const } Oyster::Math::Float3 Player::GetLookDir() const { - return this->lookDir.xyz; + return this->lookDir; } int Player::GetTeamID() const { diff --git a/Code/Game/GameLogic/Player.h b/Code/Game/GameLogic/Player.h index 5244f541..0df0d040 100644 --- a/Code/Game/GameLogic/Player.h +++ b/Code/Game/GameLogic/Player.h @@ -16,7 +16,13 @@ namespace GameLogic { public: Player(void); + Player(OBJECT_TYPE type); + Player(Oyster::Physics::ICustomBody *rigidBody, OBJECT_TYPE type); + Player(void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type); + Player(Oyster::Physics::ICustomBody *rigidBody ,void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type); + Player(Oyster::Physics::ICustomBody *rigidBody ,Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncBefore)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter), Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncAfter)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter,Oyster::Math::Float kineticEnergyLoss), OBJECT_TYPE type); ~Player(void); + void InitPlayer(); /******************************************************** * Moves the player based on input @@ -41,6 +47,17 @@ namespace GameLogic ********************************************************/ void Respawn(Oyster::Math::Float3 spawnPoint); + + void Rotate(const Oyster::Math3D::Float3 lookDir); + + /******************************************************** + * Collision function for player, this is to be sent to physics through the subscribe function with the rigidbody + * Will be called when the physics detect a collision + * @param rigidBodyPlayer: physics object of the player + * @param obj: physics object for the object that collided with the player + ********************************************************/ + static void PlayerCollision(Oyster::Physics::ICustomBody *rigidBodyPlayer, Oyster::Physics::ICustomBody *obj, Oyster::Math::Float kineticEnergyLoss); + bool IsWalking(); bool IsJumping(); @@ -62,7 +79,10 @@ namespace GameLogic int teamID; Weapon *weapon; PLAYER_STATE playerState; - Oyster::Math::Float4 lookDir; + Oyster::Math::Float3 lookDir; + + bool hasTakenDamage; + float invincibleCooldown; }; } diff --git a/Code/Game/GameLogic/StaticObject.cpp b/Code/Game/GameLogic/StaticObject.cpp index 155834fe..21b339be 100644 --- a/Code/Game/GameLogic/StaticObject.cpp +++ b/Code/Game/GameLogic/StaticObject.cpp @@ -9,13 +9,32 @@ StaticObject::StaticObject() { } +StaticObject::StaticObject(OBJECT_TYPE type) + :Object(type) +{ -StaticObject::StaticObject(void* collisionFunc, OBJECT_TYPE type) - :Object(collisionFunc,type) +} +StaticObject::StaticObject(Oyster::Physics::ICustomBody *rigidBody, OBJECT_TYPE type) + :Object(rigidBody,type) { } +StaticObject::StaticObject(void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type) + :Object(collisionFuncBefore,collisionFuncAfter,type) +{ + +} +StaticObject::StaticObject(Oyster::Physics::ICustomBody *rigidBody ,void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type) + :Object(rigidBody, collisionFuncBefore, collisionFuncAfter, type) +{ + +} +StaticObject::StaticObject(Oyster::Physics::ICustomBody *rigidBody ,Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncBefore)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter), Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncAfter)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter,Oyster::Math::Float kineticEnergyLoss), OBJECT_TYPE type) + :Object(rigidBody, collisionFuncBefore, collisionFuncAfter, type) +{ + +} StaticObject::~StaticObject(void) { diff --git a/Code/Game/GameLogic/StaticObject.h b/Code/Game/GameLogic/StaticObject.h index 31121447..c51f93a1 100644 --- a/Code/Game/GameLogic/StaticObject.h +++ b/Code/Game/GameLogic/StaticObject.h @@ -16,7 +16,12 @@ namespace GameLogic public: StaticObject(); - StaticObject(void* collisionFunc, OBJECT_TYPE type); + StaticObject(OBJECT_TYPE type); + StaticObject(Oyster::Physics::ICustomBody *rigidBody, OBJECT_TYPE type); + StaticObject(void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type); + StaticObject(Oyster::Physics::ICustomBody *rigidBody ,void* collisionFuncBefore, void* collisionFuncAfter, OBJECT_TYPE type); + StaticObject(Oyster::Physics::ICustomBody *rigidBody ,Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncBefore)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter), Oyster::Physics::ICustomBody::SubscriptMessage (*collisionFuncAfter)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter,Oyster::Math::Float kineticEnergyLoss), OBJECT_TYPE type); + ~StaticObject(void); private: diff --git a/Code/Game/GameLogic/Weapon.cpp b/Code/Game/GameLogic/Weapon.cpp index 28765cf3..a4c87e9e 100644 --- a/Code/Game/GameLogic/Weapon.cpp +++ b/Code/Game/GameLogic/Weapon.cpp @@ -1,60 +1,52 @@ #include "Weapon.h" -#include "AttatchmentSocket.h" #include "AttatchmentMassDriver.h" -#include "DynamicArray.h" +#include "Player.h" + using namespace GameLogic; using namespace Utility::DynamicMemory; -struct Weapon::PrivateData -{ - PrivateData() - { - weaponState = WEAPON_STATE_IDLE; - selectedAttatchment = 0; - currentNrOfAttatchments = 0; - selectedSocketID = 0; - attatchmentSockets = 0; - } - - ~PrivateData() - { - } - - WEAPON_STATE weaponState; - - DynamicArray> attatchmentSockets; - int currentNrOfAttatchments; - SmartPointer selectedAttatchment; - int selectedSocketID; - -}myData; Weapon::Weapon() { - myData = new PrivateData(); + weaponState = WEAPON_STATE_IDLE; + selectedAttatchment = 0; + currentNrOfAttatchments = 0; + selectedSocketID = 0; + attatchmentSockets = 0; } -Weapon::Weapon(int MaxNrOfSockets) +Weapon::Weapon(int MaxNrOfSockets,Player *owner) { - myData = new PrivateData(); - myData->attatchmentSockets.Resize(MaxNrOfSockets); + attatchmentSockets.Resize(MaxNrOfSockets); + attatchmentSockets[0] = new AttatchmentSocket(); + + weaponState = WEAPON_STATE_IDLE; + currentNrOfAttatchments = 0; + selectedAttatchment = 0; + + //give the weapon a massdriver on socket 0 + IAttatchment *mD = new AttatchmentMassDriver(*owner); + attatchmentSockets[0]->SetAttatchment(mD); + this->currentNrOfAttatchments = 1; + SelectAttatchment(0); + //give the weapon a massdriver on socket 0 } Weapon::~Weapon(void) { - delete myData; + } /******************************************************** * Uses the weapon based on the input given and the current chosen attatchment ********************************************************/ -void Weapon::Use(const WEAPON_FIRE &usage) +void Weapon::Use(const WEAPON_FIRE &usage, float dt) { - if (myData->selectedAttatchment) + if (selectedAttatchment) { - myData->selectedAttatchment->UseAttatchment(usage); + selectedAttatchment->UseAttatchment(usage, dt); } } @@ -68,24 +60,24 @@ void Weapon::Use(const WEAPON_FIRE &usage) ********************************************************/ bool Weapon::IsFireing() { - return (myData->weaponState == WEAPON_STATE::WEAPON_STATE_FIRING); + return (weaponState == WEAPON_STATE::WEAPON_STATE_FIRING); } bool Weapon::IsIdle() { - return (myData->weaponState == WEAPON_STATE::WEAPON_STATE_IDLE); + return (weaponState == WEAPON_STATE::WEAPON_STATE_IDLE); } bool Weapon::IsReloading() { - return (myData->weaponState == WEAPON_STATE::WEAPON_STATE_RELOADING); + return (weaponState == WEAPON_STATE::WEAPON_STATE_RELOADING); } bool Weapon::IsValidSocket(int socketID) { - if(socketID < (int)myData->attatchmentSockets.Size() && socketID >= 0) + if(socketID < (int)attatchmentSockets.Size() && socketID >= 0) { - if (myData->attatchmentSockets[socketID]->GetAttatchment() != 0) + if (attatchmentSockets[socketID]->GetAttatchment() != 0) { return true; } @@ -96,16 +88,16 @@ bool Weapon::IsValidSocket(int socketID) int Weapon::GetCurrentSocketID() { - return myData->selectedSocketID; + return selectedSocketID; } void Weapon::AddNewAttatchment(IAttatchment *attatchment, Player *owner) { - if(myData->currentNrOfAttatchments < (int)myData->attatchmentSockets.Size()) + if(currentNrOfAttatchments < (int)attatchmentSockets.Size()) { - myData->attatchmentSockets[myData->currentNrOfAttatchments]->SetAttatchment(attatchment); - myData->currentNrOfAttatchments++; + attatchmentSockets[currentNrOfAttatchments]->SetAttatchment(attatchment); + currentNrOfAttatchments++; } } @@ -113,7 +105,7 @@ void Weapon::SwitchAttatchment(IAttatchment *attatchment, int socketID, Player * { if (IsValidSocket(socketID)) { - myData->attatchmentSockets[socketID]->SetAttatchment(attatchment); + attatchmentSockets[socketID]->SetAttatchment(attatchment); } } @@ -121,7 +113,7 @@ void Weapon::RemoveAttatchment(int socketID) { if (IsValidSocket(socketID)) { - myData->attatchmentSockets[socketID]->RemoveAttatchment(); + attatchmentSockets[socketID]->RemoveAttatchment(); } } @@ -129,8 +121,8 @@ void Weapon::SelectAttatchment(int socketID) { if (IsValidSocket(socketID)) { - myData->selectedAttatchment = myData->attatchmentSockets[socketID]->GetAttatchment(); - myData->selectedSocketID = socketID; + selectedAttatchment = attatchmentSockets[socketID]->GetAttatchment(); + selectedSocketID = socketID; } } \ No newline at end of file diff --git a/Code/Game/GameLogic/Weapon.h b/Code/Game/GameLogic/Weapon.h index 719a853c..5138b2ac 100644 --- a/Code/Game/GameLogic/Weapon.h +++ b/Code/Game/GameLogic/Weapon.h @@ -6,21 +6,20 @@ #include "GameLogicStates.h" #include "IAttatchment.h" #include "Player.h" +#include "AttatchmentSocket.h" +#include "DynamicArray.h" namespace GameLogic { class Weapon { - public: - - Weapon(void); - Weapon(int nrOfAttatchmentSockets); + Weapon(int nrOfAttatchmentSockets, Player *owner); ~Weapon(void); - void Use(const WEAPON_FIRE &fireInput); + void Use(const WEAPON_FIRE &usage, float dt); void AddNewAttatchment(IAttatchment *attatchment, Player *owner); void SwitchAttatchment(IAttatchment *attatchment, int socketID, Player *owner); @@ -35,9 +34,12 @@ namespace GameLogic int GetCurrentSocketID(); - private: - struct PrivateData; - PrivateData *myData; + private: + WEAPON_STATE weaponState; + Utility::DynamicMemory::DynamicArray attatchmentSockets; + int currentNrOfAttatchments; + IAttatchment *selectedAttatchment; + int selectedSocketID; }; } diff --git a/Code/Game/GameProtocols/GameProtocols.vcxproj b/Code/Game/GameProtocols/GameProtocols.vcxproj index e01959b8..826f9df4 100644 --- a/Code/Game/GameProtocols/GameProtocols.vcxproj +++ b/Code/Game/GameProtocols/GameProtocols.vcxproj @@ -154,8 +154,7 @@ - - + diff --git a/Code/Game/GameProtocols/GameplayProtocols.h b/Code/Game/GameProtocols/GameplayProtocols.h deleted file mode 100644 index b595ce36..00000000 --- a/Code/Game/GameProtocols/GameplayProtocols.h +++ /dev/null @@ -1,63 +0,0 @@ -#ifndef GAMEPROTOCOLS_GAMEPLAYPROTOCOLS_H -#define GAMEPROTOCOLS_GAMEPLAYPROTOCOLS_H - -#include -#include -#include "ProtocolIdentificationID.h" - -namespace GameLogic -{ - struct Protocol_GameplayInitiateSession :public Oyster::Network::CustomProtocolObject - { - struct SessionInitData - { - int id; - int type; - //std::string text; - }; - std::vector element; - - Protocol_GameplayInitiateSession() - { - this->protocol[protocol_INDEX_ID].value = protocol_Gameplay_Initiate; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; - } - Protocol_GameplayInitiateSession(Oyster::Network::CustomNetProtocol& p) - { - int size = p[1].value.netInt; - for (int i = 0; i < size; i++) - { - SessionInitData d = { p[i+2].value.netInt, p[i+3].value.netInt /*, p[i+4].value.netCharPtr */ }; - element.push_back(d); - } - } - void Add(int id, int type, std::string text) - { - SessionInitData d = { id, type /*, text*/ }; - element.push_back(d); - } - Oyster::Network::CustomNetProtocol* GetProtocol() override - { - //Store the elements count - this->protocol[1].value = element.size(); - this->protocol[1].type = Oyster::Network::NetAttributeType_Int; - - for (unsigned int i = 0; i < element.size(); i+=3) - { - this->protocol[i+2].value = element[i].id; - this->protocol[i+3].value = element[i].type; - //element[i].text.copy(this->protocol[i+4].value.netCharPtr, element[i].text.size()); - - this->protocol[i+2].type = Oyster::Network::NetAttributeType_Int; - this->protocol[i+3].type = Oyster::Network::NetAttributeType_Int; - //this->protocol[i+4].type = Oyster::Network::NetAttributeType_CharArray; - } - return &protocol; - } - - private: - Oyster::Network::CustomNetProtocol protocol; - }; -} - -#endif // !GAMEPROTOCOLS_GAMEPLAYPROTOCOLS_H diff --git a/Code/Game/GameProtocols/ControlProtocols.h b/Code/Game/GameProtocols/GeneralProtocols.h similarity index 50% rename from Code/Game/GameProtocols/ControlProtocols.h rename to Code/Game/GameProtocols/GeneralProtocols.h index 0aba4dc6..02763ba0 100644 --- a/Code/Game/GameProtocols/ControlProtocols.h +++ b/Code/Game/GameProtocols/GeneralProtocols.h @@ -1,5 +1,5 @@ -#ifndef GAMELOGIC_CONTROL_PROTOCOLS_H -#define GAMELOGIC_CONTROL_PROTOCOLS_H +#ifndef GAMELOGIC_GENERAL_PROTOCOLS_H +#define GAMELOGIC_GENERAL_PROTOCOLS_H #include #include "ProtocolIdentificationID.h" @@ -12,23 +12,27 @@ namespace GameLogic { States_ready, States_idle, - States_bussy, - State_waiting, States_disconected, + States_leave }; States status; Protocol_General_Status() { - this->protocol[protocol_INDEX_ID].value = protocol_General_Status; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; + this->protocol[0].value = protocol_General_Status; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; this->protocol[1].type = Oyster::Network::NetAttributeType_Short; } + Protocol_General_Status(Oyster::Network::CustomNetProtocol& p) + { + this->protocol = p; + status = (States)p[1].value.netShort; + } Protocol_General_Status(States state) { - this->protocol[protocol_INDEX_ID].value = protocol_General_Status; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; + this->protocol[0].value = protocol_General_Status; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; this->status = state; this->protocol[1].type = Oyster::Network::NetAttributeType_Short; } @@ -45,18 +49,21 @@ namespace GameLogic struct Protocol_General_Text :public Oyster::Network::CustomProtocolObject { - char* text; - int destination; + std::string text; //The text to send + int destination; //The destination if any (Ie a whisper to a player) Protocol_General_Text() + : destination(-1) {} + Protocol_General_Text(Oyster::Network::CustomNetProtocol& p) { - this->protocol[protocol_INDEX_ID].value = protocol_General_Text; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; - this->protocol[1].type = Oyster::Network::NetAttributeType_CharArray; + destination = p.Get(1).value.netInt; + text = p.Get(2).value.netCharPtr; } Oyster::Network::CustomNetProtocol* GetProtocol() override { - this->protocol[1].value.netCharPtr = text; + this->protocol.Set(0, protocol_General_Text, Oyster::Network::NetAttributeType_Short); + this->protocol.Set(1, destination, Oyster::Network::NetAttributeType_Int); + this->protocol.Set(2, text); return &protocol; } diff --git a/Code/Game/GameProtocols/LobbyProtocols.h b/Code/Game/GameProtocols/LobbyProtocols.h index 71e6e3b6..192d81f2 100644 --- a/Code/Game/GameProtocols/LobbyProtocols.h +++ b/Code/Game/GameProtocols/LobbyProtocols.h @@ -9,8 +9,12 @@ #include #include "ProtocolIdentificationID.h" +#include + + namespace GameLogic { + /* struct Protocol_LobbyCreateGame :public Oyster::Network::CustomProtocolObject { char* mapName; @@ -18,8 +22,8 @@ namespace GameLogic Protocol_LobbyCreateGame() { - this->protocol[protocol_INDEX_ID].value = protocol_Lobby_CreateGame; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; + this->protocol[0].value = protocol_Lobby_Create; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; this->protocol[1].type = Oyster::Network::NetAttributeType_CharArray; this->protocol[2].type = Oyster::Network::NetAttributeType_Char; @@ -39,38 +43,21 @@ namespace GameLogic private: Oyster::Network::CustomNetProtocol protocol; }; - - struct Protocol_LobbyJoinGame :public Oyster::Network::CustomProtocolObject - { - char gameId; - - Protocol_LobbyJoinGame() - { - this->protocol[protocol_INDEX_ID].value = protocol_Lobby_JoinGame; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; - - this->protocol[1].type = Oyster::Network::NetAttributeType_Char; - } - Oyster::Network::CustomNetProtocol* GetProtocol() override - { - protocol[1].value = gameId; - return &protocol; - } - - private: - Oyster::Network::CustomNetProtocol protocol; - }; - + */ struct Protocol_LobbyStartGame :public Oyster::Network::CustomProtocolObject { - char gameId; + short gameId; Protocol_LobbyStartGame() { - this->protocol[protocol_INDEX_ID].value = protocol_Lobby_StartGame; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; + this->protocol[0].value = protocol_Lobby_Start; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; - this->protocol[1].type = Oyster::Network::NetAttributeType_Char; + this->protocol[1].type = Oyster::Network::NetAttributeType_Short; + } + Protocol_LobbyStartGame(Oyster::Network::CustomNetProtocol& o) + { + gameId = o[1].value.netInt; } Oyster::Network::CustomNetProtocol* GetProtocol() override { @@ -82,39 +69,19 @@ namespace GameLogic Oyster::Network::CustomNetProtocol protocol; }; - struct Protocol_LobbyJoinLobby :public Oyster::Network::CustomProtocolObject + struct Protocol_LobbyLogin :public Oyster::Network::CustomProtocolObject { - int LobbyID; - Protocol_LobbyJoinLobby(int id = -1) + // Login stuff + Protocol_LobbyLogin() { - this->protocol[protocol_INDEX_ID].value = protocol_Lobby_JoinLobby; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; + this->protocol[0].value = protocol_Lobby_Join; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; - this->protocol[1].type = Oyster::Network::NetAttributeType_Int; - LobbyID = id; + this->protocol[1].type = Oyster::Network::NetAttributeType_Short; } - Protocol_LobbyJoinLobby(Oyster::Network::CustomNetProtocol& o) + Protocol_LobbyLogin(Oyster::Network::CustomNetProtocol& p) { - LobbyID = o[1].value.netInt; - } - Oyster::Network::CustomNetProtocol* GetProtocol() override - { - this->protocol[1].value = LobbyID; - return &protocol; - } - - private: - Oyster::Network::CustomNetProtocol protocol; - }; - - struct Protocol_LobbyLeaveLobby :public Oyster::Network::CustomProtocolObject - { - - Protocol_LobbyLeaveLobby() - { - this->protocol[protocol_INDEX_ID].value = protocol_Lobby_LeaveLobby; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; } Oyster::Network::CustomNetProtocol* GetProtocol() override { @@ -125,53 +92,176 @@ namespace GameLogic Oyster::Network::CustomNetProtocol protocol; }; - struct Protocol_LobbyUpdate :public Oyster::Network::CustomProtocolObject + //struct Protocol_LobbyJoin :public Oyster::Network::CustomProtocolObject + //{ + // short value; + // + // Protocol_LobbyJoin() + // { + // this->protocol[0].value = protocol_Lobby_Join; + // this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + // this->protocol[1].type = Oyster::Network::NetAttributeType_Short; + // } + // Protocol_LobbyJoin(Oyster::Network::CustomNetProtocol& p) + // { + // this->protocol[0].value = protocol_Lobby_Join; + // this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + // this->protocol[1].type = Oyster::Network::NetAttributeType_Short; + // value = p[1].value.netShort; + // } + // Oyster::Network::CustomNetProtocol* GetProtocol() override + // { + // protocol[1].value = value; + // return &protocol; + // } + // + // private: + // Oyster::Network::CustomNetProtocol protocol; + //}; + + struct Protocol_LobbyRefresh :public Oyster::Network::CustomProtocolObject { - struct LobbyUpdateData + Protocol_LobbyRefresh() { - std::string mapName; - int LobbyId; + this->protocol[0].value = protocol_Lobby_Login; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + } + Protocol_LobbyRefresh(Oyster::Network::CustomNetProtocol& o) + { + + } + Oyster::Network::CustomNetProtocol* GetProtocol() override + { return &protocol; } + + private: + Oyster::Network::CustomNetProtocol protocol; + }; + + /** + * A protocol that contains all data to send to client when update game lobby + */ + + struct Protocol_LobbyClientData :public Oyster::Network::CustomProtocolObject + { + // Player list + struct PlayerData + { + std::string name; + std::string ip; + int id; + int team; }; - int count; - LobbyUpdateData* data; - Protocol_LobbyUpdate() + Utility::DynamicMemory::DynamicArray list; + + Protocol_LobbyClientData() { - this->protocol[protocol_INDEX_ID].value = protocol_Lobby_LeaveLobby; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; + this->protocol[0].value = protocol_Lobby_ClientData; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; - this->protocol[1].type = Oyster::Network::NetAttributeType_Int; + list.Reserve(10); } - Protocol_LobbyUpdate( Oyster::Network::CustomNetProtocol* p ) + Protocol_LobbyClientData(Oyster::Network::CustomNetProtocol& p) { - count = (*p)[1].value.netInt; - data = new LobbyUpdateData[count]; - for (int i = 0; i < count; i++) + unsigned int size = this->protocol[1].value.netUInt; + list.Reserve(size); + int a = 2; + for (unsigned int i = 0; i < list.Size(); i++) { - //data[i].mapName = (*p)[i].value. + PlayerData d; + d.id = this->protocol[a++].value.netInt; + d.team = this->protocol[a++].value.netInt; + d.name = this->protocol.Get(a++).value.netCharPtr; + d.ip = this->protocol.Get(a++).value.netCharPtr; + list.Push(d); } } - ~Protocol_LobbyUpdate() - { - delete [] data; - data = 0; - } Oyster::Network::CustomNetProtocol* GetProtocol() override { - this->protocol[1].value.netInt = count; - for (int i = 2; i < count; i++) - { - protocol[i].type = Oyster::Network::NetAttributeType_CharArray; - protocol[i+1].type = Oyster::Network::NetAttributeType_Int; + this->protocol[1].value = list.Size(); - protocol[i].value.netCharPtr = const_cast(data[i-2].mapName.c_str()); - protocol[i+1].value.netInt = data[i-1].LobbyId; + int a = 2; + for (unsigned int i = 0; i < list.Size(); i++) + { + this->protocol[a].type = Oyster::Network::NetAttributeType_Int; // client-id + this->protocol[a++].value = list[i].id; + + this->protocol[a].type = Oyster::Network::NetAttributeType_Int; // team-id + this->protocol[a++].value = list[i].team; + + this->protocol[a].type = Oyster::Network::NetAttributeType_CharArray; // clientName + this->protocol.Set(a++, list[i].name); + + this->protocol[a].type = Oyster::Network::NetAttributeType_CharArray; // clientIP + this->protocol.Set(a++, list[i].ip); } + return &protocol; } private: Oyster::Network::CustomNetProtocol protocol; }; + + struct Protocol_LobbyGameData :public Oyster::Network::CustomProtocolObject + { + std::string mapName; + int majorVersion; + int minorVersion; + + Protocol_LobbyGameData() + { + this->protocol[0].value = protocol_Lobby_GameData; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + + this->protocol[1].type = Oyster::Network::NetAttributeType_Int; + this->protocol[2].type = Oyster::Network::NetAttributeType_Int; + this->protocol[3].type = Oyster::Network::NetAttributeType_CharArray; + } + Protocol_LobbyGameData(Oyster::Network::CustomNetProtocol& p) + { + majorVersion = (int)p.Get(1).value.netInt; + minorVersion = (int)p.Get(2).value.netInt; + mapName = p.Get(3).value.netCharPtr; + } + Oyster::Network::CustomNetProtocol* GetProtocol() override + { + this->protocol[1].value = majorVersion; + this->protocol[2].value = minorVersion; + this->protocol.Set(3, mapName.c_str()); + + return &protocol; + } + + private: + Oyster::Network::CustomNetProtocol protocol; + }; + + /** + * A protocol that contains all data to send to client when update main lobby + */ + //struct Protocol_LobbyMainData :public Oyster::Network::CustomProtocolObject + //{ + // // Game instance list + // + // Protocol_LobbyMainData() + // { + // this->protocol[0].value = protocol_Lobby_MainData; + // this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + // + // this->protocol[1].type = Oyster::Network::NetAttributeType_Short; + // } + // Protocol_LobbyMainData(Oyster::Network::CustomNetProtocol& p) + // { + // + // } + // Oyster::Network::CustomNetProtocol* GetProtocol() override + // { + // return &protocol; + // } + // + // private: + // Oyster::Network::CustomNetProtocol protocol; + //}; } #endif // !GAMELOGIC_PLAYER_PROTOCOLS_H diff --git a/Code/Game/GameProtocols/ObjectProtocols.h b/Code/Game/GameProtocols/ObjectProtocols.h index 2a538714..b71599b1 100644 --- a/Code/Game/GameProtocols/ObjectProtocols.h +++ b/Code/Game/GameProtocols/ObjectProtocols.h @@ -4,21 +4,244 @@ #include #include "ProtocolIdentificationID.h" - - namespace GameLogic { - struct Protocol_CreateObject :public Oyster::Network::CustomProtocolObject + struct Protocol_ObjectPickup :public Oyster::Network::CustomProtocolObject + { + short object_ID; + short pickup_ID; + + Protocol_ObjectPickup() + { + this->protocol[0].value = protocol_Gameplay_ObjectPickup; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + + this->protocol[1].type = Oyster::Network::NetAttributeType_Short; + this->protocol[2].type = Oyster::Network::NetAttributeType_Short; + + object_ID = -1; + pickup_ID = -1; + } + Protocol_ObjectPickup(Oyster::Network::CustomNetProtocol& p) + { + object_ID = p[1].value.netShort; + pickup_ID = p[2].value.netShort; + } + Protocol_ObjectPickup(int objectID, short pickupID) + { + this->protocol[0].value = protocol_Gameplay_ObjectPosition; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + + this->protocol[1].type = Oyster::Network::NetAttributeType_Short; + this->protocol[2].type = Oyster::Network::NetAttributeType_Short; + + object_ID = objectID; + pickup_ID = pickupID; + + } + Oyster::Network::CustomNetProtocol* GetProtocol() override + { + this->protocol[1].value = object_ID; + this->protocol[2].value = pickup_ID; + return &protocol; + } + + private: + Oyster::Network::CustomNetProtocol protocol; + }; + + struct Protocol_ObjectDamage :public Oyster::Network::CustomProtocolObject + { + int object_ID; + float health; //Precentage% + + Protocol_ObjectDamage() + { + this->protocol[0].value = protocol_Gameplay_ObjectDamage; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + + this->protocol[1].type = Oyster::Network::NetAttributeType_Int; + this->protocol[2].type = Oyster::Network::NetAttributeType_Float; + + object_ID = -1; + health = 0.0f; + } + Protocol_ObjectDamage(Oyster::Network::CustomNetProtocol& p) + { + + } + Protocol_ObjectDamage(int id, float hp) + { + this->protocol[0].value = protocol_Gameplay_ObjectDamage; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + + this->protocol[2].type = Oyster::Network::NetAttributeType_Float; + + object_ID = id; + health = hp; + } + Oyster::Network::CustomNetProtocol* GetProtocol() override + { + this->protocol[1].value = object_ID; + this->protocol[2].value = health; + return &protocol; + } + + private: + Oyster::Network::CustomNetProtocol protocol; + }; + + struct Protocol_ObjectPosition :public Oyster::Network::CustomProtocolObject { int object_ID; - char *path; float worldMatrix[16]; - - Protocol_CreateObject() + Protocol_ObjectPosition() { - this->protocol[protocol_INDEX_ID].value = protocol_Gameplay_CreateObject; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; + this->protocol[0].value = protocol_Gameplay_ObjectPosition; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + + this->protocol[1].type = Oyster::Network::NetAttributeType_Int; + + for (int i = 2; i <= 17; i++) + { + this->protocol[i].type = Oyster::Network::NetAttributeType_Float; + } + object_ID = -1; + memset(&worldMatrix[0], 0, sizeof(float) * 16); + } + Protocol_ObjectPosition(Oyster::Network::CustomNetProtocol& p) + { + + } + Protocol_ObjectPosition(float m[16], int id) + { + this->protocol[0].value = protocol_Gameplay_ObjectPosition; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + + this->protocol[1].type = Oyster::Network::NetAttributeType_Int; + + for (int i = 2; i <= 17; i++) + { + this->protocol[i].type = Oyster::Network::NetAttributeType_Float; + } + + object_ID = id; + memcpy(&worldMatrix[0], &m[0], sizeof(float)*16); + } + Oyster::Network::CustomNetProtocol* GetProtocol() override + { + this->protocol[1].value = object_ID; + for (int i = 2; i <= 17; i++) + { + this->protocol[i].value = worldMatrix[i-2]; + } + return &protocol; + } + + private: + Oyster::Network::CustomNetProtocol protocol; + }; + + struct Protocol_ObjectEnable :public Oyster::Network::CustomProtocolObject + { + int object_ID; + float worldMatrix[16]; + + Protocol_ObjectEnable() + { + this->protocol[0].value = protocol_Gameplay_ObjectEnabled; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + + this->protocol[1].type = Oyster::Network::NetAttributeType_Int; + + for (int i = 2; i <= 17; i++) + { + this->protocol[i].type = Oyster::Network::NetAttributeType_Float; + } + object_ID = -1; + memset(&worldMatrix[0], 0, sizeof(float) * 16); + } + Protocol_ObjectEnable(Oyster::Network::CustomNetProtocol& p) + { + + } + Protocol_ObjectEnable(float m[16], int id) + { + this->protocol[0].value = protocol_Gameplay_ObjectEnabled; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + + this->protocol[1].type = Oyster::Network::NetAttributeType_Int; + + for (int i = 2; i <= 17; i++) + { this->protocol[i].type = Oyster::Network::NetAttributeType_Float; } + + object_ID = id; + memcpy(&worldMatrix[0], &m[0], sizeof(float)*16); + } + Oyster::Network::CustomNetProtocol* GetProtocol() override + { + this->protocol[1].value = object_ID; + for (int i = 2; i <= 17; i++) + { + this->protocol[i].value = worldMatrix[i-2]; + } + return &protocol; + } + + private: + Oyster::Network::CustomNetProtocol protocol; + }; + + struct Protocol_ObjectDisable :public Oyster::Network::CustomProtocolObject + { + int object_ID; + float timer; + + Protocol_ObjectDisable() + { + this->protocol[0].value = protocol_Gameplay_ObjectDisabled; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + + this->protocol[1].type = Oyster::Network::NetAttributeType_Int; + this->protocol[2].type = Oyster::Network::NetAttributeType_Float; + } + Protocol_ObjectDisable(Oyster::Network::CustomNetProtocol& p) + { + + } + Protocol_ObjectDisable(int id, float time) + { + this->protocol[0].value = protocol_Gameplay_ObjectDisabled; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + + this->protocol[1].type = Oyster::Network::NetAttributeType_Int; + this->protocol[2].type = Oyster::Network::NetAttributeType_Float; + + object_ID = id; + timer = time; + } + Oyster::Network::CustomNetProtocol* GetProtocol() override + { + this->protocol[1].value = object_ID; + this->protocol[2].value = timer; + return &protocol; + } + + private: + Oyster::Network::CustomNetProtocol protocol; + }; + + struct Protocol_ObjectCreate :public Oyster::Network::CustomProtocolObject + { + int object_ID; + char *name; + float worldMatrix[16]; + + Protocol_ObjectCreate() + { + this->protocol[0].value = protocol_Gameplay_ObjectCreate; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; this->protocol[1].type = Oyster::Network::NetAttributeType_Int; this->protocol[2].type = Oyster::Network::NetAttributeType_CharArray; @@ -28,10 +251,14 @@ namespace GameLogic this->protocol[i].type = Oyster::Network::NetAttributeType_Float; } } - Protocol_CreateObject(float m[16], int id, char *path) + Protocol_ObjectCreate(Oyster::Network::CustomNetProtocol& p) { - this->protocol[protocol_INDEX_ID].value = protocol_Gameplay_CreateObject; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Int; + + } + Protocol_ObjectCreate(float m[16], int id, char *path) + { + this->protocol[0].value = protocol_Gameplay_ObjectCreate; + this->protocol[0].type = Oyster::Network::NetAttributeType_Int; this->protocol[1].type = Oyster::Network::NetAttributeType_Int; this->protocol[2].type = Oyster::Network::NetAttributeType_CharArray; @@ -42,14 +269,14 @@ namespace GameLogic } object_ID = id; - this->path = path; + this->name = path; memcpy(&worldMatrix[0], &m[0], sizeof(float)*16); } Oyster::Network::CustomNetProtocol* GetProtocol() override { this->protocol[1].value = object_ID; - this->protocol[2].value = path; + this->protocol[2].value = name; this->protocol[3].value = worldMatrix[0]; this->protocol[4].value = worldMatrix[1]; this->protocol[5].value = worldMatrix[2]; @@ -70,77 +297,6 @@ namespace GameLogic - return &protocol; - } - - private: - Oyster::Network::CustomNetProtocol protocol; - }; - - struct Protocol_ObjectPosition :public Oyster::Network::CustomProtocolObject - { - int object_ID; - float worldMatrix[16]; - // look at dir - - Protocol_ObjectPosition() - { - this->protocol[protocol_INDEX_ID].value = protocol_Gameplay_ObjectPosition; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Int; - - this->protocol[1].type = Oyster::Network::NetAttributeType_Int; - - for (int i = 2; i <= 17; i++) - { - this->protocol[i].type = Oyster::Network::NetAttributeType_Float; - } - object_ID = -1; - memset(&worldMatrix[0], 0, sizeof(float) * 16); - } - Protocol_ObjectPosition(float m[16], int id) - { - this->protocol[protocol_INDEX_ID].value = protocol_Gameplay_ObjectPosition; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Int; - - this->protocol[1].type = Oyster::Network::NetAttributeType_Int; - - for (int i = 2; i <= 17; i++) - { - this->protocol[i].type = Oyster::Network::NetAttributeType_Float; - } - - object_ID = id; - memcpy(&worldMatrix[0], &m[0], sizeof(float)*16); - } - Oyster::Network::CustomNetProtocol* GetProtocol() override - { - this->protocol[1].value = object_ID; - for (int i = 2; i <= 17; i++) - { - this->protocol[i].value = worldMatrix[i-2]; - } - return &protocol; - } - - private: - Oyster::Network::CustomNetProtocol protocol; - }; - - struct Protocol_RemoveObject :public Oyster::Network::CustomProtocolObject - { - int object_ID; - - Protocol_RemoveObject() - { - this->protocol[protocol_INDEX_ID].value = protocol_Gameplay_RemoveObject; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; - - this->protocol[1].type = Oyster::Network::NetAttributeType_Int; - } - Oyster::Network::CustomNetProtocol* GetProtocol() override - { - - this->protocol[1].value = object_ID; return &protocol; } diff --git a/Code/Game/GameProtocols/PlayerProtocols.h b/Code/Game/GameProtocols/PlayerProtocols.h index 96686807..2413aa92 100644 --- a/Code/Game/GameProtocols/PlayerProtocols.h +++ b/Code/Game/GameProtocols/PlayerProtocols.h @@ -8,41 +8,44 @@ #include #include "ProtocolIdentificationID.h" +#include - +//protocol_Gameplay_PlayerMovement 300 +//protocol_Gameplay_PlayerMouseMovement 301 +//protocol_Gameplay_PlayerChangeWeapon 302 namespace GameLogic { struct Protocol_PlayerMovement :public Oyster::Network::CustomProtocolObject { - bool bForward; bool bBackward; - bool bTurnLeft; - bool bTurnRight; - bool bStrafeRight; - bool bStrafeLeft; + bool bLeft; + bool bRight; Protocol_PlayerMovement() { - this->protocol[protocol_INDEX_ID].value = protocol_Gameplay_PlayerNavigation; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; + this->protocol[0].value = protocol_Gameplay_PlayerMovement; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; this->protocol[1].type = Oyster::Network::NetAttributeType_Bool; this->protocol[2].type = Oyster::Network::NetAttributeType_Bool; this->protocol[3].type = Oyster::Network::NetAttributeType_Bool; this->protocol[4].type = Oyster::Network::NetAttributeType_Bool; - this->protocol[5].type = Oyster::Network::NetAttributeType_Bool; - this->protocol[6].type = Oyster::Network::NetAttributeType_Bool; + } + Protocol_PlayerMovement(Oyster::Network::CustomNetProtocol& p) + { + bForward = p[1].value.netBool; + bBackward = p[2].value.netBool; + bLeft = p[3].value.netBool; + bRight = p[4].value.netBool; } const Protocol_PlayerMovement& operator=(Oyster::Network::CustomNetProtocol& val) { bForward = val[1].value.netBool; bBackward = val[2].value.netBool; - bTurnLeft = val[3].value.netBool; - bTurnRight = val[4].value.netBool; - bStrafeRight = val[5].value.netBool; - bStrafeLeft = val[6].value.netBool; + bLeft = val[3].value.netBool; + bRight = val[4].value.netBool; return *this; } @@ -50,10 +53,8 @@ namespace GameLogic { this->protocol[1].value = bForward; this->protocol[2].value = bBackward; - this->protocol[3].value = bTurnLeft; - this->protocol[4].value = bTurnRight; - this->protocol[5].value = bStrafeRight; - this->protocol[6].value = bStrafeLeft; + this->protocol[3].value = bLeft; + this->protocol[4].value = bRight; return &protocol; } @@ -62,70 +63,43 @@ namespace GameLogic Oyster::Network::CustomNetProtocol protocol; }; - struct Protocol_PlayerMouse :public Oyster::Network::CustomProtocolObject + struct Protocol_PlayerLook :public Oyster::Network::CustomProtocolObject { - float dxMouse; - float dyMouse; - + float lookDirX; + float lookDirY; + float lookDirZ; - Protocol_PlayerMouse() + Protocol_PlayerLook() { - this->protocol[protocol_INDEX_ID].value = protocol_Gameplay_PlayerMouseMovement; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; - - this->protocol[1].type = Oyster::Network::NetAttributeType_Float; - this->protocol[2].type = Oyster::Network::NetAttributeType_Float; - - } - const Protocol_PlayerMouse& operator=(Oyster::Network::CustomNetProtocol& val) - { - dxMouse = val[1].value.netFloat; - dyMouse = val[2].value.netFloat; - - return *this; - } - Oyster::Network::CustomNetProtocol* GetProtocol() override - { - this->protocol[1].value = dxMouse; - this->protocol[2].value = dyMouse; - - return &protocol; - } - - private: - Oyster::Network::CustomNetProtocol protocol; - }; - - struct Protocol_PlayerPosition :public Oyster::Network::CustomProtocolObject - { - - float position[3]; - // look at dir - - Protocol_PlayerPosition() - { - this->protocol[protocol_INDEX_ID].value = protocol_Gameplay_PlayerPosition; - this->protocol[protocol_INDEX_ID].type = Oyster::Network::NetAttributeType_Short; + this->protocol[0].value = protocol_Gameplay_PlayerLookDir; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; this->protocol[1].type = Oyster::Network::NetAttributeType_Float; this->protocol[2].type = Oyster::Network::NetAttributeType_Float; this->protocol[3].type = Oyster::Network::NetAttributeType_Float; } - const Protocol_PlayerPosition& operator=(Oyster::Network::CustomNetProtocol& val) + Protocol_PlayerLook(Oyster::Network::CustomNetProtocol& p) { - position[0] = val[1].value.netFloat; - position[1] = val[2].value.netFloat; - position[2] = val[3].value.netFloat; + lookDirX = p[1].value.netFloat; + lookDirY = p[2].value.netFloat; + lookDirZ = p[3].value.netFloat; + } + const Protocol_PlayerLook& operator=(Oyster::Network::CustomNetProtocol& val) + { + lookDirX = val[1].value.netFloat; + lookDirY = val[2].value.netFloat; + lookDirZ = val[3].value.netFloat; return *this; } Oyster::Network::CustomNetProtocol* GetProtocol() override { - this->protocol[1].value = position[0]; - this->protocol[2].value = position[1]; - this->protocol[3].value = position[2]; + this->protocol[1].value = lookDirX; + this->protocol[2].value = lookDirY; + this->protocol[3].value = lookDirZ; + return &protocol; } @@ -133,6 +107,92 @@ namespace GameLogic Oyster::Network::CustomNetProtocol protocol; }; + struct Protocol_PlayerChangeWeapon :public Oyster::Network::CustomProtocolObject + { + + int ID; + + Protocol_PlayerChangeWeapon() + { + this->protocol[0].value = protocol_Gameplay_PlayerChangeWeapon; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + } + Protocol_PlayerChangeWeapon(Oyster::Network::CustomNetProtocol& p) + { + + } + const Protocol_PlayerChangeWeapon& operator=(Oyster::Network::CustomNetProtocol& val) + { + return *this; + } + Oyster::Network::CustomNetProtocol* GetProtocol() override + { + return &protocol; + } + + private: + Oyster::Network::CustomNetProtocol protocol; + }; + + struct Protocol_PlayerShot :public Oyster::Network::CustomProtocolObject + { + bool hasShot; + + Protocol_PlayerShot() + { + this->protocol[0].value = protocol_Gameplay_PlayerShot; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + + this->protocol[1].type = Oyster::Network::NetAttributeType_Bool; + } + Protocol_PlayerShot(Oyster::Network::CustomNetProtocol& p) + { + hasShot = p[1].value.netBool; + } + const Protocol_PlayerShot& operator=(Oyster::Network::CustomNetProtocol& val) + { + hasShot = val[1].value.netBool; + return *this; + } + Oyster::Network::CustomNetProtocol* GetProtocol() override + { + this->protocol[1].value = hasShot; + return &protocol; + } + + private: + Oyster::Network::CustomNetProtocol protocol; + }; + + struct Protocol_PlayerJump :public Oyster::Network::CustomProtocolObject + { + bool hasJumped; + + Protocol_PlayerJump() + { + this->protocol[0].value = protocol_Gameplay_PlayerJump; + this->protocol[0].type = Oyster::Network::NetAttributeType_Short; + + this->protocol[1].type = Oyster::Network::NetAttributeType_Bool; + } + Protocol_PlayerJump(Oyster::Network::CustomNetProtocol& p) + { + hasJumped = p[1].value.netBool; + } + const Protocol_PlayerJump& operator=(Oyster::Network::CustomNetProtocol& val) + { + hasJumped = val[1].value.netBool; + return *this; + } + Oyster::Network::CustomNetProtocol* GetProtocol() override + { + this->protocol[1].value = hasJumped; + return &protocol; + } + + private: + Oyster::Network::CustomNetProtocol protocol; + }; } #endif // !GAMELOGIC_PLAYER_PROTOCOLS_H diff --git a/Code/Game/GameProtocols/ProtocolIdentificationID.h b/Code/Game/GameProtocols/ProtocolIdentificationID.h index fb54e403..cb596a1c 100644 --- a/Code/Game/GameProtocols/ProtocolIdentificationID.h +++ b/Code/Game/GameProtocols/ProtocolIdentificationID.h @@ -8,20 +8,15 @@ /* THERE CAN ABSOLUTLEY NOT BE TWO DEFINITIONS WITH THE SAME ID!! */ -/** Index where the identifier is located(aka protocol identification index) **/ -/* Use this as id accesser since it may change in the future. */ -#define protocol_INDEX_ID 0 - - /***********************************/ /********* RESERVERD PROTOCOLS ***************************************************************************************************/ -/********** [ 0 - 100 ] *********/ +/********** [ 0 - 99 ] *********/ #define protocol_RESERVED_MIN 0 #define protocol_RESERVED_MAX 99 /***********************************/ /********* GENERAL PROTOCOLS ***************************************************************************************************/ -/***********[ 100 - 200 ]***********/ +/***********[ 100 - 199 ]***********/ #define protocol_GeneralMIN 100 #define protocol_General_Status 100 #define protocol_General_Text 101 @@ -30,28 +25,33 @@ /***********************************/ /********* LOBBY PROTOCOLS ***************************************************************************************************/ -/***********[ 200 - 300 ]***********/ +/***********[ 200 - 299 ]***********/ #define protocol_LobbyMIN 200 -#define protocol_Lobby_CreateGame 200 -#define protocol_Lobby_JoinGame 201 -#define protocol_Lobby_StartGame 202 -#define protocol_Lobby_JoinLobby 203 -#define protocol_Lobby_LeaveLobby 204 -#define protocol_Lobby_CreateGameLobby 205 +#define protocol_Lobby_Create 200 +#define protocol_Lobby_Start 201 +#define protocol_Lobby_Join 202 +#define protocol_Lobby_Login 203 +#define protocol_Lobby_Refresh 204 +#define protocol_Lobby_ClientData 205 +#define protocol_Lobby_GameData 206 #define protocol_LobbyMAX 299 /***********************************/ /********* GAMEPLAY PROTOCOLS ***************************************************************************************************/ -/***********[ 300 - 400 ]***********/ +/***********[ 300 - 399 ]***********/ #define protocol_GameplayMIN 300 -#define protocol_Gameplay_PlayerNavigation 300 -#define protocol_Gameplay_PlayerMouseMovement 301 -#define protocol_Gameplay_PlayerPosition 302 -#define protocol_Gameplay_CreateObject 303 -#define protocol_Gameplay_RemoveObject 304 -#define protocol_Gameplay_ObjectPosition 305 -#define protocol_Gameplay_Initiate 306 +#define protocol_Gameplay_PlayerMovement 300 +#define protocol_Gameplay_PlayerLookDir 301 +#define protocol_Gameplay_PlayerChangeWeapon 302 +#define protocol_Gameplay_PlayerShot 303 +#define protocol_Gameplay_PlayerJump 304 +#define protocol_Gameplay_ObjectPickup 305 +#define protocol_Gameplay_ObjectDamage 306 +#define protocol_Gameplay_ObjectPosition 307 +#define protocol_Gameplay_ObjectEnabled 308 +#define protocol_Gameplay_ObjectDisabled 309 +#define protocol_Gameplay_ObjectCreate 310 #define protocol_GameplayMAX 399 diff --git a/Code/Game/GameProtocols/Protocols.h b/Code/Game/GameProtocols/Protocols.h index 6e084b75..06b0df82 100644 --- a/Code/Game/GameProtocols/Protocols.h +++ b/Code/Game/GameProtocols/Protocols.h @@ -4,7 +4,6 @@ #include "ObjectProtocols.h" #include "PlayerProtocols.h" #include "LobbyProtocols.h" -#include "ControlProtocols.h" -#include "GameplayProtocols.h" +#include "GeneralProtocols.h" #endif // !GAMEPROTOCOLS_GAMEPROTOCOLS_H diff --git a/Code/Game/GameServer/GameClient.h b/Code/Game/GameServer/GameClient.h new file mode 100644 index 00000000..5db6efdb --- /dev/null +++ b/Code/Game/GameServer/GameClient.h @@ -0,0 +1,38 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// +#ifndef DANBIASSERVER_CLIENT_OBJECT_H +#define DANBIASSERVER_CLIENT_OBJECT_H + +#include +#include +#include +#include + +namespace DanBias +{ + /** + * Container to keep logic player and network client together as a unit. + */ + class GameClient + { + public: + GameClient(Utility::DynamicMemory::SmartPointer client, GameLogic::IPlayerData* player); + virtual~GameClient(); + + GameLogic::IPlayerData* GetPlayer(); + GameLogic::IPlayerData* ReleasePlayer(); + Utility::DynamicMemory::SmartPointer GetClient(); + Utility::DynamicMemory::SmartPointer ReleaseClient(); + int GetID() const; + + bool Equals(const Oyster::Network::NetworkClient* c); + + private: + GameLogic::IPlayerData* player; + Utility::DynamicMemory::SmartPointer client; + int id; + }; + +}//End namespace DanBias +#endif // !DANBIASSERVER_CLIENT_OBJECT_H diff --git a/Code/Game/GameServer/GameLobby.h b/Code/Game/GameServer/GameLobby.h new file mode 100644 index 00000000..8a421e1d --- /dev/null +++ b/Code/Game/GameServer/GameLobby.h @@ -0,0 +1,59 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// +#ifndef DANBIASSERVER_MAINLOBBY_H +#define DANBIASSERVER_MAINLOBBY_H + +#include +#include +#include +#include +#include "GameSession.h" + +namespace DanBias +{ + struct LobbyLevelData + { + int mapNumber; + int maxClients; + int gameMode; + int gameTime; + std::string gameName; + }; + class GameLobby :public Oyster::Network::NetworkSession + { + public: + GameLobby(); + virtual~GameLobby(); + void Release(); + void Update(); + + void SetGameDesc(const LobbyLevelData& desc); + void GetGameDesc(LobbyLevelData& desc); + bool StartGameSession(); + + private: + void ParseProtocol(Oyster::Network::CustomNetProtocol& p, Oyster::Network::NetworkClient* c); + + void GeneralStatus(GameLogic::Protocol_General_Status& p, Oyster::Network::NetworkClient* c); //id = protocol_General_Status: + void GeneralText(GameLogic::Protocol_General_Text& p, Oyster::Network::NetworkClient* c); //id = protocol_General_Text: + //void LobbyCreateGame(GameLogic::Protocol_LobbyCreateGame& p, Oyster::Network::NetworkClient* c); //id = protocol_Lobby_Create: + void LobbyStartGame(GameLogic::Protocol_LobbyStartGame& p, Oyster::Network::NetworkClient* c); //id = protocol_Lobby_Start: + //void LobbyJoin(GameLogic::Protocol_LobbyJoin& p, Oyster::Network::NetworkClient* c); //id = protocol_Lobby_Join: + void LobbyLogin(GameLogic::Protocol_LobbyLogin& p, Oyster::Network::NetworkClient* c); //id = protocol_Lobby_Login: + void LobbyRefresh(GameLogic::Protocol_LobbyRefresh& p, Oyster::Network::NetworkClient* c); //id = protocol_Lobby_Refresh: + void LobbyGameData(GameLogic::Protocol_LobbyGameData& p, Oyster::Network::NetworkClient* c); //id = protocol_Lobby_GameData: + void LobbyMainData(GameLogic::Protocol_LobbyClientData& p, Oyster::Network::NetworkClient* c); //id = protocol_Lobby_MainData: + + private: + void ClientEventCallback(Oyster::Network::NetEvent e) override; + void ClientConnectedEvent(Utility::DynamicMemory::SmartPointer client) override; + + private: + Utility::WinTimer timer; + float refreshFrequency; + GameSession gameSession; + LobbyLevelData description; + }; +}//End namespace DanBias +#endif // !DANBIASGAME_GAMELOBBY_H diff --git a/Code/Game/DanBiasServer/DanBiasServer.vcxproj b/Code/Game/GameServer/GameServer.vcxproj similarity index 81% rename from Code/Game/DanBiasServer/DanBiasServer.vcxproj rename to Code/Game/GameServer/GameServer.vcxproj index b491c65e..6c0f3ea9 100644 --- a/Code/Game/DanBiasServer/DanBiasServer.vcxproj +++ b/Code/Game/GameServer/GameServer.vcxproj @@ -19,9 +19,10 @@ - {52380DAA-0F4A-4D97-8E57-98DF39319CAF} + {143BD516-20A1-4890-A3E4-F8BFD02220E7} Win32Proj - DanBiasServer + GameServer + GameServer @@ -73,32 +74,32 @@ $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D - $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Game\GameLogic\;$(SolutionDir)Network\NetworkAPI\;$(SolutionDir)OysterMath\;$(SolutionDir)GamePhysics\;$(SolutionDir)Misc\;$(SolutionDir)WindowManager\;C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)OysterPhysics3D\;$(IncludePath) - $(OutDir);$(SolutionDir)..\External\Lib\WindowManager\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) + $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Game\GameLogic\;$(SolutionDir)Network\NetworkAPI\;$(SolutionDir)OysterMath\;$(SolutionDir)GamePhysics\;$(SolutionDir)Misc\;$(SolutionDir)WindowManager\;$(SolutionDir)OysterPhysics3D\;$(SolutionDir)Game\ServerDependencies;C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + $(OutDir);$(SolutionDir)..\External\Lib\WindowManager\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(SolutionDir)..\External\Lib\ServerDependencies\;$(LibraryPath) true $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D - $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Game\GameLogic\;$(SolutionDir)Network\NetworkAPI\;$(SolutionDir)OysterMath\;$(SolutionDir)GamePhysics\;$(SolutionDir)Misc\;$(SolutionDir)WindowManager\;C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)OysterPhysics3D\;$(IncludePath) - $(OutDir);$(SolutionDir)..\External\Lib\WindowManager\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) + $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Game\GameLogic\;$(SolutionDir)Network\NetworkAPI\;$(SolutionDir)OysterMath\;$(SolutionDir)GamePhysics\;$(SolutionDir)Misc\;$(SolutionDir)WindowManager\;$(SolutionDir)OysterPhysics3D\;$(SolutionDir)Game\ServerDependencies;C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + $(OutDir);$(SolutionDir)..\External\Lib\WindowManager\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(SolutionDir)..\External\Lib\ServerDependencies\;$(LibraryPath) false $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) - $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Game\GameLogic\;$(SolutionDir)Network\NetworkAPI\;$(SolutionDir)OysterMath\;$(SolutionDir)GamePhysics\;$(SolutionDir)Misc\;$(SolutionDir)WindowManager\;C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)OysterPhysics3D\;$(IncludePath) - $(OutDir);$(SolutionDir)..\External\Lib\WindowManager\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) + $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Game\GameLogic\;$(SolutionDir)Network\NetworkAPI\;$(SolutionDir)OysterMath\;$(SolutionDir)GamePhysics\;$(SolutionDir)Misc\;$(SolutionDir)WindowManager\;$(SolutionDir)OysterPhysics3D\;$(SolutionDir)Game\ServerDependencies;C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + $(OutDir);$(SolutionDir)..\External\Lib\WindowManager\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(SolutionDir)..\External\Lib\ServerDependencies\;$(LibraryPath) false $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) - $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Game\GameLogic\;$(SolutionDir)Network\NetworkAPI\;$(SolutionDir)OysterMath\;$(SolutionDir)GamePhysics\;$(SolutionDir)Misc\;$(SolutionDir)WindowManager\;C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)OysterPhysics3D\;$(IncludePath) - $(OutDir);$(SolutionDir)..\External\Lib\WindowManager\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) + $(SolutionDir)..\External\Include\;$(SolutionDir)Game\GameProtocols\;$(SolutionDir)Game\GameLogic\;$(SolutionDir)Network\NetworkAPI\;$(SolutionDir)OysterMath\;$(SolutionDir)GamePhysics\;$(SolutionDir)Misc\;$(SolutionDir)WindowManager\;$(SolutionDir)OysterPhysics3D\;$(SolutionDir)Game\ServerDependencies;C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + $(OutDir);$(SolutionDir)..\External\Lib\WindowManager\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(SolutionDir)..\External\Lib\ServerDependencies\;$(LibraryPath) @@ -173,37 +174,24 @@ - - - - - - - - - - - - - - - + + + + + + + + false + false + false + false + - - - - - - - - - - - - - - + + + + diff --git a/Code/Game/DanBiasServer/DanBiasServer.vcxproj.user b/Code/Game/GameServer/GameServer.vcxproj.user similarity index 100% rename from Code/Game/DanBiasServer/DanBiasServer.vcxproj.user rename to Code/Game/GameServer/GameServer.vcxproj.user diff --git a/Code/Game/GameServer/GameServerAPI.h b/Code/Game/GameServer/GameServerAPI.h new file mode 100644 index 00000000..e76b4264 --- /dev/null +++ b/Code/Game/GameServer/GameServerAPI.h @@ -0,0 +1,69 @@ +///////////////////////////////////////// +// Created by [Dennis Andersen] [2013] // +///////////////////////////////////////// +#ifndef DANBIAS_SERVER_DANBIAS_SERVER_H +#define DANBIAS_SERVER_DANBIAS_SERVER_H + +#include + +#define DANBIAS_SERVER + +#ifdef DANBIAS_SERVER_DLL_EXPORT + #define DANBIAS_SERVER_DLL __declspec(dllexport) +#else + #define DANBIAS_SERVER_DLL __declspec(dllimport) +#endif + +namespace DanBias +{ + enum DanBiasServerReturn + { + DanBiasServerReturn_Error, + DanBiasServerReturn_Sucess, + DanBiasServerReturn_GameNotCreated, + }; + + extern "C" + { + class DANBIAS_SERVER_DLL GameServerAPI + { + public: + struct ServerInitDesc + { + char* serverName; + int listenPort; + ServerInitDesc() + : serverName("Game Server") + , listenPort(15151) + {}; + }; + struct GameServerInfo + { + unsigned int listenPort; // If set to 0, the default port 15151 will be used + const char *serverIp; // This cant be mofidfied.. + }; + + public: + static DanBiasServerReturn ServerInitiate(const ServerInitDesc& desc); + static void ServerStart(); + static void ServerStop(); + static void ServerUpdate(); + static GameServerInfo ServerGetInfo(); + + static void GameSetMapId(const int& val); + static void GameSetMaxClients(const int& val); + static void GameSetGameMode(const int& val); + static void GameSetGameTime(const int& val); + static int GameGetMapId(); + static int GameGetMaxClients(); + static int GameGetGameMode(); + static int GameGetGameTime(); + static const char* GameGetGameName(); + static bool GameStart(); + + + };//End class DanBiasServer + }//End Extern "C" +} //End namspace DanBias + +#endif // !DANBIAS_SERVER_DANBIAS_SERVER_H diff --git a/Code/Game/GameServer/GameSession.h b/Code/Game/GameServer/GameSession.h new file mode 100644 index 00000000..899bc189 --- /dev/null +++ b/Code/Game/GameServer/GameSession.h @@ -0,0 +1,108 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// +#ifndef DANBIASSERVER_GAME_SESSION_H +#define DANBIASSERVER_GAME_SESSION_H + +//warning C4150: deletion of pointer to incomplete type, no destructor called, because of forward decleration and the use of smartpointer. +#pragma warning(disable: 4150) + + +#include "GameClient.h" +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace DanBias +{ + class GameSession : public Oyster::Network::NetworkSession + , public Oyster::Thread::IThreadObject + { + public: + + /** + * A container to use when initiating a new session + */ + struct GameDescription + { + int mapNumber; + int gameMode; + int gameTime; + Oyster::Network::NetworkSession* owner; + Utility::DynamicMemory::DynamicArray clients; + }; + + public: + GameSession(); + virtual~GameSession(); + + /** Initiates and creates a game session. */ + bool Create(GameDescription& desc); + + /** Runs the game session (ie starts the game loop). */ + void Run(); + + /** Join an existing/running game session + * @param client The client to attach to the session + */ + bool Attach(Oyster::Network::NetClient client) override; + + inline bool IsCreated() const { return this->isCreated; } + inline bool IsRunning() const { return this->isRunning; } + + //Private member functions + private: + // TODO: find out what this method does.. + void ClientEventCallback(Oyster::Network::NetEvent e) override; + + + //Sends a client to the owner, if obj is NULL then all clients is sent + void SendToOwner(DanBias::GameClient* obj); + + //Frame function, derived from IThreadObject + bool DoWork ( ) override; + + private: + void ParseProtocol (Oyster::Network::CustomNetProtocol& p, DanBias::GameClient* c); + + void Gameplay_PlayerMovement ( GameLogic::Protocol_PlayerMovement& p, DanBias::GameClient* c ); + void Gameplay_PlayerLookDir ( GameLogic::Protocol_PlayerLook& p, DanBias::GameClient* c ); + void Gameplay_PlayerChangeWeapon ( GameLogic::Protocol_PlayerChangeWeapon& p, DanBias::GameClient* c ); + void Gameplay_PlayerShot ( GameLogic::Protocol_PlayerShot& p, DanBias::GameClient* c ); + void Gameplay_PlayerJump ( GameLogic::Protocol_PlayerJump& p, DanBias::GameClient* c ); + void Gameplay_ObjectPickup ( GameLogic::Protocol_ObjectPickup& p, DanBias::GameClient* c ); + void Gameplay_ObjectDamage ( GameLogic::Protocol_ObjectDamage& p, DanBias::GameClient* c ); + void Gameplay_ObjectPosition ( GameLogic::Protocol_ObjectPosition& p, DanBias::GameClient* c ); + void Gameplay_ObjectEnabled ( GameLogic::Protocol_ObjectEnable& p, DanBias::GameClient* c ); + void Gameplay_ObjectDisabled ( GameLogic::Protocol_ObjectDisable& p, DanBias::GameClient* c ); + void Gameplay_ObjectCreate ( GameLogic::Protocol_ObjectCreate& p, DanBias::GameClient* c ); + void General_Status ( GameLogic::Protocol_General_Status& p, DanBias::GameClient* c ); + void General_Text ( GameLogic::Protocol_General_Text& p, DanBias::GameClient* c ); + + //Callback method recieving from gamelogic + static void ObjectMove(GameLogic::IObjectData* movedObject); + + //Private member variables + private: + Utility::DynamicMemory::DynamicArray> clients; + Oyster::Thread::OysterThread worker; + GameLogic::GameAPI& gameInstance; + GameLogic::ILevelData *levelData; + NetworkSession* owner; + bool isCreated; + bool isRunning; + Utility::WinTimer timer; + GameDescription description; + + //TODO: Remove this uggly hax + static GameSession* gameSession; + + };//End GameSession +}//End namespace DanBias +#endif // !DANBIASSERVER_GAME_SESSION_H \ No newline at end of file diff --git a/Code/Game/DanBiasServer/DLLMain.cpp b/Code/Game/GameServer/Implementation/DLLMain.cpp similarity index 100% rename from Code/Game/DanBiasServer/DLLMain.cpp rename to Code/Game/GameServer/Implementation/DLLMain.cpp diff --git a/Code/Game/GameServer/Implementation/GameClient.cpp b/Code/Game/GameServer/Implementation/GameClient.cpp new file mode 100644 index 00000000..3f0c8308 --- /dev/null +++ b/Code/Game/GameServer/Implementation/GameClient.cpp @@ -0,0 +1,58 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + +#include "..\GameClient.h" +#include +#include + +using namespace Utility::DynamicMemory; +using namespace Oyster::Network; +using namespace DanBias; +using namespace GameLogic; + +static int gameClientIDCount = 1; + +GameClient::GameClient(SmartPointer client, GameLogic::IPlayerData* player) +{ + this->client = client; + this->id = gameClientIDCount++; + this->player = player; +} +GameClient::~GameClient() +{ + this->client->Disconnect(); + this->player = 0; + this->id = -1; +} + +GameLogic::IPlayerData* GameClient::GetPlayer() +{ + return this->player; +} +GameLogic::IPlayerData* GameClient::ReleasePlayer() +{ + GameLogic::IPlayerData *temp = this->player; + this->player = 0; + return temp; +} +SmartPointer GameClient::GetClient() +{ + return this->client; +} +SmartPointer GameClient::ReleaseClient() +{ + SmartPointer temp = this->client; + this->client = 0; + return temp; +} +int GameClient::GetID() const +{ + return this->id; +} +bool GameClient::Equals(const NetworkClient* c) +{ + return (c->GetID() == this->client->GetID()); +} + + diff --git a/Code/Game/GameServer/Implementation/GameLobby.cpp b/Code/Game/GameServer/Implementation/GameLobby.cpp new file mode 100644 index 00000000..b68846d4 --- /dev/null +++ b/Code/Game/GameServer/Implementation/GameLobby.cpp @@ -0,0 +1,113 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// +#include "..\GameLobby.h" +#include +#include +#include + +using namespace Utility::DynamicMemory; +using namespace Oyster::Network; +using namespace Oyster; +using namespace GameLogic; + +namespace DanBias +{ + GameLobby::GameLobby() + { } + + GameLobby::~GameLobby() + { } + + void GameLobby::Release() + { + NetworkSession::CloseSession(true); + } + + void GameLobby::Update() + { + if(GetAsyncKeyState(VK_DOWN)) //TODO: Dont forget to remove this... + this->Send(*GameLogic::Protocol_General_Status().GetProtocol()); + + this->ProcessClients(); + } + void GameLobby::SetGameDesc(const LobbyLevelData& desc) + { + this->description.gameMode = desc.gameMode; + this->description.gameTime = desc.gameTime; + this->description.mapNumber = desc.mapNumber; + this->description.maxClients = desc.maxClients; + } + void GameLobby::GetGameDesc(LobbyLevelData& desc) + { + desc.gameMode = this->description.gameMode; + desc.gameTime = this->description.gameTime; + desc.mapNumber = this->description.mapNumber; + desc.maxClients = this->description.maxClients; + } + bool GameLobby::StartGameSession() + { + GameSession::GameDescription desc; + desc.gameMode = this->description.gameMode; + desc.gameTime = this->description.gameTime; + desc.mapNumber = this->description.mapNumber; + desc.owner = this; + desc.clients = this->clients; + + this->clients.Clear(); + + if(this->gameSession.Create(desc)) + { + this->gameSession.Run(); + return true; + } + return false; + } + + void GameLobby::ClientEventCallback(NetEvent e) + { + switch (e.args.type) + { + case NetworkClient::ClientEventArgs::EventType_Disconnect: + break; + case NetworkClient::ClientEventArgs::EventType_ProtocolFailedToRecieve: + break; + case NetworkClient::ClientEventArgs::EventType_ProtocolFailedToSend: + printf("\t(%i : %s) - EventType_ProtocolFailedToSend\n", e.sender->GetID(), e.sender->GetIpAddress().c_str()); + e.sender->Disconnect(); + break; + case NetworkClient::ClientEventArgs::EventType_ProtocolRecieved: + printf("\t(%i : %s) - EventType_ProtocolRecieved\n", e.sender->GetID(), e.sender->GetIpAddress().c_str()); + this->ParseProtocol(e.args.data.protocol, e.sender); + break; + } + } + void GameLobby::ClientConnectedEvent(Utility::DynamicMemory::SmartPointer client) + { + printf("New client(%i) connected - %s \n", client->GetID(), client->GetIpAddress().c_str()); + Attach(client); + + Protocol_LobbyClientData p1; + Protocol_LobbyGameData p2; + + for (unsigned int i = 0; i < this->clients.Size(); i++) + { + if(this->clients[i]) + { + Protocol_LobbyClientData::PlayerData t; + t.id = this->clients[i]->GetID(); + t.ip = this->clients[i]->GetIpAddress(); + t.team = 0; + t.name = "DennisÄrKung"; + p1.list.Push(t); + } + } + p2.majorVersion = 1; + p2.minorVersion = 0; + p2.mapName = "BetsMap"; + + client->Send(p1.GetProtocol()); + client->Send(p2.GetProtocol()); + } + +}//End namespace DanBias \ No newline at end of file diff --git a/Code/Game/GameServer/Implementation/GameLobby_ProtocolParser.cpp b/Code/Game/GameServer/Implementation/GameLobby_ProtocolParser.cpp new file mode 100644 index 00000000..3a86bc6b --- /dev/null +++ b/Code/Game/GameServer/Implementation/GameLobby_ProtocolParser.cpp @@ -0,0 +1,95 @@ +#include "..\GameLobby.h" + +using namespace DanBias; +using namespace GameLogic; +using namespace Oyster::Network; + + +void GameLobby::ParseProtocol(Oyster::Network::CustomNetProtocol& p, NetworkClient* c) +{ + switch (p[0].value.netShort) + { + case protocol_General_Status: this->GeneralStatus (Protocol_General_Status (p), c); + break; + case protocol_General_Text: this->GeneralText (Protocol_General_Text (p), c); + break; + //case protocol_Lobby_Create: this->LobbyCreateGame (Protocol_LobbyCreateGame (p), c); + //break; + case protocol_Lobby_Start: this->LobbyStartGame (Protocol_LobbyStartGame (p), c); + break; + //case protocol_Lobby_Join: this->LobbyJoin (Protocol_LobbyJoin (p), c); + //break; + case protocol_Lobby_Login: this->LobbyLogin (Protocol_LobbyLogin (p), c); + break; + case protocol_Lobby_Refresh: this->LobbyRefresh (Protocol_LobbyRefresh (p), c); + break; + case protocol_Lobby_GameData: this->LobbyGameData (Protocol_LobbyGameData (p), c); + break; + case protocol_Lobby_ClientData: this->LobbyMainData (Protocol_LobbyClientData (p), c); + break; + //case protocol_Lobby_GameData: this->LobbyGameData (Protocol_LobbyGameData (p), c); + //break; + } +} + + +void GameLobby::GeneralStatus(GameLogic::Protocol_General_Status& p, Oyster::Network::NetworkClient* c) +{ + switch (p.status) + { + case Protocol_General_Status::States_ready: + { + + } + case Protocol_General_Status::States_idle: + { + + } + case Protocol_General_Status::States_leave: + case Protocol_General_Status::States_disconected: + { + Detach(c)->Disconnect(); + } + } +} +void GameLobby::GeneralText(GameLogic::Protocol_General_Text& p, Oyster::Network::NetworkClient* c) +{ + printf(p.text.c_str()); +} +//void GameLobby::LobbyCreateGame(GameLogic::Protocol_LobbyCreateGame& p, Oyster::Network::NetworkClient* c) +//{ +// +//} +void GameLobby::LobbyStartGame(GameLogic::Protocol_LobbyStartGame& p, Oyster::Network::NetworkClient* c) +{ + //TODO: Prio 1 +} +//void GameLobby::LobbyJoin(GameLogic::Protocol_LobbyJoin& p, Oyster::Network::NetworkClient* c) +//{ +// //for (unsigned int i = 0; i < this->gameLobby.Size(); i++) +// //{ +// // if (this->gameLobby[i]->GetID() == p.value) +// // { +// // this->gameLobby[i]->Attach(Detach(c)); +// // return; +// // } +// //} +//} +void GameLobby::LobbyLogin(GameLogic::Protocol_LobbyLogin& p, Oyster::Network::NetworkClient* c) +{ + +} +void GameLobby::LobbyRefresh(GameLogic::Protocol_LobbyRefresh& p, Oyster::Network::NetworkClient* c) +{ + //Dont need to handle this on the server... +} +void GameLobby::LobbyGameData(GameLogic::Protocol_LobbyGameData& p, Oyster::Network::NetworkClient* c) +{ + +} +void GameLobby::LobbyMainData(GameLogic::Protocol_LobbyClientData& p, Oyster::Network::NetworkClient* c) +{ + +} + + diff --git a/Code/Game/GameServer/Implementation/GameServer.cpp b/Code/Game/GameServer/Implementation/GameServer.cpp new file mode 100644 index 00000000..416503e5 --- /dev/null +++ b/Code/Game/GameServer/Implementation/GameServer.cpp @@ -0,0 +1,155 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// +#define NOMINMAX +#include +#include +#include + +#include "..\GameServerAPI.h" +#include "..\GameLobby.h" +#include "..\GameSession.h" + +#include +#include + +#include +#include +#include +#include + +using namespace DanBias; +using namespace Oyster::Network; +using namespace Oyster::Thread; +using namespace Utility; + +namespace +{ + GameLobby lobby; + NetworkServer server; + WinTimer timer; +} + + + +DanBiasServerReturn GameServerAPI::ServerInitiate(const ServerInitDesc& desc) +{ + if(server.Init(desc.listenPort, &lobby) == NetworkServer::ServerReturnCode_Error) + { + return DanBiasServerReturn_Error; + } + GameSession::GameDescription d; + + std::printf("Server created!\t-\t%s: [%i]\n\n", server.GetLanAddress().c_str(), desc.listenPort); + + return DanBiasServerReturn_Sucess; +} +void GameServerAPI::ServerStart() +{ + timer.reset(); + server.Start(); + + +} +void GameServerAPI::ServerStop() +{ + lobby.Release(); + server.Shutdown(); + + + double total = timer.getElapsedSeconds(); + int time = (int)total; + int hour, min, sec; + + hour=time / 3600; + time=time % 3600; + min=time / 60; + time=time % 60; + sec = time; + + printf( "Server has been running for: %i:%i:%i - [hh:mm:ss] \n\n", hour, min, sec ); + printf( "Terminating in : "); + for (int i = 0; i < 3; i++) + { + printf( "%i ", 3-i ); + Sleep(1000); + } + printf( "\nServer terminated!" ); +} +void GameServerAPI::ServerUpdate() +{ + server.Update(); + lobby.Update(); + +} + +GameServerAPI::GameServerInfo GameServerAPI::ServerGetInfo() +{ + GameServerAPI::GameServerInfo i; + i.serverIp = server.GetLanAddress().c_str(); + i.listenPort = server.GetPort(); + return i; +} +void GameServerAPI::GameSetMapId(const int& val) +{ + LobbyLevelData d; + lobby.GetGameDesc(d); + d.mapNumber = val; + lobby.SetGameDesc(d); +} +void GameServerAPI::GameSetMaxClients(const int& val) +{ + LobbyLevelData d; + lobby.GetGameDesc(d); + d.maxClients = val; + lobby.SetGameDesc(d); +} +void GameServerAPI::GameSetGameMode(const int& val) +{ + LobbyLevelData d; + lobby.GetGameDesc(d); + d.gameMode = val; + lobby.SetGameDesc(d); +} +void GameServerAPI::GameSetGameTime(const int& val) +{ + LobbyLevelData d; + lobby.GetGameDesc(d); + d.gameTime = val; + lobby.SetGameDesc(d); +} +int GameServerAPI::GameGetMapId() +{ + LobbyLevelData d; + lobby.GetGameDesc(d); + return d.mapNumber; +} +int GameServerAPI::GameGetMaxClients() +{ + LobbyLevelData d; + lobby.GetGameDesc(d); + return d.maxClients; +} +int GameServerAPI::GameGetGameMode() +{ + LobbyLevelData d; + lobby.GetGameDesc(d); + return d.gameMode; +} +int GameServerAPI::GameGetGameTime() +{ + LobbyLevelData d; + lobby.GetGameDesc(d); + return d.gameTime; +} +const char* GameServerAPI::GameGetGameName() +{ + LobbyLevelData d; + lobby.GetGameDesc(d); + return d.gameName.c_str(); +} +bool GameServerAPI::GameStart() +{ + return lobby.StartGameSession(); +} + diff --git a/Code/Game/GameServer/Implementation/GameSession_Gameplay.cpp b/Code/Game/GameServer/Implementation/GameSession_Gameplay.cpp new file mode 100644 index 00000000..c0041301 --- /dev/null +++ b/Code/Game/GameServer/Implementation/GameSession_Gameplay.cpp @@ -0,0 +1,248 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// +#include "..\GameSession.h" +#include "..\GameClient.h" + +#include +#include +#include +#include +#define NOMINMAX +#include + +#define DELTA_TIME_20 0.05f +#define DELTA_TIME_24 0.04166666666666666666666666666667f +#define DELTA_TIME_30 0.03333333333333333333333333333333f +#define DELTA_TIME_60 0.01666666666666666666666666666667f +#define DELTA_TIME_120 0.00833333333333333333333333333333f + +using namespace Utility::DynamicMemory; +using namespace Oyster; +using namespace Oyster::Network; +using namespace Oyster::Thread; +using namespace GameLogic; + +namespace DanBias +{ + bool GameSession::DoWork( ) + { + if(this->isRunning) + { + double dt = this->timer.getElapsedSeconds(); + gameInstance.SetFrameTimeLength((float)dt); + + if(dt >= DELTA_TIME_20) + { + this->ProcessClients(); + + this->gameInstance.NewFrame(); + + this->timer.reset(); + } + } + + return this->isRunning; + } + + void GameSession::ClientEventCallback(NetEvent e) + { + int temp = -1; + //Find the idiot + for (unsigned int i = 0; i < this->clients.Size(); i++) + { + if(this->clients[i]->Equals(e.sender)) + { + temp = i; + } + } + + if(temp == -1) + { + this->Detach(e.sender)->Disconnect(); + return; + } + SmartPointer cl = this->clients[temp]; + + switch (e.args.type) + { + case NetworkClient::ClientEventArgs::EventType_Disconnect: + break; + case NetworkClient::ClientEventArgs::EventType_ProtocolFailedToRecieve: + break; + case NetworkClient::ClientEventArgs::EventType_ProtocolFailedToSend: + printf("\t(%i : %s) - EventType_ProtocolFailedToSend\n", e.sender->GetID(), e.sender->GetIpAddress().c_str()); + this->Detach(e.sender)->Disconnect(); + break; + case NetworkClient::ClientEventArgs::EventType_ProtocolRecieved: + printf("\t(%i : %s) - EventType_ProtocolRecieved\n", e.sender->GetID(), e.sender->GetIpAddress().c_str()); + this->ParseProtocol(e.args.data.protocol, cl); + break; + } + } + + void GameSession::ObjectMove(GameLogic::IObjectData* movedObject) + { + if(dynamic_cast (movedObject)) + { + IPlayerData* temp = (IPlayerData*)movedObject; + temp->GetID(); + Oyster::Math::Float4x4 world = temp->GetOrientation(); + + Protocol_ObjectPosition p(world, 2); + GameSession::gameSession->Send(*p.GetProtocol()); + } + GameLogic::IObjectData* obj = NULL; + if(dynamic_cast(movedObject)) + { + obj = ((GameLogic::ILevelData*)movedObject)->GetObjectAt(0); + if(obj) + { + if(obj->GetObjectType() == OBJECT_TYPE_WORLD) + { + obj->GetID(); + Oyster::Math::Float4x4 world =obj->GetOrientation(); + + Protocol_ObjectPosition p(world, 0); + GameSession::gameSession->Send(*p.GetProtocol()); + } + } + + obj = NULL; + obj =((GameLogic::ILevelData*)movedObject)->GetObjectAt(1); + if(obj) + { + if(obj->GetObjectType() == OBJECT_TYPE_BOX) + { + obj->GetID(); + Oyster::Math::Float4x4 world = obj->GetOrientation(); + Protocol_ObjectPosition p(world, 1); + GameSession::gameSession->Send(*p.GetProtocol()); + } + } + } + + } + +//*****************************************************// +//****************** Protocol methods *****************// +//******************************************************************************************************************// + + void GameSession::ParseProtocol(Oyster::Network::CustomNetProtocol& p, DanBias::GameClient* c) + { + switch (p[0].value.netShort) + { + case protocol_Gameplay_PlayerMovement: this->Gameplay_PlayerMovement ( Protocol_PlayerMovement (p), c ); + break; + case protocol_Gameplay_PlayerLookDir: this->Gameplay_PlayerLookDir ( Protocol_PlayerLook (p), c ); + break; + case protocol_Gameplay_PlayerChangeWeapon: this->Gameplay_PlayerChangeWeapon ( Protocol_PlayerChangeWeapon (p), c ); + break; + case protocol_Gameplay_PlayerShot: this->Gameplay_PlayerShot ( Protocol_PlayerShot (p), c ); + break; + case protocol_Gameplay_PlayerJump: this->Gameplay_PlayerJump ( Protocol_PlayerJump (p), c ); + break; + case protocol_Gameplay_ObjectPickup: this->Gameplay_ObjectPickup ( Protocol_ObjectPickup (p), c ); + break; + case protocol_Gameplay_ObjectDamage: this->Gameplay_ObjectDamage ( Protocol_ObjectDamage (p), c ); + break; + case protocol_Gameplay_ObjectPosition: this->Gameplay_ObjectPosition ( Protocol_ObjectPosition (p), c ); + break; + case protocol_Gameplay_ObjectEnabled: this->Gameplay_ObjectEnabled ( Protocol_ObjectEnable (p), c ); + break; + case protocol_Gameplay_ObjectDisabled: this->Gameplay_ObjectDisabled ( Protocol_ObjectDisable (p), c ); + break; + case protocol_Gameplay_ObjectCreate: this->Gameplay_ObjectCreate ( Protocol_ObjectCreate (p), c ); + break; + case protocol_General_Status: this->General_Status ( Protocol_General_Status (p), c ); + break; + case protocol_General_Text: this->General_Text ( Protocol_General_Text (p), c ); + break; + } + } + + void GameSession::Gameplay_PlayerMovement ( Protocol_PlayerMovement& p, DanBias::GameClient* c ) + { + if(p.bForward) c->GetPlayer()->Move(GameLogic::PLAYER_MOVEMENT_FORWARD); + if(p.bBackward) c->GetPlayer()->Move(GameLogic::PLAYER_MOVEMENT_BACKWARD); + if(p.bLeft) c->GetPlayer()->Move(GameLogic::PLAYER_MOVEMENT_LEFT); + if(p.bRight) c->GetPlayer()->Move(GameLogic::PLAYER_MOVEMENT_RIGHT); + } + void GameSession::Gameplay_PlayerLookDir ( Protocol_PlayerLook& p, DanBias::GameClient* c ) + { + Oyster::Math3D::Float3 lookDir; + lookDir.x = p.lookDirX; + lookDir.y = p.lookDirY; + lookDir.z = p.lookDirZ; + c->GetPlayer()->Rotate(lookDir); + } + void GameSession::Gameplay_PlayerChangeWeapon ( Protocol_PlayerChangeWeapon& p, DanBias::GameClient* c ) + { + + } + void GameSession::Gameplay_PlayerShot ( Protocol_PlayerShot& p, DanBias::GameClient* c ) + { + c->GetPlayer()->UseWeapon(GameLogic::WEAPON_USE_PRIMARY_PRESS); + } + void GameSession::Gameplay_PlayerJump ( Protocol_PlayerJump& p, DanBias::GameClient* c ) + { + if(p.hasJumped) c->GetPlayer()->Move(GameLogic::PLAYER_MOVEMENT_JUMP); + } + void GameSession::Gameplay_ObjectPickup ( Protocol_ObjectPickup& p, DanBias::GameClient* c ) + { + + } + void GameSession::Gameplay_ObjectDamage ( Protocol_ObjectDamage& p, DanBias::GameClient* c ) + { + + } + void GameSession::Gameplay_ObjectPosition ( Protocol_ObjectPosition& p, DanBias::GameClient* c ) + { + + } + void GameSession::Gameplay_ObjectEnabled ( Protocol_ObjectEnable& p, DanBias::GameClient* c ) + { + + } + void GameSession::Gameplay_ObjectDisabled ( Protocol_ObjectDisable& p, DanBias::GameClient* c ) + { + + } + void GameSession::Gameplay_ObjectCreate ( Protocol_ObjectCreate& p, DanBias::GameClient* c ) + { + + } + void GameSession::General_Status ( Protocol_General_Status& p, DanBias::GameClient* c ) + { + switch (p.status) + { + case GameLogic::Protocol_General_Status::States_disconected: + printf("Client with ID [%i] dissconnected\n", c->GetClient()->GetID()); + this->Detach(c->GetClient()->GetID()); + break; + + case GameLogic::Protocol_General_Status::States_idle: + + break; + + case GameLogic::Protocol_General_Status::States_ready: + + break; + + case GameLogic::Protocol_General_Status::States_leave: + + break; + } + } + void GameSession::General_Text ( Protocol_General_Text& p, DanBias::GameClient* c ) + { + printf("Message recieved from (%i):\t %s\n", c->GetID(), p.text.c_str()); + } + +}//End namespace DanBias + + + + + + diff --git a/Code/Game/DanBiasServer/GameSession/GameSession_General.cpp b/Code/Game/GameServer/Implementation/GameSession_General.cpp similarity index 53% rename from Code/Game/DanBiasServer/GameSession/GameSession_General.cpp rename to Code/Game/GameServer/Implementation/GameSession_General.cpp index 0f9f3c57..ae947874 100644 --- a/Code/Game/DanBiasServer/GameSession/GameSession_General.cpp +++ b/Code/Game/GameServer/Implementation/GameSession_General.cpp @@ -1,13 +1,13 @@ ///////////////////////////////////////////////////////////////////// // Created by [Dennis Andersen] [2013] ///////////////////////////////////////////////////////////////////// -#include "GameSession.h" -#include "GameClient.h" -#include "..\GameServer.h" +#include "..\GameSession.h" +#include "..\GameClient.h" #include #include #include +#define NOMINMAX #include @@ -19,33 +19,40 @@ using namespace GameLogic; namespace DanBias { + GameSession* GameSession::gameSession = nullptr; + GameSession::GameSession() :gameInstance(GameAPI::Instance()) { this->owner = 0; - this->box = 0; this->isCreated = false; this->isRunning = false; + this->gameSession = this; + + memset(&this->description, 0, sizeof(GameDescription)); } GameSession::~GameSession() { - delete this->box; - this->box = 0; + this->worker.Terminate(); + this->clients.Clear(); + this->gameInstance; this->owner = 0; + this->isCreated = false; + this->isRunning = false; } bool GameSession::Create(GameDescription& desc) { + this->description = desc; /* Do some error checking */ if(desc.clients.Size() == 0) return false; if(!desc.owner) return false; - if(!desc.mapName.size()) return false; if(this->isCreated) return false; /* standard initialization of some data */ + NetworkSession::clients = desc.clients; this->clients.Resize(desc.clients.Size()); - this->box = new PostBox(); this->owner = desc.owner; /* Initiate the game instance */ @@ -61,18 +68,14 @@ namespace DanBias return false; } - /* Create a callback object */ - Oyster::Callback::OysterCallback c; - c.value.callbackPostBox = this->box; - c.callbackType = Oyster::Callback::CallbackType_PostBox; - /* Create the players in the game instance */ GameLogic::IPlayerData* p = 0; for (unsigned int i = 0; i < desc.clients.Size(); i++) { if( (p = this->gameInstance.CreatePlayer()) ) { - this->clients[i] = new GameClient(desc.clients[i], p, c); + desc.clients[i]->SetOwner(this); + this->clients[i] = new GameClient(desc.clients[i], p); } else { @@ -81,12 +84,12 @@ namespace DanBias } /* Create the worker thread */ - if(this->worker.Create(this, true, true) != OYSTER_THREAD_ERROR_SUCCESS) + if(this->worker.Create(this, false) != OYSTER_THREAD_ERROR_SUCCESS) return false; this->worker.SetPriority(Oyster::Thread::OYSTER_THREAD_PRIORITY_3); - /* Set some gameinstance data options */ + /* Set some game instance data options */ this->gameInstance.SetSubscription(GameLogic::GameEvent::ObjectEventFunctionType_OnMove, GameSession::ObjectMove); this->isCreated = true; @@ -95,106 +98,39 @@ namespace DanBias void GameSession::Run() { - if(this->isRunning) return; if(this->clients.Size() > 0) { + this->worker.Start(); this->worker.SetPriority(OYSTER_THREAD_PRIORITY_1); this->isRunning = true; } } - bool GameSession::Join(Utility::DynamicMemory::SmartPointer client) + + + bool GameSession::Attach(Utility::DynamicMemory::SmartPointer client) { if(!this->isCreated) return false; - Oyster::Callback::OysterCallback c; - c.value.callbackPostBox = this->box; - c.callbackType = Oyster::Callback::CallbackType_PostBox; - - SmartPointer obj = new GameClient(client, this->gameInstance.CreatePlayer(), c); - InsertClient(obj); - - return true; - } - - void GameSession::CloseSession(bool dissconnectClients) - { - if(dissconnectClients) - { - for (unsigned int i = 0; i < this->clients.Size(); i++) - { - this->clients[i]->GetClient()->Disconnect(); - } - } - else - { - this->SendToOwner(0); //Send all clients to the current owner - } - this->Clean(); - } - - void GameSession::InsertClient(SmartPointer obj) - { + client->SetOwner(this); + SmartPointer obj = new GameClient(client, this->gameInstance.CreatePlayer()); + for (unsigned int i = 0; i < clients.Size(); i++) { if(!clients[i]) { clients[i] = obj; - return; + return true; } } + clients.Push(obj); + + return true; } - void GameSession::RemoveClient(DanBias::GameClient* obj) - { - for (unsigned int i = 0; i < clients.Size(); i++) - { - if(clients[i] && clients[i]->GetID() == obj->GetID()) - { - clients[i] = 0; - return; - } - } - } - - void GameSession::SendToOwner(DanBias::GameClient* obj) - { - DanBias::NetworkSession *s = GameServer::MainLobbyInstance(); - - if(this->owner) s = this->owner; - - if(obj) - { - s->Attach(obj->ReleaseClient()); - RemoveClient(obj); - } - else - { - for (unsigned int i = 0; i < this->clients.Size(); i++) - { - if(this->clients[i]) - { - s->Attach(this->clients[i]->ReleaseClient()); - RemoveClient(this->clients[i]); - } - } - } - } - - void GameSession::Clean() - { - this->worker.Terminate(); - this->clients.Clear(); - delete this->box; - this->box = 0; - this->gameInstance; - this->owner = 0; - this->isCreated = false; - this->isRunning = false; - } }//End namespace DanBias diff --git a/Code/Game/aDanBiasGameLauncher/Launcher.cpp b/Code/Game/aDanBiasGameLauncher/Launcher.cpp new file mode 100644 index 00000000..e13baff1 --- /dev/null +++ b/Code/Game/aDanBiasGameLauncher/Launcher.cpp @@ -0,0 +1,70 @@ + +#define NOMINMAX +#include +#include + +#include "DanBiasGame.h" +#include + +#include + + +void ServerFnc() +{ + DanBias::GameServerAPI::ServerInitDesc desc; + desc.listenPort = 15151; + if(DanBias::GameServerAPI::ServerInitiate(desc) == DanBias::DanBiasServerReturn_Sucess) + { + DanBias::GameServerAPI::ServerStart(); + while (!(GetAsyncKeyState(0x51))) //Q for exit + { + DanBias::GameServerAPI::ServerUpdate(); + Sleep(1); + } + DanBias::GameServerAPI::ServerStop(); + } + + Sleep(100); +} +void ClientFnc() +{ + // Game client starter code goes here + DanBias::DanBiasGameDesc gameDesc; + gameDesc.port = 15151; + //gameDesc.port = 15152; + //gameDesc.IP = "193.11.184.196"; + //gameDesc.IP = "193.11.184.31"; + //gameDesc.IP = "194.47.150.56"; + gameDesc.IP = "127.0.0.1"; + //gameDesc.IP = "194.47.150.184"; + + if( DanBias::DanBiasGame::Initiate(gameDesc) == DanBias::DanBiasClientReturn_Sucess) + { + DanBias::DanBiasGame::Run(); + DanBias::DanBiasGame::Release(); + } + Sleep(100); +} + + +int WINAPI WinMain( HINSTANCE hinst, HINSTANCE prevInst, PSTR cmdLine, int cmdShow) +{ + std::thread serverThread; + std::thread clientThread; + + if(SetDllDirectory(L"..\\DLL") == FALSE) + { + return cmdShow; + } + + serverThread = std::thread(ServerFnc); + + Sleep(200); + + clientThread = std::thread(ClientFnc); + + if (serverThread.joinable()) serverThread.join(); + if (clientThread.joinable()) clientThread.join(); + + return cmdShow; +} \ No newline at end of file diff --git a/Code/Game/aDanBiasGameLauncher/aDanBiasGameLauncher.vcxproj b/Code/Game/aDanBiasGameLauncher/aDanBiasGameLauncher.vcxproj new file mode 100644 index 00000000..f9b46097 --- /dev/null +++ b/Code/Game/aDanBiasGameLauncher/aDanBiasGameLauncher.vcxproj @@ -0,0 +1,187 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {666FEA52-975F-41CD-B224-B19AF3C0ABBA} + Win32Proj + aDanBiasGameLauncher + + + + 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 + $(SolutionDir)..\External\Include\;C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)Game\GameServer;$(IncludePath) + $(OutDir)..\DLL\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) + + + true + $(SolutionDir)..\Bin\Executable\ + $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ + $(ProjectName)_$(PlatformShortName)D + $(SolutionDir)..\External\Include\;C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)Game\GameServer;$(IncludePath) + $(OutDir)..\DLL\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) + + + false + $(SolutionDir)..\Bin\Executable\ + $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ + $(ProjectName)_$(PlatformShortName) + $(SolutionDir)..\External\Include\;C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)Game\GameServer;$(IncludePath) + $(OutDir)..\DLL\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) + + + false + $(SolutionDir)..\Bin\Executable\ + $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ + $(ProjectName)_$(PlatformShortName) + $(SolutionDir)..\External\Include\;C:\Program Files %28x86%29\Visual Leak Detector\include;$(SolutionDir)Game\GameServer;$(IncludePath) + $(OutDir)..\DLL\;C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + $(SolutionDir)Game\DanBiasServer\;$(SolutionDir)Game\DanBiasGame\Include + + + Windows + true + DanBiasGame_$(PlatformShortName)D.dll;GameServer_$(PlatformShortName)D.dll;%(DelayLoadDLLs) + DanBiasGame_$(PlatformShortName)D.lib;GameServer_$(PlatformShortName)D.lib;%(AdditionalDependencies) + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + $(SolutionDir)Game\DanBiasServer\Include;$(SolutionDir)Game\DanBiasGame\Include + + + Windows + true + DanBiasGame_$(PlatformShortName)D.dll;GameServer_$(PlatformShortName)D.dll;%(DelayLoadDLLs) + DanBiasGame_$(PlatformShortName)D.lib;GameServer_$(PlatformShortName)D.lib;%(AdditionalDependencies) + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + $(SolutionDir)Game\DanBiasServer\Include;$(SolutionDir)Game\DanBiasGame\Include + + + Windows + true + true + true + DanBiasGame_$(PlatformShortName).dll;GameServer_$(PlatformShortName).dll;%(DelayLoadDLLs) + DanBiasGame_$(PlatformShortName).lib;GameServer_$(PlatformShortName).lib;%(AdditionalDependencies) + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + $(SolutionDir)Game\DanBiasServer\Include;$(SolutionDir)Game\DanBiasGame\Include + + + Windows + true + true + true + DanBiasGame_$(PlatformShortName).dll;GameServer_$(PlatformShortName).dll;%(DelayLoadDLLs) + DanBiasGame_$(PlatformShortName).lib;GameServer_$(PlatformShortName).lib;%(AdditionalDependencies) + + + + + + + + {2a1bc987-af42-4500-802d-89cd32fc1309} + + + {143bd516-20a1-4890-a3e4-f8bfd02220e7} + + + + + + \ No newline at end of file diff --git a/Code/Game/aDanBiasGameLauncher/aDanBiasGameLauncher.vcxproj.user b/Code/Game/aDanBiasGameLauncher/aDanBiasGameLauncher.vcxproj.user new file mode 100644 index 00000000..2e28d6f7 --- /dev/null +++ b/Code/Game/aDanBiasGameLauncher/aDanBiasGameLauncher.vcxproj.user @@ -0,0 +1,22 @@ + + + + true + + + $(OutDir) + WindowsLocalDebugger + + + $(OutDir) + WindowsLocalDebugger + + + $(OutDir) + WindowsLocalDebugger + + + $(OutDir) + WindowsLocalDebugger + + \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/Octree.cpp b/Code/GamePhysics/Implementation/Octree.cpp index 3faff29e..b4395516 100644 --- a/Code/GamePhysics/Implementation/Octree.cpp +++ b/Code/GamePhysics/Implementation/Octree.cpp @@ -128,13 +128,13 @@ void Octree::Visit(ICustomBody* customBodyRef, VisitorAction hitAction ) } } -void Octree::Visit(const Oyster::Collision3D::ICollideable& collideable, VisitorActionCollideable hitAction) +void Octree::Visit(const Oyster::Collision3D::ICollideable& collideable, void* args, VisitorActionCollideable hitAction) { for(unsigned int i = 0; ileafData.size(); i++) { if(collideable.Intersects(this->leafData[i].container)) { - hitAction( this->GetCustomBody(i) ); + hitAction( this->GetCustomBody(i), args ); } } } diff --git a/Code/GamePhysics/Implementation/Octree.h b/Code/GamePhysics/Implementation/Octree.h index 7b350795..50b9569a 100644 --- a/Code/GamePhysics/Implementation/Octree.h +++ b/Code/GamePhysics/Implementation/Octree.h @@ -18,7 +18,7 @@ namespace Oyster static const unsigned int invalid_ref; typedef void(*VisitorAction)(Octree&, unsigned int, unsigned int); - typedef void(*VisitorActionCollideable)(ICustomBody*); + typedef void(*VisitorActionCollideable)(ICustomBody*, void*); struct Data { @@ -53,7 +53,7 @@ namespace Oyster std::vector& Sample(ICustomBody* customBodyRef, std::vector& updateList); std::vector& Sample(const Oyster::Collision3D::ICollideable& collideable, std::vector& updateList); void Visit(ICustomBody* customBodyRef, VisitorAction hitAction ); - void Visit(const Oyster::Collision3D::ICollideable& collideable, VisitorActionCollideable hitAction ); + void Visit(const Oyster::Collision3D::ICollideable& collideable, void* args, VisitorActionCollideable hitAction ); ICustomBody* GetCustomBody(const unsigned int tempRef); diff --git a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp index bfef1a61..6f164810 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp @@ -22,92 +22,71 @@ namespace Float4 worldPointOfContact; if( proto->Intersects(*deuter, worldPointOfContact) ) { - switch( proto->CallSubscription_Collision(deuter) ) - { - case ICustomBody::SubscriptMessage_ignore_collision_response: - break; - default: - { // Apply CollisionResponse in pure gather pattern - ICustomBody::State protoState; proto->GetState( protoState ); - ICustomBody::State deuterState; deuter->GetState( deuterState ); + // Apply CollisionResponse in pure gather pattern + ICustomBody::State protoState; proto->GetState( protoState ); + ICustomBody::State deuterState; deuter->GetState( deuterState ); - Float4 protoG = protoState.GetLinearMomentum( worldPointOfContact ), - deuterG = deuterState.GetLinearMomentum( worldPointOfContact ); + Float4 protoG = protoState.GetLinearMomentum( worldPointOfContact.xyz ), + deuterG = deuterState.GetLinearMomentum( worldPointOfContact.xyz ); - // calc from perspective of deuter - Float4 normal; deuter->GetNormalAt( worldPointOfContact, normal ); - Float protoG_Magnitude = protoG.Dot( normal ), - deuterG_Magnitude = deuterG.Dot( normal ); - - // if they are not relatively moving towards eachother, there is no collision - Float deltaPos = normal.Dot( deuterState.GetCenterPosition() - protoState.GetCenterPosition() ); - if( deltaPos < 0.0f ) - { - if( protoG_Magnitude >= deuterG_Magnitude ) - { - break; - } - } - else if( deltaPos > 0.0f ) - { - if( protoG_Magnitude <= deuterG_Magnitude ) - { - break; - } - } - else - { - break; - } - - // bounce - Float4 bounceD = normal * -Formula::CollisionResponse::Bounce( deuterState.GetRestitutionCoeff(), - deuterState.GetMass(), deuterG_Magnitude, - protoState.GetMass(), protoG_Magnitude ); - - //sumJ -= Formula::CollisionResponse::Friction( impulse, normal, - // protoState.GetLinearMomentum(), protoState.GetFrictionCoeff_Static(), protoState.GetFrictionCoeff_Kinetic(), protoState.GetMass(), - // deuterState.GetLinearMomentum(), deuterState.GetFrictionCoeff_Static(), deuterState.GetFrictionCoeff_Kinetic(), deuterState.GetMass()); - - // calc from perspective of proto - proto->GetNormalAt( worldPointOfContact, normal ); - protoG_Magnitude = protoG.Dot( normal ), + // calc from perspective of deuter + Float4 normal; deuter->GetNormalAt( worldPointOfContact, normal ); + Float protoG_Magnitude = protoG.Dot( normal ), deuterG_Magnitude = deuterG.Dot( normal ); - - // bounce - Float4 bounceP = normal * Formula::CollisionResponse::Bounce( protoState.GetRestitutionCoeff(), - protoState.GetMass(), protoG_Magnitude, - deuterState.GetMass(), deuterG_Magnitude ); - Float4 bounce = Average( bounceD, bounceP ); - //Float4 bounce = bounceD + bounceP; - - // FRICTION - // Apply - //sumJ += ( 1 / deuterState.GetMass() )*frictionImpulse; - // FRICTION END - -// Float4 forwardedDeltaPos, forwardedDeltaAxis; -// { // @todo TODO: is this right? -// Float4 bounceAngularImpulse = ::Oyster::Math::Float4( (worldPointOfContact - protoState.GetCenterPosition()).xyz.Cross(bounce.xyz), 0.0f ), -// bounceLinearImpulse = bounce - bounceAngularImpulse; -// proto->Predict( forwardedDeltaPos, forwardedDeltaAxis, bounceLinearImpulse, bounceAngularImpulse, API_instance.GetFrameTimeLength() ); -// } - - - Float kineticEnergyPBefore = Oyster::Physics3D::Formula::LinearKineticEnergy( protoState.GetMass(), protoState.GetLinearMomentum().xyz/protoState.GetMass() ); - -// protoState.ApplyForwarding( forwardedDeltaPos, forwardedDeltaAxis ); - protoState.ApplyImpulse( bounce, worldPointOfContact, normal ); - proto->SetState( protoState ); - - Float kineticEnergyPAFter = Oyster::Physics3D::Formula::LinearKineticEnergy( protoState.GetMass(), (protoState.GetLinearMomentum().xyz + protoState.GetLinearImpulse().xyz)/protoState.GetMass() ); - - proto->CallSubscription_CollisionResponse( deuter, kineticEnergyPBefore - kineticEnergyPAFter ); - + // if they are not relatively moving towards eachother, there is no collision + Float deltaPos = normal.Dot( Float4(deuterState.GetCenterPosition(), 1) - Float4(protoState.GetCenterPosition(), 1) ); + if( deltaPos < 0.0f ) + { + if( protoG_Magnitude >= deuterG_Magnitude ) + { + return; } - break; } + else if( deltaPos > 0.0f ) + { + if( protoG_Magnitude <= deuterG_Magnitude ) + { + return; + } + } + else + { + return; + } + + if( proto->CallSubscription_BeforeCollisionResponse(proto) == ICustomBody::SubscriptMessage_ignore_collision_response ) + { + return; + } + + + // bounce + Float4 bounceD = normal * -Formula::CollisionResponse::Bounce( deuterState.GetRestitutionCoeff(), + deuterState.GetMass(), deuterG_Magnitude, + protoState.GetMass(), protoG_Magnitude ); + + + // calc from perspective of proto + proto->GetNormalAt( worldPointOfContact, normal ); + protoG_Magnitude = protoG.Dot( normal ), + deuterG_Magnitude = deuterG.Dot( normal ); + + // bounce + Float4 bounceP = normal * Formula::CollisionResponse::Bounce( protoState.GetRestitutionCoeff(), + protoState.GetMass(), protoG_Magnitude, + deuterState.GetMass(), deuterG_Magnitude ); + + Float4 bounce = Average( bounceD, bounceP ); + + Float kineticEnergyPBefore = Oyster::Physics3D::Formula::LinearKineticEnergy( protoState.GetMass(), protoState.GetLinearMomentum()/protoState.GetMass() ); + + protoState.ApplyImpulse( bounce.xyz, worldPointOfContact.xyz, normal.xyz ); + proto->SetState( protoState ); + + Float kineticEnergyPAFter = Oyster::Physics3D::Formula::LinearKineticEnergy( protoState.GetMass(), (protoState.GetLinearMomentum() + protoState.GetLinearImpulse())/protoState.GetMass() ); + + proto->CallSubscription_AfterCollisionResponse( deuter, kineticEnergyPBefore - kineticEnergyPAFter ); } } } @@ -120,6 +99,7 @@ API & API::Instance() API_Impl::API_Impl() { this->gravityConstant = Constant::gravity_constant; + this->epsilon = Constant::epsilon; this->updateFrameLength = 1.0f / 120.0f; this->destructionAction = Default::EventAction_Destruction; this->gravity = ::std::vector(); @@ -146,6 +126,11 @@ void API_Impl::SetGravityConstant( float g ) this->gravityConstant = g; } +void API_Impl::SetEpsilon( float e ) +{ + this->epsilon = e; +} + void API_Impl::SetSubscription( API::EventAction_Destruction functionPointer ) { if( functionPointer ) @@ -179,7 +164,7 @@ void API_Impl::Update() { case Gravity::GravityType_Well: { - Float4 d = Float4( this->gravity[i].well.position, 1.0f ) - state.GetCenterPosition(); + Float4 d = Float4( this->gravity[i].well.position, 1.0f ) - Float4( state.GetCenterPosition(), 1.0f ); Float rSquared = d.Dot( d ); if( rSquared != 0.0 ) { @@ -201,7 +186,7 @@ void API_Impl::Update() if( gravityImpulse != Float4::null ) { - state.ApplyLinearImpulse( gravityImpulse ); + state.ApplyLinearImpulse( gravityImpulse.xyz ); (*proto)->SetGravityNormal( gravityImpulse.GetNormalized().xyz ); (*proto)->SetState( state ); } @@ -213,12 +198,31 @@ void API_Impl::Update() proto = updateList.begin(); for( ; proto != updateList.end(); ++proto ) { + Float3 lM = state.GetLinearMomentum() + state.GetLinearImpulse(); + + if( lM.x < this->epsilon ) + { + state.SetLinearMomentum( Float3(0, lM.y, lM.z) ); + state.SetLinearImpulse( Float3(0, lM.y, lM.z) ); + } + if( lM.y < this->epsilon ) + { + state.SetLinearMomentum( Float3(lM.x, 0, lM.z) ); + state.SetLinearImpulse( Float3(lM.x, 0, lM.z) ); + } + if( lM.z < this->epsilon ) + { + state.SetLinearMomentum( Float3(lM.x, lM.y, 0) ); + state.SetLinearImpulse( Float3(lM.x, lM.y, 0) ); + } + switch( (*proto)->Update(this->updateFrameLength) ) { case UpdateState_altered: this->worldScene.SetAsAltered( this->worldScene.GetTemporaryReferenceOf(*proto) ); (*proto)->CallSubscription_Move(); - case UpdateState_resting: default: + case UpdateState_resting: + default: break; } } @@ -276,9 +280,9 @@ void API_Impl::RemoveGravity( const API::Gravity &g ) } } -void API_Impl::ApplyEffect( const Oyster::Collision3D::ICollideable& collideable, void(hitAction)(ICustomBody*) ) +void API_Impl::ApplyEffect( const Oyster::Collision3D::ICollideable& collideable, void* args, void(hitAction)(ICustomBody*, void*) ) { - this->worldScene.Visit(collideable, hitAction); + this->worldScene.Visit(collideable, args, hitAction); } //void API_Impl::ApplyForceAt( const ICustomBody* objRef, const Float3 &worldPos, const Float3 &worldF ) @@ -384,12 +388,12 @@ namespace Oyster { namespace Physics 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 ) + ::Oyster::Physics::ICustomBody::SubscriptMessage EventAction_BeforeCollisionResponse( const ::Oyster::Physics::ICustomBody *proto, const ::Oyster::Physics::ICustomBody *deuter ) { /* Do nothing except returning business as usual. */ return ::Oyster::Physics::ICustomBody::SubscriptMessage_none; } - void EventAction_CollisionResponse( const ::Oyster::Physics::ICustomBody *proto, const ::Oyster::Physics::ICustomBody *deuter, ::Oyster::Math::Float kineticEnergyLoss ) + void EventAction_AfterCollisionResponse( const ::Oyster::Physics::ICustomBody *proto, const ::Oyster::Physics::ICustomBody *deuter, ::Oyster::Math::Float kineticEnergyLoss ) { /* Do nothing except returning business as usual. */ } diff --git a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h index b9343ae6..21460944 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h @@ -18,6 +18,7 @@ namespace Oyster void SetFrameTimeLength( float deltaTime ); void SetGravityConstant( float g ); + void SetEpsilon( float e ); void SetSubscription( EventAction_Destruction functionPointer ); float GetFrameTimeLength() const; @@ -35,7 +36,7 @@ namespace Oyster void AddGravity( const API::Gravity &g ); void RemoveGravity( const API::Gravity &g ); - void ApplyEffect( const Oyster::Collision3D::ICollideable& collideable, void(hitAction)(ICustomBody*) ); + void ApplyEffect( const Oyster::Collision3D::ICollideable& collideable, void* args, void(hitAction)(ICustomBody*, void*) ); //void ApplyForceAt( const ICustomBody* objRef, const ::Oyster::Math::Float3 &worldPos, const ::Oyster::Math::Float3 &worldF ); @@ -52,7 +53,7 @@ namespace Oyster ::Utility::DynamicMemory::UniquePointer CreateRigidBody( const SphericalBodyDescription &desc ) const; private: - ::Oyster::Math::Float gravityConstant, updateFrameLength; + ::Oyster::Math::Float gravityConstant, updateFrameLength, epsilon; EventAction_Destruction destructionAction; ::std::vector gravity; Octree worldScene; @@ -61,8 +62,8 @@ namespace Oyster 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 ); - void EventAction_CollisionResponse( const ::Oyster::Physics::ICustomBody *proto, const ::Oyster::Physics::ICustomBody *deuter, ::Oyster::Math::Float kineticEnergyLoss ); + ::Oyster::Physics::ICustomBody::SubscriptMessage EventAction_BeforeCollisionResponse( const ::Oyster::Physics::ICustomBody *proto, const ::Oyster::Physics::ICustomBody *deuter ); + void EventAction_AfterCollisionResponse( const ::Oyster::Physics::ICustomBody *proto, const ::Oyster::Physics::ICustomBody *deuter, ::Oyster::Math::Float kineticEnergyLoss ); void EventAction_Move( const ::Oyster::Physics::ICustomBody *object ); } } diff --git a/Code/GamePhysics/Implementation/SimpleRigidBody.cpp b/Code/GamePhysics/Implementation/SimpleRigidBody.cpp index 5a9bf53f..ef3027ee 100644 --- a/Code/GamePhysics/Implementation/SimpleRigidBody.cpp +++ b/Code/GamePhysics/Implementation/SimpleRigidBody.cpp @@ -46,8 +46,8 @@ SimpleRigidBody::SimpleRigidBody() this->rigid = RigidBody(); this->rigid.SetMass_KeepMomentum( 16.0f ); this->gravityNormal = Float3::null; - this->onCollision = Default::EventAction_Collision; - this->onCollisionResponse = Default::EventAction_CollisionResponse; + this->onCollision = Default::EventAction_BeforeCollisionResponse; + this->onCollisionResponse = Default::EventAction_AfterCollisionResponse; this->onMovement = Default::EventAction_Move; this->scene = nullptr; this->customTag = nullptr; @@ -56,7 +56,7 @@ SimpleRigidBody::SimpleRigidBody() SimpleRigidBody::SimpleRigidBody( const API::SimpleBodyDescription &desc ) { - this->rigid.SetRotation( desc.rotation ); + //this->rigid.SetRotation( desc.rotation ); this->rigid.centerPos = desc.centerPosition; this->rigid.SetSize( desc.size ); this->rigid.SetMass_KeepMomentum( desc.mass ); @@ -72,7 +72,7 @@ SimpleRigidBody::SimpleRigidBody( const API::SimpleBodyDescription &desc ) } else { - this->onCollision = Default::EventAction_Collision; + this->onCollision = Default::EventAction_BeforeCollisionResponse; } if( desc.subscription_onCollisionResponse ) @@ -81,7 +81,7 @@ SimpleRigidBody::SimpleRigidBody( const API::SimpleBodyDescription &desc ) } else { - this->onCollisionResponse = Default::EventAction_CollisionResponse; + this->onCollisionResponse = Default::EventAction_AfterCollisionResponse; } if( desc.subscription_onMovement ) @@ -143,8 +143,8 @@ void SimpleRigidBody::SetState( const SimpleRigidBody::State &state ) if( state.IsForwarded() ) { - this->deltaPos += state.GetForward_DeltaPos(); - this->deltaAxis += state.GetForward_DeltaAxis(); + this->deltaPos += Float4(state.GetForward_DeltaPos(), 0); + this->deltaAxis += Float4(state.GetForward_DeltaAxis(), 0); this->isForwarded; } @@ -163,12 +163,12 @@ void SimpleRigidBody::SetState( const SimpleRigidBody::State &state ) } } -ICustomBody::SubscriptMessage SimpleRigidBody::CallSubscription_Collision( const ICustomBody *deuter ) +ICustomBody::SubscriptMessage SimpleRigidBody::CallSubscription_BeforeCollisionResponse( const ICustomBody *deuter ) { return this->onCollision( this, deuter ); } -void SimpleRigidBody::CallSubscription_CollisionResponse( const ICustomBody *deuter, Float kineticEnergyLoss ) +void SimpleRigidBody::CallSubscription_AfterCollisionResponse( const ICustomBody *deuter, Float kineticEnergyLoss ) { return this->onCollisionResponse( this, deuter, kineticEnergyLoss ); } @@ -205,7 +205,7 @@ Sphere & SimpleRigidBody::GetBoundingSphere( Sphere &targetMem ) const Float4 & SimpleRigidBody::GetNormalAt( const Float4 &worldPos, Float4 &targetMem ) const { - Float4 offset = worldPos - this->rigid.centerPos; + Float4 offset = worldPos.xyz - this->rigid.centerPos; Float distance = offset.Dot( offset ); Float3 normal = Float3::null; @@ -295,7 +295,7 @@ UpdateState SimpleRigidBody::Update( Float timeStepLength ) { if( this->isForwarded ) { - this->rigid.Move( this->deltaPos, this->deltaAxis ); + this->rigid.Move( this->deltaPos.xyz, this->deltaAxis.xyz ); this->deltaPos = Float4::null; this->deltaAxis = Float4::null; this->isForwarded = false; @@ -310,7 +310,7 @@ UpdateState SimpleRigidBody::Update( Float timeStepLength ) void SimpleRigidBody::Predict( Float4 &outDeltaPos, Float4 &outDeltaAxis, const Float4 &actingLinearImpulse, const Float4 &actingAngularImpulse, Float deltaTime ) { - this->rigid.Predict_LeapFrog( outDeltaPos, outDeltaAxis, actingLinearImpulse, actingAngularImpulse, deltaTime ); + this->rigid.Predict_LeapFrog( outDeltaPos.xyz, outDeltaAxis.xyz, actingLinearImpulse.xyz, actingAngularImpulse.xyz, deltaTime ); } void SimpleRigidBody::SetScene( void *scene ) @@ -318,7 +318,7 @@ void SimpleRigidBody::SetScene( void *scene ) this->scene = (Octree*)scene; } -void SimpleRigidBody::SetSubscription( ICustomBody::EventAction_Collision functionPointer ) +void SimpleRigidBody::SetSubscription( ICustomBody::EventAction_BeforeCollisionResponse functionPointer ) { if( functionPointer ) { @@ -326,11 +326,11 @@ void SimpleRigidBody::SetSubscription( ICustomBody::EventAction_Collision functi } else { - this->onCollision = Default::EventAction_Collision; + this->onCollision = Default::EventAction_BeforeCollisionResponse; } } -void SimpleRigidBody::SetSubscription( ICustomBody::EventAction_CollisionResponse functionPointer ) +void SimpleRigidBody::SetSubscription( ICustomBody::EventAction_AfterCollisionResponse functionPointer ) { if( functionPointer ) { @@ -338,7 +338,7 @@ void SimpleRigidBody::SetSubscription( ICustomBody::EventAction_CollisionRespons } else { - this->onCollisionResponse = Default::EventAction_CollisionResponse; + this->onCollisionResponse = Default::EventAction_AfterCollisionResponse; } } diff --git a/Code/GamePhysics/Implementation/SimpleRigidBody.h b/Code/GamePhysics/Implementation/SimpleRigidBody.h index 271c4362..9e61cee3 100644 --- a/Code/GamePhysics/Implementation/SimpleRigidBody.h +++ b/Code/GamePhysics/Implementation/SimpleRigidBody.h @@ -21,8 +21,8 @@ namespace Oyster { namespace Physics void SetState( const State &state ); //::Oyster::Math::Float3 GetRigidLinearVelocity() const; - SubscriptMessage CallSubscription_Collision( const ICustomBody *deuter ); - void CallSubscription_CollisionResponse( const ICustomBody *deuter, ::Oyster::Math::Float kineticEnergyLoss ); + SubscriptMessage CallSubscription_BeforeCollisionResponse( const ICustomBody *deuter ); + void CallSubscription_AfterCollisionResponse( const ICustomBody *deuter, ::Oyster::Math::Float kineticEnergyLoss ); void CallSubscription_Move(); bool IsAffectedByGravity() const; @@ -44,8 +44,8 @@ namespace Oyster { namespace Physics void SetScene( void *scene ); - void SetSubscription( EventAction_Collision functionPointer ); - void SetSubscription( EventAction_CollisionResponse functionPointer ); + void SetSubscription( EventAction_BeforeCollisionResponse functionPointer ); + void SetSubscription( EventAction_AfterCollisionResponse functionPointer ); void SetSubscription( EventAction_Move functionPointer ); void SetGravity( bool ignore); @@ -65,8 +65,8 @@ namespace Oyster { namespace Physics ::Oyster::Physics3D::RigidBody rigid; ::Oyster::Math::Float4 deltaPos, deltaAxis; ::Oyster::Math::Float3 gravityNormal; - EventAction_Collision onCollision; - EventAction_CollisionResponse onCollisionResponse; + EventAction_BeforeCollisionResponse onCollision; + EventAction_AfterCollisionResponse onCollisionResponse; EventAction_Move onMovement; Octree *scene; void *customTag; diff --git a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp index 9fd8d219..539093db 100644 --- a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp +++ b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp @@ -13,8 +13,8 @@ SphericalRigidBody::SphericalRigidBody() this->rigid = RigidBody(); this->rigid.SetMass_KeepMomentum( 10.0f ); this->gravityNormal = Float3::null; - this->onCollision = Default::EventAction_Collision; - this->onCollisionResponse = Default::EventAction_CollisionResponse; + this->onCollision = Default::EventAction_BeforeCollisionResponse; + this->onCollisionResponse = Default::EventAction_AfterCollisionResponse; this->onMovement = Default::EventAction_Move; this->scene = nullptr; this->customTag = nullptr; @@ -24,11 +24,11 @@ SphericalRigidBody::SphericalRigidBody() SphericalRigidBody::SphericalRigidBody( const API::SphericalBodyDescription &desc ) { this->rigid = RigidBody(); - this->rigid.SetRotation( desc.rotation ); + //this->rigid.SetRotation( desc.rotation ); this->rigid.centerPos = desc.centerPosition; this->rigid.boundingReach = Float4( desc.radius, desc.radius, desc.radius, 0.0f ); this->rigid.SetMass_KeepMomentum( desc.mass ); - this->rigid.SetMomentOfInertia_KeepMomentum( Formula::MomentOfInertia::CreateSphereMatrix( desc.mass, desc.radius ) ); + this->rigid.SetMomentOfInertia_KeepMomentum( MomentOfInertia::Sphere(desc.mass, desc.radius) ); this->deltaPos = Float4::null; this->deltaAxis = Float4::null; @@ -40,7 +40,7 @@ SphericalRigidBody::SphericalRigidBody( const API::SphericalBodyDescription &des } else { - this->onCollision = Default::EventAction_Collision; + this->onCollision = Default::EventAction_BeforeCollisionResponse; } if( desc.subscription_onCollisionResponse ) @@ -49,7 +49,7 @@ SphericalRigidBody::SphericalRigidBody( const API::SphericalBodyDescription &des } else { - this->onCollisionResponse = Default::EventAction_CollisionResponse; + this->onCollisionResponse = Default::EventAction_AfterCollisionResponse; } if( desc.subscription_onMovement ) @@ -108,8 +108,8 @@ void SphericalRigidBody::SetState( const SphericalRigidBody::State &state ) if( state.IsForwarded() ) { - this->deltaPos += state.GetForward_DeltaPos(); - this->deltaAxis += state.GetForward_DeltaAxis(); + this->deltaPos += Float4(state.GetForward_DeltaPos(), 0); + this->deltaAxis += Float4(state.GetForward_DeltaAxis()); this->isForwarded = false; } @@ -128,12 +128,12 @@ void SphericalRigidBody::SetState( const SphericalRigidBody::State &state ) } } -ICustomBody::SubscriptMessage SphericalRigidBody::CallSubscription_Collision( const ICustomBody *deuter ) +ICustomBody::SubscriptMessage SphericalRigidBody::CallSubscription_BeforeCollisionResponse( const ICustomBody *deuter ) { return this->onCollision( this, deuter ); } -void SphericalRigidBody::CallSubscription_CollisionResponse( const ICustomBody *deuter, Float kineticEnergyLoss ) +void SphericalRigidBody::CallSubscription_AfterCollisionResponse( const ICustomBody *deuter, Float kineticEnergyLoss ) { this->onCollisionResponse( this, deuter, kineticEnergyLoss); } @@ -171,7 +171,7 @@ Sphere & SphericalRigidBody::GetBoundingSphere( Sphere &targetMem ) const Float4 & SphericalRigidBody::GetNormalAt( const Float4 &worldPos, Float4 &targetMem ) const { - targetMem = worldPos - this->rigid.centerPos; + targetMem = Float4( worldPos.xyz - this->rigid.centerPos, 0); Float magnitude = targetMem.GetMagnitude(); if( magnitude != 0.0f ) { // sanity check @@ -220,7 +220,7 @@ UpdateState SphericalRigidBody::Update( Float timeStepLength ) { if( this->isForwarded ) { - this->rigid.Move( this->deltaPos, this->deltaAxis ); + this->rigid.Move( this->deltaPos.xyz, this->deltaAxis.xyz ); this->deltaPos = Float4::null; this->deltaAxis = Float4::null; this->isForwarded = false; @@ -235,10 +235,10 @@ UpdateState SphericalRigidBody::Update( Float timeStepLength ) void SphericalRigidBody::Predict( ::Oyster::Math::Float4 &outDeltaPos, ::Oyster::Math::Float4 &outDeltaAxis, const ::Oyster::Math::Float4 &actingLinearImpulse, const ::Oyster::Math::Float4 &actingAngularImpulse, ::Oyster::Math::Float deltaTime ) { - this->rigid.Predict_LeapFrog( outDeltaPos, outDeltaAxis, actingLinearImpulse, actingAngularImpulse, deltaTime ); + this->rigid.Predict_LeapFrog( outDeltaPos.xyz, outDeltaAxis.xyz, actingLinearImpulse.xyz, actingAngularImpulse.xyz, deltaTime ); } -void SphericalRigidBody::SetSubscription( ICustomBody::EventAction_Collision functionPointer ) +void SphericalRigidBody::SetSubscription( ICustomBody::EventAction_BeforeCollisionResponse functionPointer ) { if( functionPointer ) { @@ -246,11 +246,11 @@ void SphericalRigidBody::SetSubscription( ICustomBody::EventAction_Collision fun } else { - this->onCollision = Default::EventAction_Collision; + this->onCollision = Default::EventAction_BeforeCollisionResponse; } } -void SphericalRigidBody::SetSubscription( ICustomBody::EventAction_CollisionResponse functionPointer ) +void SphericalRigidBody::SetSubscription( ICustomBody::EventAction_AfterCollisionResponse functionPointer ) { if( functionPointer ) { @@ -258,7 +258,7 @@ void SphericalRigidBody::SetSubscription( ICustomBody::EventAction_CollisionResp } else { - this->onCollisionResponse = Default::EventAction_CollisionResponse; + this->onCollisionResponse = Default::EventAction_AfterCollisionResponse; } } diff --git a/Code/GamePhysics/Implementation/SphericalRigidBody.h b/Code/GamePhysics/Implementation/SphericalRigidBody.h index 213e225b..390b7171 100644 --- a/Code/GamePhysics/Implementation/SphericalRigidBody.h +++ b/Code/GamePhysics/Implementation/SphericalRigidBody.h @@ -22,8 +22,8 @@ namespace Oyster { namespace Physics void SetState( const State &state ); //::Oyster::Math::Float3 GetRigidLinearVelocity() const; - SubscriptMessage CallSubscription_Collision( const ICustomBody *deuter ); - void CallSubscription_CollisionResponse( const ICustomBody *deuter, ::Oyster::Math::Float kineticEnergyLoss ); + SubscriptMessage CallSubscription_BeforeCollisionResponse( const ICustomBody *deuter ); + void CallSubscription_AfterCollisionResponse( const ICustomBody *deuter, ::Oyster::Math::Float kineticEnergyLoss ); void CallSubscription_Move(); bool IsAffectedByGravity() const; @@ -45,8 +45,8 @@ namespace Oyster { namespace Physics void SetScene( void *scene ); - void SetSubscription( EventAction_Collision functionPointer ); - void SetSubscription( EventAction_CollisionResponse functionPointer ); + void SetSubscription( EventAction_BeforeCollisionResponse functionPointer ); + void SetSubscription( EventAction_AfterCollisionResponse functionPointer ); void SetSubscription( EventAction_Move functionPointer ); void SetGravity( bool ignore); @@ -66,8 +66,8 @@ namespace Oyster { namespace Physics ::Oyster::Physics3D::RigidBody rigid; ::Oyster::Math::Float4 deltaPos, deltaAxis; ::Oyster::Math::Float3 gravityNormal; - EventAction_Collision onCollision; - EventAction_CollisionResponse onCollisionResponse; + EventAction_BeforeCollisionResponse onCollision; + EventAction_AfterCollisionResponse onCollisionResponse; EventAction_Move onMovement; Octree *scene; void *customTag; diff --git a/Code/GamePhysics/PhysicsAPI.h b/Code/GamePhysics/PhysicsAPI.h index 7f20fcf7..78b65f5e 100644 --- a/Code/GamePhysics/PhysicsAPI.h +++ b/Code/GamePhysics/PhysicsAPI.h @@ -34,6 +34,7 @@ namespace Oyster namespace Constant { const float gravity_constant = (const float)6.67284e-11; //!< The _big_G_! ( N(m/kg)^2 ) Used in real gravityforcefields. + const float epsilon = (const float)1.0e-7; } class PHYSICS_DLL_USAGE API @@ -139,9 +140,11 @@ namespace Oyster /******************************************************** * Applies an effect to objects that collide with the set volume. * @param collideable: An ICollideable that defines the volume of the effect. - * @param hitAction: A function that contains the effect. + * @param args: The arguments needed for the hitAction function. + * @param hitAction: A function that contains the effect. Parameterlist contains the custom body + the collideable hits, and the arguments sent to the function. ********************************************************/ - virtual void ApplyEffect( const Oyster::Collision3D::ICollideable& collideable, void(hitAction)(ICustomBody*) ) = 0; + virtual void ApplyEffect( const Oyster::Collision3D::ICollideable& collideable, void* args, void(hitAction)(ICustomBody*, void*) ) = 0; ///******************************************************** // * Apply force on an object. @@ -242,8 +245,8 @@ namespace Oyster SubscriptMessage_ignore_collision_response }; - typedef SubscriptMessage (*EventAction_Collision)( const ICustomBody *proto, const ICustomBody *deuter ); - typedef void (*EventAction_CollisionResponse)( const ICustomBody *proto, const ICustomBody *deuter, ::Oyster::Math::Float kineticEnergyLoss ); + typedef SubscriptMessage (*EventAction_BeforeCollisionResponse)( const ICustomBody *proto, const ICustomBody *deuter ); + typedef void (*EventAction_AfterCollisionResponse)( const ICustomBody *proto, const ICustomBody *deuter, ::Oyster::Math::Float kineticEnergyLoss ); typedef void (*EventAction_Move)( const ICustomBody *object ); typedef Struct::SimpleBodyDescription SimpleBodyDescription; typedef Struct::SphericalBodyDescription SphericalBodyDescription; @@ -260,12 +263,12 @@ namespace Oyster /******************************************************** * @todo TODO: need doc ********************************************************/ - virtual SubscriptMessage CallSubscription_Collision( const ICustomBody *deuter ) = 0; + virtual SubscriptMessage CallSubscription_BeforeCollisionResponse( const ICustomBody *deuter ) = 0; /******************************************************** * @todo TODO: need doc ********************************************************/ - virtual void CallSubscription_CollisionResponse( const ICustomBody *deuter, ::Oyster::Math::Float kineticEnergyLoss ) = 0; + virtual void CallSubscription_AfterCollisionResponse( const ICustomBody *deuter, ::Oyster::Math::Float kineticEnergyLoss ) = 0; /******************************************************** * @todo TODO: need doc @@ -395,14 +398,14 @@ namespace Oyster * whenever a collision occurs. * @param functionPointer: If NULL, an empty default function will be set. ********************************************************/ - virtual void SetSubscription( EventAction_Collision functionPointer ) = 0; + virtual void SetSubscription( EventAction_BeforeCollisionResponse functionPointer ) = 0; /******************************************************** * Sets the function that will be called by the engine * whenever a collision has finished. * @param functionPointer: If NULL, an empty default function will be set. ********************************************************/ - virtual void SetSubscription( EventAction_CollisionResponse functionPointer ) = 0; + virtual void SetSubscription( EventAction_AfterCollisionResponse functionPointer ) = 0; /******************************************************** * Sets the function that will be called by the engine diff --git a/Code/GamePhysics/PhysicsStructs-Impl.h b/Code/GamePhysics/PhysicsStructs-Impl.h index 46de90cc..05cba2da 100644 --- a/Code/GamePhysics/PhysicsStructs-Impl.h +++ b/Code/GamePhysics/PhysicsStructs-Impl.h @@ -13,13 +13,13 @@ namespace Oyster inline SimpleBodyDescription::SimpleBodyDescription() { this->rotation = ::Oyster::Math::Float4x4::identity; - this->centerPosition = ::Oyster::Math::Float4::standard_unit_w; - this->size = ::Oyster::Math::Float4( 1.0f ); - this->mass = 12.0f; + this->centerPosition = ::Oyster::Math::Float3::null; + this->size = ::Oyster::Math::Float3( 1.0f ); + this->mass = 6.0f; this->restitutionCoeff = 1.0f; this->frictionCoeff_Dynamic = 0.5f; this->frictionCoeff_Static = 0.5f; - this->inertiaTensor = ::Oyster::Math::Float4x4::identity; + this->inertiaTensor = ::Oyster::Physics3D::MomentOfInertia(); this->subscription_onCollision = NULL; this->subscription_onCollisionResponse = NULL; this->subscription_onMovement = NULL; @@ -29,7 +29,7 @@ namespace Oyster inline SphericalBodyDescription::SphericalBodyDescription() { this->rotation = ::Oyster::Math::Float4x4::identity; - this->centerPosition = ::Oyster::Math::Float4::standard_unit_w; + this->centerPosition = ::Oyster::Math::Float3::null; this->radius = 0.5f; this->mass = 10.0f; this->restitutionCoeff = 1.0f; @@ -41,7 +41,7 @@ namespace Oyster this->ignoreGravity = false; } - inline CustomBodyState::CustomBodyState( ::Oyster::Math::Float mass, ::Oyster::Math::Float restitutionCoeff, ::Oyster::Math::Float staticFrictionCoeff, ::Oyster::Math::Float kineticFrictionCoeff, const ::Oyster::Math::Float4x4 &inertiaTensor, const ::Oyster::Math::Float4 &reach, const ::Oyster::Math::Float4 ¢erPos, const ::Oyster::Math::Float4 &rotation, const ::Oyster::Math::Float4 &linearMomentum, const ::Oyster::Math::Float4 &angularMomentum, const ::Oyster::Math::Float4 &gravityNormal ) + inline CustomBodyState::CustomBodyState( ::Oyster::Math::Float mass, ::Oyster::Math::Float restitutionCoeff, ::Oyster::Math::Float staticFrictionCoeff, ::Oyster::Math::Float kineticFrictionCoeff, const ::Oyster::Physics3D::MomentOfInertia &inertiaTensor, const ::Oyster::Math::Float3 &reach, const ::Oyster::Math::Float3 ¢erPos, const ::Oyster::Math::Float3 &rotation, const ::Oyster::Math::Float3 &linearMomentum, const ::Oyster::Math::Float3 &angularMomentum, const ::Oyster::Math::Float3 &gravityNormal ) { this->mass = mass; this->restitutionCoeff = restitutionCoeff; @@ -53,8 +53,8 @@ namespace Oyster this->angularAxis = rotation; this->linearMomentum = linearMomentum; this->angularMomentum = angularMomentum; - this->linearImpulse = this->angularImpulse = ::Oyster::Math::Float4::null; - this->deltaPos = this->deltaAxis = ::Oyster::Math::Float4::null; + this->linearImpulse = this->angularImpulse = ::Oyster::Math::Float3::null; + this->deltaPos = this->deltaAxis = ::Oyster::Math::Float3::null; this->isSpatiallyAltered = this->isDisturbed = this->isForwarded = false; this->gravityNormal = gravityNormal; } @@ -102,92 +102,92 @@ namespace Oyster return this->kineticFrictionCoeff; } - inline const ::Oyster::Math::Float4x4 & CustomBodyState::GetMomentOfInertia() const + inline const ::Oyster::Physics3D::MomentOfInertia & CustomBodyState::GetMomentOfInertia() const { return this->inertiaTensor; } - inline const ::Oyster::Math::Float4 & CustomBodyState::GetReach() const + inline const ::Oyster::Math::Float3 & CustomBodyState::GetReach() const { return this->reach; } - inline ::Oyster::Math::Float4 CustomBodyState::GetSize() const + inline ::Oyster::Math::Float3 CustomBodyState::GetSize() const { return 2.0f * this->GetReach(); } - inline const ::Oyster::Math::Float4 & CustomBodyState::GetCenterPosition() const + inline const ::Oyster::Math::Float3 & CustomBodyState::GetCenterPosition() const { return this->centerPos; } - inline const ::Oyster::Math::Float4 & CustomBodyState::GetAngularAxis() const + inline const ::Oyster::Math::Float3 & CustomBodyState::GetAngularAxis() const { - return this->angularAxis; + return ::Utility::Value::Radian(this->angularAxis); } inline ::Oyster::Math::Float4x4 CustomBodyState::GetRotation() const { - return ::Oyster::Math3D::RotationMatrix( this->GetAngularAxis().xyz ); + return ::Oyster::Math3D::RotationMatrix( this->GetAngularAxis() ); } inline ::Oyster::Math::Float4x4 CustomBodyState::GetOrientation() const { - return ::Oyster::Math3D::OrientationMatrix( this->angularAxis.xyz, this->centerPos.xyz ); + return ::Oyster::Math3D::OrientationMatrix( this->angularAxis, this->centerPos ); } - inline ::Oyster::Math::Float4x4 CustomBodyState::GetOrientation( const ::Oyster::Math::Float4 &offset ) const + inline ::Oyster::Math::Float4x4 CustomBodyState::GetOrientation( const ::Oyster::Math::Float3 &offset ) const { - return ::Oyster::Math3D::OrientationMatrix( this->angularAxis.xyz, (this->centerPos + offset).xyz ); + return ::Oyster::Math3D::OrientationMatrix( this->angularAxis, (this->centerPos + offset) ); } inline ::Oyster::Math::Float4x4 CustomBodyState::GetView() const { - return ::Oyster::Math3D::ViewMatrix( this->angularAxis.xyz, this->centerPos.xyz ); + return ::Oyster::Math3D::ViewMatrix( this->angularAxis, this->centerPos ); } - inline ::Oyster::Math::Float4x4 CustomBodyState::GetView( const ::Oyster::Math::Float4 &offset ) const + inline ::Oyster::Math::Float4x4 CustomBodyState::GetView( const ::Oyster::Math::Float3 &offset ) const { - return ::Oyster::Math3D::ViewMatrix( this->angularAxis.xyz, (this->centerPos + offset).xyz ); + return ::Oyster::Math3D::ViewMatrix( this->angularAxis, (this->centerPos + offset) ); } - inline const ::Oyster::Math::Float4 & CustomBodyState::GetLinearMomentum() const + inline const ::Oyster::Math::Float3 & CustomBodyState::GetLinearMomentum() const { return this->linearMomentum; } - inline ::Oyster::Math::Float4 CustomBodyState::GetLinearMomentum( const ::Oyster::Math::Float4 &at ) const + inline ::Oyster::Math::Float3 CustomBodyState::GetLinearMomentum( const ::Oyster::Math::Float3 &at ) const { return this->linearMomentum + ::Oyster::Physics3D::Formula::TangentialLinearMomentum( this->angularMomentum, at - this->centerPos ); } - inline const ::Oyster::Math::Float4 & CustomBodyState::GetAngularMomentum() const + inline const ::Oyster::Math::Float3 & CustomBodyState::GetAngularMomentum() const { return this->angularMomentum; } - inline const ::Oyster::Math::Float4 & CustomBodyState::GetLinearImpulse() const + inline const ::Oyster::Math::Float3 & CustomBodyState::GetLinearImpulse() const { return this->linearImpulse; } - inline const ::Oyster::Math::Float4 & CustomBodyState::GetAngularImpulse() const + inline const ::Oyster::Math::Float3 & CustomBodyState::GetAngularImpulse() const { return this->angularImpulse; } - inline const ::Oyster::Math::Float4 & CustomBodyState::GetForward_DeltaPos() const + inline const ::Oyster::Math::Float3 & CustomBodyState::GetForward_DeltaPos() const { return this->deltaPos; } - inline const ::Oyster::Math::Float4 & CustomBodyState::GetForward_DeltaAxis() const + inline const ::Oyster::Math::Float3 & CustomBodyState::GetForward_DeltaAxis() const { return this->deltaAxis; } - inline const ::Oyster::Math::Float4 & CustomBodyState::GetGravityNormal() const + inline const ::Oyster::Math::Float3 & CustomBodyState::GetGravityNormal() const { return this->gravityNormal; } @@ -201,8 +201,6 @@ namespace Oyster { if( m != 0.0f ) { // sanity block! - // Formula::LinearMomentum( m, Formula::LinearVelocity(this->mass, this->linearMomentum) ) - // is the same as (this->linearMomentum / this->mass) * m = (m / this->mass) * this->linearMomentum this->linearMomentum *= (m / this->mass); this->mass = m; } @@ -219,121 +217,114 @@ namespace Oyster this->kineticFrictionCoeff = kineticU; } - inline void CustomBodyState::SetMomentOfInertia_KeepMomentum( const ::Oyster::Math::Float4x4 &tensor ) + inline void CustomBodyState::SetMomentOfInertia_KeepMomentum( const ::Oyster::Physics3D::MomentOfInertia &tensor ) { this->inertiaTensor = tensor; } - inline void CustomBodyState::SetMomentOfInertia_KeepVelocity( const ::Oyster::Math::Float4x4 &tensor ) + inline void CustomBodyState::SetMomentOfInertia_KeepVelocity( const ::Oyster::Physics3D::MomentOfInertia &tensor ) { - if( tensor.GetDeterminant() != 0.0f ) - { // sanity block! - ::Oyster::Math::Float4x4 rotation = ::Oyster::Math3D::RotationMatrix(this->angularAxis.xyz); - ::Oyster::Math::Float4 w = ::Oyster::Physics3D::Formula::AngularVelocity( (rotation * this->inertiaTensor).GetInverse(), this->angularMomentum ); - this->inertiaTensor = tensor; - this->angularMomentum = ::Oyster::Physics3D::Formula::AngularMomentum( rotation * tensor, w ); - } + ::Oyster::Math::Quaternion rotation = ::Oyster::Math3D::Rotation(this->angularAxis); + ::Oyster::Math::Float3 w = this->inertiaTensor.CalculateAngularVelocity( rotation, this->angularMomentum ); + this->inertiaTensor = tensor; + this->angularMomentum = this->inertiaTensor.CalculateAngularMomentum( rotation, w ); } - inline void CustomBodyState::SetSize( const ::Oyster::Math::Float4 &size ) + inline void CustomBodyState::SetSize( const ::Oyster::Math::Float3 &size ) { this->SetReach( 0.5f * size ); } - inline void CustomBodyState::SetReach( const ::Oyster::Math::Float4 &halfSize ) + inline void CustomBodyState::SetReach( const ::Oyster::Math::Float3 &halfSize ) { - this->reach.xyz = halfSize; - this->reach = ::Utility::Value::Max( this->reach, ::Oyster::Math::Float4::null ); + this->reach = halfSize; + this->reach = ::Utility::Value::Max( this->reach, ::Oyster::Math::Float3::null ); this->isSpatiallyAltered = this->isDisturbed = true; } - inline void CustomBodyState::SetCenterPosition( const ::Oyster::Math::Float4 ¢erPos ) + inline void CustomBodyState::SetCenterPosition( const ::Oyster::Math::Float3 ¢erPos ) { - this->centerPos.xyz = centerPos; + this->centerPos = centerPos; this->isSpatiallyAltered = this->isDisturbed = true; } - inline void CustomBodyState::SetRotation( const ::Oyster::Math::Float4 &angularAxis ) + inline void CustomBodyState::SetRotation( const ::Oyster::Math::Float3 &angularAxis ) { - this->angularAxis.xyz = angularAxis; + this->angularAxis = angularAxis; this->isSpatiallyAltered = this->isDisturbed = true; } - inline void CustomBodyState::SetRotation( const ::Oyster::Math::Float4x4 &rotation ) + inline void CustomBodyState::SetOrientation( const ::Oyster::Math::Float3 &angularAxis, const ::Oyster::Math::Float3 &translation ) { - this->SetRotation( ::Oyster::Math3D::AngularAxis(rotation) ); + this->angularAxis = angularAxis ; + this->centerPos = translation; + this->isSpatiallyAltered = this->isDisturbed = true; } - inline void CustomBodyState::SetOrientation( const ::Oyster::Math::Float4x4 &orientation ) + inline void CustomBodyState::SetLinearMomentum( const ::Oyster::Math::Float3 &g ) { - this->SetRotation( ::Oyster::Math3D::ExtractAngularAxis(orientation) ); - this->SetCenterPosition( orientation.v[3] ); - } - - inline void CustomBodyState::SetLinearMomentum( const ::Oyster::Math::Float4 &g ) - { - this->linearMomentum.xyz = g; + this->linearMomentum = g; this->isDisturbed = true; } - inline void CustomBodyState::SetAngularMomentum( const ::Oyster::Math::Float4 &h ) + inline void CustomBodyState::SetAngularMomentum( const ::Oyster::Math::Float3 &h ) { - this->angularMomentum.xyz = h; + this->angularMomentum = h; this->isDisturbed = true; } - inline void CustomBodyState::SetLinearImpulse( const ::Oyster::Math::Float4 &j ) + inline void CustomBodyState::SetLinearImpulse( const ::Oyster::Math::Float3 &j ) { - this->linearImpulse.xyz = j; + this->linearImpulse = j; this->isDisturbed = true; } - inline void CustomBodyState::SetAngularImpulse( const ::Oyster::Math::Float4 &j ) + inline void CustomBodyState::SetAngularImpulse( const ::Oyster::Math::Float3 &j ) { - this->angularImpulse.xyz = j; + this->angularImpulse = j; this->isDisturbed = true; } - inline void CustomBodyState::SetGravityNormal( const ::Oyster::Math::Float4 &gravityNormal ) + inline void CustomBodyState::SetGravityNormal( const ::Oyster::Math::Float3 &gravityNormal ) { this->gravityNormal = gravityNormal; } - inline void CustomBodyState::AddRotation( const ::Oyster::Math::Float4 &angularAxis ) + inline void CustomBodyState::AddRotation( const ::Oyster::Math::Float3 &angularAxis ) { this->angularAxis += angularAxis; this->isSpatiallyAltered = this->isDisturbed = true; } - inline void CustomBodyState::AddTranslation( const ::Oyster::Math::Float4 &deltaPos ) + inline void CustomBodyState::AddTranslation( const ::Oyster::Math::Float3 &deltaPos ) { this->centerPos += deltaPos; this->isSpatiallyAltered = this->isDisturbed = true; } - inline void CustomBodyState::ApplyLinearImpulse( const ::Oyster::Math::Float4 &j ) + inline void CustomBodyState::ApplyLinearImpulse( const ::Oyster::Math::Float3 &j ) { this->linearImpulse += j; this->isDisturbed = true; } - inline void CustomBodyState::ApplyAngularImpulse( const ::Oyster::Math::Float4 &j ) + inline void CustomBodyState::ApplyAngularImpulse( const ::Oyster::Math::Float3 &j ) { this->angularImpulse += j; this->isDisturbed = true; } - inline void CustomBodyState::ApplyImpulse( const ::Oyster::Math::Float4 &j, const ::Oyster::Math::Float4 &at, const ::Oyster::Math::Float4 &normal ) + inline void CustomBodyState::ApplyImpulse( const ::Oyster::Math::Float3 &j, const ::Oyster::Math::Float3 &at, const ::Oyster::Math::Float3 &normal ) { - ::Oyster::Math::Float4 offset = at - this->centerPos; - ::Oyster::Math::Float4 deltaAngularImpulse = ::Oyster::Physics3D::Formula::AngularMomentum( j, offset ); + ::Oyster::Math::Float3 offset = at - this->centerPos; + ::Oyster::Math::Float3 deltaAngularImpulse = ::Oyster::Physics3D::Formula::AngularMomentum( j, offset ); this->linearImpulse += j - ::Oyster::Physics3D::Formula::TangentialLinearMomentum( deltaAngularImpulse, offset ); - this->angularImpulse += deltaAngularImpulse; + this->angularImpulse += deltaAngularImpulse; this->isDisturbed = true; } - inline void CustomBodyState::ApplyForwarding( const ::Oyster::Math::Float4 &deltaPos, const ::Oyster::Math::Float4 &deltaAxis ) + inline void CustomBodyState::ApplyForwarding( const ::Oyster::Math::Float3 &deltaPos, const ::Oyster::Math::Float3 &deltaAxis ) { this->deltaPos += deltaPos; this->deltaAxis += deltaAxis; diff --git a/Code/GamePhysics/PhysicsStructs.h b/Code/GamePhysics/PhysicsStructs.h index 1bc1736f..00c07b2d 100644 --- a/Code/GamePhysics/PhysicsStructs.h +++ b/Code/GamePhysics/PhysicsStructs.h @@ -3,6 +3,7 @@ #include "OysterMath.h" #include "PhysicsAPI.h" +#include "Inertia.h" namespace Oyster { namespace Physics { @@ -11,15 +12,15 @@ namespace Oyster { namespace Physics struct SimpleBodyDescription { ::Oyster::Math::Float4x4 rotation; - ::Oyster::Math::Float4 centerPosition; - ::Oyster::Math::Float4 size; + ::Oyster::Math::Float3 centerPosition; + ::Oyster::Math::Float3 size; ::Oyster::Math::Float mass; ::Oyster::Math::Float restitutionCoeff; ::Oyster::Math::Float frictionCoeff_Static; ::Oyster::Math::Float frictionCoeff_Dynamic; - ::Oyster::Math::Float4x4 inertiaTensor; - ::Oyster::Physics::ICustomBody::EventAction_Collision subscription_onCollision; - ::Oyster::Physics::ICustomBody::EventAction_CollisionResponse subscription_onCollisionResponse; + ::Oyster::Physics3D::MomentOfInertia inertiaTensor; + ::Oyster::Physics::ICustomBody::EventAction_BeforeCollisionResponse subscription_onCollision; + ::Oyster::Physics::ICustomBody::EventAction_AfterCollisionResponse subscription_onCollisionResponse; ::Oyster::Physics::ICustomBody::EventAction_Move subscription_onMovement; bool ignoreGravity; @@ -29,14 +30,14 @@ namespace Oyster { namespace Physics struct SphericalBodyDescription { ::Oyster::Math::Float4x4 rotation; - ::Oyster::Math::Float4 centerPosition; + ::Oyster::Math::Float3 centerPosition; ::Oyster::Math::Float radius; ::Oyster::Math::Float mass; ::Oyster::Math::Float restitutionCoeff; ::Oyster::Math::Float frictionCoeff_Static; ::Oyster::Math::Float frictionCoeff_Dynamic; - ::Oyster::Physics::ICustomBody::EventAction_Collision subscription_onCollision; - ::Oyster::Physics::ICustomBody::EventAction_CollisionResponse subscription_onCollisionResponse; + ::Oyster::Physics::ICustomBody::EventAction_BeforeCollisionResponse subscription_onCollision; + ::Oyster::Physics::ICustomBody::EventAction_AfterCollisionResponse subscription_onCollisionResponse; ::Oyster::Physics::ICustomBody::EventAction_Move subscription_onMovement; bool ignoreGravity; @@ -50,13 +51,13 @@ namespace Oyster { namespace Physics ::Oyster::Math::Float restitutionCoeff = 1.0f, ::Oyster::Math::Float staticFrictionCoeff = 1.0f, ::Oyster::Math::Float kineticFrictionCoeff = 1.0f, - const ::Oyster::Math::Float4x4 &inertiaTensor = ::Oyster::Math::Float4x4::identity, - const ::Oyster::Math::Float4 &reach = ::Oyster::Math::Float4::null, - const ::Oyster::Math::Float4 ¢erPos = ::Oyster::Math::Float4::standard_unit_w, - const ::Oyster::Math::Float4 &rotation = ::Oyster::Math::Float4::null, - const ::Oyster::Math::Float4 &linearMomentum = ::Oyster::Math::Float4::null, - const ::Oyster::Math::Float4 &angularMomentum = ::Oyster::Math::Float4::null, - const ::Oyster::Math::Float4 &gravityNormal = ::Oyster::Math::Float4::null); + const ::Oyster::Physics3D::MomentOfInertia &inertiaTensor = ::Oyster::Physics3D::MomentOfInertia(), + const ::Oyster::Math::Float3 &reach = ::Oyster::Math::Float3::null, + const ::Oyster::Math::Float3 ¢erPos = ::Oyster::Math::Float3::null, + const ::Oyster::Math::Float3 &rotation = ::Oyster::Math::Float3::null, + const ::Oyster::Math::Float3 &linearMomentum = ::Oyster::Math::Float3::null, + const ::Oyster::Math::Float3 &angularMomentum = ::Oyster::Math::Float3::null, + const ::Oyster::Math::Float3 &gravityNormal = ::Oyster::Math::Float3::null); CustomBodyState & operator = ( const CustomBodyState &state ); @@ -64,50 +65,51 @@ namespace Oyster { namespace Physics const ::Oyster::Math::Float GetRestitutionCoeff() const; const ::Oyster::Math::Float GetFrictionCoeff_Static() const; const ::Oyster::Math::Float GetFrictionCoeff_Kinetic() const; - const ::Oyster::Math::Float4x4 & GetMomentOfInertia() const; - const ::Oyster::Math::Float4 & GetReach() const; - ::Oyster::Math::Float4 GetSize() const; - const ::Oyster::Math::Float4 & GetCenterPosition() const; - const ::Oyster::Math::Float4 & GetAngularAxis() const; + const ::Oyster::Physics3D::MomentOfInertia & GetMomentOfInertia() const; + const ::Oyster::Math::Float3 & GetReach() const; + ::Oyster::Math::Float3 GetSize() const; + const ::Oyster::Math::Float3 & GetCenterPosition() const; + const ::Oyster::Math::Float3 & GetAngularAxis() const; ::Oyster::Math::Float4x4 GetRotation() const; ::Oyster::Math::Float4x4 GetOrientation() const; - ::Oyster::Math::Float4x4 GetOrientation( const ::Oyster::Math::Float4 &offset ) const; + ::Oyster::Math::Float4x4 GetOrientation( const ::Oyster::Math::Float3 &offset ) const; ::Oyster::Math::Float4x4 GetView() const; - ::Oyster::Math::Float4x4 GetView( const ::Oyster::Math::Float4 &offset ) const; - const ::Oyster::Math::Float4 & GetLinearMomentum() const; - ::Oyster::Math::Float4 GetLinearMomentum( const ::Oyster::Math::Float4 &at ) const; - const ::Oyster::Math::Float4 & GetAngularMomentum() const; - const ::Oyster::Math::Float4 & GetLinearImpulse() const; - const ::Oyster::Math::Float4 & GetAngularImpulse() const; - const ::Oyster::Math::Float4 & GetForward_DeltaPos() const; - const ::Oyster::Math::Float4 & GetForward_DeltaAxis() const; - const ::Oyster::Math::Float4 & GetGravityNormal() const; + ::Oyster::Math::Float4x4 GetView( const ::Oyster::Math::Float3 &offset ) const; + const ::Oyster::Math::Float3 & GetLinearMomentum() const; + ::Oyster::Math::Float3 GetLinearMomentum( const ::Oyster::Math::Float3 &at ) const; + const ::Oyster::Math::Float3 & GetAngularMomentum() const; + const ::Oyster::Math::Float3 & GetLinearImpulse() const; + const ::Oyster::Math::Float3 & GetAngularImpulse() const; + const ::Oyster::Math::Float3 & GetForward_DeltaPos() const; + const ::Oyster::Math::Float3 & GetForward_DeltaAxis() const; + const ::Oyster::Math::Float3 & GetGravityNormal() const; void SetMass_KeepMomentum( ::Oyster::Math::Float m ); void SetMass_KeepVelocity( ::Oyster::Math::Float m ); void SetRestitutionCoeff( ::Oyster::Math::Float e ); void SetFrictionCoeff( ::Oyster::Math::Float staticU, ::Oyster::Math::Float kineticU ); - void SetMomentOfInertia_KeepMomentum( const ::Oyster::Math::Float4x4 &tensor ); - void SetMomentOfInertia_KeepVelocity( const ::Oyster::Math::Float4x4 &tensor ); - void SetSize( const ::Oyster::Math::Float4 &size ); - void SetReach( const ::Oyster::Math::Float4 &halfSize ); - void SetCenterPosition( const ::Oyster::Math::Float4 ¢erPos ); - void SetRotation( const ::Oyster::Math::Float4 &angularAxis ); - void SetRotation( const ::Oyster::Math::Float4x4 &rotation ); - void SetOrientation( const ::Oyster::Math::Float4x4 &orientation ); - void SetLinearMomentum( const ::Oyster::Math::Float4 &g ); - void SetAngularMomentum( const ::Oyster::Math::Float4 &h ); - void SetLinearImpulse( const ::Oyster::Math::Float4 &j ); - void SetAngularImpulse( const ::Oyster::Math::Float4 &j ); - void SetGravityNormal( const ::Oyster::Math::Float4 &gravityNormal ); + void SetMomentOfInertia_KeepMomentum( const ::Oyster::Physics3D::MomentOfInertia &tensor ); + void SetMomentOfInertia_KeepVelocity( const ::Oyster::Physics3D::MomentOfInertia &tensor ); + void SetSize( const ::Oyster::Math::Float3 &size ); + void SetReach( const ::Oyster::Math::Float3 &halfSize ); + void SetCenterPosition( const ::Oyster::Math::Float3 ¢erPos ); + void SetRotation( const ::Oyster::Math::Float3 &angularAxis ); + //void SetRotation( const ::Oyster::Math::Float4x4 &rotation ); + //void SetOrientation( const ::Oyster::Math::Float4x4 &orientation ); + void SetOrientation( const ::Oyster::Math::Float3 &angularAxis, const ::Oyster::Math::Float3 &translation ); + void SetLinearMomentum( const ::Oyster::Math::Float3 &g ); + void SetAngularMomentum( const ::Oyster::Math::Float3 &h ); + void SetLinearImpulse( const ::Oyster::Math::Float3 &j ); + void SetAngularImpulse( const ::Oyster::Math::Float3 &j ); + void SetGravityNormal( const ::Oyster::Math::Float3 &gravityNormal ); - void AddRotation( const ::Oyster::Math::Float4 &angularAxis ); - void AddTranslation( const ::Oyster::Math::Float4 &deltaPos ); + void AddRotation( const ::Oyster::Math::Float3 &angularAxis ); + void AddTranslation( const ::Oyster::Math::Float3 &deltaPos ); - void ApplyLinearImpulse( const ::Oyster::Math::Float4 &j ); - void ApplyAngularImpulse( const ::Oyster::Math::Float4 &j ); - void ApplyImpulse( const ::Oyster::Math::Float4 &j, const ::Oyster::Math::Float4 &at, const ::Oyster::Math::Float4 &normal ); - void ApplyForwarding( const ::Oyster::Math::Float4 &deltaPos, const ::Oyster::Math::Float4 &deltaAxis ); + void ApplyLinearImpulse( const ::Oyster::Math::Float3 &j ); + void ApplyAngularImpulse( const ::Oyster::Math::Float3 &j ); + void ApplyImpulse( const ::Oyster::Math::Float3 &j, const ::Oyster::Math::Float3 &at, const ::Oyster::Math::Float3 &normal ); + void ApplyForwarding( const ::Oyster::Math::Float3 &deltaPos, const ::Oyster::Math::Float3 &deltaAxis ); bool IsSpatiallyAltered() const; bool IsDisturbed() const; @@ -115,12 +117,12 @@ namespace Oyster { namespace Physics private: ::Oyster::Math::Float mass, restitutionCoeff, staticFrictionCoeff, kineticFrictionCoeff; - ::Oyster::Math::Float4x4 inertiaTensor; - ::Oyster::Math::Float4 reach, centerPos, angularAxis; - ::Oyster::Math::Float4 linearMomentum, angularMomentum; - ::Oyster::Math::Float4 linearImpulse, angularImpulse; - ::Oyster::Math::Float4 deltaPos, deltaAxis; // Forwarding data sum - ::Oyster::Math::Float4 gravityNormal; + ::Oyster::Physics3D::MomentOfInertia inertiaTensor; + ::Oyster::Math::Float3 reach, centerPos, angularAxis; + ::Oyster::Math::Float3 linearMomentum, angularMomentum; + ::Oyster::Math::Float3 linearImpulse, angularImpulse; + ::Oyster::Math::Float3 deltaPos, deltaAxis; // Forwarding data sum + ::Oyster::Math::Float3 gravityNormal; bool isSpatiallyAltered, isDisturbed, isForwarded; }; diff --git a/Code/Misc/DynamicArray.h b/Code/Misc/DynamicArray.h index 35df725f..1db30719 100644 --- a/Code/Misc/DynamicArray.h +++ b/Code/Misc/DynamicArray.h @@ -4,6 +4,8 @@ #ifndef MISC_DYNAMIC_ARRAY_H #define MISC_DYNAMIC_ARRAY_H +#include + namespace Utility { namespace DynamicMemory @@ -35,6 +37,8 @@ namespace Utility void Resize(unsigned int size); + void Reserve(unsigned int size); + void Swap(unsigned int a, unsigned int b); unsigned int Size() const; @@ -201,6 +205,11 @@ namespace Utility this->data = temp; } + template void DynamicArray::Reserve(unsigned int size) + { + Expand(size); + } + template void DynamicArray::Swap(unsigned int a, unsigned int b) { T temp = this->data[a]; diff --git a/Code/Misc/Misc.vcxproj b/Code/Misc/Misc.vcxproj index 0b7bf576..6c3db1ec 100644 --- a/Code/Misc/Misc.vcxproj +++ b/Code/Misc/Misc.vcxproj @@ -146,6 +146,7 @@ + @@ -164,6 +165,7 @@ + diff --git a/Code/Misc/Misc.vcxproj.filters b/Code/Misc/Misc.vcxproj.filters index 44348332..8413642a 100644 --- a/Code/Misc/Misc.vcxproj.filters +++ b/Code/Misc/Misc.vcxproj.filters @@ -48,6 +48,9 @@ Source Files + + Source Files + @@ -110,5 +113,8 @@ Header Files + + Header Files + \ No newline at end of file diff --git a/Code/Misc/OysterCallback.h b/Code/Misc/OysterCallback.h index 258408cb..48e967ed 100644 --- a/Code/Misc/OysterCallback.h +++ b/Code/Misc/OysterCallback.h @@ -59,11 +59,11 @@ namespace Oyster switch (callbackType) { case CallbackType_Function: - value.callbackFunction(e); + if(value.callbackFunction) value.callbackFunction(e); return true; break; case CallbackType_Object: - value.callbackObject->ObjectCallback(e); + if(value.callbackObject) value.callbackObject->ObjectCallback(e); return true; break; case CallbackType_PostBox: diff --git a/Code/Misc/Packing/Packing.cpp b/Code/Misc/Packing/Packing.cpp new file mode 100644 index 00000000..30064b0a --- /dev/null +++ b/Code/Misc/Packing/Packing.cpp @@ -0,0 +1,346 @@ +#include "Packing.h" + +/*************************** + Packing +***************************/ + +#include + +namespace Oyster +{ + 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 = (int)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 = (short)strlen(str); + Pack(buffer, len); + buffer += 2; + memcpy(buffer, str, len); + } + + void Pack(unsigned char buffer[], std::string& str) + { + short len = (short)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 = (long long)(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 *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 + char* UnpackCStr(unsigned char buffer[]) + { + short len = UnpackS(buffer); + char* str = new char[len+1]; + + buffer += 2; + for(int i = 0; i < len; i++) + { + str[i] = buffer[i]; + } + + str[len] = '\0'; + + return str; + } + + 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 = (long double)(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; + } + } +} diff --git a/Code/Misc/Packing/Packing.h b/Code/Misc/Packing/Packing.h new file mode 100644 index 00000000..47a65c51 --- /dev/null +++ b/Code/Misc/Packing/Packing.h @@ -0,0 +1,81 @@ +#ifndef PACKING_H +#define PACKING_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include + +/****************************** + Packing +******************************/ +namespace Oyster +{ + 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 + char* UnpackCStr(unsigned char buffer[]); + std::string UnpackStr(unsigned char buffer[]); + + long double Unpack754(unsigned __int64 i, unsigned bits, unsigned expbits); + } +} + +#endif \ No newline at end of file diff --git a/Code/Misc/Resource/OResource.h b/Code/Misc/Resource/OResource.h index a0573c92..83ed474f 100644 --- a/Code/Misc/Resource/OResource.h +++ b/Code/Misc/Resource/OResource.h @@ -38,11 +38,11 @@ namespace Oyster { return this->resourceData; } - inline unsigned long long GetResourceSize() const + inline unsigned int GetResourceSize() const { return this->resourceSize; } - inline unsigned long long GetResourceElementSize() const + inline unsigned int GetResourceElementSize() const { return this->resourceElementSize; } diff --git a/Code/Misc/Resource/OResourceHandler.cpp b/Code/Misc/Resource/OResourceHandler.cpp index 918ecd1d..52d93af0 100644 --- a/Code/Misc/Resource/OResourceHandler.cpp +++ b/Code/Misc/Resource/OResourceHandler.cpp @@ -214,7 +214,14 @@ int OysterResource::GetResourceId(const wchar_t c[]) return -1; } +int OysterResource::GetResourceSize(const OHRESOURCE& resource) +{ + OResource* t = resourcePrivate.FindResource(resource); + if(t) return t->GetResourceSize(); + + return -1; +} OResource* ResourcePrivate::FindResource(const OHRESOURCE& h) const { diff --git a/Code/Misc/Resource/OysterResource.h b/Code/Misc/Resource/OysterResource.h index d6509b54..8adce704 100644 --- a/Code/Misc/Resource/OysterResource.h +++ b/Code/Misc/Resource/OysterResource.h @@ -150,6 +150,11 @@ namespace Oyster * @return Returns the accociated ID */ static int GetResourceId(const wchar_t filename[]); + + + static int GetResourceSize(const OHRESOURCE& resource); + + }; } diff --git a/Code/Misc/Resource/ResourceManager.cpp b/Code/Misc/Resource/ResourceManager.cpp new file mode 100644 index 00000000..ec951bfd --- /dev/null +++ b/Code/Misc/Resource/ResourceManager.cpp @@ -0,0 +1,442 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + + +#include "ResourceManager.h" +#include "..\Utilities.h" + +using namespace Oyster::Resource; + +struct ::ResourceData +{ + LoadFunction loadFnc; + UnloadFunction unloadFnc; + ResourceType resourcetype; + HRESOURCE resource; + unsigned int resourceSize; + int resourceID; + Utility::DynamicMemory::ReferenceCount referenceCount; +}; + +bool ReadFromFile(const wchar_t fileName[], const char openFlag[], std::string& outData, size_t elemSize, bool ANSI = false) +{ + std::string sFilename; + std::wstring wsFile = fileName; + ::Utility::String::WStringToString(wsFile, sFilename); + size_t bytesTotal = 0; + size_t bytesRead = 0; + FILE *stream; + + if( fopen_s( &stream, sFilename.c_str(), openFlag ) == 0 ) + { + //Get size of the file + fseek(stream, 0L, SEEK_END); + bytesTotal = ftell(stream); + fseek(stream, 0L, SEEK_SET); + fflush(stream); + + //Sanity check + if(bytesTotal == 0) return false; + + //Create the new byte buffer + char *buff = new char[bytesTotal + 1]; + + //Read the bytes to the end + bytesRead = fread_s( buff, bytesTotal, elemSize, bytesTotal ,stream ); + fclose( stream ); + + //Did we read enough bytes (Get the bytes if we read with ANSI since the hidden characters is ignored) + if(!ANSI && bytesRead != bytesTotal) return false; + + buff[bytesRead + 1]; + + outData.clear(); + outData.resize(bytesRead); + memcpy(&outData[0], &buff[0], bytesRead); + + delete [] buff; + } + else + { + std::string msg = "Failed to open file: \n"; + msg.append(sFilename.c_str()); + + return false; + } + + return true; +} +const wchar_t* FindResourceKey(std::map& resources, const HRESOURCE h) +{ + for (auto i = resources.begin(); i != resources.end() ; i++) + { + if(i->second->resource == h) + { + return i->first.c_str(); + } + } + return 0; +} +ResourceData* FindResource(std::map& resources, const HRESOURCE h) +{ + for (auto i = resources.begin(); i != resources.end() ; i++) + { + if(i->second->resource == h) + { + return i->second; + } + } + return 0; +} +ResourceData* FindResource(std::map& resources, const wchar_t c[]) +{ + std::wstring temp = c; + auto t = resources.find(c); + if(t == resources.end()) return 0; + + return t->second; +} +void SaveResource( std::map& resources, ResourceData* r, const std::wstring& key, bool addNew ) +{ + if(addNew) + { + resources[key] = r; + } + + r->referenceCount.Incref(); +} +bool Release(std::map& resources, ResourceData* resource) +{ + if(resource->referenceCount.Decref() < 1) + { + const wchar_t* temp = FindResourceKey(resources, resource->resource); + + switch (resource->resourcetype) + { + case Oyster::Resource::ResourceType_Byte_Raw: + case Oyster::Resource::ResourceType_Byte_ANSI: + case Oyster::Resource::ResourceType_Byte_UTF8: + case Oyster::Resource::ResourceType_Byte_UNICODE: + case Oyster::Resource::ResourceType_Byte_UTF16LE: + delete [] ((char*)resource->resource); + resource->resource = 0; + break; + + case Oyster::Resource::ResourceType_CUSTOM: + resource->unloadFnc(resource->resource); + resource->resource = 0; + break; + } + + if(temp) delete resources[temp]; + + return true; + } + return false; +} +ResourceData* Load(/*Out*/ResourceData* targetMem, /*in*/const wchar_t source[], /*in*/ResourceType type) +{ + targetMem->resource = 0; + targetMem->loadFnc = 0; + targetMem->unloadFnc = 0; + targetMem->resourceID = 0; + targetMem->resourcetype = type; + targetMem->resourceSize = 0; + + std::string sOut; + bool success = false; + + switch (type) + { + case Oyster::Resource::ResourceType_Byte_Raw: + success = ReadFromFile(source, "rb", sOut, sizeof(char)); + break; + + case Oyster::Resource::ResourceType_Byte_ANSI: + success = ReadFromFile(source, "r", sOut, sizeof(char), true); + break; + + case Oyster::Resource::ResourceType_Byte_UTF8: + success = ReadFromFile(source, "r, ccs=UTF-8", sOut, sizeof(char)); + break; + + case Oyster::Resource::ResourceType_Byte_UNICODE: + success = ReadFromFile(source, "r, ccs=UNICODE", sOut, sizeof(char)); + break; + + case Oyster::Resource::ResourceType_Byte_UTF16LE: + success = ReadFromFile(source, "r, ccs=UTF-16LE", sOut, sizeof(char)); + break; + } + + if(!success) return 0; + + if(sOut.size()) + { + char *data = new char[sOut.size()+1]; + data[sOut.size()] = '\0'; + memcpy(&data[0], &sOut[0], sOut.size()); + + targetMem->resource = (HRESOURCE&)data; + targetMem->loadFnc = 0; + targetMem->unloadFnc = 0; + targetMem->resourceID = 0; + targetMem->resourcetype = type; + } + + return targetMem; +} +ResourceData* Load(/*Out*/ResourceData* targetMem, /*in*/const wchar_t source[], LoadFunction loadFnc, UnloadFunction unloadFnc) +{ + targetMem->resource = 0; + targetMem->loadFnc = 0; + targetMem->unloadFnc = 0; + targetMem->resourceID = 0; + targetMem->resourcetype = ResourceType_CUSTOM; + targetMem->resourceSize = 0; + + if(loadFnc) + { + targetMem->resource = loadFnc(source); + if(targetMem->resource) + { + targetMem->resourceSize = 0; + targetMem->resourcetype = ResourceType_CUSTOM; + targetMem->loadFnc = loadFnc; + targetMem->unloadFnc = unloadFnc; + } + } + return targetMem; +} +ResourceData* Reload(std::map resources, ResourceData* resource, const wchar_t* filename) +{ + switch (resource->resourcetype) + { + case Oyster::Resource::ResourceType_Byte_Raw: + case Oyster::Resource::ResourceType_Byte_ANSI: + case Oyster::Resource::ResourceType_Byte_UTF8: + case Oyster::Resource::ResourceType_Byte_UNICODE: + case Oyster::Resource::ResourceType_Byte_UTF16LE: + if(Release(resources, resource)) + return Load(resource, filename, resource->loadFnc, resource->unloadFnc); + break; + + case Oyster::Resource::ResourceType_CUSTOM: + { + resource->unloadFnc(resource->resource); + + HRESOURCE r = resource->loadFnc(filename); + if(!r) return 0; + resource->resource = r; + } + break; + } + + return resource; +} + + + +ResourceManager::ResourceManager() +{ } +ResourceManager::~ResourceManager() +{ Clean(); } + +HBYTEARRAY ResourceManager::LoadBytes(const wchar_t filename[], ResourceType type, int customID, bool force) +{ + if(!filename) return 0; + + ResourceData *t = FindResource(this->resources, filename); + + if(t) + { + if(force) + { + return (HBYTEARRAY)Reload(resources, t, filename )->resource; + } + else + { + //Add new reference + SaveResource(this->resources, t, filename, false); + return (HBYTEARRAY)t->resource; + } + } + else + { + t = Load(new ResourceData(), filename, type); + if(t) + { + t->resourceID = (customID); + SaveResource(this->resources, t, filename, true); + } + else + { + return 0; + } + } + + return (HBYTE*)t->resource; +} +HRESOURCE ResourceManager::LoadResource(const wchar_t filename[], LoadFunction loadFnc, UnloadFunction unloadFnc, int customId, bool force) +{ + if(!filename) + { + return 0; + } + if(!loadFnc) + { + return 0; + } + + ResourceData *t = FindResource(this->resources, filename); + if(t) + { + if(force) + { + return ResourceManager::ReloadResource(filename); + } + else + { + //Add new reference + SaveResource(this->resources, t, filename, false); + return t->resource; + } + } + else + { + t = Load(new ResourceData(), filename, loadFnc, unloadFnc ); + if(t && t->resource) + { + t->resourceID = (customId); + SaveResource(this->resources, t, filename, true); + } + else + { + delete t; + t = 0; + } + } + if(!t) + { + return 0; + } + return (HRESOURCE)t->resource; +} + +HRESOURCE ResourceManager::ReloadResource(const wchar_t filename[]) +{ + ResourceData *t = FindResource(this->resources, filename); + if(!t) return 0; //The resource has not been loaded + + return Reload(this->resources, t, filename)->resource; +} +HRESOURCE ResourceManager::ReloadResource(HRESOURCE& resource) +{ + ResourceData *t = FindResource(this->resources, resource); + if(!t) return 0; + return Reload(this->resources, t, FindResourceKey(this->resources, resource))->resource; +} + +void ResourceManager::Clean() +{ + if(this->resources.empty()) return; + + auto i = this->resources.begin(); + auto last = resources.end(); + + for (i; i != last; i++) + { + //Remove all the references + while (!Release(resources, i->second)); + } + resources.clear(); +} +void ResourceManager::ReleaseResource(const HRESOURCE& resourceData) +{ + const wchar_t* temp = FindResourceKey(resources, resourceData); + + if(temp) + { + ResourceData *t = FindResource(this->resources, resourceData); + if(Release(resources, t)) + { + resources.erase(temp); + } + } +} +void ResourceManager::ReleaseResource(const wchar_t filename[]) +{ + ResourceData *t = FindResource(this->resources, filename); + if(t) + { + if(Release(resources, t)) + { + resources.erase(filename); + } + } +} + + + +void ResourceManager::SetResourceId (const HRESOURCE& resourceData, unsigned int id) +{ + ResourceData *t = FindResource(this->resources, resourceData); + + if(t) t->resourceID = (id); +} +void ResourceManager::SetResourceId(const wchar_t c[], unsigned int id) +{ + ResourceData *t = FindResource(this->resources, c); + + if(t) t->resourceID = (id); +} +ResourceType ResourceManager::GetResourceType (const HRESOURCE& resourceData) +{ + ResourceData *t = FindResource(this->resources, resourceData); + + if(t) return t->resourcetype; + + return ResourceType_INVALID; +} +ResourceType ResourceManager::GetResourceType (const wchar_t c[]) +{ + ResourceData *t = FindResource(this->resources, c); + + if(t) return t->resourcetype; + + return ResourceType_INVALID; +} +const wchar_t* ResourceManager::GetResourceFilename (const HRESOURCE& resourceData) +{ + return FindResourceKey(this->resources, resourceData); +} +HRESOURCE ResourceManager::GetResourceHandle(const wchar_t filename[]) +{ + ResourceData *t = FindResource(this->resources, filename); + + if(t) return t->resource; + + return 0; +} +int ResourceManager::GetResourceId (const HRESOURCE& resourceData) +{ + ResourceData *t = FindResource(this->resources, resourceData); + + if(t) return t->resourceID; + + return -1; +} +int ResourceManager::GetResourceId(const wchar_t c[]) +{ + ResourceData *t = FindResource(this->resources, c); + + if(t) return t->resourceID; + + return -1; +} + + + + + diff --git a/Code/Misc/Resource/ResourceManager.h b/Code/Misc/Resource/ResourceManager.h new file mode 100644 index 00000000..4c90966e --- /dev/null +++ b/Code/Misc/Resource/ResourceManager.h @@ -0,0 +1,160 @@ +#ifndef MISC_RESOURCELOADER_H +#define MISC_RESOURCELOADER_H + +#include +#include + +namespace Oyster +{ + namespace Resource + { + struct ResourceData; + + typedef void* HRESOURCE; + typedef char HBYTE; + typedef HBYTE* HBYTEARRAY; + /** Typedef on a fuction required for custom unloading */ + typedef void(*UnloadFunction)(void* loadedData); + + /** Typedef on a fuction required for custom loading */ + typedef void*(*LoadFunction)(const wchar_t filename[]); + + /** An enum class representing all avalible resources that is supported. */ + enum ResourceType + { + //Byte + ResourceType_Byte_Raw, /**< Handle can be interpeted as char[] or char* */ + ResourceType_Byte_ANSI, /**< Handle can be interpeted as char[] or char* */ + ResourceType_Byte_UTF8, /**< Handle can be interpeted as char[] or char* */ + ResourceType_Byte_UNICODE, /**< Handle can be interpeted as char[] or char* */ + ResourceType_Byte_UTF16LE, /**< Handle can be interpeted as char[] or char* */ + + ResourceType_CUSTOM, /**< Handle can be interpeted as whatever */ + ResourceType_INVALID, /**< Handle can be interpeted as whatever */ + }; + + /** A resource handler interface to interact with when loading resources. + * The resource handler uses the filename to make resources unuiqe. + */ + class ResourceManager + { + public: + ResourceManager(); + ~ResourceManager(); + + /** + * Load a resource given a type. + * @param filename The path to the resource. + * @param customId An optional custom ID to associate with the resource. + * @param type The resource type to load. + * @param force If set to true, the resource will be reloaded if it already exists. If it does not, nothing happens. + * @return If function suceeds, a handle to the resource will be returned. If failed 0 is returned. + */ + HBYTEARRAY LoadBytes(const wchar_t filename[], ResourceType type, int customId = -1, bool force = false); + + /** + * Load a resource with a custom loading function + * @param filename The path to the resource. + * @param loadFnc The function that will load the data. + * @param unloadFnc The function that will unload the loaded data. + * @param customId An optional custom ID to associate with the resource. + * @param force If set to true, the resource will be removed and loaded if exists. + * @return If function suceeds, a handle to the resource will be returned. If failed 0 is returned. + */ + HRESOURCE LoadResource(const wchar_t filename[], LoadFunction loadFnc = 0, UnloadFunction unloadFnc = 0, int customId = -1, bool force = false); + + /** + * Reload a resource + * @param filename The path to the resource. + * @return If function suceeds, the return value is the reloaded resource. + */ + HRESOURCE ReloadResource(const wchar_t filename[]); + + /** + * Reload a resource + * @param filename The path to the resource. + * @return If function suceeds, the return value is the reloaded resource. + */ + HRESOURCE ReloadResource(HRESOURCE& resource); + + /** + * Releases all resources loaded by the resource handler. + * @return Nothing + */ + void Clean(); + + /** + * Release a reference to the resource handle + * @param resource The handle to release. + * @return Nothing + */ + void ReleaseResource(const HRESOURCE& resource); + + /** + * Release a reference to the resource handle + * @param resource The resource filename to release reference. + * @return Nothing + */ + void ReleaseResource(const wchar_t filename[]); + + /** Set a user defined ID + * @param resource A handle to accociate the id with. + * @param id A user defined identifier that the resource handler does not touch. + */ + void SetResourceId(const HRESOURCE& resource, unsigned int id); + + /** Set a user defined ID + * If the resource is not loaded the id will not be set. + * @param resource A filename to accociate the id with. + * @param id A user defined identifier that the resource handler does not touch. + */ + void SetResourceId(const wchar_t filename[], unsigned int id); + + /** Get a resource type given a OHRESOURCE handle + * @param resource The handle to check + * @return Returns the resource type of the handle + */ + ResourceType GetResourceType(const HRESOURCE& resource); + + /** Get a resource type given a filename + * If the resource is not loaded the id will not be set. + * @param resource The filename to check + * @return Returns the resource type of the handle + */ + ResourceType GetResourceType (const wchar_t filename[]); + + /** Get a resource filename given a OHRESOURCE handle + * @param resource The handle to check + * @return Returns the accociated filename + */ + const wchar_t* GetResourceFilename(const HRESOURCE& resource); + + /** Get a resource handle given a filename + * If the resource is not loaded function returns 0. + * @param resource The filename to check + * @return Returns the accociated handle + */ + HRESOURCE GetResourceHandle(const wchar_t filename[]); + + /** Get a user defined ID accociated with a handle + * @param resource The handle to check + * @return Returns the accociated ID + */ + int GetResourceId(const HRESOURCE& resource); + + /** Get a user defined ID accociated with a filename + * @param resource The filename to check + * @return Returns the accociated ID + */ + int GetResourceId(const wchar_t filename[]); + + private: + ResourceManager(const ResourceManager& obj); + const ResourceManager& operator=(const ResourceManager&); + std::map resources; + + }; + } +} + +#endif // !MISC_RESOURCELOADER_H diff --git a/Code/Misc/Thread/OysterThread.h b/Code/Misc/Thread/OysterThread.h index cd4bfd3f..739487d9 100644 --- a/Code/Misc/Thread/OysterThread.h +++ b/Code/Misc/Thread/OysterThread.h @@ -72,8 +72,7 @@ namespace Oyster //OYSTER_THREAD_ERROR Create(Oyster::Callback::CallbackFunction::FNC worker, bool start, bool detach = false); OYSTER_THREAD_ERROR Start(); OYSTER_THREAD_ERROR Stop(); - OYSTER_THREAD_ERROR Pause(); - OYSTER_THREAD_ERROR Pause(int mSec); + OYSTER_THREAD_ERROR Stop(int msec); OYSTER_THREAD_ERROR Resume(); OYSTER_THREAD_ERROR SetWorker(IThreadObject* worker = 0); OYSTER_THREAD_ERROR SetWorker(ThreadFnc worker = 0); diff --git a/Code/Misc/Thread/OysterThread_Impl.cpp b/Code/Misc/Thread/OysterThread_Impl.cpp index 6c89567c..79c7c700 100644 --- a/Code/Misc/Thread/OysterThread_Impl.cpp +++ b/Code/Misc/Thread/OysterThread_Impl.cpp @@ -118,15 +118,17 @@ using namespace Utility::DynamicMemory; { SmartPointer data; - PrivateData(){} + PrivateData() + { + data = new RefData(); + } ~PrivateData() { - data.Release(); + data = 0; } OYSTER_THREAD_ERROR Create(ThreadFunction fnc, OwnerContainer worker, bool start, bool detach) { - if(data) return OYSTER_THREAD_ERROR_ThreadAlreadyCreated; - data = new RefData(); + if(!data) data = new RefData(); return data->Create(fnc, worker, start, detach); } OYSTER_THREAD_ERROR Terminate() @@ -205,9 +207,8 @@ using namespace Utility::DynamicMemory; OysterThread::OysterThread() -{ - this->privateData = new PrivateData(); -} + :privateData(0) +{ } OysterThread::OysterThread(const OysterThread& original) { this->privateData = new PrivateData(*original.privateData); @@ -227,7 +228,7 @@ OysterThread::~OysterThread() OYSTER_THREAD_ERROR OysterThread::Create(IThreadObject* worker, bool start, bool detach) { - if(!this->privateData) this->privateData = new PrivateData(); + if(!this->privateData) this->privateData = new PrivateData(); OwnerContainer c; c.type = Oyster::Callback::CallbackType_Object; @@ -236,7 +237,7 @@ OYSTER_THREAD_ERROR OysterThread::Create(IThreadObject* worker, bool start, bool } OYSTER_THREAD_ERROR OysterThread::Create(ThreadFnc worker, bool start, bool detach) { - if(!this->privateData) this->privateData = new PrivateData(); + if(!this->privateData) this->privateData = new PrivateData(); OwnerContainer c; c.type = Oyster::Callback::CallbackType_Function; @@ -257,15 +258,11 @@ OYSTER_THREAD_ERROR OysterThread::Start() return OYSTER_THREAD_ERROR_SUCCESS; } OYSTER_THREAD_ERROR OysterThread::Stop() -{ - return this->Terminate(); -} -OYSTER_THREAD_ERROR OysterThread::Pause() { this->privateData->data->threadData->state = OYSTER_THREAD_STATE_IDLE; return OYSTER_THREAD_ERROR_SUCCESS; } -OYSTER_THREAD_ERROR OysterThread::Pause(int msec) +OYSTER_THREAD_ERROR OysterThread::Stop(int msec) { this->privateData->data->threadData->msec = msec; return OYSTER_THREAD_ERROR_SUCCESS; @@ -299,7 +296,9 @@ OYSTER_THREAD_ERROR OysterThread::SetWorker(ThreadFnc worker) } OYSTER_THREAD_ERROR OysterThread::Terminate() { - return this->privateData->Terminate(); + if(this->privateData) + return this->privateData->Terminate(); + return OYSTER_THREAD_ERROR_SUCCESS; } OYSTER_THREAD_ERROR OysterThread::Wait() { diff --git a/Code/Misc/ThreadSafeQueue.h b/Code/Misc/ThreadSafeQueue.h index 3fab7c70..3afb1cb3 100644 --- a/Code/Misc/ThreadSafeQueue.h +++ b/Code/Misc/ThreadSafeQueue.h @@ -10,6 +10,7 @@ ///////////////////////////////////////////// #include "IQueue.h" +#include namespace Utility { @@ -20,6 +21,7 @@ namespace Utility { public: ThreadSafeQueue(); + ThreadSafeQueue(const ThreadSafeQueue& obj); virtual ~ThreadSafeQueue(); virtual void Push( Type item ); @@ -64,6 +66,12 @@ namespace Utility } + template < typename Type > + ThreadSafeQueue::ThreadSafeQueue(const ThreadSafeQueue& obj) + { + + } + template < typename Type > ThreadSafeQueue::~ThreadSafeQueue() { diff --git a/Code/Misc/Utilities-Impl.h b/Code/Misc/Utilities-Impl.h index 476861f6..1cfe8b8f 100644 --- a/Code/Misc/Utilities-Impl.h +++ b/Code/Misc/Utilities-Impl.h @@ -243,7 +243,7 @@ namespace Utility this->_ptr = p._ptr; this->_rc = p._rc; - this->_rc->Incref(); + if(this->_rc) this->_rc->Incref(); } return *this; } diff --git a/Code/Misc/WinTimer.h b/Code/Misc/WinTimer.h index 73e9091f..60d7a28d 100644 --- a/Code/Misc/WinTimer.h +++ b/Code/Misc/WinTimer.h @@ -7,6 +7,7 @@ #ifndef WINTIMER_H #define WINTIMER_H +#define NOMINMAX #include namespace Utility diff --git a/Code/Network/NetworkAPI/CustomNetProtocol.cpp b/Code/Network/NetworkAPI/CustomNetProtocol.cpp index d34832d7..2ac6fcf5 100644 --- a/Code/Network/NetworkAPI/CustomNetProtocol.cpp +++ b/Code/Network/NetworkAPI/CustomNetProtocol.cpp @@ -4,37 +4,27 @@ #include "CustomNetProtocol.h" #include #include "Translator.h" +#include "Utilities.h" using namespace Oyster::Network; +using namespace Utility::DynamicMemory; struct CustomNetProtocol::PrivateData { - std::map attributes; + std::map attributes; //...Im an idiot + Utility::DynamicMemory::ReferenceCount *c; PrivateData() - { } - PrivateData( const CustomNetProtocol::PrivateData& o) - { - for (auto i = o.attributes.begin(); i != o.attributes.end(); i++) - { - if(i->second.type == NetAttributeType_CharArray) - { - size_t size = strlen(i->second.value.netCharPtr); - if(size == 0) continue; - - attributes[i->first].value.netCharPtr = new char[size + 1]; - //strcpy_s(attributes[i->first].value.netCharPtr, size + 1, i->second.value.netCharPtr); - memcpy(&attributes[i->first].value.netCharPtr[0], &i->second.value.netCharPtr[0], size + 1); - attributes[i->first].type = NetAttributeType_CharArray; - } - else - { - attributes[i->first] = i->second; - } - } + { + //this->attributes = new std::map(); + this->c = new ReferenceCount(); + c->Incref(); } + ~PrivateData() { + delete c; + c = 0; for (auto i = attributes.begin(); i != attributes.end(); i++) { RemoveAttribute(i->first); @@ -49,8 +39,7 @@ struct CustomNetProtocol::PrivateData switch (i->second.type) { case NetAttributeType_CharArray: - //delete [] i->second.value.netCharPtr; - i->second.value.netCharPtr = 0; + delete [] i->second.value.netCharPtr; break; } } @@ -65,17 +54,40 @@ CustomNetProtocol::CustomNetProtocol() } CustomNetProtocol::CustomNetProtocol(const CustomNetProtocol& o) { - this->privateData = new PrivateData(*o.privateData); + this->privateData = o.privateData; + if(this->privateData) + { + this->privateData->c = o.privateData->c; + this->privateData->c->Incref(); + } } const CustomNetProtocol& CustomNetProtocol::operator=(const CustomNetProtocol& o) { - delete this->privateData; - this->privateData = new PrivateData(*o.privateData); + if(this->privateData && this->privateData->c) + { + if(this->privateData->c->Decref() == 0) + { + delete this->privateData; + } + } + + this->privateData = o.privateData; + if(this->privateData) + { + this->privateData->c = o.privateData->c; + this->privateData->c->Incref(); + } return *this; } CustomNetProtocol::~CustomNetProtocol() { - delete this->privateData; + if(this->privateData && this->privateData->c) + { + if(this->privateData->c->Decref() == 0) + { + delete this->privateData; + } + } } NetAttributeContainer& CustomNetProtocol::operator[](int ID) { @@ -87,4 +99,39 @@ NetAttributeContainer& CustomNetProtocol::operator[](int ID) } return this->privateData->attributes[ID]; +} + +void CustomNetProtocol::Set(int ID, Oyster::Network::NetAttributeValue val, Oyster::Network::NetAttributeType type) +{ + this->privateData->attributes[ID].type = type; + + switch (type) + { + case Oyster::Network::NetAttributeType_Bool: + case Oyster::Network::NetAttributeType_Char: + case Oyster::Network::NetAttributeType_UnsignedChar: + case Oyster::Network::NetAttributeType_Short: + case Oyster::Network::NetAttributeType_UnsignedShort: + case Oyster::Network::NetAttributeType_Int: + case Oyster::Network::NetAttributeType_UnsignedInt: + case Oyster::Network::NetAttributeType_Int64: + case Oyster::Network::NetAttributeType_UnsignedInt64: + case Oyster::Network::NetAttributeType_Float: + case Oyster::Network::NetAttributeType_Double: + this->privateData->attributes[ID].value = val; + break; + } +} +void CustomNetProtocol::Set(int ID, std::string s) +{ + if(s.size() == 0) return; + + this->privateData->attributes[ID].type = Oyster::Network::NetAttributeType_CharArray; + + this->privateData->attributes[ID].value.netCharPtr = new char[s.size() + 1]; + memcpy(&this->privateData->attributes[ID].value.netCharPtr[0], &s[0], s.size() + 1); +} +const NetAttributeContainer& CustomNetProtocol::Get(int id) +{ + return this->privateData->attributes[id]; } \ No newline at end of file diff --git a/Code/Network/NetworkAPI/CustomNetProtocol.h b/Code/Network/NetworkAPI/CustomNetProtocol.h index 82d92c99..8e531f17 100644 --- a/Code/Network/NetworkAPI/CustomNetProtocol.h +++ b/Code/Network/NetworkAPI/CustomNetProtocol.h @@ -6,12 +6,7 @@ #include //#include - -#ifdef CUSTOM_NET_PROTOCOL_EXPORT - #define NET_PROTOCOL_EXPORT __declspec(dllexport) -#else - #define NET_PROTOCOL_EXPORT __declspec(dllimport) -#endif +#include "NetworkAPI_Preprocessor.h" namespace Oyster { @@ -78,7 +73,7 @@ namespace Oyster virtual CustomNetProtocol* GetProtocol() = 0; }; - class NET_PROTOCOL_EXPORT CustomNetProtocol + class NET_API_EXPORT CustomNetProtocol { public: CustomNetProtocol(); @@ -87,6 +82,9 @@ namespace Oyster const CustomNetProtocol& operator=(const CustomNetProtocol& o); NetAttributeContainer& operator[](int ID); + void Set(int id, Oyster::Network::NetAttributeValue val, Oyster::Network::NetAttributeType type); + void Set(int ID, std::string s); + const NetAttributeContainer& Get(int id); private: struct PrivateData; diff --git a/Code/Network/NetworkAPI/NetworkAPI.vcxproj b/Code/Network/NetworkAPI/NetworkAPI.vcxproj index fe2f5c09..13ab5af9 100644 --- a/Code/Network/NetworkAPI/NetworkAPI.vcxproj +++ b/Code/Network/NetworkAPI/NetworkAPI.vcxproj @@ -88,16 +88,16 @@ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(SolutionDir)..\Bin\DLL\ $(ProjectName)_$(PlatformShortName) - C:\Program Files %28x86%29\Visual Leak Detector\include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSDK_LibraryPath_x86); + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) false $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(SolutionDir)..\Bin\DLL\ $(ProjectName)_$(PlatformShortName) - C:\Program Files %28x86%29\Visual Leak Detector\lib\Win64;$(VCInstallDir)lib\amd64;$(VCInstallDir)atlmfc\lib\amd64;$(WindowsSDK_LibraryPath_x64); - C:\Program Files %28x86%29\Visual Leak Detector\include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); + C:\Program Files %28x86%29\Visual Leak Detector\lib\Win64;$(LibraryPath) + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) @@ -105,8 +105,9 @@ Level3 Disabled - CUSTOM_NET_PROTOCOL_EXPORT;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + NETWORKAPI_EXPORT;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true + $(SolutionDir)Misc\ Console @@ -119,8 +120,9 @@ Level3 Disabled - CUSTOM_NET_PROTOCOL_EXPORT;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + NETWORKAPI_EXPORT;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true + $(SolutionDir)Misc\ Console @@ -135,8 +137,9 @@ MaxSpeed true true - CUSTOM_NET_PROTOCOL_EXPORT;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + NETWORKAPI_EXPORT;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true + $(SolutionDir)Misc\ Console @@ -153,8 +156,9 @@ MaxSpeed true true - CUSTOM_NET_PROTOCOL_EXPORT;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + NETWORKAPI_EXPORT;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true + $(SolutionDir)Misc\ Console @@ -167,13 +171,16 @@ + - + + + diff --git a/Code/Network/NetworkAPI/NetworkAPI_Preprocessor.h b/Code/Network/NetworkAPI/NetworkAPI_Preprocessor.h new file mode 100644 index 00000000..351dbaf0 --- /dev/null +++ b/Code/Network/NetworkAPI/NetworkAPI_Preprocessor.h @@ -0,0 +1,10 @@ +#ifndef NETWORK_API_NETWORK_API_PREPROCESSOR_H +#define NETWORK_API_NETWORK_API_PREPROCESSOR_H + +#ifdef NETWORKAPI_EXPORT + #define NET_API_EXPORT __declspec(dllexport) +#else + #define NET_API_EXPORT __declspec(dllimport) +#endif + +#endif // !NETWORK_API_NETWORK_API_PREPROCESSOR_H diff --git a/Code/Network/NetworkAPI/NetworkCallbackHelper.h b/Code/Network/NetworkAPI/NetworkCallbackHelper.h deleted file mode 100644 index 963dc6de..00000000 --- a/Code/Network/NetworkAPI/NetworkCallbackHelper.h +++ /dev/null @@ -1,80 +0,0 @@ -#ifndef NETWORK_API_NETWORK_CALLBACK_HELPER_H -#define NETWORK_API_NETWORK_CALLBACK_HELPER_H - -///////////////////////////////////// -// Created by Dennis Andersen 2013 // -///////////////////////////////////// - -#include - - -namespace Oyster -{ - namespace Network - { - enum NetworkProtocolCallbackType - { - NetworkProtocolCallbackType_Function, - NetworkProtocolCallbackType_Object, - NetworkProtocolCallbackType_Unknown = -1, - }; - enum NetworkClientCallbackType - { - NetworkClientCallbackType_Function, - NetworkClientCallbackType_Object, - NetworkClientCallbackType_Unknown = -1, - }; - - class NetworkClient; - class CustomNetProtocol; - - - template - struct NetRecieverObject - { - virtual void NetworkCallback(Param) = 0; - }; - struct NetClientEvent :public NetRecieverObject - { - virtual void NetworkCallback(CustomNetProtocol& protocol) = 0; - virtual void Disconnected() { }; - }; - typedef NetRecieverObject ClientConnectedObject ; - typedef NetClientEvent ProtocolRecieverObject; - - - template - struct NetCallbackFunction - { - typedef void (*FNC)(Param); - }; - typedef NetCallbackFunction::FNC ClientConnectCallbackMethod; - typedef NetCallbackFunction::FNC ProtocolRecFunction; - struct NetClientMethods - { - typedef void(*Dissconnected)(void); - ProtocolRecFunction recieved; - Dissconnected dissconnected; - void operator()(CustomNetProtocol& obj) { if(recieved) recieved(obj); } - void operator()() { if(dissconnected) dissconnected(); } - }; - typedef NetClientMethods ProtocolRecieverFunction; - - union RecieverObject - { - ClientConnectCallbackMethod clientConnectFnc; // !< A function pointer for sending or recieving NetworkClient - ProtocolRecieverFunction protocolRecieverFnc; // !< A function pointer for sending or recieving CustomNetProtocol - - ClientConnectedObject *clientConnectObject; // !< An object for sending or recieving NetworkClient - ProtocolRecieverObject *protocolRecievedObject; // !< An object with collected client events methods. - - RecieverObject() { memset(this, 0, sizeof(RecieverObject)); } - RecieverObject(ClientConnectCallbackMethod o) { clientConnectFnc = o; } - RecieverObject(ProtocolRecieverFunction o) { protocolRecieverFnc = o; } - RecieverObject(ClientConnectedObject* o) { clientConnectObject = o; } - RecieverObject(ProtocolRecieverObject* o) { protocolRecievedObject = o; } - }; - } -} - -#endif \ No newline at end of file diff --git a/Code/Network/NetworkAPI/NetworkClient.cpp b/Code/Network/NetworkAPI/NetworkClient.cpp index b55e4d7e..8e8c28fa 100644 --- a/Code/Network/NetworkAPI/NetworkClient.cpp +++ b/Code/Network/NetworkAPI/NetworkClient.cpp @@ -7,6 +7,7 @@ #include "Translator.h" #include "CustomNetProtocol.h" +#include "NetworkSession.h" #include "../NetworkDependencies/Connection.h" #include "../NetworkDependencies/PostBox.h" @@ -19,274 +20,238 @@ using namespace Oyster::Network; using namespace Oyster::Thread; using namespace Utility::DynamicMemory; +using namespace Utility::Container; /************************************* PrivateData *************************************/ -struct ClientDataContainer +typedef NetworkClient::ClientEventArgs CEA; + +struct NetworkClient::PrivateData : public IThreadObject { + NetworkSession *owner; + NetworkClient *parent; Connection connection; - - SmartPointer> sendPostBox; - - RecieverObject recvObj; - NetworkProtocolCallbackType callbackType; - - Oyster::Thread::OysterThread thread; - std::mutex recvObjMutex; - std::mutex postBoxMutex; - Translator translator; + OysterThread thread; + + //Message queue for sending and recieving + ThreadSafeQueue sendQueue; + ThreadSafeQueue> recieveQueue; + //ID static unsigned int currID; const unsigned int ID; - ClientDataContainer(IThreadObject* o) - : ID(currID++) - { - InitWinSock(); - callbackType = NetworkProtocolCallbackType_Unknown; - sendPostBox = new PostBox(); - connection.InitiateClient(); - connection.SetBlockingMode(false); + PrivateData() + : ID(currID++) + , parent(0) + , owner(0) + { - } - ClientDataContainer(IThreadObject* o, unsigned int socket ) - :connection(socket), ID(currID++) - { InitWinSock(); - callbackType = NetworkProtocolCallbackType_Unknown; - sendPostBox = new PostBox(); - connection.InitiateClient(); - connection.SetBlockingMode(false); + this->thread.Create(this, false); + this->thread.SetPriority(Oyster::Thread::OYSTER_THREAD_PRIORITY_1); } - ~ClientDataContainer() - { - connection.Disconnect(); - thread.Stop(); - callbackType = NetworkProtocolCallbackType_Unknown; - + ~PrivateData() + { ShutdownWinSock(); + this->connection.Disconnect(); + this->thread.Terminate(); + this->owner = 0; + this->parent = 0; } - -}; -unsigned int ClientDataContainer::currID = 0; - -struct NetworkClient::PrivateData : public IThreadObject -{ - Utility::DynamicMemory::SmartPointer data; - - PrivateData() { this->data = new ClientDataContainer(this); } - PrivateData(unsigned int socket) { this->data = new ClientDataContainer(this, socket); } - ~PrivateData() { } - - bool DoWork() + bool DoWork() override { - if(!this->data) return false; - if(!this->data->connection.IsConnected()) return false; + if(!this->connection.IsConnected()) return false; Send(); Recv(); return true; } - - - void Send(CustomNetProtocol* protocol) - { - if(!data) return; - - this->data->postBoxMutex.lock(); - this->data->sendPostBox->PostMessage(*protocol); - this->data->postBoxMutex.unlock(); - } - int Send() { int errorCode = 0; - if(!data) return -1; - this->data->postBoxMutex.lock(); - if(this->data->sendPostBox->IsFull()) + if(!this->sendQueue.IsEmpty()) { SmartPointer temp = new OysterByte(); - this->data->translator.Pack(temp, this->data->sendPostBox->FetchMessage()); - errorCode = this->data->connection.Send(temp); + CustomNetProtocol p = this->sendQueue.Pop(); + this->translator.Pack(temp, p); + errorCode = this->connection.Send(temp); if(errorCode != 0) { - //Failed - this->data->connection.Disconnect(); - - this->data->recvObjMutex.lock(); - if(this->data->callbackType == NetworkProtocolCallbackType_Function) - { - this->data->recvObj.protocolRecieverFnc(); - } - else if(this->data->callbackType == NetworkProtocolCallbackType_Object) - { - this->data->recvObj.protocolRecievedObject->Disconnected(); - } - this->data->recvObjMutex.unlock(); + CEA parg; + parg.type = CEA::EventType_ProtocolFailedToSend; + parg.data.protocol = p; + NetEvent e = { this->parent, parg }; + this->recieveQueue.Push(e); } } - this->data->postBoxMutex.unlock(); return errorCode; } - int Recv() { int errorCode = -1; OysterByte temp = OysterByte(); - errorCode = this->data->connection.Recieve(temp); + errorCode = this->connection.Recieve(temp); if(errorCode == 0 && temp.GetSize()) { CustomNetProtocol protocol; - bool ok = this->data->translator.Unpack(protocol, temp); + bool ok = this->translator.Unpack(protocol, temp); //Check if the protocol was unpacked correctly if(ok) { - this->data->recvObjMutex.lock(); - if(this->data->callbackType == NetworkProtocolCallbackType_Function) - { - this->data->recvObj.protocolRecieverFnc(protocol); - } - else if(this->data->callbackType == NetworkProtocolCallbackType_Object) - { - this->data->recvObj.protocolRecievedObject->NetworkCallback(protocol); - } - this->data->recvObjMutex.unlock(); + CEA parg; + parg.type = CEA::EventType_ProtocolRecieved; + parg.data.protocol = protocol; + NetEvent e = { this->parent, parg }; + this->recieveQueue.Push(e); } } + //else + //{ + // CEA parg; + // parg.type = CEA::EventType_ProtocolFailedToRecieve; + // parg.data.nothing = 0; + // NetEvent e = { this->parent, parg }; + // this->recieveQueue.Push(e); + //} return errorCode; } - }; - +unsigned int NetworkClient::PrivateData::currID = 0; /************************************* NetworkClient *************************************/ NetworkClient::NetworkClient() -{ - privateData = new PrivateData(); - this->privateData->data->thread.SetPriority(Oyster::Thread::OYSTER_THREAD_PRIORITY_1); -} - -NetworkClient::NetworkClient(unsigned int socket) -{ - privateData = new PrivateData(socket); - this->privateData->data->thread.Create(this->privateData, true); - this->privateData->data->thread.SetPriority(Oyster::Thread::OYSTER_THREAD_PRIORITY_1); -} - -NetworkClient::NetworkClient(RecieverObject recvObj, NetworkProtocolCallbackType type) -{ - privateData = new PrivateData(); - this->privateData->data->callbackType = type; - this->privateData->data->recvObj = recvObj; -} - -NetworkClient::NetworkClient(RecieverObject recvObj, NetworkProtocolCallbackType type, unsigned int socket) -{ - privateData = new PrivateData(socket); - this->privateData->data->callbackType = type; - this->privateData->data->recvObj = recvObj; - this->privateData->data->thread.Create(this->privateData, true); - this->privateData->data->thread.SetPriority(Oyster::Thread::OYSTER_THREAD_PRIORITY_1); -} - -NetworkClient::NetworkClient(const NetworkClient& obj) -{ - this->privateData = new PrivateData(*obj.privateData); -} - -NetworkClient& NetworkClient::operator =(const NetworkClient& obj) -{ - delete privateData; - this->privateData = new PrivateData(*obj.privateData); - return *this; -} + : privateData(0) +{ } NetworkClient::~NetworkClient() { - if(privateData) + if(this->privateData) { - delete privateData; - privateData = NULL; + delete this->privateData; + this->privateData = NULL; } } -bool NetworkClient::Connect(unsigned short port, const char serverIP[]) -{ - privateData->data->connection.SetBlockingMode(true); - int result = this->privateData->data->connection.Connect(port, serverIP); - - //Connect has succeeded - if(result == 0) - { - if(this->privateData->data->thread.IsCreated()) return false; - - this->privateData->data->thread.Create(this->privateData, true); - privateData->data->connection.SetBlockingMode(false); - return true; - } - - - - //Connect has failed - return false; -} - -void NetworkClient::Disconnect() -{ - privateData->data->connection.Disconnect(); - privateData->data->thread.Terminate(); -} - -bool NetworkClient::IsConnected() -{ - return privateData->data->connection.IsConnected(); -} - -void NetworkClient::Send(CustomProtocolObject& protocol) -{ - this->privateData->Send(protocol.GetProtocol()); -} - -void NetworkClient::Send(CustomNetProtocol* protocol) -{ - this->privateData->Send(protocol); -} - -void NetworkClient::SetRecieverObject(RecieverObject recvObj, NetworkProtocolCallbackType type) -{ - if (type == NetworkProtocolCallbackType_Unknown) return; //It should probably still be set even if it is unknown. - - privateData->data->recvObjMutex.lock(); - privateData->data->recvObj = recvObj; - privateData->data->callbackType = type; - privateData->data->recvObjMutex.unlock(); -} - bool NetworkClient::operator ==(const NetworkClient& obj) { - return (this->privateData->data->ID == obj.privateData->data->ID); + return (this->privateData->ID == obj.privateData->ID); } bool NetworkClient::operator ==(const int& ID) { - return this->privateData->data->ID == ID; + return this->privateData->ID == ID; +} + +void NetworkClient::Update() +{ + if(!this->privateData) return; + while (!this->privateData->recieveQueue.IsEmpty()) + { + NetEvent temp = this->privateData->recieveQueue.Pop(); + + this->DataRecieved(temp); + + //--------- Deprecate --------- + this->NetworkCallback(temp.args.data.protocol); + //------------------------------ + } +} + +bool NetworkClient::Connect(ConnectionInfo& socket) +{ + if(this->IsConnected()) return true; + if(this->privateData) return false; + if(!this->privateData) this->privateData = new PrivateData(); + + int result = this->privateData->connection.Connect(socket, false); + + //Connect has succeeded + if(result != 0) return false; + + this->privateData->parent = this; + this->privateData->thread.Start(); + + //Connect has failed + return true; +} + +bool NetworkClient::Connect(unsigned short port, const char serverIP[]) +{ + if(this->IsConnected()) return false; + if(this->privateData) return false; + if(!this->privateData) this->privateData = new PrivateData(); + + int result = this->privateData->connection.Connect(port, serverIP, false); + + //Connect has succeeded + if(result != 0) return false; + this->privateData->owner = 0; + this->privateData->parent = this; + this->privateData->thread.Start(); + + //Connect has failed + return true; +} + +void NetworkClient::Disconnect() +{ + privateData->connection.Disconnect(); + privateData->thread.Terminate(); +} + +void NetworkClient::Send(CustomProtocolObject& protocol) +{ + this->privateData->sendQueue.Push(*protocol.GetProtocol()); +} + +void NetworkClient::Send(CustomNetProtocol* protocol) +{ + this->privateData->sendQueue.Push(*protocol); +} + +void NetworkClient::SetOwner(NetworkSession* owner) +{ + this->privateData->owner = owner; +} + +bool NetworkClient::IsConnected() +{ + if(!this->privateData) return false; + return privateData->connection.IsConnected(); } int NetworkClient::GetID() const { - return this->privateData->data->ID; -} \ No newline at end of file + return this->privateData->ID; +} + +void NetworkClient::DataRecieved(NetEvent e) +{ + if(this->privateData->owner) + { + this->privateData->owner->ClientEventCallback(e); + } +} + +void NetworkClient::NetworkCallback(Oyster::Network::CustomNetProtocol& p) +{} + +std::string NetworkClient::GetIpAddress() +{ + return this->privateData->connection.GetIpAddress(); +} diff --git a/Code/Network/NetworkAPI/NetworkClient.h b/Code/Network/NetworkAPI/NetworkClient.h index 5a8dd5e5..dfe247de 100644 --- a/Code/Network/NetworkAPI/NetworkClient.h +++ b/Code/Network/NetworkAPI/NetworkClient.h @@ -1,59 +1,116 @@ #ifndef NETWORK_API_NETWORK_CLIENT_H #define NETWORK_API_NETWORK_CLIENT_H -///////////////////////////////////// -// Created by Pontus Fransson 2013 // -///////////////////////////////////// +////////////////////////////////////// +// Created by Pontus Fransson 2013 // +// Modified by Dennis Andersen 2014 // +////////////////////////////////////// -#ifdef CUSTOM_NET_PROTOCOL_EXPORT - #define NET_PROTOCOL_EXPORT __declspec(dllexport) -#else - #define NET_PROTOCOL_EXPORT __declspec(dllimport) -#endif - -#include "NetworkCallbackHelper.h" -//#include +#include "CustomNetProtocol.h" +#include "NetworkServerEventStruct.h" +#include "NetworkAPI_Preprocessor.h" namespace Oyster { namespace Network { + class NetworkSession; + struct ConnectionInfo; + extern "C" { - struct CustomProtocolObject; - class NET_PROTOCOL_EXPORT NetworkClient + class NET_API_EXPORT NetworkClient { + public: + struct ClientEventArgs + { + enum EventType + { + EventType_ProtocolFailedToRecieve, // No data + EventType_ProtocolFailedToSend, // Data in data.protocol + EventType_ProtocolRecieved, // Data in data.protocol + EventType_Disconnect, // No data + } type; + + union EventData + { + struct { Oyster::Network::CustomNetProtocol protocol; }; + void * nothing; + } data; + }; + typedef void(*ClientEventFunction)(NetEvent e); + public: NetworkClient(); - NetworkClient(unsigned int socket); - NetworkClient(RecieverObject recvObj, NetworkProtocolCallbackType type); - NetworkClient(RecieverObject recvObj, NetworkProtocolCallbackType type, unsigned int socket); - NetworkClient(const NetworkClient& obj); - - NetworkClient& operator =(const NetworkClient& obj); virtual ~NetworkClient(); - bool Connect(unsigned short port, const char serverIP[]); - void Disconnect(); - - bool IsConnected(); - - //Adds the protocol to the queue of protocols to be sent. - void Send(CustomProtocolObject& protocol); - void Send(CustomNetProtocol* protocol); - - void SetRecieverObject(RecieverObject recvObj, NetworkProtocolCallbackType type); - - //Compares the internal ID. bool operator ==(const NetworkClient& obj); bool operator ==(const int& ID); + /** + * + */ + void Update(); + + /** + * + */ + bool Connect(ConnectionInfo& data); + + /** + * + */ + bool Connect(unsigned short port, const char serverIP[]); + + /** + * + */ + void Disconnect(); + + /** + * + */ + void Send(CustomProtocolObject& protocol); + + /** + * + */ + void Send(CustomNetProtocol* protocol); + + /** + * + */ + void SetOwner(NetworkSession* owner); + + /** + * + */ + bool IsConnected(); + + /** + * + */ int GetID() const; + /** + * + */ + virtual void DataRecieved(NetEvent e); + + /** ! Deprecate ! + * Do not use this furthermore, instead use void DataRecieved(NetEvent e); + * @see DataRecieved + */ + virtual void NetworkCallback(Oyster::Network::CustomNetProtocol& p); + + virtual std::string GetIpAddress(); + private: + NetworkClient(const NetworkClient& obj); + NetworkClient& operator =(const NetworkClient& obj); + struct PrivateData; PrivateData* privateData; - }; } } diff --git a/Code/Network/NetworkAPI/NetworkServer.cpp b/Code/Network/NetworkAPI/NetworkServer.cpp index ec4da231..4bdc4abf 100644 --- a/Code/Network/NetworkAPI/NetworkServer.cpp +++ b/Code/Network/NetworkAPI/NetworkServer.cpp @@ -9,11 +9,14 @@ #include "../NetworkDependencies/PostBox.h" #include "../NetworkDependencies/WinsockFunctions.h" -#include "../../Misc/Utilities.h" -#include "../../Misc/Thread/OysterThread.h" +#include "Utilities.h" +#include "Thread/OysterThread.h" + +#ifndef _DEBUG +#include +#endif using namespace Oyster::Network; -using namespace ::Server; using namespace Utility::DynamicMemory; using namespace Oyster::Thread; @@ -21,148 +24,89 @@ using namespace Oyster::Thread; PrivateData *************************************/ +void Broadcast() +{ + char pkt[4]; + size_t pkt_length = 4; + sockaddr_in dest; + sockaddr_in local; + WSAData data; + WSAStartup( MAKEWORD( 2, 2 ), &data ); + + local.sin_family = AF_INET; + local.sin_addr.s_addr = inet_addr( "127.0.0.1" ); + local.sin_port = 15151; // choose any + + dest.sin_family = AF_INET; + dest.sin_port = htons( 15151 ); + + // create the socket + SOCKET s = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ); + // bind to the local address + bind( s, (sockaddr *)&local, sizeof(local) ); + + std::string addr; + for (int i = 0; i < 256; i++) + { + addr = "192.168.0."; + char buff[5]; + _itoa_s<5>(i, buff, 10); + + addr.append(buff); + dest.sin_addr.s_addr = inet_addr( addr.c_str() ); + // send the pkt + int ret = sendto( s, pkt, pkt_length, 0, (sockaddr *)&dest, sizeof(dest) ); + } +} + struct NetworkServer::PrivateData : public IThreadObject { - PrivateData(); - ~PrivateData(); - - bool Init(INIT_DESC& initDesc); - bool Start(); - void Stop(); - void Shutdown(); - - void CheckForNewClient(); +public: + PrivateData() + : listener(0) + , mainSession(0) + , isInitiated(0) + , isReleased(0) + , isRunning(0) + , port(-1) + { } + ~PrivateData() + { } bool DoWork(); - // - IListener* listener; - INIT_DESC initDesc; - bool started; - - //Postbox for new clients - PostBox postBox; - - //Server thread - OysterThread thread; +public: + Listener* listener; + PostBox postBox; //Postbox for new clients + OysterThread thread; //Server thread + NetworkSession *mainSession; + Utility::Container::ThreadSafeQueue> clientQueue; + bool isInitiated; + bool isReleased; + bool isRunning; + int port; }; -NetworkServer::PrivateData::PrivateData() -{ - listener = 0; - started = false; - //postBox = new PostBox; -} - -NetworkServer::PrivateData::~PrivateData() -{ - Shutdown(); -} - -bool NetworkServer::PrivateData::Init(INIT_DESC& initDesc) -{ - //Check if it's a valid port - if(initDesc.port == 0) - { - return false; - } - - if(!InitWinSock()) - return false; - - this->initDesc = initDesc; - - //Initiate listener - listener = new Listener(&postBox); - if(!((Listener*)listener)->Init(this->initDesc.port, false)) - { - return false; - } - - if(thread.Create(this, false) == OYSTER_THREAD_ERROR_FAILED) - { - return false; - } - - return true; -} - -bool NetworkServer::PrivateData::Start() -{ - //Start listener - if(!((Listener*)listener)->Start()) - { - return false; - } - - started = true; - - if(thread.Start() == OYSTER_THREAD_ERROR_FAILED) - { - return false; - } - - return true; -} - -void NetworkServer::PrivateData::Stop() -{ - if(listener) - { - ((Listener*)listener)->Stop(); - } - - started = false; - - thread.Stop(); -} - -void NetworkServer::PrivateData::Shutdown() -{ - if(listener) - { - listener->Shutdown(); - delete listener; - listener = NULL; - } - - started = false; - thread.Terminate(); - - ShutdownWinSock(); -} - -//Checks for new clients and sends them to the proc function. -void NetworkServer::PrivateData::CheckForNewClient() -{ - if(postBox.IsFull()) - { - int clientSocketNum = postBox.FetchMessage(); - - //Safety check that is probably not needed. - if(clientSocketNum == -1) - { - return; - } - - //Create client and Proc function if the pointer is not NULL - if(initDesc.callbackType == NetworkClientCallbackType_Function) - { - Oyster::Network::NetworkClient *client = new Oyster::Network::NetworkClient(clientSocketNum); - initDesc.recvObj.clientConnectFnc(client); - } - else if(initDesc.callbackType == NetworkClientCallbackType_Object) - { - Oyster::Network::NetworkClient *client = new Oyster::Network::NetworkClient(clientSocketNum); - initDesc.recvObj.clientConnectObject->NetworkCallback(client); - } - } -} - bool NetworkServer::PrivateData::DoWork() { - CheckForNewClient(); + //Broadcast(); + + /** Check for new clients **/ + if(postBox.IsFull()) + { + ConnectionInfo clientSocketNum = postBox.FetchMessage(); + + if(clientSocketNum.socket == -1) + { + //Something went wrong somewhere... do we care? + } + + SmartPointer client(new NetworkClient()); + client->Connect(clientSocketNum); + + this->clientQueue.Push(client); + } return true; } @@ -173,48 +117,176 @@ bool NetworkServer::PrivateData::DoWork() NetworkServer::NetworkServer() { - privateData = new PrivateData(); + this->privateData = new PrivateData(); +} +NetworkServer::NetworkServer(const NetworkServer& obj) +{ + delete this->privateData; + this->privateData = new PrivateData(*obj.privateData); +} +const NetworkServer& NetworkServer::operator=(const NetworkServer& obj) +{ + delete this->privateData; + this->privateData = new PrivateData(*obj.privateData); + return *this; } - NetworkServer::~NetworkServer() { - if(privateData) + if(this->privateData) { - delete privateData; + delete this->privateData; + this->privateData = 0; } } -bool NetworkServer::Init(INIT_DESC& initDesc) +NetworkServer::ServerReturnCode NetworkServer::Init(const int& port, NetworkSession const* mainSession) { - if(!privateData->Init(initDesc)) + this->privateData->mainSession = const_cast(mainSession); + //Check if it's a valid port + if(port == 0 || port == -1) { - return false; + return NetworkServer::ServerReturnCode_Error; + } + else if(this->privateData->port != 0 && this->privateData->port != -1) + { + return NetworkServer::ServerReturnCode_Error; + } + if(!InitWinSock()) + { + return NetworkServer::ServerReturnCode_Error; } - return true; + //Initiate listener + this->privateData->listener = new Listener(&this->privateData->postBox); + if(!this->privateData->listener->Init(port, false)) + { + return NetworkServer::ServerReturnCode_Error; + } + + if(this->privateData->thread.Create(this->privateData, false) == OYSTER_THREAD_ERROR_FAILED) + { + return NetworkServer::ServerReturnCode_Error; + } + + this->privateData->isInitiated = true; + this->privateData->isReleased = false; + return NetworkServer::ServerReturnCode_Sucess; } -bool NetworkServer::Start() +NetworkServer::ServerReturnCode NetworkServer::Start() { - if(!privateData->Start()) + //Start listener + if(!this->privateData->listener->Start()) { - return false; + return NetworkServer::ServerReturnCode_Error; } - return true; + if(this->privateData->thread.Start() == OYSTER_THREAD_ERROR_FAILED) + { + return NetworkServer::ServerReturnCode_Error; + } + + this->privateData->isRunning = true; + return NetworkServer::ServerReturnCode_Sucess; } void NetworkServer::Stop() { - privateData->Stop(); + if(this->privateData->listener) + { + this->privateData->listener->Stop(); + } + + this->privateData->thread.Stop(); + + this->privateData->isRunning = false; } void NetworkServer::Shutdown() { - privateData->Shutdown(); + if(this->privateData->mainSession) + { + this->privateData->mainSession->CloseSession(true); + } + if(this->privateData->listener) + { + this->privateData->listener->Shutdown(); + delete this->privateData->listener; + this->privateData->listener = NULL; + } + + this->privateData->thread.Terminate(); + + ShutdownWinSock(); + + this->privateData->isRunning = false; + this->privateData->mainSession = 0; + this->privateData->isReleased = true; +} + +int NetworkServer::Update() +{ + int c = 0; + while(!this->privateData->clientQueue.IsEmpty()) + { + if(this->privateData->mainSession) + { + this->privateData->mainSession->ClientConnectedEvent(this->privateData->clientQueue.Pop()); + c++; + } + else + { + //Clients have nowhere to go? + this->privateData->clientQueue.Pop()->Disconnect(); + } + } + return c; +} + +void NetworkServer::SetSession(NetworkSession const* mainSession) +{ + this->privateData->mainSession = const_cast(mainSession); +} + +NetworkSession const* NetworkServer::GetMainSession() +{ + return this->privateData->mainSession; +} + +NetworkSession const* NetworkServer::ReleaseMainSession() +{ + NetworkSession const * temp; + temp = this->privateData->mainSession; + this->privateData->mainSession = 0; + return temp; } bool NetworkServer::IsStarted() const { - return privateData->started; -} \ No newline at end of file + return this->privateData->isRunning; +} + +std::string NetworkServer::GetLanAddress() +{ + std::string szLocalIP; + char szHostName[255]; + struct hostent *host_entry; + + gethostname(szHostName, 255); + + host_entry = gethostbyname(szHostName); + char* temp = inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list); + + char buff[255]; + strcpy_s(buff, temp); + szLocalIP = buff; + return szLocalIP; +} +int NetworkServer::GetPort() +{ + return this->privateData->port; +} + + + + diff --git a/Code/Network/NetworkAPI/NetworkServer.h b/Code/Network/NetworkAPI/NetworkServer.h index 8edc59ff..97a3e024 100644 --- a/Code/Network/NetworkAPI/NetworkServer.h +++ b/Code/Network/NetworkAPI/NetworkServer.h @@ -1,18 +1,15 @@ #ifndef NETWORK_API_NETWORK_SERVER_H #define NETWORK_API_NETWORK_SERVER_H -///////////////////////////////////// -// Created by Pontus Fransson 2013 // -///////////////////////////////////// +////////////////////////////////////// +// Created by Pontus Fransson 2013 // +// Modified by Dennis Andersen 2014 // +////////////////////////////////////// -#ifdef CUSTOM_NET_PROTOCOL_EXPORT - #define NET_PROTOCOL_EXPORT __declspec(dllexport) -#else - #define NET_PROTOCOL_EXPORT __declspec(dllimport) -#endif +#include "NetworkAPI_Preprocessor.h" #include "NetworkClient.h" -#include "NetworkCallbackHelper.h" +#include "NetworkSession.h" #include namespace Oyster @@ -21,27 +18,77 @@ namespace Oyster { extern "C" { - class NET_PROTOCOL_EXPORT NetworkServer + class NET_API_EXPORT NetworkServer { public: - struct INIT_DESC + enum ServerReturnCode { - unsigned short port; //Port the server should be accepting clients on. - - NetworkClientCallbackType callbackType; //The recieverObject type. Function or object. - RecieverObject recvObj; //The functions that is called when a new client has connected. + ServerReturnCode_Error, + ServerReturnCode_Sucess }; + public: NetworkServer(); + NetworkServer(const NetworkServer&); + const NetworkServer& operator=(const NetworkServer&); virtual ~NetworkServer(); - bool Init(INIT_DESC& initDesc); - bool Start(); + + /** Creates a server that clients can connect to + * @param port The port the server will be listening for clients. + * @param mainSession The main session the server will send connected clients to. + * @return The server returncode + */ + ServerReturnCode Init(const int& port, NetworkSession const* mainSession); + + /** Starts the server allowing clients to connect + * @return The server returncode + */ + ServerReturnCode Start(); + + /** Parses asynchronous connected clients. + */ + int Update(); + + /** + * + */ void Stop(); + + /** Shutdown the server and return all resources. + */ void Shutdown(); + /** Set the main session connected clients will enter when connected to server. + * @param mainSession The session to connect as main server session. + */ + void SetSession(NetworkSession const* mainSession); + + /** Get the main session connected with the server + * @return Returns the main session + */ + NetworkSession const* GetMainSession(); + + /** Sets the main session to NULL and returns it + * @return Returns the main session + */ + NetworkSession const* ReleaseMainSession(); + + /** + * + */ bool IsStarted() const; + /** + * + */ + std::string GetLanAddress(); + + /** + * + */ + int NetworkServer::GetPort(); + private: struct PrivateData; PrivateData* privateData; diff --git a/Code/Network/NetworkAPI/NetworkServerEventStruct.h b/Code/Network/NetworkAPI/NetworkServerEventStruct.h new file mode 100644 index 00000000..a48d97de --- /dev/null +++ b/Code/Network/NetworkAPI/NetworkServerEventStruct.h @@ -0,0 +1,17 @@ +#ifndef NETWORK_API_SERVEREVENT_H +#define NETWORK_API_SERVEREVENT_H + +namespace Oyster +{ + namespace Network + { + template + struct NetEvent + { + Sender sender; + Args args; + }; + } +} + +#endif // !SERVERDEPENDENCIES_SERVEREVENT_H diff --git a/Code/Network/NetworkAPI/NetworkSession.cpp b/Code/Network/NetworkAPI/NetworkSession.cpp new file mode 100644 index 00000000..c7bf15ba --- /dev/null +++ b/Code/Network/NetworkAPI/NetworkSession.cpp @@ -0,0 +1,241 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + +#include "NetworkSession.h" +#include "..\..\Misc\Utilities.h" +#include "..\..\Misc\DynamicArray.h" +#include "..\..\Misc\GID.h" +#include "CustomNetProtocol.h" +#include +#include + +using namespace Utility::DynamicMemory; +using namespace Oyster::Network; + + +struct NetworkSession::PrivateSessionData +{ + NetworkClient::ClientEventFunction messageCallback; + std::mutex clientListLock; + NetworkSession* owner; //Where clients end up when session is closed. + int id; + NetworkSession::PrivateSessionData() + : owner(0) + , id(GID()) + {} +}; + + + +NetworkSession::NetworkSession() + : data(new PrivateSessionData()) +{} +NetworkSession::NetworkSession(const NetworkSession& orig) +{ + this->clients = orig.clients; + this->data->owner = orig.data->owner; + this->clientCount = orig.clientCount; + this->data->id = orig.data->id; + this->data->messageCallback = orig.data->messageCallback; +} + +const NetworkSession& NetworkSession::operator=(const NetworkSession& orig) +{ + this->clients = orig.clients; + this->data->owner = orig.data->owner; + this->clientCount = orig.clientCount; + this->data->id = orig.data->id; + this->data->messageCallback = orig.data->messageCallback; + + return *this; +} + +NetworkSession::~NetworkSession() +{ + this->clients.Clear(); + this->clientCount = 0; + this->data->messageCallback = 0; + delete this->data; + this->data = 0; +} + +void NetworkSession::ProcessClients() +{ + for (unsigned int i = 0; i < this->clients.Size(); i++) + { + if(this->clients[i]) this->clients[i]->Update(); + } +} + +bool NetworkSession::Attach(NetClient client) +{ + this->data->clientListLock.lock(); + + int k = -1; + for (unsigned int i = 0; (k == -1) && i < this->clients.Size(); i++) + { + if(!this->clients[i]->IsConnected()) //TODO: Dont check connection status, check more general status.. + k = i; + } + + if(k == -1) + { + this->clients.Push(client); + } + else + { + this->clients[k] = client; + } + + this->clientCount++; + + client->SetOwner(this); + this->data->clientListLock.unlock(); + + return true; +} + +void NetworkSession::DetachAll() +{ + if(this->data->owner) + { + for (unsigned int i = 0; i < this->clients.Size(); i++) + { + this->data->owner->Attach(this->clients[i]); + this->clients[i] = 0; + } + } + else + { + for (unsigned int i = 0; i < this->clients.Size(); i++) + { + this->clients[i]->Disconnect(); + this->clients[i] = 0; + } + } + this->clientCount = 0; +} + +NetClient NetworkSession::Detach(const NetworkClient* client) +{ + NetClient val; + + this->data->clientListLock.lock(); + + for (unsigned int i = 0; i < this->clients.Size(); i++) + { + if(this->clients[i] && this->clients[0]->GetID() == client->GetID()) + { + val = this->clients[i]; + this->clients[i] = 0; + this->clientCount--; + } + } + + this->data->clientListLock.unlock(); + + return val; +} + +NetClient NetworkSession::Detach(short ID) +{ + NetClient val; + + this->data->clientListLock.lock(); + + for (unsigned int i = 0; i < this->clients.Size(); i++) + { + if(this->clients[i] && this->clients[0]->GetID() == ID) + { + val = this->clients[i]; + this->clients[i] = 0; + this->clientCount--; + } + } + + this->data->clientListLock.unlock(); + + return val; +} + +NetClient NetworkSession::Detach() +{ + NetClient val; + + this->data->clientListLock.lock(); + + for (unsigned int i = 0; i < this->clients.Size(); i++) + { + if(this->clients[i]) + { + val = this->clients[i]; + this->clients[i] = 0; + this->clientCount--; + break; + } + } + + this->data->clientListLock.unlock(); + + return val; +} + +bool NetworkSession::Send(Oyster::Network::CustomNetProtocol& protocol) +{ + bool returnValue = false; + for (unsigned int i = 0; i < this->clients.Size(); i++) + { + if(this->clients[i]) + { + this->clients[i]->Send(&protocol); + returnValue = true; + } + } + + return returnValue; +} + +bool NetworkSession::Send(Oyster::Network::CustomNetProtocol& protocol, int ID) +{ + for (unsigned int i = 0; i < this->clients.Size(); i++) + { + if(this->clients[i] && this->clients[i]->GetID() == ID) + { + this->clients[i]->Send(&protocol); + return true; + } + } + return false; +} + +void NetworkSession::CloseSession(bool dissconnectClients) +{ + this->data->clientListLock.lock(); + + for (unsigned int i = 0; i < this->clients.Size(); i++) + { + if(this->clients[i]) + { + if(dissconnectClients) this->clients[i]->Disconnect(); + else if(this->data->owner) this->data->owner->Attach(this->clients[i]); + else this->clients[i]->Disconnect(); //Idiot check, clients have to go somewhere.. + } + } + + this->clients.Clear(); + this->clientCount = 0; + + this->data->clientListLock.unlock(); +} + +void NetworkSession::SetOwner(NetworkSession* owner) +{ + this->data->owner = owner; +} + +void NetworkSession::ClientConnectedEvent(NetClient client) +{ + this->Attach(client); +} + diff --git a/Code/Network/NetworkAPI/NetworkSession.h b/Code/Network/NetworkAPI/NetworkSession.h new file mode 100644 index 00000000..f0677c77 --- /dev/null +++ b/Code/Network/NetworkAPI/NetworkSession.h @@ -0,0 +1,110 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// +#ifndef NETWORK_API_NETWORK_SESSION_H +#define NETWORK_API_NETWORK_SESSION_H + +//warning C4150: deletion of pointer to incomplete type, no destructor called +#pragma warning(disable : 4150) +//needs to have dll-interface to be used by clients of class 'Oyster::Network::NetworkSession' +#pragma warning(disable : 4251) + + +#include "NetworkAPI_Preprocessor.h" +#include "NetworkServerEventStruct.h" +#include "NetworkClient.h" +#include "Utilities.h" +#include "DynamicArray.h" + +namespace Oyster +{ + namespace Network + { + typedef Utility::DynamicMemory::SmartPointer NetClient; + typedef Utility::DynamicMemory::DynamicArray NetClientList; + class NET_API_EXPORT NetworkSession + { + public: + NetworkSession(); + NetworkSession(const NetworkSession& orig); + const NetworkSession& operator=(const NetworkSession& orig); + virtual~NetworkSession(); + + /** Parse session events such as protocols recieved etc. + */ + virtual void ProcessClients(); + + /** + * + */ + virtual bool Attach(NetClient client); + + /** + * Detaches all clients and sends them to owner. + * If no owner is set the clients is disconnected. + */ + virtual void DetachAll(); + + /** + * + */ + virtual NetClient Detach(const NetworkClient* client); + + /** + * + */ + virtual NetClient Detach(short ID); + + /** + * + */ + virtual NetClient Detach(); + + /** Send a message to all clients in this session + * @param message The message + */ + virtual bool Send(Oyster::Network::CustomNetProtocol& message); + + /** Send a message to a specific client in this session + * @param message The message + */ + virtual bool Send(Oyster::Network::CustomNetProtocol& protocol, int ID); + + /** + * + */ + virtual void CloseSession( bool dissconnectClients = false ); + + /** + * Set the owner that clients will be returned to. + * @param owner If owner is NULL, clients will be disconnected when session is over. + */ + virtual void SetOwner(NetworkSession* owner); + + /** Get the number of clients active in this session + * @return The client count + */ + inline int GetClientCount() const { return this->clientCount; } + + /** + * + */ + virtual void ClientConnectedEvent(NetClient client); + + /** + * + */ + virtual void ClientEventCallback(NetEvent e) = 0; + + protected: + NetClientList clients; + + private: + int clientCount; + struct PrivateSessionData; + PrivateSessionData* data; + }; + } +}//End namespace DanBias + +#endif // !DANBIASSERVER_NETWORK_SESSION_H diff --git a/Code/Network/NetworkAPI/Translator.cpp b/Code/Network/NetworkAPI/Translator.cpp index 0829913e..9b855d47 100644 --- a/Code/Network/NetworkAPI/Translator.cpp +++ b/Code/Network/NetworkAPI/Translator.cpp @@ -5,6 +5,7 @@ #include "CustomNetProtocol.h" +#include "../../Misc/Utilities.h" #include "../NetworkDependencies/Messages/MessageHeader.h" #include "../NetworkDependencies/OysterByte.h" @@ -17,6 +18,7 @@ using namespace std; struct MyCastingStruct { std::map attributes; + Utility::DynamicMemory::ReferenceCount *c; }; // TODO: Check if the package has been packed correctly. diff --git a/Code/Network/NetworkAPI/Translator.h b/Code/Network/NetworkAPI/Translator.h index f413492e..7913c16a 100644 --- a/Code/Network/NetworkAPI/Translator.h +++ b/Code/Network/NetworkAPI/Translator.h @@ -27,13 +27,7 @@ "100F" */ -#ifdef CUSTOM_NET_PROTOCOL_EXPORT - #define NET_PROTOCOL_EXPORT __declspec(dllexport) -#else - #define NET_PROTOCOL_EXPORT __declspec(dllimport) -#endif - -#include "../../Misc/Utilities.h" +#include "NetworkAPI_Preprocessor.h" namespace Oyster { @@ -43,7 +37,8 @@ namespace Oyster { class OysterByte; class CustomNetProtocol; - class NET_PROTOCOL_EXPORT Translator + + class NET_API_EXPORT Translator { public: Translator (); diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 5ff4eeda..99cb8a71 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -1,6 +1,7 @@ #include "Connection.h" #include +#include #include #include #include @@ -40,8 +41,23 @@ Connection::~Connection() CloseSocket( this->socket ); } -int Connection::Connect(unsigned short port , const char serverName[]) +int Connection::Connect(ConnectionInfo info, bool blocking) { + this->addr = info.addr; + this->socket = info.socket; + this->stillSending = true; + this->closed = false; + + + SetBlockingMode(blocking); + //connection succesfull! + return 0; +} + +int Connection::Connect(unsigned short port , const char serverName[], bool blocking) +{ + if(this->socket == -1 || this->socket == 0) InitiateSocket(); + struct hostent *hostEnt; if((hostEnt = gethostbyname(serverName)) == NULL) { @@ -61,6 +77,8 @@ int Connection::Connect(unsigned short port , const char serverName[]) closed = false; stillSending = true; + SetBlockingMode(blocking); + //connection succesfull! return 0; } @@ -152,17 +170,24 @@ int Connection::Recieve(OysterByte &bytes) } //Listen will only return the correct socket or -1 for failure. -int Connection::Listen() +ConnectionInfo Connection::Listen() { - if(this->closed) return -1; + ConnectionInfo val = { 0 }; + if(this->closed) return val; - int clientSocket; - if((clientSocket = (int)accept(this->socket, NULL, NULL)) == INVALID_SOCKET) + SOCKADDR_IN client_info = { 0 }; + int addrsize = sizeof(client_info); + + if((val.socket = (int)accept(this->socket, (struct sockaddr*)&client_info, &addrsize)) == INVALID_SOCKET) { - return (int)INVALID_SOCKET;//WSAGetLastError(); + val.socket = WSAGetLastError(); + } + else + { + val.addr = inet_ntoa(client_info.sin_addr); } - return clientSocket; + return val; } bool Connection::IsSending() @@ -198,6 +223,12 @@ int Connection::SetBlockingMode(bool blocking) return 0; } + +std::string Connection::GetIpAddress() +{ + return this->addr; +} + /////////////////////////////////////// //Private functions /////////////////////////////////////// diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index ae76a3f7..0f46a599 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -14,7 +14,6 @@ namespace Oyster { class Connection : public IConnection { - public: Connection(); Connection( int socket ); @@ -27,9 +26,10 @@ namespace Oyster virtual int Recieve( OysterByte &bytes ); virtual int Disconnect(); - virtual int Connect( unsigned short port , const char serverName[] ); + virtual int Connect(ConnectionInfo info, bool blocking = false); + virtual int Connect(unsigned short port , const char serverName[], bool blocking = false); - virtual int Listen(); + virtual ConnectionInfo Listen(); bool IsSending(); bool IsConnected(); @@ -37,6 +37,8 @@ namespace Oyster //Setting the socket to blocking/non-blocking mode. int SetBlockingMode( bool blocking ); + std::string GetIpAddress(); + private: int InitiateSocket(); @@ -44,7 +46,7 @@ namespace Oyster bool stillSending; bool closed; - + std::string addr; }; } } diff --git a/Code/Network/NetworkDependencies/IConnection.h b/Code/Network/NetworkDependencies/IConnection.h index 76736071..bd59de65 100644 --- a/Code/Network/NetworkDependencies/IConnection.h +++ b/Code/Network/NetworkDependencies/IConnection.h @@ -11,6 +11,12 @@ namespace Oyster { namespace Network { + struct ConnectionInfo + { + int socket; + std::string addr; + }; + class OysterByte; class IConnection { @@ -27,7 +33,7 @@ namespace Oyster virtual int InitiateClient() { return false; }; //Listen function to let client connect, only used by the server - virtual int Listen() { return -1; }; + virtual ConnectionInfo Listen() { return ConnectionInfo(); }; //enables the client to connect with a server with use of name and port //(servers uses Listen instead of connect) diff --git a/Code/Network/NetworkDependencies/IListener.h b/Code/Network/NetworkDependencies/IListener.h deleted file mode 100644 index fc7bb4f5..00000000 --- a/Code/Network/NetworkDependencies/IListener.h +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef NETWORK_SERVER_ILISTENER_H -#define NETWORK_SERVER_ILISTENER_H - -///////////////////////////////////// -// Created by Pontus Fransson 2013 // -///////////////////////////////////// - -namespace Oyster -{ - namespace Network - { - namespace Server - { - class IListener - { - public: - virtual ~IListener() {} - virtual bool Init(unsigned int port) = 0; - virtual int Accept() = 0; - virtual void Shutdown() = 0; - - }; - } - } -} - -#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Listener.cpp b/Code/Network/NetworkDependencies/Listener.cpp index deb0d992..d4ee396a 100644 --- a/Code/Network/NetworkDependencies/Listener.cpp +++ b/Code/Network/NetworkDependencies/Listener.cpp @@ -1,8 +1,8 @@ #include "Listener.h" -using namespace Oyster::Network::Server; using namespace Utility::DynamicMemory; using namespace Oyster::Thread; +using namespace Oyster::Network; Listener::Listener() { @@ -11,7 +11,7 @@ Listener::Listener() connection = NULL; } -Listener::Listener(Oyster::Network::IPostBox* postBox) +Listener::Listener(Oyster::Network::IPostBox* postBox) { this->isListening = false; connection = NULL; @@ -88,7 +88,7 @@ void Listener::Shutdown() StopListen(); } -void Listener::SetPostBox(Oyster::Network::IPostBox* postBox) +void Listener::SetPostBox(Oyster::Network::IPostBox* postBox) { stdMutex.lock(); this->postBox = postBox; @@ -97,21 +97,21 @@ void Listener::SetPostBox(Oyster::Network::IPostBox* postBox) int Listener::Accept() { - int clientSocket = -1; + ConnectionInfo clientSocket = {0}; clientSocket = connection->Listen(); if(!this->isListening.load()) { return -1; } - if(clientSocket != -1) + if(clientSocket.socket != -1) { stdMutex.lock(); postBox->PostMessage(clientSocket); stdMutex.unlock(); } - return clientSocket; + return clientSocket.socket; } void Listener::StopListen() { @@ -120,7 +120,7 @@ void Listener::StopListen() this->isListening = false; Connection c; c.InitiateClient(); - c.Connect(this->port, "127.0.0.1"); + c.Connect(this->port, "127.0.0.1", false); } } bool Listener::DoWork() diff --git a/Code/Network/NetworkDependencies/Listener.h b/Code/Network/NetworkDependencies/Listener.h index 422592e7..49449990 100644 --- a/Code/Network/NetworkDependencies/Listener.h +++ b/Code/Network/NetworkDependencies/Listener.h @@ -5,7 +5,6 @@ // Created by Pontus Fransson 2013 // ///////////////////////////////////// -#include "IListener.h" #include "Connection.h" #include "IPostBox.h" #include "../../Misc/Thread/OysterThread.h" @@ -17,45 +16,43 @@ namespace Oyster { namespace Network { - namespace Server + class Listener : public ::Oyster::Thread::IThreadObject { - class Listener : public IListener, public ::Oyster::Thread::IThreadObject - { - public: - Listener(); - Listener(Oyster::Network::IPostBox* postBox); - ~Listener(); + public: + Listener(); + Listener(Oyster::Network::IPostBox* postBox); + ~Listener(); - bool Init(unsigned int port) override; - bool Init(unsigned int port, bool start); - bool Start(); - void Stop(); - void Shutdown(); + bool Init(unsigned int port); + bool Init(unsigned int port, bool start); + bool Start(); + void Stop(); + void Shutdown(); - void SetPostBox(IPostBox* postBox); + void SetPostBox(IPostBox* postBox); - private: - //Thread functions - bool DoWork(); - void ThreadEntry(); - void ThreadExit(); + private: + //Thread functions + bool DoWork(); + void ThreadEntry(); + void ThreadExit(); - //Function that runs in the thread. - int Accept(); - void StopListen(); + //Function that runs in the thread. + int Accept(); + void StopListen(); - private: - ::Oyster::Network::Connection* connection; + private: + ::Oyster::Network::Connection* connection; - ::Oyster::Thread::OysterThread thread; - OysterMutex mutex; - std::mutex stdMutex; + ::Oyster::Thread::OysterThread thread; + OysterMutex mutex; + std::mutex stdMutex; + + IPostBox* postBox; + std::atomic isListening; + int port; + }; - IPostBox* postBox; - std::atomic isListening; - int port; - }; - } } } diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp index d2823b62..8f315797 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp @@ -1,8 +1,9 @@ #include "MessageHeader.h" -#include "../Packing.h" +#include "../../../Misc/Packing/Packing.h" #include using namespace std; +using namespace Oyster::Packing; using namespace Oyster::Network; using namespace Oyster::Network::Messages; using namespace Oyster::Network::Protocols; diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj index 4d2ad291..a723d1f7 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj @@ -157,14 +157,12 @@ - - @@ -172,7 +170,6 @@ - diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters index eadbbeb3..6a695e88 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters @@ -7,14 +7,12 @@ - - @@ -22,7 +20,6 @@ - diff --git a/Code/Network/NetworkDependencies/Packing.cpp b/Code/Network/NetworkDependencies/Packing.cpp deleted file mode 100644 index 41d059a3..00000000 --- a/Code/Network/NetworkDependencies/Packing.cpp +++ /dev/null @@ -1,486 +0,0 @@ -#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 = (int)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 = (short)strlen(str); - Pack(buffer, len); - buffer += 2; - memcpy(buffer, str, len); - } - - void Pack(unsigned char buffer[], std::string& str) - { - short len = (short)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 = (long long)(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 *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 - char* UnpackCStr(unsigned char buffer[]) - { - short len = UnpackS(buffer); - char* str = new char[len+1]; - - buffer += 2; - for(int i = 0; i < len; i++) - { - str[i] = buffer[i]; - } - - str[len] = '\0'; - - return str; - } - - 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 = (long double)(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 deleted file mode 100644 index aaf3a1b8..00000000 --- a/Code/Network/NetworkDependencies/Packing.h +++ /dev/null @@ -1,107 +0,0 @@ -#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 - char* UnpackCStr(unsigned char buffer[]); - 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/OysterGraphics/Core/Core.cpp b/Code/OysterGraphics/Core/Core.cpp index 9f7ce465..f2392f4c 100644 --- a/Code/OysterGraphics/Core/Core.cpp +++ b/Code/OysterGraphics/Core/Core.cpp @@ -15,6 +15,11 @@ IDXGISwapChain* Core::swapChain = NULL; std::stringstream Core::log; +Oyster::Resource::ResourceManager Core::loader; + +std::wstring Core::modelPath; +std::wstring Core::texturePath; + ID3D11RenderTargetView* Core::backBufferRTV = NULL; ID3D11UnorderedAccessView* Core::backBufferUAV = NULL; diff --git a/Code/OysterGraphics/Core/Core.h b/Code/OysterGraphics/Core/Core.h index 3e8ffdd6..050d54c5 100644 --- a/Code/OysterGraphics/Core/Core.h +++ b/Code/OysterGraphics/Core/Core.h @@ -7,6 +7,7 @@ #include "Dx11Includes.h" #include #include "OysterMath.h" +#include "../Misc/Resource/ResourceManager.h" //#include namespace Oyster @@ -25,6 +26,10 @@ namespace Oyster static std::stringstream log; + static Resource::ResourceManager loader; + + static std::wstring modelPath, texturePath; + //BackBufferRTV static ID3D11RenderTargetView* backBufferRTV; //BackBufferUAV diff --git a/Code/OysterGraphics/Core/PipelineManager.cpp b/Code/OysterGraphics/Core/PipelineManager.cpp index c77873b5..d60c1641 100644 --- a/Code/OysterGraphics/Core/PipelineManager.cpp +++ b/Code/OysterGraphics/Core/PipelineManager.cpp @@ -2,7 +2,6 @@ #include #include #include "../FileLoader/GeneralLoader.h" -#include "Resource\OysterResource.h" const char* ShaderFunction = "main"; @@ -49,7 +48,7 @@ namespace Oyster case Oyster::Graphics::Core::PipelineManager::Vertex: if(!VSMap.count(name) || ForceReload) { - data = Resource::OysterResource::LoadResource(filename.c_str(),Loading::LoadShaderV, -1, ForceReload); + data = Core::loader.LoadResource(filename.c_str(),Loading::LoadShaderV, Loading::UnloadShaderV, -1, ForceReload); if(data) { if(ForceReload && VSMap.count(name)) @@ -65,7 +64,7 @@ namespace Oyster } break; case Oyster::Graphics::Core::PipelineManager::Hull: - data = Resource::OysterResource::LoadResource(filename.c_str(),Loading::LoadShaderH, -1, ForceReload); + data = Core::loader.LoadResource(filename.c_str(),Loading::LoadShaderH, Loading::UnloadShaderH, -1, ForceReload); if(!HSMap.count(name) || ForceReload) { if(data!=0) @@ -84,7 +83,7 @@ namespace Oyster } break; case Oyster::Graphics::Core::PipelineManager::Domain: - data = Resource::OysterResource::LoadResource(filename.c_str(),Loading::LoadShaderD, -1, ForceReload); + data = Core::loader.LoadResource(filename.c_str(),Loading::LoadShaderD, Loading::UnloadShaderD, -1, ForceReload); if(!DSMap.count(name) || ForceReload) { if(data!=0) @@ -102,7 +101,7 @@ namespace Oyster } break; case Oyster::Graphics::Core::PipelineManager::Geometry: - data = Resource::OysterResource::LoadResource(filename.c_str(),Loading::LoadShaderG, -1, ForceReload); + data = Core::loader.LoadResource(filename.c_str(),Loading::LoadShaderG, Loading::UnloadShaderG, -1, ForceReload); if(!GSMap.count(name) || ForceReload) { if(data!=0) @@ -120,7 +119,7 @@ namespace Oyster } break; case Oyster::Graphics::Core::PipelineManager::Pixel: - data = Resource::OysterResource::LoadResource(filename.c_str(),Loading::LoadShaderP, -1, ForceReload); + data = Core::loader.LoadResource(filename.c_str(),Loading::LoadShaderP, Loading::UnloadShaderP, -1, ForceReload); if(!PSMap.count(name) || ForceReload) { if(data!=0) @@ -138,7 +137,7 @@ namespace Oyster } break; case Oyster::Graphics::Core::PipelineManager::Compute: - data = Resource::OysterResource::LoadResource(filename.c_str(),Loading::LoadShaderC, -1, ForceReload); + data = Core::loader.LoadResource(filename.c_str(),Loading::LoadShaderC, Loading::UnloadShaderC, -1, ForceReload); if(!CSMap.count(name) || ForceReload) { if(data!=0) diff --git a/Code/OysterGraphics/Definitions/GraphicalDefinition.h b/Code/OysterGraphics/Definitions/GraphicalDefinition.h index d7dbc9f0..d84f7506 100644 --- a/Code/OysterGraphics/Definitions/GraphicalDefinition.h +++ b/Code/OysterGraphics/Definitions/GraphicalDefinition.h @@ -51,9 +51,9 @@ namespace Oyster struct AnimationData { + Math::Float4x4 animatedData[100]; int Animated; Math::Float3 Pad; - Math::Matrix animatedData[10]; }; } diff --git a/Code/OysterGraphics/DllInterfaces/GFXAPI.cpp b/Code/OysterGraphics/DllInterfaces/GFXAPI.cpp index 396ad41e..2d9c3dc6 100644 --- a/Code/OysterGraphics/DllInterfaces/GFXAPI.cpp +++ b/Code/OysterGraphics/DllInterfaces/GFXAPI.cpp @@ -4,7 +4,8 @@ #include "../Render/Resources/Deffered.h" #include "../Render/Rendering/Render.h" #include "../FileLoader/ObjReader.h" -#include "../../Misc/Resource/OysterResource.h" +//#include "../../Misc/Resource/OysterResource.h" +#include "../../Misc/Resource/ResourceManager.h" #include "../FileLoader/GeneralLoader.h" #include "../Model/ModelInfo.h" #include @@ -73,6 +74,8 @@ namespace Oyster API::State API::SetOptions(API::Option option) { + Core::modelPath = option.modelPath; + Core::texturePath = option.texturePath; return API::Sucsess; } @@ -83,8 +86,7 @@ namespace Oyster m->WorldMatrix = Oyster::Math::Float4x4::identity; m->Visible = true; m->AnimationPlaying = -1; - - m->info = (Model::ModelInfo*)Oyster::Resource::OysterResource::LoadResource(filename.c_str(),Oyster::Graphics::Loading::LoadDAN); + m->info = (Model::ModelInfo*)Core::loader.LoadResource((Core::modelPath + filename).c_str(),Oyster::Graphics::Loading::LoadDAN, Oyster::Graphics::Loading::UnloadDAN); Model::ModelInfo* mi = (Model::ModelInfo*)m->info; if(!mi || mi->Vertices->GetBufferPointer() == NULL) @@ -102,13 +104,13 @@ namespace Oyster return; Model::ModelInfo* info = (Model::ModelInfo*)model->info; delete model; - Oyster::Resource::OysterResource::ReleaseResource((Oyster::Resource::OHRESOURCE)info); + Core::loader.ReleaseResource(info); } void API::Clean() { SAFE_DELETE(Core::viewPort); - Oyster::Resource::OysterResource::Clean(); + Core::loader.Clean(); Oyster::Graphics::Core::PipelineManager::Clean(); Oyster::Graphics::Render::Resources::Deffered::Clean(); diff --git a/Code/OysterGraphics/DllInterfaces/GFXAPI.h b/Code/OysterGraphics/DllInterfaces/GFXAPI.h index 950ef19f..81a3bedc 100644 --- a/Code/OysterGraphics/DllInterfaces/GFXAPI.h +++ b/Code/OysterGraphics/DllInterfaces/GFXAPI.h @@ -26,6 +26,7 @@ namespace Oyster }; struct Option { + std::wstring modelPath, texturePath; }; static State Init(HWND Window, bool MSAA_Quality, bool Fullscreen, Oyster::Math::Float2 StartResulotion); diff --git a/Code/OysterGraphics/FileLoader/DanLoader.cpp b/Code/OysterGraphics/FileLoader/DanLoader.cpp index 4cff47ed..0eff143a 100644 --- a/Code/OysterGraphics/FileLoader/DanLoader.cpp +++ b/Code/OysterGraphics/FileLoader/DanLoader.cpp @@ -132,9 +132,24 @@ void Oyster::Graphics::Loading::UnloadDAN(void* data) { SAFE_DELETE(info->Indecies); } + if(info->Animated) + { + //clean animation + delete[] info->bones; + for(int a = 0; a < info->AnimationCount; ++a) + { + for(int x = 0; x < info->Animations[a].Bones; ++x) + { + delete[] info->Animations[a].Keyframes[x]; + } + delete[] info->Animations[a].Frames; + delete[] info->Animations[a].Keyframes; + } + delete[] info->Animations; + } for(int i =0;iMaterial.size();++i) { - Oyster::Resource::OysterResource::ReleaseResource(info->Material[i]); + Core::loader.ReleaseResource(info->Material[i]); } delete info; } @@ -158,7 +173,7 @@ static void ReadData(void* Destination, std::ifstream& file, int size) } /// -void Oyster::Graphics::Loading::LoadDAN(const wchar_t filename[], Oyster::Resource::CustomData& out) +void* Oyster::Graphics::Loading::LoadDAN(const wchar_t filename[]) { // Oyster::Graphics::Model::ModelInfo* modelInfo = new Oyster::Graphics::Model::ModelInfo(); @@ -168,7 +183,7 @@ void Oyster::Graphics::Loading::LoadDAN(const wchar_t filename[], Oyster::Resour std::ifstream danFile; danFile.open(filename, std::ios::binary); if (!danFile.is_open()) - return; + return NULL; // Read file header char* buffer = new char[sizeof(FileHeader)]; @@ -180,7 +195,7 @@ void Oyster::Graphics::Loading::LoadDAN(const wchar_t filename[], Oyster::Resour if (fileHeader.versionMajor != DANFILEVERSIONMAJOR) { danFile.close(); - return; + return NULL; } // Read the .dan-file @@ -281,12 +296,12 @@ void Oyster::Graphics::Loading::LoadDAN(const wchar_t filename[], Oyster::Resour //load diffuse map wchar_t* path = charToWChar(materialHeader.diffuseMapPath); - ID3D11ShaderResourceView* diffuseMap = (ID3D11ShaderResourceView*)Oyster::Resource::OysterResource::LoadResource(path, Oyster::Graphics::Loading::LoadTexture); + ID3D11ShaderResourceView* diffuseMap = (ID3D11ShaderResourceView*)Core::loader.LoadResource((Core::texturePath + path).c_str(), Oyster::Graphics::Loading::LoadTexture, Oyster::Graphics::Loading::UnloadTexture); delete[] path; //load normal map path = charToWChar(materialHeader.normalMapPath); - ID3D11ShaderResourceView* normalMap = (ID3D11ShaderResourceView*)Oyster::Resource::OysterResource::LoadResource(path, Oyster::Graphics::Loading::LoadTexture); + ID3D11ShaderResourceView* normalMap = (ID3D11ShaderResourceView*)Core::loader.LoadResource((Core::texturePath + path).c_str(), Oyster::Graphics::Loading::LoadTexture, Oyster::Graphics::Loading::UnloadTexture); delete[] path; //add to model @@ -333,6 +348,7 @@ void Oyster::Graphics::Loading::LoadDAN(const wchar_t filename[], Oyster::Resour delete[] buffer; Oyster::Graphics::Model::Animation* anims = new Oyster::Graphics::Model::Animation[animationHeader.numAnims]; + for(int a = 0; a < animationHeader.numAnims; ++a) { //read name of animation @@ -348,12 +364,14 @@ void Oyster::Graphics::Loading::LoadDAN(const wchar_t filename[], Oyster::Resour wchar_t* wName = charToWChar(name); anims[a].name = std::wstring(wName); delete[] wName; - - //read duration + delete name; //read nr of bones in animation ReadData(&anims[a].Bones,danFile,4); + //read duration + ReadData(&anims[a].duration,danFile,8); + //create Frame array and Bone part of KeyFrameArray; anims[a].Frames = new int[anims[a].Bones]; anims[a].Keyframes = new Oyster::Graphics::Model::Frame*[anims[a].Bones]; @@ -399,6 +417,5 @@ void Oyster::Graphics::Loading::LoadDAN(const wchar_t filename[], Oyster::Resour danFile.close(); // Set modelinfo as output data - out.loadedData = modelInfo; - out.resourceUnloadFnc = Oyster::Graphics::Loading::UnloadDAN; + return modelInfo; } \ No newline at end of file diff --git a/Code/OysterGraphics/FileLoader/GeneralLoader.h b/Code/OysterGraphics/FileLoader/GeneralLoader.h index cd6806e1..4a707699 100644 --- a/Code/OysterGraphics/FileLoader/GeneralLoader.h +++ b/Code/OysterGraphics/FileLoader/GeneralLoader.h @@ -1,5 +1,4 @@ #pragma once -#include "..\..\Misc\Resource\OysterResource.h" namespace Oyster { namespace Graphics @@ -7,31 +6,31 @@ namespace Oyster namespace Loading { void UnloadTexture(void* loadedData); - void LoadTexture(const wchar_t filename[], Oyster::Resource::CustomData& out); + void* LoadTexture(const wchar_t filename[]); void UnloadShaderP(void* loadedData); - void LoadShaderP(const wchar_t filename[], Oyster::Resource::CustomData& out); + void* LoadShaderP(const wchar_t filename[]); void UnloadShaderG(void* loadedData); - void LoadShaderG(const wchar_t filename[], Oyster::Resource::CustomData& out); + void* LoadShaderG(const wchar_t filename[]); void UnloadShaderC(void* loadedData); - void LoadShaderC(const wchar_t filename[], Oyster::Resource::CustomData& out); + void* LoadShaderC(const wchar_t filename[]); void UnloadShaderV(void* loadedData); - void LoadShaderV(const wchar_t filename[], Oyster::Resource::CustomData& out); + void* LoadShaderV(const wchar_t filename[]); void UnloadShaderH(void* loadedData); - void LoadShaderH(const wchar_t filename[], Oyster::Resource::CustomData& out); + void* LoadShaderH(const wchar_t filename[]); void UnloadShaderD(void* loadedData); - void LoadShaderD(const wchar_t filename[], Oyster::Resource::CustomData& out); + void* LoadShaderD(const wchar_t filename[]); void UnloadOBJ(void* loadedData); - void LoadOBJ(const wchar_t filename[], Oyster::Resource::CustomData& out); + void* LoadOBJ(const wchar_t filename[]); void UnloadDAN(void* loadedData); - void LoadDAN(const wchar_t filename[], Oyster::Resource::CustomData& out); + void* LoadDAN(const wchar_t filename[]); } } } \ No newline at end of file diff --git a/Code/OysterGraphics/FileLoader/ModelLoader.cpp b/Code/OysterGraphics/FileLoader/ModelLoader.cpp index cfd61e0d..b7b8b09a 100644 --- a/Code/OysterGraphics/FileLoader/ModelLoader.cpp +++ b/Code/OysterGraphics/FileLoader/ModelLoader.cpp @@ -2,7 +2,6 @@ #include "..\Core\Dx11Includes.h" #include "..\Core\Core.h" #include "ObjReader.h" -#include "..\..\Misc\Resource\OysterResource.h" HRESULT CreateWICTextureFromFileEx( ID3D11Device* d3dDevice, ID3D11DeviceContext* d3dContext, @@ -16,18 +15,17 @@ HRESULT CreateWICTextureFromFileEx( ID3D11Device* d3dDevice, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView ); -void Oyster::Graphics::Loading::LoadTexture(const wchar_t filename[], Oyster::Resource::CustomData& out) +void* Oyster::Graphics::Loading::LoadTexture(const wchar_t filename[]) { ID3D11ShaderResourceView* srv = NULL; HRESULT hr = CreateWICTextureFromFileEx(Core::device,Core::deviceContext,filename,0,D3D11_USAGE_DEFAULT,D3D11_BIND_SHADER_RESOURCE,0,0,false,NULL,&srv); if(hr!=S_OK) { - memset(&out,0,sizeof(out)); + return NULL; } else { - out.loadedData = (void*)srv; - out.resourceUnloadFnc = Loading::UnloadTexture; + return srv; } } @@ -37,7 +35,7 @@ void Oyster::Graphics::Loading::UnloadTexture(void* data) SAFE_RELEASE(srv); } -void Oyster::Graphics::Loading::LoadOBJ(const wchar_t filename[], Oyster::Resource::CustomData& out) +void* Oyster::Graphics::Loading::LoadOBJ(const wchar_t filename[]) { FileLoaders::ObjReader obj; obj.LoadFile(filename); @@ -57,12 +55,11 @@ void Oyster::Graphics::Loading::LoadOBJ(const wchar_t filename[], Oyster::Resour info->Vertices->Init(desc); info->Indexed = false; - void* texture = Oyster::Resource::OysterResource::LoadResource((std::wstring(filename)+ L".png").c_str(),Graphics::Loading::LoadTexture); + void* texture = Core::loader.LoadResource((std::wstring(filename)+ L".png").c_str(),Graphics::Loading::LoadTexture, Graphics::Loading::UnloadTexture); info->Material.push_back((ID3D11ShaderResourceView*)texture); - out.loadedData = info; - out.resourceUnloadFnc = Oyster::Graphics::Loading::UnloadOBJ; + return info; } void Oyster::Graphics::Loading::UnloadOBJ(void* data) @@ -75,7 +72,7 @@ void Oyster::Graphics::Loading::UnloadOBJ(void* data) } for(int i =0;iMaterial.size();++i) { - Oyster::Resource::OysterResource::ReleaseResource(info->Material[i]); + Core::loader.ReleaseResource(info->Material[i]); } delete info; } diff --git a/Code/OysterGraphics/FileLoader/ShaderLoader.cpp b/Code/OysterGraphics/FileLoader/ShaderLoader.cpp index 9a8cff37..17e9d1fe 100644 --- a/Code/OysterGraphics/FileLoader/ShaderLoader.cpp +++ b/Code/OysterGraphics/FileLoader/ShaderLoader.cpp @@ -10,7 +10,7 @@ namespace Oyster { namespace Loading { - void LoadShader(const wchar_t filename[], Oyster::Resource::CustomData& out, int type); + void* LoadShader(const wchar_t filename[], int type); void UnloadShaderP(void* loadedData) { @@ -48,78 +48,41 @@ namespace Oyster SAFE_RELEASE(ps); } - void LoadShaderP(const wchar_t filename[], Oyster::Resource::CustomData& out) + void* LoadShaderP(const wchar_t filename[]) { - LoadShader(filename,out,Core::PipelineManager::Pixel); - if(out.loadedData==NULL) - { - memset(&out,0,sizeof(out)); - return; - } - out.resourceUnloadFnc = UnloadShaderP; + return LoadShader(filename,Core::PipelineManager::Pixel); } - void LoadShaderG(const wchar_t filename[], Oyster::Resource::CustomData& out) + void* LoadShaderG(const wchar_t filename[]) { - LoadShader(filename,out,Core::PipelineManager::Geometry); - if(out.loadedData==NULL) - { - memset(&out,0,sizeof(out)); - return; - } - out.resourceUnloadFnc = UnloadShaderG; + return LoadShader(filename,Core::PipelineManager::Geometry); } - void LoadShaderC(const wchar_t filename[], Oyster::Resource::CustomData& out) + void* LoadShaderC(const wchar_t filename[]) { - LoadShader(filename,out,Core::PipelineManager::Compute); - if(out.loadedData==NULL) - { - memset(&out,0,sizeof(out)); - return; - } - out.resourceUnloadFnc = UnloadShaderC; + return LoadShader(filename,Core::PipelineManager::Compute); } - void LoadShaderH(const wchar_t filename[], Oyster::Resource::CustomData& out) + void* LoadShaderH(const wchar_t filename[]) { - LoadShader(filename,out,Core::PipelineManager::Hull); - if(out.loadedData==NULL) - { - memset(&out,0,sizeof(out)); - return; - } - out.resourceUnloadFnc = UnloadShaderH; + return LoadShader(filename,Core::PipelineManager::Hull); } - void LoadShaderD(const wchar_t filename[], Oyster::Resource::CustomData& out) + void* LoadShaderD(const wchar_t filename[]) { - LoadShader(filename,out,Core::PipelineManager::Domain); - if(out.loadedData==NULL) - { - memset(&out,0,sizeof(out)); - return; - } - out.resourceUnloadFnc = UnloadShaderD; + return LoadShader(filename,Core::PipelineManager::Domain); } - void LoadShaderV(const wchar_t filename[], Oyster::Resource::CustomData& out) + void* LoadShaderV(const wchar_t filename[]) { - - LoadShader(filename,out,Core::PipelineManager::Vertex); - if(out.loadedData==NULL) - { - memset(&out,0,sizeof(out)); - return; - } - out.resourceUnloadFnc = UnloadShaderV; + return LoadShader(filename,Core::PipelineManager::Vertex); } - void LoadShader(const wchar_t filename[], Oyster::Resource::CustomData& out, int type) + void* LoadShader(const wchar_t filename[], int type) { Core::PipelineManager::ShaderData data; #ifdef _DEBUG @@ -159,8 +122,7 @@ namespace Oyster { Shader->Release(); } - memset(&out,0,sizeof(out)); - return; + return NULL; } data.size = Shader->GetBufferSize(); @@ -185,7 +147,7 @@ namespace Oyster return; } #endif - out.loadedData = Core::PipelineManager::CreateShader(data, Core::PipelineManager::ShaderType(type)); + return Core::PipelineManager::CreateShader(data, Core::PipelineManager::ShaderType(type)); } } } diff --git a/Code/OysterGraphics/Model/ModelInfo.h b/Code/OysterGraphics/Model/ModelInfo.h index 27efe0bb..3a184f65 100644 --- a/Code/OysterGraphics/Model/ModelInfo.h +++ b/Code/OysterGraphics/Model/ModelInfo.h @@ -27,6 +27,7 @@ namespace Oyster int Bones; int* Frames; //! Bone as index Frame** Keyframes; //! @brief [Bone][Frame] + double duration; }; struct ModelInfo { diff --git a/Code/OysterGraphics/Render/Rendering/BasicRender.cpp b/Code/OysterGraphics/Render/Rendering/BasicRender.cpp index bfcf231b..113d7b6f 100644 --- a/Code/OysterGraphics/Render/Rendering/BasicRender.cpp +++ b/Code/OysterGraphics/Render/Rendering/BasicRender.cpp @@ -73,11 +73,16 @@ namespace Oyster //loop bones in animation am.Animated = 1; + + Model::Frame Prev, Next; + + models[i].AnimationTime = fmod(models[i].AnimationTime,info->Animations[models[i].AnimationPlaying].duration); for(int x = 0; x < info->Animations[models[i].AnimationPlaying].Bones; ++x) { - Model::Frame Prev, Next; //loop frame per bone + Prev.bone.Parent = 0; + Next = Prev; for(int y = 0; y < info->Animations[models[i].AnimationPlaying].Frames[x]; ++y) { ///TODO replace with binary search? @@ -113,7 +118,7 @@ namespace Oyster //write magic to animated data am2.animatedData[Prev.bone.Parent] = Interpolated * am2.animatedData[info->bones[Prev.bone.Parent].Parent]; //sneaky write do correct data buffer - am.animatedData[x] = am2.animatedData[Prev.bone.Parent].GetInverse() * info->bones[Prev.bone.Parent].Transform; + am.animatedData[x] = (am2.animatedData[Prev.bone.Parent] * info->bones[Prev.bone.Parent].Transform.GetInverse()); } } else diff --git a/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GBufferHeader.hlsli b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GBufferHeader.hlsli index 95012a3b..f28c1b0b 100644 --- a/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GBufferHeader.hlsli +++ b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/GBufferHeader.hlsli @@ -32,9 +32,9 @@ SamplerState S1 : register(s0); cbuffer Animation : register(b0) { + float4x4 BoneAnimation[100]; int Animated; float3 Pad; - float4x4 BoneAnimation[10]; } cbuffer PerModel : register(b1) diff --git a/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/VertexGatherData.hlsl b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/VertexGatherData.hlsl index 09312dbc..7395e08d 100644 --- a/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/VertexGatherData.hlsl +++ b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/VertexGatherData.hlsl @@ -3,7 +3,17 @@ VertexOut main( VertexIn input ) { VertexOut output; - input.pos = mul(BoneAnimation[input.boneIndex.x], input.pos) * Animated + input.pos * int(1-Animated); + /*input.pos = ( + (mul(BoneAnimation[input.boneIndex.x], input.pos) * input.boneWeight.x) + + (mul(BoneAnimation[input.boneIndex.y], input.pos) * input.boneWeight.y) + + (mul(BoneAnimation[input.boneIndex.z], input.pos) * input.boneWeight.z) + + (mul(BoneAnimation[input.boneIndex.w], input.pos) * input.boneWeight.w) + * Animated) + input.pos * int(1-Animated);*/ + + input.pos = ( + (mul(BoneAnimation[input.boneIndex.x], input.pos)/* * input.boneWeight.x*/) + * Animated) + input.pos * int(1-Animated); + //float4x4 m = matrix(float4(1,0,0,0),float4(0,1,0,0), float4(0,0,1,0), float4(0,0,0,1)); //input.pos = mul(BoneAnimation[0], float4(input.pos,1)); //input.pos = mul(m, float4(input.pos,1)); diff --git a/Code/OysterMath/LinearMath.h b/Code/OysterMath/LinearMath.h index 4d8b4efd..50bcd36b 100644 --- a/Code/OysterMath/LinearMath.h +++ b/Code/OysterMath/LinearMath.h @@ -35,7 +35,7 @@ namespace std // x2 template -::LinearAlgebra::Matrix2x2 operator * ( const ::LinearAlgebra::Matrix2x2 &left, const ::LinearAlgebra::Matrix2x2 &right ) +inline ::LinearAlgebra::Matrix2x2 operator * ( const ::LinearAlgebra::Matrix2x2 &left, const ::LinearAlgebra::Matrix2x2 &right ) { return ::LinearAlgebra::Matrix2x2( (left.m11 * right.m11) + (left.m12 * right.m21), (left.m11 * right.m12) + (left.m12 * right.m22), @@ -44,14 +44,14 @@ template } template -::LinearAlgebra::Vector2 operator * ( const ::LinearAlgebra::Matrix2x2 &matrix, const ::LinearAlgebra::Vector2 &vector ) +inline ::LinearAlgebra::Vector2 operator * ( const ::LinearAlgebra::Matrix2x2 &matrix, const ::LinearAlgebra::Vector2 &vector ) { return ::LinearAlgebra::Vector2( (matrix.m11 * vector.x) + (matrix.m12 * vector.y), (matrix.m21 * vector.x) + (matrix.m22 * vector.y) ); } template -::LinearAlgebra::Vector2 operator * ( const ::LinearAlgebra::Vector2 &vector, const ::LinearAlgebra::Matrix2x2 &left ) +inline ::LinearAlgebra::Vector2 operator * ( const ::LinearAlgebra::Vector2 &vector, const ::LinearAlgebra::Matrix2x2 &left ) { return ::LinearAlgebra::Vector2( (vector.x * matrix.m11) + (vector.y * matrix.m21), (vector.x * matrix.m12) + (vector.y * matrix.m22) ); @@ -60,7 +60,7 @@ template // x3 template -::LinearAlgebra::Matrix3x3 operator * ( const ::LinearAlgebra::Matrix3x3 &left, const ::LinearAlgebra::Matrix3x3 &right ) +inline ::LinearAlgebra::Matrix3x3 operator * ( const ::LinearAlgebra::Matrix3x3 &left, const ::LinearAlgebra::Matrix3x3 &right ) { return ::LinearAlgebra::Matrix3x3( (left.m11 * right.m11) + (left.m12 * right.m21) + (left.m13 * right.m31), (left.m11 * right.m12) + (left.m12 * right.m22) + (left.m13 * right.m32), (left.m11 * right.m13) + (left.m12 * right.m23) + (left.m13 * right.m33), (left.m21 * right.m11) + (left.m22 * right.m21) + (left.m23 * right.m31), (left.m21 * right.m12) + (left.m22 * right.m22) + (left.m23 * right.m32), (left.m21 * right.m13) + (left.m22 * right.m23) + (left.m23 * right.m33), @@ -68,7 +68,7 @@ template } template -::LinearAlgebra::Vector3 operator * ( const ::LinearAlgebra::Matrix3x3 &matrix, const ::LinearAlgebra::Vector3 &vector ) +inline ::LinearAlgebra::Vector3 operator * ( const ::LinearAlgebra::Matrix3x3 &matrix, const ::LinearAlgebra::Vector3 &vector ) { return ::LinearAlgebra::Vector3( (matrix.m11 * vector.x) + (matrix.m12 * vector.y) + (matrix.m13 * vector.z), (matrix.m21 * vector.x) + (matrix.m22 * vector.y) + (matrix.m23 * vector.z), @@ -76,7 +76,7 @@ template } template -::LinearAlgebra::Vector3 operator * ( const ::LinearAlgebra::Vector3 &vector, const ::LinearAlgebra::Matrix3x3 &left ) +inline ::LinearAlgebra::Vector3 operator * ( const ::LinearAlgebra::Vector3 &vector, const ::LinearAlgebra::Matrix3x3 &left ) { return ::LinearAlgebra::Vector3( (vector.x * matrix.m11) + (vector.y * matrix.m21) + (vector.z * matrix.m31), (vector.x * matrix.m12) + (vector.y * matrix.m22) + (vector.z * matrix.m32), @@ -86,7 +86,7 @@ template // x4 template -::LinearAlgebra::Matrix4x4 operator * ( const ::LinearAlgebra::Matrix4x4 &left, const ::LinearAlgebra::Matrix4x4 &right ) +inline ::LinearAlgebra::Matrix4x4 operator * ( const ::LinearAlgebra::Matrix4x4 &left, const ::LinearAlgebra::Matrix4x4 &right ) { return ::LinearAlgebra::Matrix4x4( (left.m11 * right.m11) + (left.m12 * right.m21) + (left.m13 * right.m31) + (left.m14 * right.m41), (left.m11 * right.m12) + (left.m12 * right.m22) + (left.m13 * right.m32) + (left.m14 * right.m42), (left.m11 * right.m13) + (left.m12 * right.m23) + (left.m13 * right.m33) + (left.m14 * right.m43), (left.m11 * right.m14) + (left.m12 * right.m24) + (left.m13 * right.m34) + (left.m14 * right.m44), (left.m21 * right.m11) + (left.m22 * right.m21) + (left.m23 * right.m31) + (left.m24 * right.m41), (left.m21 * right.m12) + (left.m22 * right.m22) + (left.m23 * right.m32) + (left.m24 * right.m42), (left.m21 * right.m13) + (left.m22 * right.m23) + (left.m23 * right.m33) + (left.m24 * right.m43), (left.m21 * right.m14) + (left.m22 * right.m24) + (left.m23 * right.m34) + (left.m24 * right.m44), @@ -95,7 +95,7 @@ template } template -::LinearAlgebra::Vector4 operator * ( const ::LinearAlgebra::Matrix4x4 &matrix, const ::LinearAlgebra::Vector4 &vector ) +inline ::LinearAlgebra::Vector4 operator * ( const ::LinearAlgebra::Matrix4x4 &matrix, const ::LinearAlgebra::Vector4 &vector ) { return ::LinearAlgebra::Vector4( (matrix.m11 * vector.x) + (matrix.m12 * vector.y) + (matrix.m13 * vector.z) + (matrix.m14 * vector.w), (matrix.m21 * vector.x) + (matrix.m22 * vector.y) + (matrix.m23 * vector.z) + (matrix.m24 * vector.w), @@ -104,7 +104,7 @@ template } template -::LinearAlgebra::Vector4 operator * ( const ::LinearAlgebra::Vector4 &vector, const ::LinearAlgebra::Matrix4x4 &matrix ) +inline ::LinearAlgebra::Vector4 operator * ( const ::LinearAlgebra::Vector4 &vector, const ::LinearAlgebra::Matrix4x4 &matrix ) { return ::LinearAlgebra::Vector4( (vector.x * matrix.m11) + (vector.y * matrix.m21) + (vector.z * matrix.m31) + (vector.w * matrix.m41), (vector.x * matrix.m12) + (vector.y * matrix.m22) + (vector.z * matrix.m32) + (vector.w * matrix.m42), @@ -325,23 +325,24 @@ namespace LinearAlgebra2D namespace LinearAlgebra3D { - template - inline ::LinearAlgebra::Vector4 AngularAxis( const ::LinearAlgebra::Matrix3x3 &rotationMatrix ) - { - return ::std::asin( ::LinearAlgebra::Vector4(rotationMatrix.v[1].z, rotationMatrix.v[2].x, rotationMatrix.v[0].y, 1) ); - } + // All Matrix to AngularAxis conversions here is incorrect + //template + //inline ::LinearAlgebra::Vector4 AngularAxis( const ::LinearAlgebra::Matrix3x3 &rotationMatrix ) + //{ + // return ::std::asin( ::LinearAlgebra::Vector4(rotationMatrix.v[1].z, rotationMatrix.v[2].x, rotationMatrix.v[0].y, 1) ); + //} - template - inline ::LinearAlgebra::Vector4 AngularAxis( const ::LinearAlgebra::Matrix4x4 &rotationMatrix ) - { - return ::std::asin( ::LinearAlgebra::Vector4(rotationMatrix.v[1].z, rotationMatrix.v[2].x, rotationMatrix.v[0].y, 1) ); - } + //template + //inline ::LinearAlgebra::Vector4 AngularAxis( const ::LinearAlgebra::Matrix4x4 &rotationMatrix ) + //{ + // return ::std::asin( ::LinearAlgebra::Vector4(rotationMatrix.v[1].z, rotationMatrix.v[2].x, rotationMatrix.v[0].y, 1) ); + //} - template - inline ::LinearAlgebra::Vector4 ExtractAngularAxis( const ::LinearAlgebra::Matrix4x4 &orientationMatrix ) - { - return ::std::asin( ::LinearAlgebra::Vector4(orientationMatrix.v[1].z, orientationMatrix.v[2].x, orientationMatrix.v[0].y, 0) ); - } + //template + //inline ::LinearAlgebra::Vector4 ExtractAngularAxis( const ::LinearAlgebra::Matrix4x4 &orientationMatrix ) + //{ + // return ::std::asin( ::LinearAlgebra::Vector4(orientationMatrix.v[1].z, orientationMatrix.v[2].x, orientationMatrix.v[0].y, 0) ); + //} template inline ::LinearAlgebra::Matrix4x4 & TranslationMatrix( const ::LinearAlgebra::Vector3 &position, ::LinearAlgebra::Matrix4x4 &targetMem = ::LinearAlgebra::Matrix4x4() ) diff --git a/Code/OysterMath/Matrix.h b/Code/OysterMath/Matrix.h index c7b6b9e0..5d129431 100644 --- a/Code/OysterMath/Matrix.h +++ b/Code/OysterMath/Matrix.h @@ -163,12 +163,18 @@ namespace LinearAlgebra Vector4 GetRowVector( unsigned int rowID ) const; const Vector4 & GetColumnVector( unsigned int colID ) const; }; +} +template LinearAlgebra::Matrix2x2 operator * ( const ScalarType &left, const LinearAlgebra::Matrix2x2 &right ); +template LinearAlgebra::Matrix3x3 operator * ( const ScalarType &left, const LinearAlgebra::Matrix3x3 &right ); +template LinearAlgebra::Matrix4x4 operator * ( const ScalarType &left, const LinearAlgebra::Matrix4x4 &right ); /////////////////////////////////////////////////////////////////////////////////// // Body /////////////////////////////////////////////////////////////////////////////////// +namespace LinearAlgebra +{ // Matrix2x2 /////////////////////////////////////// template @@ -753,4 +759,22 @@ namespace LinearAlgebra { return this->v[colID]; } } +template +inline LinearAlgebra::Matrix2x2 operator * ( const ScalarType &left, const LinearAlgebra::Matrix2x2 &right ) +{ + return right * left; +} + +template +inline LinearAlgebra::Matrix3x3 operator * ( const ScalarType &left, const LinearAlgebra::Matrix3x3 &right ) +{ + return right * left; +} + +template +inline LinearAlgebra::Matrix4x4 operator * ( const ScalarType &left, const LinearAlgebra::Matrix4x4 &right ) +{ + return right * left; +} + #endif \ No newline at end of file diff --git a/Code/OysterMath/OysterMath.cpp b/Code/OysterMath/OysterMath.cpp index f44de9fd..bbaccf11 100644 --- a/Code/OysterMath/OysterMath.cpp +++ b/Code/OysterMath/OysterMath.cpp @@ -81,20 +81,20 @@ namespace Oyster { namespace Math2D namespace Oyster { namespace Math3D { - Float4 AngularAxis( const Float3x3 &rotationMatrix ) - { - return ::LinearAlgebra3D::AngularAxis( rotationMatrix ); - } + //Float4 AngularAxis( const Float3x3 &rotationMatrix ) + //{ + // return ::LinearAlgebra3D::AngularAxis( rotationMatrix ); + //} - Float4 AngularAxis( const Float4x4 &rotationMatrix ) - { - return ::LinearAlgebra3D::AngularAxis( rotationMatrix ); - } + //Float4 AngularAxis( const Float4x4 &rotationMatrix ) + //{ + // return ::LinearAlgebra3D::AngularAxis( rotationMatrix ); + //} - Float4 ExtractAngularAxis( const Float4x4 &orientationMatrix ) - { - return ::LinearAlgebra3D::ExtractAngularAxis( orientationMatrix ); - } + //Float4 ExtractAngularAxis( const Float4x4 &orientationMatrix ) + //{ + // return ::LinearAlgebra3D::ExtractAngularAxis( orientationMatrix ); + //} Float4x4 & TranslationMatrix( const Float3 &position, Float4x4 &targetMem ) { diff --git a/Code/OysterMath/OysterMath.h b/Code/OysterMath/OysterMath.h index 559ba0d3..5970face 100644 --- a/Code/OysterMath/OysterMath.h +++ b/Code/OysterMath/OysterMath.h @@ -66,55 +66,29 @@ namespace Oyster { namespace Math //! Oyster's native math library inline ::Oyster::Math::Float2 & operator *= ( ::Oyster::Math::Float2 &left, const ::Oyster::Math::Float2 &right ) { - left.x *= right.x; - left.y *= right.y; - return left; + return left.PiecewiseMultiplicationAdd( right ); } inline ::Oyster::Math::Float2 operator * ( const ::Oyster::Math::Float2 &left, const ::Oyster::Math::Float2 &right ) -{ return ::Oyster::Math::Float2(left) *= right; } - -inline ::Oyster::Math::Float2 operator * ( const ::Oyster::Math::Float &left, const ::Oyster::Math::Float2 &right ) -{ return ::Oyster::Math::Float2(right) *= left; } +{ + return left.PiecewiseMultiplication( right ); +} inline ::Oyster::Math::Float3 & operator *= ( ::Oyster::Math::Float3 &left, const ::Oyster::Math::Float3 &right ) { - left.x *= right.x; - left.y *= right.y; - left.z *= right.z; - return left; + return left.PiecewiseMultiplicationAdd( right ); } inline ::Oyster::Math::Float3 operator * ( const ::Oyster::Math::Float3 &left, const ::Oyster::Math::Float3 &right ) -{ return ::Oyster::Math::Float3(left) *= right; } - -inline ::Oyster::Math::Float3 operator * ( const ::Oyster::Math::Float &left, const ::Oyster::Math::Float3 &right ) -{ return ::Oyster::Math::Float3(right) *= left; } +{ + return left.PiecewiseMultiplication( right ); +} inline ::Oyster::Math::Float4 & operator *= ( ::Oyster::Math::Float4 &left, const ::Oyster::Math::Float4 &right ) { - left.x *= right.x; - left.y *= right.y; - left.z *= right.z; - left.w *= right.w; - return left; + return left.PiecewiseMultiplicationAdd( right ); } -inline ::Oyster::Math::Float4 operator * ( const ::Oyster::Math::Float4 &left, const ::Oyster::Math::Float4 &right ) -{ return ::Oyster::Math::Float4(left) *= right; } - -inline ::Oyster::Math::Float4 operator * ( const ::Oyster::Math::Float &left, const ::Oyster::Math::Float4 &right ) -{ return ::Oyster::Math::Float4(right) *= left; } - -inline ::Oyster::Math::Float2x2 operator * ( const ::Oyster::Math::Float &left, const ::Oyster::Math::Float2x2 &right ) -{ return ::Oyster::Math::Float2x2(right) *= left; } - -inline ::Oyster::Math::Float3x3 operator * ( const ::Oyster::Math::Float &left, const ::Oyster::Math::Float3x3 &right ) -{ return ::Oyster::Math::Float3x3(right) *= left; } - -inline ::Oyster::Math::Float4x4 operator * ( const ::Oyster::Math::Float &left, const ::Oyster::Math::Float4x4 &right ) -{ return ::Oyster::Math::Float4x4(right) *= left; } - namespace Oyster { namespace Math2D //! Oyster's native math library specialized for 2D { using namespace ::Oyster::Math; // deliberate inheritance from ::Oyster::Math namespace @@ -167,13 +141,13 @@ namespace Oyster { namespace Math3D //! Oyster's native math library specialized using namespace ::Oyster::Math; // deliberate inheritance from ::Oyster::Math namespace //! Extracts the angularAxis from rotationMatrix - Float4 AngularAxis( const Float3x3 &rotationMatrix ); + //Float4 AngularAxis( const Float3x3 &rotationMatrix ); - //! Extracts the angularAxis from rotationMatrix - Float4 AngularAxis( const Float4x4 &rotationMatrix ); + ////! Extracts the angularAxis from rotationMatrix + //Float4 AngularAxis( const Float4x4 &rotationMatrix ); - //! Extracts the angularAxis from orientationMatrix - Float4 ExtractAngularAxis( const Float4x4 &orientationMatrix ); + ////! Extracts the angularAxis from orientationMatrix + //Float4 ExtractAngularAxis( const Float4x4 &orientationMatrix ); //! Sets and returns targetMem to a translationMatrix with position as translation. Float4x4 & TranslationMatrix( const Float3 &position, Float4x4 &targetMem = Float4x4() ); diff --git a/Code/OysterMath/Vector.h b/Code/OysterMath/Vector.h index 901ea5e4..ea36cfc9 100644 --- a/Code/OysterMath/Vector.h +++ b/Code/OysterMath/Vector.h @@ -57,6 +57,12 @@ namespace LinearAlgebra ScalarType GetMagnitude( ) const; ScalarType Dot( const Vector2 &vector ) const; + //! @return (a.x * b.x, a.y * b.y) + Vector2 PiecewiseMultiplication( const Vector2 &vector ) const; + + //! @return a = (a.x * b.x, a.y * b.y) + Vector2 & PiecewiseMultiplicationAdd( const Vector2 &vector ); + Vector2 & Normalize( ); Vector2 GetNormalized( ) const; }; @@ -112,6 +118,12 @@ namespace LinearAlgebra ScalarType Dot( const Vector3 &vector ) const; Vector3 Cross( const Vector3 &vector ) const; + //! @return (a.x * b.x, a.y * b.y, a.z * b.z) + Vector3 PiecewiseMultiplication( const Vector3 &vector ) const; + + //! @return a = (a.x * b.x, a.y * b.y, a.z * b.z) + Vector3 & PiecewiseMultiplicationAdd( const Vector3 &vector ); + Vector3 & Normalize( ); Vector3 GetNormalized( ) const; }; @@ -169,14 +181,27 @@ namespace LinearAlgebra ScalarType GetMagnitude( ) const; ScalarType Dot( const Vector4 &vector ) const; + //! @return (a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w) + Vector4 PiecewiseMultiplication( const Vector4 &vector ) const; + + //! @return a = (a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w) + Vector4 & PiecewiseMultiplicationAdd( const Vector4 &vector ); + Vector4 & Normalize( ); Vector4 GetNormalized( ) const; }; +} + +template ::LinearAlgebra::Vector2 operator * ( const ScalarType &left, const ::LinearAlgebra::Vector2 &right ); +template ::LinearAlgebra::Vector3 operator * ( const ScalarType &left, const ::LinearAlgebra::Vector3 &right ); +template ::LinearAlgebra::Vector4 operator * ( const ScalarType &left, const ::LinearAlgebra::Vector4 &right ); /////////////////////////////////////////////////////////////////////////////////// // Body /////////////////////////////////////////////////////////////////////////////////// +namespace LinearAlgebra +{ // Vector2 /////////////////////////////////////// template const Vector2 Vector2::null = Vector2( 0, 0 ); @@ -184,22 +209,22 @@ namespace LinearAlgebra template const Vector2 Vector2::standard_unit_y = Vector2( 0, 1 ); template - Vector2::Vector2( ) : x(), y() {} + inline Vector2::Vector2( ) : x(), y() {} template - Vector2::Vector2( const Vector2 &vector ) + inline Vector2::Vector2( const Vector2 &vector ) { this->x = vector.x; this->y = vector.y; } template - Vector2::Vector2( const ScalarType &_element ) + inline Vector2::Vector2( const ScalarType &_element ) { this->x = this->y = _element; } template - Vector2::Vector2( const ScalarType _element[2] ) + inline Vector2::Vector2( const ScalarType _element[2] ) { this->x = _element[0]; this->y = _element[1]; } template - Vector2::Vector2( const ScalarType &_x, const ScalarType &_y ) + inline Vector2::Vector2( const ScalarType &_x, const ScalarType &_y ) { this->x = _x; this->y = _y; } template @@ -227,7 +252,7 @@ namespace LinearAlgebra { return this->element[i]; } template - Vector2 & Vector2::operator = ( const Vector2 &vector ) + inline Vector2 & Vector2::operator = ( const Vector2 &vector ) { this->element[0] = vector.element[0]; this->element[1] = vector.element[1]; @@ -235,7 +260,7 @@ namespace LinearAlgebra } template - Vector2 & Vector2::operator = ( const ScalarType _element[2] ) + inline Vector2 & Vector2::operator = ( const ScalarType _element[2] ) { this->element[0] = _element[0]; this->element[1] = _element[1]; @@ -243,7 +268,7 @@ namespace LinearAlgebra } template - Vector2 & Vector2::operator *= ( const ScalarType &scalar ) + inline Vector2 & Vector2::operator *= ( const ScalarType &scalar ) { this->element[0] *= scalar; this->element[1] *= scalar; @@ -251,7 +276,7 @@ namespace LinearAlgebra } template - Vector2 & Vector2::operator /= ( const ScalarType &scalar ) + inline Vector2 & Vector2::operator /= ( const ScalarType &scalar ) { this->element[0] /= scalar; this->element[1] /= scalar; @@ -259,7 +284,7 @@ namespace LinearAlgebra } template - Vector2 & Vector2::operator += ( const Vector2 &vector ) + inline Vector2 & Vector2::operator += ( const Vector2 &vector ) { this->element[0] += vector.element[0]; this->element[1] += vector.element[1]; @@ -267,7 +292,7 @@ namespace LinearAlgebra } template - Vector2 & Vector2::operator -= ( const Vector2 &vector ) + inline Vector2 & Vector2::operator -= ( const Vector2 &vector ) { this->element[0] -= vector.element[0]; this->element[1] -= vector.element[1]; @@ -295,7 +320,7 @@ namespace LinearAlgebra { return Vector2(-this->x, -this->y); } template - bool Vector2::operator == ( const Vector2 &vector ) const + inline bool Vector2::operator == ( const Vector2 &vector ) const { if( this->x != vector.x ) return false; if( this->y != vector.y ) return false; @@ -303,7 +328,7 @@ namespace LinearAlgebra } template - bool Vector2::operator != ( const Vector2 &vector ) const + inline bool Vector2::operator != ( const Vector2 &vector ) const { if( this->x != vector.x ) return true; if( this->y != vector.y ) return true; @@ -319,7 +344,7 @@ namespace LinearAlgebra { return (ScalarType) ::sqrt( this->Dot(*this) ); } template - ScalarType Vector2::Dot( const Vector2 &vector ) const + inline ScalarType Vector2::Dot( const Vector2 &vector ) const { ScalarType value = 0; value += this->element[0] * vector.element[0]; @@ -327,6 +352,20 @@ namespace LinearAlgebra return value; } + template + inline Vector2 Vector2::PiecewiseMultiplication( const Vector2 &vector ) const + { + return Vector2( this->x * vector.x, this->y * vector.y ); + } + + template + inline Vector2 & Vector2::PiecewiseMultiplicationAdd( const Vector2 &vector ) + { + this->x *= vector.x; + this->y *= vector.y; + return *this; + } + template inline Vector2 & Vector2::Normalize( ) { return (*this) /= this->GetLength(); } @@ -343,26 +382,26 @@ namespace LinearAlgebra template const Vector3 Vector3::standard_unit_z = Vector3( 0, 0, 1 ); template - Vector3::Vector3( ) : x(), y(), z() {} + inline Vector3::Vector3( ) : x(), y(), z() {} template - Vector3::Vector3( const Vector3 &vector ) + inline Vector3::Vector3( const Vector3 &vector ) { this->x = vector.x; this->y = vector.y; this->z = vector.z; } template - Vector3::Vector3( const Vector2 &vector, const ScalarType &_z ) + inline Vector3::Vector3( const Vector2 &vector, const ScalarType &_z ) { this->x = vector.x; this->y = vector.y; this->z = _z; } template - Vector3::Vector3( const ScalarType &_element ) + inline Vector3::Vector3( const ScalarType &_element ) { this->x = this->y = this->z = _element; } template - Vector3::Vector3( const ScalarType _element[3] ) + inline Vector3::Vector3( const ScalarType _element[3] ) { this->x = _element[0]; this->y = _element[1]; this->z = _element[2]; } template - Vector3::Vector3( const ScalarType &_x, const ScalarType &_y, const ScalarType &_z ) + inline Vector3::Vector3( const ScalarType &_x, const ScalarType &_y, const ScalarType &_z ) { this->x = _x; this->y = _y; this->z = _z; } template @@ -382,7 +421,7 @@ namespace LinearAlgebra { return this->element[i]; } template - Vector3 & Vector3::operator = ( const Vector3 &vector ) + inline Vector3 & Vector3::operator = ( const Vector3 &vector ) { this->element[0] = vector.element[0]; this->element[1] = vector.element[1]; @@ -391,7 +430,7 @@ namespace LinearAlgebra } template - Vector3 & Vector3::operator = ( const ScalarType element[3] ) + inline Vector3 & Vector3::operator = ( const ScalarType element[3] ) { this->element[0] = element[0]; this->element[1] = element[1]; @@ -400,7 +439,7 @@ namespace LinearAlgebra } template - Vector3 & Vector3::operator *= ( const ScalarType &scalar ) + inline Vector3 & Vector3::operator *= ( const ScalarType &scalar ) { this->element[0] *= scalar; this->element[1] *= scalar; @@ -409,7 +448,7 @@ namespace LinearAlgebra } template - Vector3 & Vector3::operator /= ( const ScalarType &scalar ) + inline Vector3 & Vector3::operator /= ( const ScalarType &scalar ) { this->element[0] /= scalar; this->element[1] /= scalar; @@ -418,7 +457,7 @@ namespace LinearAlgebra } template - Vector3 & Vector3::operator += ( const Vector3 &vector ) + inline Vector3 & Vector3::operator += ( const Vector3 &vector ) { this->element[0] += vector.element[0]; this->element[1] += vector.element[1]; @@ -427,7 +466,7 @@ namespace LinearAlgebra } template - Vector3 & Vector3::operator -= ( const Vector3 &vector ) + inline Vector3 & Vector3::operator -= ( const Vector3 &vector ) { this->element[0] -= vector.element[0]; this->element[1] -= vector.element[1]; @@ -456,7 +495,7 @@ namespace LinearAlgebra { return Vector3(-this->x, -this->y, -this->z); } template - bool Vector3::operator == ( const Vector3 &vector ) const + inline bool Vector3::operator == ( const Vector3 &vector ) const { if( this->x != vector.x ) return false; if( this->y != vector.y ) return false; @@ -465,7 +504,7 @@ namespace LinearAlgebra } template - bool Vector3::operator != ( const Vector3 &vector ) const + inline bool Vector3::operator != ( const Vector3 &vector ) const { if( this->x != vector.x ) return true; if( this->y != vector.y ) return true; @@ -482,7 +521,7 @@ namespace LinearAlgebra { return (ScalarType) ::sqrt( this->Dot(*this) ); } template - ScalarType Vector3::Dot( const Vector3 &vector ) const + inline ScalarType Vector3::Dot( const Vector3 &vector ) const { ScalarType value = 0; value += this->element[0] * vector.element[0]; @@ -492,13 +531,28 @@ namespace LinearAlgebra } template - Vector3 Vector3::Cross( const Vector3 &vector ) const + inline Vector3 Vector3::Cross( const Vector3 &vector ) const { return Vector3( (this->y*vector.z) - (this->z*vector.y), (this->z*vector.x) - (this->x*vector.z), (this->x*vector.y) - (this->y*vector.x) ); } + template + inline Vector3 Vector3::PiecewiseMultiplication( const Vector3 &vector ) const + { + return Vector3( this->x * vector.x, this->y * vector.y, this->z * vector.z ); + } + + template + inline Vector3 & Vector3::PiecewiseMultiplicationAdd( const Vector3 &vector ) + { + this->x *= vector.x; + this->y *= vector.y; + this->z *= vector.z; + return *this; + } + template inline Vector3 & Vector3::Normalize( ) { return (*this) /= this->GetLength(); } @@ -516,30 +570,30 @@ namespace LinearAlgebra template const Vector4 Vector4::standard_unit_w = Vector4( 0, 0, 0, 1 ); template - Vector4::Vector4( ) : x(), y(), z(), w() {} + inline Vector4::Vector4( ) : x(), y(), z(), w() {} template - Vector4::Vector4( const Vector4 &vector ) + inline Vector4::Vector4( const Vector4 &vector ) { this->x = vector.x; this->y = vector.y; this->z = vector.z; this->w = vector.w; } template - Vector4::Vector4( const Vector3 &vector, const ScalarType &_w ) + inline Vector4::Vector4( const Vector3 &vector, const ScalarType &_w ) { this->x = vector.x; this->y = vector.y; this->z = vector.z; this->w = _w; } template - Vector4::Vector4( const Vector2 &vector, const ScalarType &_z, const ScalarType &_w ) + inline Vector4::Vector4( const Vector2 &vector, const ScalarType &_z, const ScalarType &_w ) { this->x = vector.x; this->y = vector.y; this->z = _z; this->w = _w; } template - Vector4::Vector4( const ScalarType &_element ) + inline Vector4::Vector4( const ScalarType &_element ) { this->x = this->y = this->z = this->w = _element; } template - Vector4::Vector4( const ScalarType _element[4] ) + inline Vector4::Vector4( const ScalarType _element[4] ) { this->x = _element[0]; this->y = _element[1]; this->z = _element[2]; this->w = _element[3]; } template - Vector4::Vector4( const ScalarType &_x, const ScalarType &_y, const ScalarType &_z, const ScalarType &_w ) + inline Vector4::Vector4( const ScalarType &_x, const ScalarType &_y, const ScalarType &_z, const ScalarType &_w ) { this->x = _x; this->y = _y; this->z = _z; this->w = _w; } template @@ -559,7 +613,7 @@ namespace LinearAlgebra { return this->element[i]; } template - Vector4 & Vector4::operator = ( const Vector4 &vector ) + inline Vector4 & Vector4::operator = ( const Vector4 &vector ) { this->element[0] = vector.element[0]; this->element[1] = vector.element[1]; @@ -569,7 +623,7 @@ namespace LinearAlgebra } template - Vector4 & Vector4::operator = ( const ScalarType element[4] ) + inline Vector4 & Vector4::operator = ( const ScalarType element[4] ) { this->element[0] = element[0]; this->element[1] = element[1]; @@ -579,7 +633,7 @@ namespace LinearAlgebra } template - Vector4 & Vector4::operator *= ( const ScalarType &scalar ) + inline Vector4 & Vector4::operator *= ( const ScalarType &scalar ) { this->element[0] *= scalar; this->element[1] *= scalar; @@ -589,7 +643,7 @@ namespace LinearAlgebra } template - Vector4 & Vector4::operator /= ( const ScalarType &scalar ) + inline Vector4 & Vector4::operator /= ( const ScalarType &scalar ) { this->element[0] /= scalar; this->element[1] /= scalar; @@ -599,7 +653,7 @@ namespace LinearAlgebra } template - Vector4 & Vector4::operator += ( const Vector4 &vector ) + inline Vector4 & Vector4::operator += ( const Vector4 &vector ) { this->element[0] += vector.element[0]; this->element[1] += vector.element[1]; @@ -609,7 +663,7 @@ namespace LinearAlgebra } template - Vector4 & Vector4::operator -= ( const Vector4 &vector ) + inline Vector4 & Vector4::operator -= ( const Vector4 &vector ) { this->element[0] -= vector.element[0]; this->element[1] -= vector.element[1]; @@ -639,7 +693,7 @@ namespace LinearAlgebra { return Vector4(-this->x, -this->y, -this->z, -this->w); } template - bool Vector4::operator == ( const Vector4 &vector ) const + inline bool Vector4::operator == ( const Vector4 &vector ) const { if( this->x != vector.x ) return false; if( this->y != vector.y ) return false; @@ -649,7 +703,7 @@ namespace LinearAlgebra } template - bool Vector4::operator != ( const Vector4 &vector ) const + inline bool Vector4::operator != ( const Vector4 &vector ) const { if( this->x != vector.x ) return true; if( this->y != vector.y ) return true; @@ -667,7 +721,7 @@ namespace LinearAlgebra { return (ScalarType) ::sqrt( this->Dot(*this) ); } template - ScalarType Vector4::Dot( const Vector4 &vector ) const + inline ScalarType Vector4::Dot( const Vector4 &vector ) const { ScalarType value = 0; value += this->element[0] * vector.element[0]; @@ -677,6 +731,22 @@ namespace LinearAlgebra return value; } + template + inline Vector4 Vector4::PiecewiseMultiplication( const Vector4 &vector ) const + { + return Vector4( this->x * vector.x, this->y * vector.y, this->z * vector.z, this->w * vector.w ); + } + + template + inline Vector4 & Vector4::PiecewiseMultiplicationAdd( const Vector4 &vector ) + { + this->x *= vector.x; + this->y *= vector.y; + this->z *= vector.z; + this->w *= vector.w; + return *this; + } + template inline Vector4 & Vector4::Normalize( ) { return (*this) /= this->GetLength(); } @@ -686,4 +756,22 @@ namespace LinearAlgebra { return Vector4(*this).Normalize(); } } +template +inline ::LinearAlgebra::Vector2 operator * ( const ScalarType &left, const ::LinearAlgebra::Vector2 &right ) +{ + return right * left; +} + +template +inline ::LinearAlgebra::Vector3 operator * ( const ScalarType &left, const ::LinearAlgebra::Vector3 &right ) +{ + return right * left; +} + +template +inline ::LinearAlgebra::Vector4 operator * ( const ScalarType &left, const ::LinearAlgebra::Vector4 &right ) +{ + return right * left; +} + #endif \ No newline at end of file diff --git a/Code/OysterPhysics3D/Frustrum.cpp b/Code/OysterPhysics3D/Frustrum.cpp index 54e6a67f..ce2c5256 100644 --- a/Code/OysterPhysics3D/Frustrum.cpp +++ b/Code/OysterPhysics3D/Frustrum.cpp @@ -241,4 +241,9 @@ bool Frustrum::Contains( const ICollideable &target ) const //case Type_line: return false; // TODO: default: return false; } +} + +::Oyster::Math::Float3 Frustrum::ExtractForwad() +{ + return this->bottomPlane.normal.xyz; } \ No newline at end of file diff --git a/Code/OysterPhysics3D/Frustrum.h b/Code/OysterPhysics3D/Frustrum.h index ba5656c5..ae0f086c 100644 --- a/Code/OysterPhysics3D/Frustrum.h +++ b/Code/OysterPhysics3D/Frustrum.h @@ -41,6 +41,8 @@ namespace Oyster { namespace Collision3D bool Intersects( const ICollideable &target ) const; bool Intersects( const ICollideable &target, Oyster::Math::Float4 &worldPointOfContact ) const; bool Contains( const ICollideable &target ) const; + + ::Oyster::Math::Float3 ExtractForwad(); }; // INLINE IMPLEMENTATIONS /////////////////////////////////////// diff --git a/Code/OysterPhysics3D/Inertia.cpp b/Code/OysterPhysics3D/Inertia.cpp new file mode 100644 index 00000000..45551e2c --- /dev/null +++ b/Code/OysterPhysics3D/Inertia.cpp @@ -0,0 +1,65 @@ +/******************************************************************** + * Created by Dan Andersson 2014 + ********************************************************************/ + +#include "Inertia.h" + +using namespace ::Oyster::Math3D; +using namespace ::Oyster::Physics3D; + +MomentOfInertia::MomentOfInertia() +{ + this->rotation = Quaternion::identity; + this->magnitude = Float3( 1.0f ); +} + +MomentOfInertia::MomentOfInertia( const Quaternion &r, const Float3 &m ) +{ + this->rotation = r; + this->magnitude = m; +} + +MomentOfInertia & MomentOfInertia::operator = ( const MomentOfInertia &i ) +{ + this->rotation = i.rotation; + this->magnitude = i.magnitude; + return *this; +} + +Float3 MomentOfInertia::CalculateAngularVelocity( const Quaternion &externR, const Float3 &h ) const +{ + return this->CalculateAngularVelocity( externR, h, Float3() ); +} + +Float3 & MomentOfInertia::CalculateAngularVelocity( const Quaternion &externR, const Float3 &h, Float3 &targetMem ) const +{ // w = h * | (2/3) * I_M^-1 (R I_R)^-1 h | / |h| + Float hMagnitudeSquared = h.Dot( h ); + if( hMagnitudeSquared > 0.0f ) + { + Float4x4 rotationInverse = (RotationMatrix( externR ) * RotationMatrix( this->rotation )).Transpose(); + Float4 v = rotationInverse * Float4( h, 0.0f ); + v.PiecewiseMultiplicationAdd( Float4((2.0f/3.0f) / this->magnitude.x, (2.0f/3.0f) / this->magnitude.y, (2.0f/3.0f) / this->magnitude.z, 0.0f) ); + return targetMem = (Float4( h, 0.0f ) * ( v.GetMagnitude() / ( (Float)::std::sqrt(hMagnitudeSquared)) ) ).xyz; + } + else + return targetMem = Float3::null; +} + +Float3 MomentOfInertia::CalculateAngularMomentum( const Quaternion &externR, const Float3 &w ) const +{ + return this->CalculateAngularMomentum( externR, w, Float3() ); +} + +Float3 & MomentOfInertia::CalculateAngularMomentum( const Quaternion &externR, const Float3 &w, Float3 &targetMem ) const +{ // h = w * | (3/2) * I_M (R I_R)^-1 w | / |w| + Float wMagnitudeSquared = w.Dot( w ); + if( wMagnitudeSquared > 0.0f ) + { + Float4x4 rotationInverse = (RotationMatrix( externR ) * RotationMatrix( this->rotation )).Transpose(); + Float4 v = rotationInverse * Float4( w, 0.0f ); + v.PiecewiseMultiplicationAdd( Float4((3.0f/2.0f) * this->magnitude.x, (3.0f/2.0f) * this->magnitude.y, (3.0f/2.0f) * this->magnitude.z, 0.0f) ); + return targetMem = (Float4( w, 0.0f ) * ( v.GetMagnitude() / (Float)::std::sqrt(wMagnitudeSquared) ) ).xyz; + } + else + return targetMem = Float3::null; +} \ No newline at end of file diff --git a/Code/OysterPhysics3D/Inertia.h b/Code/OysterPhysics3D/Inertia.h new file mode 100644 index 00000000..502074a6 --- /dev/null +++ b/Code/OysterPhysics3D/Inertia.h @@ -0,0 +1,119 @@ +/******************************************************************** + * Created by Dan Andersson & Robin Engman 2014 + ********************************************************************/ + +#ifndef OYSTER_PHYSICS_3D_INERTIA_H +#define OYSTER_PHYSICS_3D_INERTIA_H + +#include "OysterMath.h" + +namespace Oyster { namespace Physics3D +{ + struct MomentOfInertia + { + ::Oyster::Math::Quaternion rotation; + ::Oyster::Math::Float3 magnitude; + + MomentOfInertia(); + MomentOfInertia( const ::Oyster::Math::Quaternion &r, const ::Oyster::Math::Float3 &m ); + + MomentOfInertia & operator = ( const MomentOfInertia &i ); + + ::Oyster::Math::Float3 CalculateAngularVelocity( const ::Oyster::Math::Quaternion &externR, const ::Oyster::Math::Float3 &angularMomentum ) const; + ::Oyster::Math::Float3 & CalculateAngularVelocity( const ::Oyster::Math::Quaternion &externR, const ::Oyster::Math::Float3 &angularMomentum, ::Oyster::Math::Float3 &targetMem ) const; + + ::Oyster::Math::Float3 CalculateAngularMomentum( const ::Oyster::Math::Quaternion &externR, const ::Oyster::Math::Float3 &angularVelocity ) const; + ::Oyster::Math::Float3 & CalculateAngularMomentum( const ::Oyster::Math::Quaternion &externR, const ::Oyster::Math::Float3 &angularVelocity, ::Oyster::Math::Float3 &targetMem ) const; + + static ::Oyster::Math::Float CalculateSphere( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ); + static ::Oyster::Math::Float CalculateHollowSphere( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ); + static ::Oyster::Math::Float CalculateCuboidX( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float height, const ::Oyster::Math::Float depth ); + static ::Oyster::Math::Float CalculateCuboidY( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float width, const ::Oyster::Math::Float depth ); + static ::Oyster::Math::Float CalculateCuboidZ( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float width, const ::Oyster::Math::Float height ); + static ::Oyster::Math::Float CalculateRodCenter( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float length ); + static ::Oyster::Math::Float CalculateCylinderXY( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float height, const ::Oyster::Math::Float radius ); + static ::Oyster::Math::Float CalculateCylinderZ( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ); + + static MomentOfInertia Sphere( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ); + static MomentOfInertia HollowSphere( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ); + static MomentOfInertia Cuboid( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float height, const ::Oyster::Math::Float width, const ::Oyster::Math::Float depth ); + static MomentOfInertia RodCenter( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float length ); + static MomentOfInertia Cylinder( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float height, const ::Oyster::Math::Float radius ); + }; + + inline ::Oyster::Math::Float MomentOfInertia::CalculateSphere( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ) + { + return (2.0f / 5.0f) * mass * radius * radius; + } + + inline ::Oyster::Math::Float MomentOfInertia::CalculateHollowSphere( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ) + { + return (2.0f / 3.0f) * mass * radius * radius; + } + + inline ::Oyster::Math::Float MomentOfInertia::CalculateCuboidX( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float height, const ::Oyster::Math::Float depth ) + { + return (1.0f / 12.0f) * mass * (height * height + depth * depth); + } + + inline ::Oyster::Math::Float MomentOfInertia::CalculateCuboidY( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float width, const ::Oyster::Math::Float depth ) + { + return (1.0f / 12.0f) * mass * (width * width + depth * depth); + } + + inline ::Oyster::Math::Float MomentOfInertia::CalculateCuboidZ( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float width, const ::Oyster::Math::Float height ) + { + return (1.0f / 12.0f) * mass * (height * height + width * width); + } + + inline ::Oyster::Math::Float MomentOfInertia::CalculateRodCenter( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float length ) + { + return (1.0f / 12.0f) * mass * length * length; + } + + inline ::Oyster::Math::Float MomentOfInertia::CalculateCylinderXY( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float height, const ::Oyster::Math::Float radius ) + { + return (1.0f / 12.0f) * mass * (3.0f * radius * radius + height * height); + } + + inline ::Oyster::Math::Float MomentOfInertia::CalculateCylinderZ( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ) + { + return 0.5f * mass * radius * radius; + } + + inline MomentOfInertia MomentOfInertia::Sphere( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ) + { + return MomentOfInertia( ::Oyster::Math::Quaternion::identity, + ::Oyster::Math::Float3(MomentOfInertia::CalculateSphere(mass, radius)) ); + } + + inline MomentOfInertia MomentOfInertia::HollowSphere( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float radius ) + { + return MomentOfInertia( ::Oyster::Math::Quaternion::identity, + ::Oyster::Math::Float3(MomentOfInertia::CalculateHollowSphere(mass, radius)) ); + } + + inline MomentOfInertia MomentOfInertia::Cuboid( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float height, const ::Oyster::Math::Float width, const ::Oyster::Math::Float depth ) + { + return MomentOfInertia( ::Oyster::Math::Quaternion::identity, + ::Oyster::Math::Float3(MomentOfInertia::CalculateCuboidX(mass, height, depth), + MomentOfInertia::CalculateCuboidY(mass, width, depth), + MomentOfInertia::CalculateCuboidZ(mass, height, width)) ); + } + + inline MomentOfInertia MomentOfInertia::RodCenter( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float length ) + { + return MomentOfInertia( ::Oyster::Math::Quaternion::identity, + ::Oyster::Math::Float3(MomentOfInertia::CalculateRodCenter(mass , length)) ); + } + + inline MomentOfInertia MomentOfInertia::Cylinder( const ::Oyster::Math::Float mass, const ::Oyster::Math::Float height, const ::Oyster::Math::Float radius ) + { + ::Oyster::Math::Float cylinderXY = MomentOfInertia::CalculateCylinderXY( mass , height, radius ); + return MomentOfInertia( ::Oyster::Math::Quaternion::identity, + ::Oyster::Math::Float3(cylinderXY, cylinderXY, + MomentOfInertia::CalculateCylinderZ(mass, radius)) ); + } +} } + +#endif \ No newline at end of file diff --git a/Code/OysterPhysics3D/OysterPhysics3D.h b/Code/OysterPhysics3D/OysterPhysics3D.h index f814ff46..e1eb94e3 100644 --- a/Code/OysterPhysics3D/OysterPhysics3D.h +++ b/Code/OysterPhysics3D/OysterPhysics3D.h @@ -113,6 +113,7 @@ namespace Oyster { namespace Physics3D /****************************************************************** * Returns the world angular momentum of a mass in rotation. + * H = r x G * @todo TODO: improve doc ******************************************************************/ inline ::Oyster::Math::Float3 AngularMomentum( const ::Oyster::Math::Float3 linearMomentum, const ::Oyster::Math::Float3 &worldOffset ) @@ -381,7 +382,6 @@ namespace Oyster { namespace Physics3D return inertia; } - } } } } diff --git a/Code/OysterPhysics3D/OysterPhysics3D.vcxproj b/Code/OysterPhysics3D/OysterPhysics3D.vcxproj index 186ea535..dffeca4f 100644 --- a/Code/OysterPhysics3D/OysterPhysics3D.vcxproj +++ b/Code/OysterPhysics3D/OysterPhysics3D.vcxproj @@ -155,6 +155,7 @@ + @@ -174,6 +175,7 @@ + diff --git a/Code/OysterPhysics3D/OysterPhysics3D.vcxproj.filters b/Code/OysterPhysics3D/OysterPhysics3D.vcxproj.filters index 02919d28..da336ce5 100644 --- a/Code/OysterPhysics3D/OysterPhysics3D.vcxproj.filters +++ b/Code/OysterPhysics3D/OysterPhysics3D.vcxproj.filters @@ -78,6 +78,9 @@ Header Files\Physics + + Header Files\Physics + @@ -125,5 +128,8 @@ Source Files\Physics + + Source Files\Physics + \ No newline at end of file diff --git a/Code/OysterPhysics3D/RigidBody.cpp b/Code/OysterPhysics3D/RigidBody.cpp index 80c800a6..0c60c597 100644 --- a/Code/OysterPhysics3D/RigidBody.cpp +++ b/Code/OysterPhysics3D/RigidBody.cpp @@ -23,7 +23,7 @@ RigidBody::RigidBody( ) this->frictionCoeff_Static = 0.5f; this->frictionCoeff_Kinetic = 1.0f; this->mass = 10; - this->momentOfInertiaTensor = Float4x4::identity; + this->momentOfInertiaTensor = MomentOfInertia(); this->rotation = Quaternion::identity; } @@ -51,51 +51,46 @@ void RigidBody::Update_LeapFrog( Float updateFrameLength ) // updating the linear // ds = dt * Formula::LinearVelocity( m, avg_G ) = dt * avg_G / m = (dt / m) * avg_G this->centerPos += ( updateFrameLength / this->mass ) * AverageWithDelta( this->momentum_Linear, this->impulse_Linear ); - - // updating the angular - Float4x4 rotationMatrix; ::Oyster::Math3D::RotationMatrix( this->rotation, rotationMatrix ); - // Important! The member data is all world data except the Inertia tensor. Thus a new InertiaTensor needs to be created to be compatible with the rest of the world data. - Float4x4 wMomentOfInertiaTensor = TransformMatrix( rotationMatrix, this->momentOfInertiaTensor ); // RI - - // dO = dt * Formula::AngularVelocity( (RI)^-1, avg_H ) = dt * (RI)^-1 * avg_H - //! HACK: @todo Rotation temporary disabled - //this->axis += Radian( Formula::AngularVelocity(wMomentOfInertiaTensor.GetInverse(), AverageWithDelta(this->momentum_Angular, this->impulse_Angular)) ); - //this->rotation = Rotation( this->axis ); + // updating the angular + // dO = dt * Formula::AngularVelocity( (RI)^-1, avg_H ) = dt * (RI)^-1 * avg_H + this->axis += updateFrameLength * this->momentOfInertiaTensor.CalculateAngularVelocity( this->rotation, AverageWithDelta(this->momentum_Angular, this->impulse_Angular) ); + this->rotation = Rotation( this->axis ); // update momentums and clear impulse_Linear and impulse_Angular this->momentum_Linear += this->impulse_Linear; this->impulse_Linear = Float4::null; - //this->momentum_Angular += this->impulse_Angular; //! HACK: @todo Rotation temporary disabled + this->momentum_Angular += this->impulse_Angular; //! HACK: @todo Rotation temporary disabled this->impulse_Angular = Float4::null; } -void RigidBody::Predict_LeapFrog( Float4 &outDeltaPos, Float4 &outDeltaAxis, const Float4 &actingLinearImpulse, const Float4 &actingAngularImpulse, Float deltaTime ) +void RigidBody::Predict_LeapFrog( Float3 &outDeltaPos, Float3 &outDeltaAxis, const Float3 &actingLinearImpulse, const Float3 &actingAngularImpulse, Float deltaTime ) { // updating the linear // ds = dt * Formula::LinearVelocity( m, avg_G ) = dt * avg_G / m = (dt / m) * avg_G outDeltaPos = ( deltaTime / this->mass ) * AverageWithDelta( this->momentum_Linear, actingLinearImpulse ); // updating the angular - Float4x4 rotationMatrix; ::Oyster::Math3D::RotationMatrix( this->rotation, rotationMatrix ); - Float4x4 wMomentOfInertiaTensor = TransformMatrix( rotationMatrix, this->momentOfInertiaTensor ); // RI + //Float4x4 rotationMatrix; ::Oyster::Math3D::RotationMatrix( this->rotation, rotationMatrix ); + //Float4x4 wMomentOfInertiaTensor = TransformMatrix( rotationMatrix, this->momentOfInertiaTensor ); // RI // dO = dt * Formula::AngularVelocity( (RI)^-1, avg_H ) = dt * (RI)^-1 * avg_H - outDeltaAxis = Formula::AngularVelocity( wMomentOfInertiaTensor.GetInverse(), AverageWithDelta(this->momentum_Angular, actingAngularImpulse) ); + //outDeltaAxis = Formula::AngularVelocity( wMomentOfInertiaTensor.GetInverse(), AverageWithDelta(this->momentum_Angular, actingAngularImpulse) ); + outDeltaAxis = this->momentOfInertiaTensor.CalculateAngularVelocity( this->rotation, AverageWithDelta(this->momentum_Angular, this->impulse_Angular) ); } -void RigidBody::Move( const Float4 &deltaPos, const Float4 &deltaAxis ) +void RigidBody::Move( const Float3 &deltaPos, const Float3 &deltaAxis ) { this->centerPos += deltaPos; this->axis += deltaAxis; this->rotation = Rotation( this->axis ); } -void RigidBody::ApplyImpulse( const Float4 &worldJ, const Float4 &atWorldPos ) +void RigidBody::ApplyImpulse( const Float3 &worldJ, const Float3 &atWorldPos ) { // by Dan Andersson - Float4 worldOffset = atWorldPos - this->centerPos; - if( worldOffset != Float4::null ) + Float3 worldOffset = atWorldPos - this->centerPos; + if( worldOffset != Float3::null ) { this->impulse_Linear += VectorProjection( worldJ, atWorldPos ); this->impulse_Angular += Formula::ImpulseTorque( worldJ, atWorldPos ); @@ -106,7 +101,7 @@ void RigidBody::ApplyImpulse( const Float4 &worldJ, const Float4 &atWorldPos ) } } -const Float4x4 & RigidBody::GetMomentOfInertia() const +const MomentOfInertia & RigidBody::GetMomentOfInertia() const { // by Dan Andersson return this->momentOfInertiaTensor; } @@ -116,7 +111,7 @@ Float RigidBody::GetMass() const return this->mass; } -const Quaternion & RigidBody::GetRotation() const +const Quaternion & RigidBody::GetRotationQuaternion() const { // by Dan Andersson return this->rotation; } @@ -136,46 +131,38 @@ Float4x4 RigidBody::GetView() const return ViewMatrix( this->rotation, this->centerPos ); } -Float4 RigidBody::GetVelocity_Linear() const +Float3 RigidBody::GetVelocity_Linear() const { // by Dan Andersson return Formula::LinearVelocity( this->mass, this->momentum_Linear ); } -Float4 RigidBody::GetVelocity_Angular() const +Float3 RigidBody::GetVelocity_Angular() const { // by Dan Andersson - return Formula::AngularVelocity( this->momentOfInertiaTensor.GetInverse(), this->momentum_Angular ); + return this->momentOfInertiaTensor.CalculateAngularVelocity( this->rotation, this->momentum_Angular ); } -Float4 RigidBody::GetLinearMomentum( const Float4 &atWorldPos ) const +Float3 RigidBody::GetLinearMomentum( const Float3 &atWorldPos ) const { // by Dan Andersson return this->momentum_Linear + Formula::TangentialLinearMomentum( this->momentum_Angular, atWorldPos - this->centerPos ); } -void RigidBody::SetMomentOfInertia_KeepVelocity( const Float4x4 &localTensorI ) +void RigidBody::SetMomentOfInertia_KeepVelocity( const MomentOfInertia &localTensorI ) { // by Dan Andersson - if( localTensorI.GetDeterminant() != 0.0f ) - { // insanity check! MomentOfInertiaTensor must be invertable - Float4x4 rotationMatrix; RotationMatrix( this->rotation, rotationMatrix ); - - Float4 w = Formula::AngularVelocity( (rotationMatrix * this->momentOfInertiaTensor).GetInverse(), this->momentum_Angular ); - this->momentOfInertiaTensor = localTensorI; - this->momentum_Angular = Formula::AngularMomentum( rotationMatrix * localTensorI, w ); - } + Float3 w = this->momentOfInertiaTensor.CalculateAngularVelocity( this->rotation, this->momentum_Angular ); + this->momentOfInertiaTensor = localTensorI; + this->momentum_Angular = this->momentOfInertiaTensor.CalculateAngularVelocity( this->rotation, w ); } -void RigidBody::SetMomentOfInertia_KeepMomentum( const Float4x4 &localTensorI ) +void RigidBody::SetMomentOfInertia_KeepMomentum( const MomentOfInertia &localTensorI ) { // by Dan Andersson - if( localTensorI.GetDeterminant() != 0.0f ) - { // insanity check! MomentOfInertiaTensor must be invertable - this->momentOfInertiaTensor = localTensorI; - } + this->momentOfInertiaTensor = localTensorI; } void RigidBody::SetMass_KeepVelocity( const Float &m ) { // by Dan Andersson if( m != 0.0f ) { // insanity check! Mass must be invertable - Float4 v = Formula::LinearVelocity( this->mass, this->momentum_Linear ); + Float3 v = Formula::LinearVelocity( this->mass, this->momentum_Linear ); this->mass = m; this->momentum_Linear = Formula::LinearMomentum( this->mass, v ); } @@ -189,46 +176,33 @@ void RigidBody::SetMass_KeepMomentum( const Float &m ) } } -void RigidBody::SetOrientation( const Float4x4 &o ) +void RigidBody::SetMomentum_Linear( const Float3 &worldG, const Float3 &atWorldPos ) { // by Dan Andersson - this->axis = ExtractAngularAxis( o ); - this->rotation = Rotation( this->axis ); - this->centerPos = o.v[3].xyz; -} - -void RigidBody::SetRotation( const Float4x4 &r ) -{ // by Dan Andersson - this->axis = ExtractAngularAxis( r ); - this->rotation = Rotation( this->axis ); -} - -void RigidBody::SetMomentum_Linear( const Float4 &worldG, const Float4 &atWorldPos ) -{ // by Dan Andersson - Float4 worldOffset = atWorldPos - this->centerPos; + Float3 worldOffset = atWorldPos - this->centerPos; this->momentum_Linear = VectorProjection( worldG, worldOffset ); this->momentum_Angular = Formula::AngularMomentum( worldG, worldOffset ); } -void RigidBody::SetVelocity_Linear( const Float4 &worldV ) +void RigidBody::SetVelocity_Linear( const Float3 &worldV ) { // by Dan Andersson this->momentum_Linear = Formula::LinearMomentum( this->mass, worldV ); } -void RigidBody::SetVelocity_Linear( const Float4 &worldV, const Float4 &atWorldPos ) +void RigidBody::SetVelocity_Linear( const Float3 &worldV, const Float3 &atWorldPos ) { // by Dan Andersson - Float4 worldOffset = atWorldPos - this->centerPos; - this->momentum_Linear = Formula::LinearMomentum( this->mass, VectorProjection(worldV, worldOffset) ); - this->momentum_Angular = Formula::AngularMomentum( RotationMatrix(this->rotation) * this->momentOfInertiaTensor, Formula::AngularVelocity(worldV, worldOffset) ); + Float3 worldOffset = atWorldPos - this->centerPos; + this->momentum_Linear = Formula::LinearMomentum( this->mass, VectorProjection(worldV, worldOffset) ); + this->momentum_Angular = this->momentOfInertiaTensor.CalculateAngularMomentum( this->rotation, Formula::AngularVelocity(worldV, worldOffset) ); } -void RigidBody::SetVelocity_Angular( const Float4 &worldW ) +void RigidBody::SetVelocity_Angular( const Float3 &worldW ) { // by Dan Andersson - this->momentum_Angular = Formula::AngularMomentum( this->momentOfInertiaTensor, worldW ); + this->momentum_Angular = this->momentOfInertiaTensor.CalculateAngularMomentum( this->rotation, worldW ); } -void RigidBody::SetImpulse_Linear( const Float4 &worldJ, const Float4 &atWorldPos ) +void RigidBody::SetImpulse_Linear( const Float3 &worldJ, const Float3 &atWorldPos ) { // by Dan Andersson - Float4 worldOffset = atWorldPos - this->centerPos; + Float3 worldOffset = atWorldPos - this->centerPos; this->impulse_Linear = VectorProjection( worldJ, worldOffset ); this->impulse_Angular = Formula::ImpulseTorque( worldJ, worldOffset ); } \ No newline at end of file diff --git a/Code/OysterPhysics3D/RigidBody.h b/Code/OysterPhysics3D/RigidBody.h index 51c5d2d8..c666662a 100644 --- a/Code/OysterPhysics3D/RigidBody.h +++ b/Code/OysterPhysics3D/RigidBody.h @@ -8,13 +8,14 @@ #include "OysterMath.h" #include "OysterCollision3D.h" #include "OysterPhysics3D.h" +#include "Inertia.h" namespace Oyster { namespace Physics3D { struct RigidBody { //! A struct of a simple rigid body. public: - ::Oyster::Math::Float4 centerPos, //!< Location of the body's center in the world. + ::Oyster::Math::Float3 centerPos, //!< Location of the body's center in the world. axis, //!< Euler rotationAxis of the body. boundingReach, //!< momentum_Linear, //!< The linear momentum G (kg*m/s). @@ -31,54 +32,55 @@ namespace Oyster { namespace Physics3D RigidBody & operator = ( const RigidBody &body ); void Update_LeapFrog( ::Oyster::Math::Float updateFrameLength ); - void Predict_LeapFrog( ::Oyster::Math::Float4 &outDeltaPos, ::Oyster::Math::Float4 &outDeltaAxis, const ::Oyster::Math::Float4 &actingLinearImpulse, const ::Oyster::Math::Float4 &actingAngularImpulse, ::Oyster::Math::Float deltaTime ); + void Predict_LeapFrog( ::Oyster::Math::Float3 &outDeltaPos, ::Oyster::Math::Float3 &outDeltaAxis, const ::Oyster::Math::Float3 &actingLinearImpulse, const ::Oyster::Math::Float3 &actingAngularImpulse, ::Oyster::Math::Float deltaTime ); - void Move( const ::Oyster::Math::Float4 &deltaPos, const ::Oyster::Math::Float4 &deltaAxis ); - void ApplyImpulse( const ::Oyster::Math::Float4 &worldJ, const ::Oyster::Math::Float4 &atWorldPos ); - void ApplyImpulse_Linear( const ::Oyster::Math::Float4 &worldJ ); - void ApplyImpulse_Angular( const ::Oyster::Math::Float4 &worldJ ); - void ApplyForce( const ::Oyster::Math::Float4 &worldF, ::Oyster::Math::Float updateFrameLength ); - void ApplyForce( const ::Oyster::Math::Float4 &worldF, ::Oyster::Math::Float updateFrameLength, const ::Oyster::Math::Float4 &atWorldPos ); + void Move( const ::Oyster::Math::Float3 &deltaPos, const ::Oyster::Math::Float3 &deltaAxis ); + void ApplyImpulse( const ::Oyster::Math::Float3 &worldJ, const ::Oyster::Math::Float3 &atWorldPos ); + void ApplyImpulse_Linear( const ::Oyster::Math::Float3 &worldJ ); + void ApplyImpulse_Angular( const ::Oyster::Math::Float3 &worldJ ); + void ApplyForce( const ::Oyster::Math::Float3 &worldF, ::Oyster::Math::Float updateFrameLength ); + void ApplyForce( const ::Oyster::Math::Float3 &worldF, ::Oyster::Math::Float updateFrameLength, const ::Oyster::Math::Float3 &atWorldPos ); // GET METHODS //////////////////////////////// - const ::Oyster::Math::Float4x4 & GetMomentOfInertia() const; - ::Oyster::Math::Float GetMass() const; - const ::Oyster::Math::Quaternion & GetRotation() const; - ::Oyster::Math::Float4x4 GetRotationMatrix() const; - ::Oyster::Math::Float4x4 GetOrientation() const; - ::Oyster::Math::Float4x4 GetView() const; - ::Oyster::Math::Float4x4 GetToWorldMatrix() const; - ::Oyster::Math::Float4x4 GetToLocalMatrix() const; - ::Oyster::Math::Float4 GetSize() const; - ::Oyster::Math::Float4 GetVelocity_Linear() const; - ::Oyster::Math::Float4 GetVelocity_Angular() const; - ::Oyster::Math::Float4 GetLinearMomentum( const ::Oyster::Math::Float4 &atWorldPos ) const; + const ::Oyster::Physics3D::MomentOfInertia & GetMomentOfInertia() const; + ::Oyster::Math::Float GetMass() const; + const ::Oyster::Math::Quaternion & GetRotationQuaternion() const; + ::Oyster::Math::Float4x4 GetRotationMatrix() const; + ::Oyster::Math::Float4x4 GetOrientation() const; + ::Oyster::Math::Float4x4 GetView() const; + ::Oyster::Math::Float4x4 GetToWorldMatrix() const; + ::Oyster::Math::Float4x4 GetToLocalMatrix() const; + ::Oyster::Math::Float3 GetSize() const; + ::Oyster::Math::Float3 GetVelocity_Linear() const; + ::Oyster::Math::Float3 GetVelocity_Angular() const; + ::Oyster::Math::Float3 GetLinearMomentum( const ::Oyster::Math::Float3 &atWorldPos ) const; // SET METHODS //////////////////////////////// - void SetMomentOfInertia_KeepVelocity( const ::Oyster::Math::Float4x4 &localTensorI ); - void SetMomentOfInertia_KeepMomentum( const ::Oyster::Math::Float4x4 &localTensorI ); + void SetMomentOfInertia_KeepVelocity( const ::Oyster::Physics3D::MomentOfInertia &localTensorI ); + void SetMomentOfInertia_KeepMomentum( const ::Oyster::Physics3D::MomentOfInertia &localTensorI ); void SetMass_KeepVelocity( const ::Oyster::Math::Float &m ); void SetMass_KeepMomentum( const ::Oyster::Math::Float &m ); - void SetOrientation( const ::Oyster::Math::Float4x4 &o ); - void SetRotation( const ::Oyster::Math::Float4x4 &r ); - void SetSize( const ::Oyster::Math::Float4 &widthHeight ); + //void SetOrientation( const ::Oyster::Math::Float4x4 &o ); + //void SetRotation( const ::Oyster::Math::Float4x4 &r ); + void SetSize( const ::Oyster::Math::Float3 &widthHeight ); - void SetMomentum_Linear( const ::Oyster::Math::Float4 &worldG, const ::Oyster::Math::Float4 &atWorldPos ); + void SetMomentum_Linear( const ::Oyster::Math::Float3 &worldG, const ::Oyster::Math::Float3 &atWorldPos ); - void SetVelocity_Linear( const ::Oyster::Math::Float4 &worldV ); - void SetVelocity_Linear( const ::Oyster::Math::Float4 &worldV, const ::Oyster::Math::Float4 &atWorldPos ); - void SetVelocity_Angular( const ::Oyster::Math::Float4 &worldW ); + void SetVelocity_Linear( const ::Oyster::Math::Float3 &worldV ); + void SetVelocity_Linear( const ::Oyster::Math::Float3 &worldV, const ::Oyster::Math::Float3 &atWorldPos ); + void SetVelocity_Angular( const ::Oyster::Math::Float3 &worldW ); - void SetImpulse_Linear( const ::Oyster::Math::Float4 &worldJ, const ::Oyster::Math::Float4 &atWorldPos ); - void SetForce( const ::Oyster::Math::Float4 &worldF, ::Oyster::Math::Float updateFrameLength ); - void SetForce( const ::Oyster::Math::Float4 &worldF, ::Oyster::Math::Float updateFrameLength, const ::Oyster::Math::Float4 &atWorldPos ); + void SetImpulse_Linear( const ::Oyster::Math::Float3 &worldJ, const ::Oyster::Math::Float3 &atWorldPos ); + //void SetForce( const ::Oyster::Math::Float3 &worldF, ::Oyster::Math::Float updateFrameLength ); + //void SetForce( const ::Oyster::Math::Float3 &worldF, ::Oyster::Math::Float updateFrameLength, const ::Oyster::Math::Float3 &atWorldPos ); private: ::Oyster::Math::Float mass; //!< m (kg) - ::Oyster::Math::Float4x4 momentOfInertiaTensor; //!< I (Nm*s) Tensor matrix ( only need to be 3x3 matrix, but is 4x4 for future hardware acceleration ) (localValue) + //::Oyster::Math::Float4x4 momentOfInertiaTensor; //!< I (Nm*s) Tensor matrix ( only need to be 3x3 matrix, but is 4x4 for future hardware acceleration ) (localValue) + ::Oyster::Physics3D::MomentOfInertia momentOfInertiaTensor; ::Oyster::Math::Quaternion rotation; //!< RotationAxis of the body. }; } } diff --git a/Code/OysterPhysics3D/RigidBody_Inline.h b/Code/OysterPhysics3D/RigidBody_Inline.h index 980442dd..795ec5e4 100644 --- a/Code/OysterPhysics3D/RigidBody_Inline.h +++ b/Code/OysterPhysics3D/RigidBody_Inline.h @@ -10,22 +10,22 @@ namespace Oyster { namespace Physics3D { - inline void RigidBody::ApplyImpulse_Linear( const ::Oyster::Math::Float4 &worldJ ) + inline void RigidBody::ApplyImpulse_Linear( const ::Oyster::Math::Float3 &worldJ ) { this->impulse_Linear += worldJ; } - inline void RigidBody::ApplyImpulse_Angular( const ::Oyster::Math::Float4 &worldJ ) + inline void RigidBody::ApplyImpulse_Angular( const ::Oyster::Math::Float3 &worldJ ) { this->impulse_Angular += worldJ; } - inline void RigidBody::ApplyForce( const ::Oyster::Math::Float4 &worldF, ::Oyster::Math::Float updateFrameLength ) + inline void RigidBody::ApplyForce( const ::Oyster::Math::Float3 &worldF, ::Oyster::Math::Float updateFrameLength ) { this->impulse_Linear += worldF * updateFrameLength; } - inline void RigidBody::ApplyForce( const ::Oyster::Math::Float4 &worldF, ::Oyster::Math::Float updateFrameLength, const ::Oyster::Math::Float4 &atWorldPos ) + inline void RigidBody::ApplyForce( const ::Oyster::Math::Float3 &worldF, ::Oyster::Math::Float updateFrameLength, const ::Oyster::Math::Float3 &atWorldPos ) { this->ApplyImpulse( worldF * updateFrameLength, atWorldPos ); } @@ -40,26 +40,25 @@ namespace Oyster { namespace Physics3D return this->GetView(); } - inline ::Oyster::Math::Float4 RigidBody::GetSize() const + inline ::Oyster::Math::Float3 RigidBody::GetSize() const { return 2.0f * this->boundingReach; } - inline void RigidBody::SetSize( const ::Oyster::Math::Float4 &widthHeight ) + inline void RigidBody::SetSize( const ::Oyster::Math::Float3 &widthHeight ) { this->boundingReach = ::Utility::Value::Abs( 0.5f * widthHeight ); } - inline void RigidBody::SetForce( const ::Oyster::Math::Float4 &worldF, ::Oyster::Math::Float updateFrameLength ) - { - this->impulse_Linear = worldF * updateFrameLength; - } - - inline void RigidBody::SetForce( const ::Oyster::Math::Float4 &worldF, ::Oyster::Math::Float updateFrameLength, const ::Oyster::Math::Float4 &atWorldPos ) - { - this->SetImpulse_Linear( worldF * updateFrameLength, atWorldPos ); - } + //inline void RigidBody::SetForce( const ::Oyster::Math::Float3 &worldF, ::Oyster::Math::Float updateFrameLength ) + //{ + // this->impulse_Linear = worldF * updateFrameLength; + //} + //inline void RigidBody::SetForce( const ::Oyster::Math::Float3 &worldF, ::Oyster::Math::Float updateFrameLength, const ::Oyster::Math::Float3 &atWorldPos ) + //{ + // this->SetImpulse_Linear( worldF * updateFrameLength, atWorldPos ); + //} } } #endif \ No newline at end of file diff --git a/Code/Tester/MainTest.cpp b/Code/Tester/MainTest.cpp index 3b4d94fe..dcafe91f 100644 --- a/Code/Tester/MainTest.cpp +++ b/Code/Tester/MainTest.cpp @@ -160,7 +160,7 @@ HRESULT InitDirect3D() } m = Oyster::Graphics::API::CreateModel(L"untitled.dan"); - m2 = Oyster::Graphics::API::CreateModel(L"knee_noAnimation.dan"); + m2 = Oyster::Graphics::API::CreateModel(L"still.dan"); m2->WorldMatrix = Oyster::Math3D::OrientationMatrix(Oyster::Math::Float3::null,Oyster::Math::Float3(0,5,0),Oyster::Math::Float3::null); m2->AnimationPlaying = 0; m2->AnimationTime = 0.0f; @@ -192,7 +192,7 @@ HRESULT Update(float deltaTime) angle += Oyster::Math::pi/16 * deltaTime; //m->WorldMatrix = Oyster::Math3D::RotationMatrix_AxisY(angle) * Oyster::Math3D::RotationMatrix_AxisX(-Oyster::Math::pi/2); - m2->WorldMatrix = Oyster::Math3D::OrientationMatrix(Oyster::Math::Float3(0,1,0)*-Oyster::Math::pi/4,Oyster::Math::Float3(0,-4,0),Oyster::Math::Float3::null); + m2->WorldMatrix = Oyster::Math3D::OrientationMatrix(Oyster::Math::Float3(0,1,0)*-Oyster::Math::pi/2,Oyster::Math::Float3(0,-4,0),Oyster::Math::Float3::null); Oyster::Math::Matrix ma = Oyster::Math::Matrix::identity; ma *= 50; ma.m44 = 1; diff --git a/Code/Tester/Tester.vcxproj.filters b/Code/Tester/Tester.vcxproj.filters deleted file mode 100644 index 5657bd66..00000000 --- a/Code/Tester/Tester.vcxproj.filters +++ /dev/null @@ -1,22 +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 - - - \ No newline at end of file