Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 26.41 KB | None | 0 0
  1.  
  2. //=============================================================================
  3. // gameApp.cpp
  4. //
  5. //Author: Doron Nussbaum (C) 2011 All Rights Reserved.
  6. //-----------------------------------------------------
  7. //
  8. // Purpose:
  9. //--------------
  10. // a. demonstrates how to use directx input
  11. // b. demonstrates how to use directx fonts
  12. // c. demonstrates how to initialize direct3D
  13. // d. provide a framework for creating games
  14. // e. demonstrates how to create an egnine frame and provide a skeleton function of one.
  15. // f. demonstarte the usage of a camera
  16. // g. demonstrates the creation of a surface and of vertex and index buffers
  17. // h. demonstartes how to set the differnt matrices.
  18. //
  19. // Description:
  20. //--------------
  21. // A simple application that demonstrates how to use directx to surface and how to use the camea.
  22. // It uses a framework for a general purpose simple game engine
  23. //
  24. //
  25. // License
  26. //--------------
  27. //
  28. // Code can be used for instructional and educational purposes and for assignments in the gaming courses at
  29. // the School of Compuer Science at Carleton University.
  30. // Usage of code for other purposes is not allowed without a given permission by the author.
  31. //
  32. //
  33. // Disclaimer
  34. //--------------
  35. //
  36. // The code is provided as is without any warranty
  37.  
  38. //=============================================================================
  39.  
  40. #include <winsock2.h>
  41.  
  42. #include <stdlib.h>
  43.  
  44. #include "gameApp.h"
  45. #include "House.h"
  46. #include <vector>
  47. #include <string>
  48.  
  49. #include <iostream>
  50. #include <fstream>
  51. #include <agents.h>
  52. #include <thread>
  53.  
  54. /********************************************************************************/
  55.  
  56. // DEFINE
  57.  
  58. #define FRAMES_PER_SECOND 30
  59.  
  60. #define NORMAL_SPEED 0.5
  61. #define MAX_SPEED 2.0
  62.  
  63. // event types for processing game state
  64. #define GAME_UPDATE_FRAME_STATE_EVENT 1
  65. #define GAME_COLLISION_EVENT 2
  66. #define GAME_NETWORK_UPDATE_EVENT 3
  67.  
  68. // DEFINE
  69. #define MSG_LENGTH 256
  70. #define NUM_CONNECTION_ATTEMPTS 10
  71. #define CONNECTION_CLOSED -10
  72. #define SLEEP_TIME 300
  73.  
  74. /*******************************************************************************/
  75. // class static variables
  76. Camera *gameApp::cam = NULL;
  77. meshSurface *gameApp::drawSurface = NULL;
  78. Chaser *gameApp::chaserYellowKia = NULL;
  79. Prey *gameApp::preyRedKia = NULL;
  80. gameApp * gameApp::myApp;
  81. std::vector<gameObject *> gameApp::gameStaticEntities; // these entities do not change with time
  82. std::vector<gameObject *> gameApp::gameDynamicEntities; // these entities' attributes change with time
  83. bool fps;
  84.  
  85. int clientRole = 1; // lets have a default of one to the player role
  86. int playerIndex;
  87. int chaserIndex;
  88.  
  89. // networking
  90. int clientAddLen = 0;
  91. fd_set master_fds;
  92. u_long iMode = 0;
  93. static int count = 0;
  94. struct sockaddr_in clientAdd;
  95. SOCKET sockfd = INVALID_SOCKET;
  96. SOCKET clientSock = INVALID_SOCKET;
  97. int rc = 0;
  98.  
  99. int handle = 0;
  100.  
  101. char ipAddressString[1024];
  102. char portString[1024];
  103.  
  104. // ip address chunks
  105. unsigned int a;
  106. unsigned int b;
  107. unsigned int c;
  108. unsigned int d;
  109.  
  110. unsigned short port;
  111.  
  112. // struct for address
  113. unsigned int address;
  114.  
  115. /******************************************************************/
  116. /*
  117. Purpose: constructor of the game application
  118.  
  119. Descripton:
  120.  
  121. Return:
  122.  
  123. */
  124.  
  125. gameApp::gameApp(void)
  126. {
  127. myApp = this;
  128. }
  129.  
  130. /******************************************************************/
  131. /*
  132. Purpose: destructor of the game application
  133.  
  134. Descripton:
  135.  
  136. Return:
  137. 1 - if failed
  138. 0 - if successful
  139.  
  140. */
  141.  
  142. gameApp::~gameApp(void)
  143. {
  144. }
  145.  
  146. // INITIALIZATION
  147.  
  148. /******************************************************************/
  149. /*
  150. Purpose: initializes the graphics device
  151.  
  152. Descripton:
  153.  
  154. Return:
  155. 1 - if failed
  156. 0 - if successful
  157.  
  158. */
  159.  
  160. int gameApp::initGraphics(int argc, char** argv, int winWidth, int winHeight, int winPosx, int winPosy) {
  161. int rc = 0;
  162.  
  163. GLenum err;
  164.  
  165. // initialize GLUT and pass it the command variables
  166. glutInit(&argc, argv);
  167.  
  168. //glutInitDisplayMode(GLUT_DOUBLE);
  169. glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
  170.  
  171. // Set the window
  172. // instruct openGL where to put the window on the screen
  173. glutInitWindowPosition(winPosx, winPosy);
  174.  
  175. // instuct openGL what window size ot use
  176. glutInitWindowSize(winWidth, winHeight); // no magic numbers
  177.  
  178. // careate the fist window and obtain a handle to it
  179. wId = glutCreateWindow("My First Window");
  180.  
  181. glEnable(GL_CULL_FACE);
  182. glCullFace(GL_BACK);
  183. //glDisable(GL_CULL_FACE);
  184.  
  185. glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // set the colour buffer to black
  186. glEnable(GL_DEPTH_TEST); // Enable depth ubffer testing
  187. glClearDepth(1.0f); // Set depth buffer
  188. glDepthFunc(GL_LEQUAL); // depth test operation (this is the default)
  189. glShadeModel(GL_SMOOTH); // smooth shading
  190. glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // highest quality perspective corrections
  191.  
  192. // set the call back functions
  193. glutDisplayFunc(renderFrame);
  194. glutReshapeFunc(reshapeFun);
  195. glutKeyboardFunc(keyboardFun);
  196. glutSpecialFunc(specialKeyboardFun);
  197. glutTimerFunc(10, timerFun, 1);
  198.  
  199. // initialize GLEW
  200. err = glewInit();
  201. //GLenum err = glewInit();
  202. if (err != GLEW_OK) fprintf(stderr, " Error initializing GLEW! \n");
  203. else fprintf(stderr, "Initializing GLEW succeeded!\n");
  204.  
  205. return(0);
  206. }
  207.  
  208. int initCommunication(char *serverIP, char *port) {
  209.  
  210. unsigned short serverPort = 0;
  211. SOCKET clientSock = INVALID_SOCKET;
  212. struct sockaddr_in serverAdd;
  213. int clientAddLen = 0;
  214. u_long iMode = 0;
  215.  
  216. // create socket
  217. handle = socket(AF_INET,
  218. SOCK_DGRAM,
  219. IPPROTO_UDP);
  220.  
  221. if (handle <= 0) {
  222. printf("failed to create socket\n");
  223. return false;
  224. }
  225.  
  226. serverAdd.sin_family = AF_INET;
  227. serverAdd.sin_addr.s_addr = INADDR_ANY; // listen to all addresses - it can be set to a specific address
  228. sscanf(port, "%hu", &serverPort);
  229. serverAdd.sin_port = htons(serverPort);
  230.  
  231. // associate the socket to the particular address and port
  232.  
  233. if (bind(handle, (struct sockaddr *) &serverAdd, sizeof(serverAdd))) {
  234. std::cout << std::endl << "Failed to bind socket! " << std::endl;
  235. return false;
  236. }
  237.  
  238. iMode = 1; // non blocking is enabled
  239. if (ioctlsocket(handle, FIONBIO, &iMode) != 0) {
  240. printf("failed to set non-blocking\n");
  241. return false;
  242. }
  243.  
  244. }
  245.  
  246. /******************************************************************/
  247. /*
  248. Purpose: initialize the game
  249.  
  250. Descripton:
  251.  
  252. Return:
  253. 1 - if failed
  254. 0 - if successful
  255.  
  256. */
  257.  
  258. int gameApp::initGame(void) {
  259. // load game settings
  260. std::ifstream gameSettings;
  261. gameSettings.open("playerSettings.txt");
  262. std::string gameSettingsArgs[6];
  263. int argsCounter = 0;
  264. if (gameSettings.is_open()) {
  265. std::cout << "Succesfully opened file!" << std::endl;
  266. std::string textLine;
  267. while (getline(gameSettings, textLine) && argsCounter < 6) {
  268. if (textLine.at(0) != ':') {
  269. gameSettingsArgs[argsCounter] = textLine;
  270. argsCounter++;
  271. }
  272. }
  273. std::cout << "IP address was read as:" << gameSettingsArgs[0] << std::endl;
  274. std::cout << "Port was read as:" << gameSettingsArgs[1] << std::endl;
  275. std::cout << "Message delay was read as:" << gameSettingsArgs[2] << std::endl;
  276. if (gameSettingsArgs[3] == "1") {
  277. std::cout << "Role was read as: 1, player." << std::endl;
  278. clientRole = 1;
  279. } else if (gameSettingsArgs[3] == "2") {
  280. std::cout << "Role was read as: 2, auto chaser." << std::endl;
  281. clientRole = 2;
  282. } else if (gameSettingsArgs[3] == "3") {
  283. std::cout << "Role was read as: 3, manual chaser." << std::endl;
  284. clientRole = 3;
  285. } else {
  286. std::cout << "Error! Given number: " << gameSettingsArgs[3] << " which is not a valid role! Using default of 1!" << std::endl;
  287. }
  288. std::cout << "Max player speed was read as:" << gameSettingsArgs[4] << std::endl;
  289. std::cout << "Max chaser speed was read as:" << gameSettingsArgs[5] << std::endl;
  290.  
  291. gameSettings.close();
  292. }
  293. else {
  294. std::cout << "File not open!" << std::endl;
  295. }
  296.  
  297. // set network values
  298. strcpy(ipAddressString, gameSettingsArgs[0].c_str());
  299. strcpy(portString, gameSettingsArgs[1].c_str());
  300. std::cout << std::endl << "input is: Server Address " << ipAddressString << " Server Port " << portString << std::endl;
  301.  
  302. rc = initCommunication(ipAddressString, portString);
  303.  
  304. std::cout << "Starting thread for networking!" << std::endl;
  305. std::thread *networkingThread = new std::thread(&networkingCode, handle);
  306.  
  307. // create game objects
  308. Car *truck = NULL;
  309. House *house1 = NULL, *house2 = NULL, *targetHouse = NULL; // are set as static for collision
  310. Shader *shader = NULL;
  311.  
  312. fps = false;
  313. house1 = new House();
  314. house2 = new House();
  315. targetHouse = new House();
  316. truck = new Car();
  317. preyRedKia = new Prey();
  318. chaserYellowKia = new Chaser();
  319.  
  320. // create the shader that will be shared by all objects
  321. shader = new Shader();
  322. shader->createShaderProgram("general.vert", "general.frag");
  323.  
  324. // set truck object
  325. truck->setShader(shader); // use the general shader
  326. // load the geometry
  327. truck->initGeom("truck\\", "L200_OBJ_DOS.obj", MODEL_OBJ_FILE);
  328. truck->loadTexture("truck\\truck_color_clean_256.jpg"); // get the texture
  329. // set the initial position attributes - align the object wth the z-axis if needed
  330. truck->setScale((float) 0.05, (float) 0.05, (float) 0.05);
  331. truck->setPositionOrientation(Vector3f(0, 0, 0), Vector3f(0, 0, 1), Vector3f(0, 1, 0));
  332.  
  333.  
  334. // set the prey object
  335. preyRedKia->setShader(shader); // use the general shader
  336. // load the geometry
  337. preyRedKia->initGeom("kia\\", "kia_rio.obj", MODEL_OBJ_FILE);
  338. // load the textures
  339. preyRedKia->loadTexture("kia\\rio_red.bmp");
  340. // set the initial position attributes - align the object wth the z-axis if needed
  341. preyRedKia->setScale((float) 0.2, (float) 0.2, (float) 0.2);
  342. preyRedKia->setPositionOrientation(Vector3f(8, 0, 7), Vector3f(1, 0, 1), Vector3f(0, 1, 0));
  343. preyRedKia->mYaw = 90; // orient it so that it faces that +zaxis
  344.  
  345. preyRedKia->maxSpeed = std::stoi(gameSettingsArgs[4]); // set player max speed from file
  346.  
  347. // set the chaser object
  348. chaserYellowKia->setShader(shader); // use the general shader
  349. // load the geometry model
  350. chaserYellowKia->initGeom("kia\\", "kia_rio.obj", MODEL_OBJ_FILE);
  351. // load the textures
  352. chaserYellowKia->loadTexture("kia\\rio_yellow.bmp");
  353. // set the initial position attributes - align the object wth the z-axis if needed
  354. chaserYellowKia->setScale((float) 0.2, (float) 0.2, (float) 0.2);
  355. chaserYellowKia->mYaw = 90; // orient it so that it faces that +zaxis
  356. chaserYellowKia->setPositionOrientation(Vector3f(-5, 0, 5), Vector3f(0, 0, 1), Vector3f(0, 1, 0));
  357.  
  358. chaserYellowKia->maxSpeed = std::stoi(gameSettingsArgs[5]); // set chaser max speed loaded from file
  359. if (clientRole == 3) {
  360. chaserYellowKia->isAnotherPlayer = true;
  361. }
  362.  
  363. // set the house object
  364. house1->setShader(shader); // use the general shader
  365. house1->initGeom("house_obj\\", "house_obj.obj", MODEL_OBJ_FILE);
  366. // load the textures
  367. house1->loadTexture("house_obj\\house_diffuse_256.tga");
  368. // set attributes (scale, position, and initial orientation towards the (0,0,1)
  369. house1->setScale(0.006f, 0.006f, 0.006f);
  370. house1->setPositionOrientation(Vector3f(5, 0, 1.2f), Vector3f(1, 0, 1), Vector3f(0, 1, 0));
  371.  
  372. house2->setShader(shader); // use the general shader
  373. house2->initGeom("house_obj\\", "house_obj.obj", MODEL_OBJ_FILE);
  374. // load the textures
  375. house2->loadTexture("house_obj\\house_diffuse_256.tga");
  376. // set the model transformation (scale, position, and initial orientation towards the (0,0,1)
  377. house2->setScale(0.006f, 0.006f, 0.006f);
  378. house2->setPositionOrientation(Vector3f(-15, 0, -12.2f), Vector3f(-1, 0, 1), Vector3f(0, 1, 0));
  379.  
  380. targetHouse->createShaderProg("red.vert", "red.frag"); // target uses a different shader
  381. targetHouse->initGeom("targetHouse\\", "targetHouse.obj", MODEL_OBJ_FILE);
  382. // load the textures
  383. targetHouse->loadTexture("house_obj\\house_diffuse_256.tga");
  384. // set the model transformation (scale, position, and initial orientation towards the (0,0,1)
  385. targetHouse->setScale(0.01f, 0.006f, 0.01f);
  386. targetHouse->setPositionOrientation(Vector3f(-3, 1.0, 8.2f), Vector3f(-1, 0, 1), Vector3f(0, 1, 0));
  387.  
  388. // set the surface
  389. drawSurface = new meshSurface();
  390. drawSurface->setParam(1, 1, 60, 60, 0, 15, 0, 15);
  391. //drawSurface->createShaderProg("general.vert", "general.frag");
  392. drawSurface->setShader(shader);
  393. drawSurface->initGeom();
  394. drawSurface->loadTexture("surface\\grass_texture_256.tga");
  395. //drawSurface->setPositionOrientation(Vector3f(0, 0, 0), Vector3f(1, 0, 0), Vector3f(0, 1, 0));
  396.  
  397. // add the objects to the list of game objects
  398. gameDynamicEntities.push_back(chaserYellowKia);
  399. playerIndex = 0;
  400. gameDynamicEntities.push_back(preyRedKia);
  401. chaserIndex = 1;
  402. gameDynamicEntities.push_back(truck);
  403.  
  404. // add the objects to the list of game objects
  405. gameStaticEntities.push_back(drawSurface);
  406. gameStaticEntities.push_back(house1);
  407. gameStaticEntities.push_back(house2);
  408. gameStaticEntities.push_back(targetHouse);
  409.  
  410. // set the global camera
  411. cam = new Camera();
  412. cam->setCamera(Vector3f(0, 20, 40), Vector3f(0, 0, 0), Vector3f(0, 1, 0));
  413. cam->setPerspectiveView(45, 1, 0.2f, 1000);
  414.  
  415. return 0;
  416. }
  417.  
  418. // LOOPS
  419.  
  420. /******************************************************************/
  421. /*
  422. Purpose: executes the message loop
  423.  
  424. Descripton:
  425. This function is a virtual function and can be replaced by a similar function in the derived class.
  426.  
  427. Return:
  428. 1 - if failed
  429. 0 - if successful
  430.  
  431. */
  432.  
  433.  
  434. int gameApp::gameLoop(void) {
  435. // enter glut main loop
  436. glutMainLoop();
  437.  
  438. return 0;
  439. }
  440.  
  441. // UPDATES
  442.  
  443. int networkAction(fd_set *master_fds) {
  444. int len;
  445. int rc = 0;
  446. unsigned int i, j;
  447. timeval timeout;
  448. SOCKET readSocket, writeSocket;
  449. fd_set read_fds, write_fds;
  450.  
  451. char buf[MSG_LENGTH];
  452.  
  453. timeout.tv_sec = 0;
  454. timeout.tv_usec = 500000; // wait for 0.5 seconds
  455.  
  456. memset(buf, 0, MSG_LENGTH);
  457.  
  458. // copy the master list
  459.  
  460. read_fds = *master_fds;
  461. // if (read_fds.fd_count <= 0) {
  462. // std::cout << "FD count is less or equal to 0, was: " << read_fds.fd_count << std::endl;
  463. // }
  464. if (read_fds.fd_count > 0) {
  465. rc = select(0, &read_fds, NULL, NULL, &timeout); // check the status of the sockets descriptors that the server is listening to
  466.  
  467. switch (rc) {
  468. case 0:
  469. // nothing ready for readv return
  470. goto err;
  471. break;
  472. case SOCKET_ERROR:
  473. // check what is the error
  474. rc = WSAGetLastError();
  475. goto err;
  476. break;
  477. default:
  478. // some sockets are ready for read
  479. break;
  480. }
  481. }
  482.  
  483. // for (i = 0; i < master_fds->fd_count; i++) {
  484. // readSocket = master_fds->fd_array[i];
  485.  
  486. for (i = 0; i < read_fds.fd_count; i++) {
  487. readSocket = read_fds.fd_array[i];
  488. rc = recv(readSocket, buf, MSG_LENGTH - 1, 0); // wait until something was sent
  489. switch (rc) {
  490. case 0:
  491. // connecion is closed
  492. // remove from the list
  493. FD_CLR(readSocket, master_fds);
  494. break;
  495. case SOCKET_ERROR:
  496. // error
  497. rc = WSAGetLastError();
  498. switch (rc) {
  499. case WSAECONNREFUSED:
  500. // server may not be up yet
  501. Sleep(1000);
  502. break;
  503. case WSAEWOULDBLOCK:
  504. // connection was not established yet.
  505. // do not call connect again on the same socket.
  506. break;
  507. case WSAECONNRESET:
  508. FD_CLR(readSocket, master_fds);
  509. break;
  510. default:
  511. rc = -1;
  512. goto err;
  513. break;
  514. }
  515. break;
  516. default:
  517. break;
  518. }
  519.  
  520. std::cout << "server received -> " << buf << std::endl;
  521. // something was read from the connectcion
  522. // send it back
  523. len = rc;
  524. // write_fds = *master_fds;
  525. write_fds = read_fds;
  526.  
  527. // can add some code to remove the sending socket !!!
  528. for (j = 0; j < write_fds.fd_count; j++) {
  529. // send to all the clients
  530. writeSocket = write_fds.fd_array[j];
  531. //build message to send, info delimited by ';'
  532. char *s;
  533. char buffer[64];
  534. // role
  535. strcat(s, ";");
  536. rc = send(writeSocket, buf, len, 0); // note the number of bytes that were sent can be smaller then
  537. if (rc == SOCKET_ERROR) {
  538. rc = WSAGetLastError();
  539. switch (rc) {
  540. case 0:
  541. // connecion is closed
  542. // remove from the list
  543. FD_CLR(writeSocket, master_fds);
  544. break;
  545. case WSAECONNRESET:
  546. // error
  547. FD_CLR(writeSocket, master_fds);
  548. rc = -1;
  549. break;
  550. default:
  551. closesocket(writeSocket);
  552. FD_CLR(writeSocket, master_fds);
  553. rc = -1;
  554. break;
  555. }
  556. }
  557. else {
  558. if (rc != len) {
  559. // not all bytes were sent
  560. // need loop
  561. rc = 5;
  562. }
  563. std::cout << "server sent: " << buf << std::endl;
  564. }
  565. }
  566. }
  567. rc = 0;
  568.  
  569. err:
  570. return(rc);
  571. }
  572.  
  573. /******************************************************************/
  574. /*
  575. Purpose: updates the game state
  576.  
  577. Descripton:
  578.  
  579. Return:
  580. 1 - if failed
  581. 0 - if successful
  582.  
  583. */
  584.  
  585. int gameApp::updateGameState(long event) {
  586. std::string debugString;
  587. bool xCollide;
  588. bool zCollide;
  589. static int frameCount = 0;
  590. static int dir = 1;
  591. static Vector3f lastPreyPos = preyRedKia->mPosition;
  592. static Vector3f lastChaserPos = preyRedKia->mPosition;
  593. unsigned int i;
  594. int rc;
  595.  
  596. switch (event) {
  597. case GAME_UPDATE_FRAME_STATE_EVENT:
  598.  
  599. frameCount++; // increment frame count
  600. bool xDetect;
  601. bool zDetect;
  602. // this section should have the game logic with respect to time.
  603. // Then it calls each object with updateStateFunction
  604. lastPreyPos = preyRedKia->mPosition;
  605. lastChaserPos = chaserYellowKia->mPosition;
  606.  
  607. for (i = 0; i < gameDynamicEntities.size(); i++) {
  608. rc = gameDynamicEntities.at(i)->updateState(frameCount);
  609. if (rc == GAME_OBJECT_DELETE_ENTITY) {
  610. // swap current object with the last one
  611. gameObject *temp = gameDynamicEntities.at(i);
  612. gameDynamicEntities.at(i) = gameDynamicEntities.back();
  613. delete temp;
  614. gameDynamicEntities.pop_back();
  615. }
  616. }
  617.  
  618. if (clientRole == 1) {
  619. // If in proximity of prey, chase
  620. xDetect = (((preyRedKia->mPosition.x) <= (chaserYellowKia->mPosition.x + 6))
  621. && ((preyRedKia->mPosition.x) >= (chaserYellowKia->mPosition.x - 6)));
  622.  
  623. zDetect = (((preyRedKia->mPosition.z) <= (chaserYellowKia->mPosition.z + 6))
  624. && ((preyRedKia->mPosition.z) >= (chaserYellowKia->mPosition.z - 6)));
  625. // prey is in proximity of the chaser?
  626. if (xDetect && zDetect) {
  627. Vector3f directionVec = (preyRedKia->mPosition - chaserYellowKia->mPosition);
  628. directionVec.normalize();
  629. chaserYellowKia->changeLookAtVector(directionVec.x, directionVec.y, directionVec.z);
  630. chaserYellowKia->moveForward(0.05);
  631. }
  632. } else if (clientRole == 3) {
  633. // let connecting client control the car
  634.  
  635. }
  636.  
  637. if (fps) {
  638. cam->setCamera(preyRedKia->mPosition, preyRedKia->lookAtVector, preyRedKia->upVector);
  639. }
  640. break;
  641. case GAME_COLLISION_EVENT:
  642. // player collides, exclude collission with the floor
  643. for (i = 1; i < gameStaticEntities.size(); i++) {
  644. xCollide = (((preyRedKia->mPosition.x) <= (gameStaticEntities.at(i)->mPosition.x + 3))
  645. && ((preyRedKia->mPosition.x) >= (gameStaticEntities.at(i)->mPosition.x - 3)));
  646.  
  647. zCollide = (((preyRedKia->mPosition.z) <= (gameStaticEntities.at(i)->mPosition.z + 3))
  648. && ((preyRedKia->mPosition.z) >= (gameStaticEntities.at(i)->mPosition.z - 3)));
  649.  
  650. debugString = std::string("Prey X: ") + std::to_string(preyRedKia->mPosition.x) + std::string("Prey Z: ") + std::to_string(preyRedKia->mPosition.z)
  651. + std::string(" House 1 X: ") + std::to_string(gameStaticEntities.at(3)->mPosition.x) + std::string(" House 1 Z: ") + std::to_string(gameStaticEntities.at(3)->mPosition.z)
  652. + std::string(" X Collide: ") + std::to_string(xCollide) + " Z Collide: " + std::to_string(zCollide) ;
  653. // std::cout << debugString << std::endl;
  654. if (xCollide && zCollide) {
  655. preyRedKia->mPosition = lastPreyPos;
  656. }
  657. }
  658. // chaser collides, exclude collission with the floor
  659. for (i = 1; i < gameStaticEntities.size(); i++) {
  660. xCollide = (((chaserYellowKia->mPosition.x) <= (gameStaticEntities.at(i)->mPosition.x + 3))
  661. && ((chaserYellowKia->mPosition.x) >= (gameStaticEntities.at(i)->mPosition.x - 3)));
  662.  
  663. zCollide = (((chaserYellowKia->mPosition.z) <= (gameStaticEntities.at(i)->mPosition.z + 3))
  664. && ((chaserYellowKia->mPosition.z) >= (gameStaticEntities.at(i)->mPosition.z - 3)));
  665.  
  666. debugString = std::string("Chaser X: ") + std::to_string(chaserYellowKia->mPosition.x) + std::string("Chaser Z: ") + std::to_string(chaserYellowKia->mPosition.z)
  667. + std::string(" House 1 X: ") + std::to_string(gameStaticEntities.at(3)->mPosition.x) + std::string(" House 1 Z: ") + std::to_string(gameStaticEntities.at(3)->mPosition.z)
  668. + std::string(" X Collide: ") + std::to_string(xCollide) + " Z Collide: " + std::to_string(zCollide);
  669. // std::cout << debugString << std::endl;
  670. if (xCollide && zCollide) {
  671. chaserYellowKia->mPosition = lastChaserPos;
  672. }
  673. }
  674. break;
  675. default:
  676. printf("another event occurred \n");
  677. break;
  678. }
  679.  
  680. return 0;
  681. }
  682.  
  683. /******************************************************************/
  684. /*
  685. Purpose: renders one frame
  686.  
  687. Description:
  688.  
  689. Return:
  690. 1 - if failed
  691. 0 - if successful
  692.  
  693. */
  694.  
  695. void gameApp::renderFrame(void) {
  696. static int count = 0;
  697. static int dir = 1;
  698. unsigned int i;
  699.  
  700. count++;
  701. glClearColor(0, 0, 0, 0.0);
  702. glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Clear the colour and depth buffers
  703.  
  704. for (i = 0; i < gameDynamicEntities.size(); i++) {
  705. gameObject *g = gameDynamicEntities.at(i);
  706. gameDynamicEntities.at(i)->render(NULL, gameApp::cam);
  707. }
  708. for (i = 0; i < gameStaticEntities.size(); i++) {
  709. gameStaticEntities.at(i)->render(NULL, gameApp::cam);
  710. }
  711.  
  712.  
  713. // swap the buffers
  714. glutSwapBuffers();
  715. }
  716.  
  717. /****************************************************************************/
  718.  
  719. void gameApp::keyboardFun(unsigned char key, int x, int y) {
  720. switch (key) {
  721. case 033:
  722. case 'Q':
  723. case 'q':
  724. exit(1);
  725. break;
  726. case 'w':
  727. cam->moveForward(NORMAL_SPEED);
  728. break;
  729. case 'W':
  730. cam->moveForward(MAX_SPEED);
  731. break;
  732. case 's':
  733. cam->moveForward(-NORMAL_SPEED);
  734. break;
  735. case 'S':
  736. cam->moveForward(-MAX_SPEED);
  737. break;
  738. case 'a':
  739. cam->yaw((float) .2);
  740. break;
  741. case 'A':
  742. cam->yaw(1);
  743. break;
  744. case 'D':
  745. cam->yaw(-1);
  746. break;
  747. case 'd':
  748. cam->yaw((float)-.2);
  749. break;
  750. case 'z':
  751. cam->zoomIn();
  752. break;
  753. case 'Z':
  754. cam->zoomOut();
  755. break;
  756. }
  757. // Cam movmeents
  758. if(key == 'c'){
  759. // change camera view point
  760. } else if (key == 'C') {
  761. // change camera view point default
  762. cam->setCamera(Vector3f(0, 20, 40), Vector3f(0, 0, 0), Vector3f(0, 1, 0));
  763. }
  764. // vehicle movements
  765. if (clientRole == 1) {
  766. std::cout << "Listening to controls for prey player" << std::endl;
  767. // standard vehicle control
  768. preyRedKia->processKeys(key);
  769. } else if (clientRole == 3) {
  770. std::cout << "Listening to controls for chaser player" << std::endl;
  771. // if set to the chaser, proccess keys for another chaser instead.
  772. chaserYellowKia->processKeys(key);
  773. }
  774. }
  775.  
  776. void gameApp::specialKeyboardFun(int key, int x, int y)
  777. {
  778. switch (key) {
  779. case 033:
  780. case 'Q':
  781. case 'q':
  782. exit(1);
  783. break;
  784. case GLUT_KEY_LEFT:
  785. cam->roll((float) .2);
  786. break;
  787. case GLUT_KEY_UP:
  788. cam->pitch((float) .2);
  789. break;
  790. case GLUT_KEY_RIGHT:
  791. cam->roll((float) -.2);
  792. break;
  793. case GLUT_KEY_DOWN:
  794. cam->pitch((float) -.2);
  795. break;
  796. }
  797. }
  798.  
  799. /************************************************************************************************/
  800. /*
  801. This functions in invoked when there is a change to the window by the user
  802. Here a new setting of the rendering paramters are set. In most cases it consists of two things:
  803. a. changeing the view port dimensions
  804. b. changing the aspect ratio
  805.  
  806. input
  807. w, h - the width and height of the new window in the pixel coordinates
  808.  
  809. */
  810.  
  811. void gameApp::reshapeFun(int w, int h)
  812. {
  813.  
  814. float fieldOfView, aspectRatio, nearPlane, farPlane;
  815.  
  816. // change the view port
  817. glViewport (0 , 0, (GLsizei) w, (GLsizei) h);
  818.  
  819.  
  820. // Set the state to accept projection information
  821. glMatrixMode(GL_PROJECTION); // To operate on the Projection matrix
  822. glLoadIdentity();
  823. // Enable perspective projection with fovy, aspect, zNear and zFar
  824. //gluPerspective(45.0f, aspect, 0.1f, 100.0f);
  825. cam->getPerspectiveView(&fieldOfView, &aspectRatio, &nearPlane, &farPlane);
  826. // Compute aspect ratio of the new window
  827.  
  828. aspectRatio = (float)w / (float)h;
  829.  
  830. cam->setPerspectiveView(fieldOfView, aspectRatio ,nearPlane, farPlane);
  831.  
  832. }
  833.  
  834. void gameApp::networkingCode (int handle) {
  835. // networking loop
  836. while (true) {
  837. // std::cout << "LOOPED IN NETWORKING THREAD!" << std::endl;
  838. unsigned char packet_data[MSG_LENGTH];
  839.  
  840. unsigned int max_packet_size = sizeof(packet_data);
  841. sockaddr_in from;
  842. typedef int socklen_t;
  843. socklen_t fromLength = sizeof(from);
  844.  
  845. int bytes = recvfrom(handle,
  846. (char*)packet_data,
  847. max_packet_size,
  848. 0,
  849. (sockaddr*)&from,
  850. &fromLength);
  851.  
  852. if (!bytes)
  853. break;
  854.  
  855. // where did the packet come from
  856. unsigned int from_address =
  857. ntohl(from.sin_addr.s_addr);
  858.  
  859. unsigned int from_port =
  860. ntohs(from.sin_port);
  861.  
  862. std::cout << "received this from : " << from_address << " port " << from_port << std::endl;
  863. }
  864. }
  865.  
  866. /***************************************************************************************************/
  867. /*
  868. This function is a timer function for the update state event and redrawing the scenes.
  869. Here the FrameNumber does not play a role yet because there is a single event that
  870. the function is handling. Namely, the timerEvent is a frameNumber.
  871.  
  872. Currently the updateGameState() is also keeping track of the frame number. This
  873. should be modified to either a global variable (not preferable), gameApp member variable,
  874. or passed in as a parameter to updateGameState() (most likely the best option).
  875.  
  876. */
  877. void gameApp::timerFun(int timerEvent)
  878. {
  879. static int frameNumber = 0;
  880. frameNumber++;
  881.  
  882. // renderSceneFun();
  883. glutPostRedisplay();
  884.  
  885. // get next event from Queue (future implementation)
  886. // the queue should have return an event and the event timer
  887. myApp->updateGameState((long)GAME_UPDATE_FRAME_STATE_EVENT);
  888. myApp->updateGameState((long)GAME_COLLISION_EVENT);
  889. glutTimerFunc(5, timerFun, frameNumber);
  890. }
  891.  
  892. boolean udpSendMssg(int handle, char* dataToSend, char* address, char* port) {
  893. unsigned short serverPort = 0;
  894. sscanf(port, "%hu", &serverPort);
  895.  
  896. sockaddr_in addr;
  897. addr.sin_family = AF_INET;
  898. addr.sin_addr.s_addr = inet_addr(address);
  899. addr.sin_port = htons(serverPort);
  900.  
  901. int sent_bytes = sendto(handle, dataToSend, MSG_LENGTH, 0, (sockaddr*)&addr, sizeof(sockaddr_in));
  902.  
  903. if (sent_bytes != MSG_LENGTH)
  904. {
  905. printf("failed to send packet\n");
  906. return false;
  907. }
  908. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement