Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //=============================================================================
- // gameApp.cpp
- //
- //Author: Doron Nussbaum (C) 2011 All Rights Reserved.
- //-----------------------------------------------------
- //
- // Purpose:
- //--------------
- // a. demonstrates how to use directx input
- // b. demonstrates how to use directx fonts
- // c. demonstrates how to initialize direct3D
- // d. provide a framework for creating games
- // e. demonstrates how to create an egnine frame and provide a skeleton function of one.
- // f. demonstarte the usage of a camera
- // g. demonstrates the creation of a surface and of vertex and index buffers
- // h. demonstartes how to set the differnt matrices.
- //
- // Description:
- //--------------
- // A simple application that demonstrates how to use directx to surface and how to use the camea.
- // It uses a framework for a general purpose simple game engine
- //
- //
- // License
- //--------------
- //
- // Code can be used for instructional and educational purposes and for assignments in the gaming courses at
- // the School of Compuer Science at Carleton University.
- // Usage of code for other purposes is not allowed without a given permission by the author.
- //
- //
- // Disclaimer
- //--------------
- //
- // The code is provided as is without any warranty
- //=============================================================================
- #include <winsock2.h>
- #include <stdlib.h>
- #include "gameApp.h"
- #include "House.h"
- #include <vector>
- #include <string>
- #include <iostream>
- #include <fstream>
- #include <agents.h>
- #include <thread>
- /********************************************************************************/
- // DEFINE
- #define FRAMES_PER_SECOND 30
- #define NORMAL_SPEED 0.5
- #define MAX_SPEED 2.0
- // event types for processing game state
- #define GAME_UPDATE_FRAME_STATE_EVENT 1
- #define GAME_COLLISION_EVENT 2
- #define GAME_NETWORK_UPDATE_EVENT 3
- // DEFINE
- #define MSG_LENGTH 256
- #define NUM_CONNECTION_ATTEMPTS 10
- #define CONNECTION_CLOSED -10
- #define SLEEP_TIME 300
- /*******************************************************************************/
- // class static variables
- Camera *gameApp::cam = NULL;
- meshSurface *gameApp::drawSurface = NULL;
- Chaser *gameApp::chaserYellowKia = NULL;
- Prey *gameApp::preyRedKia = NULL;
- gameApp * gameApp::myApp;
- std::vector<gameObject *> gameApp::gameStaticEntities; // these entities do not change with time
- std::vector<gameObject *> gameApp::gameDynamicEntities; // these entities' attributes change with time
- bool fps;
- int clientRole = 1; // lets have a default of one to the player role
- int playerIndex;
- int chaserIndex;
- // networking
- int clientAddLen = 0;
- fd_set master_fds;
- u_long iMode = 0;
- static int count = 0;
- struct sockaddr_in clientAdd;
- SOCKET sockfd = INVALID_SOCKET;
- SOCKET clientSock = INVALID_SOCKET;
- int rc = 0;
- int handle = 0;
- char ipAddressString[1024];
- char portString[1024];
- // ip address chunks
- unsigned int a;
- unsigned int b;
- unsigned int c;
- unsigned int d;
- unsigned short port;
- // struct for address
- unsigned int address;
- /******************************************************************/
- /*
- Purpose: constructor of the game application
- Descripton:
- Return:
- */
- gameApp::gameApp(void)
- {
- myApp = this;
- }
- /******************************************************************/
- /*
- Purpose: destructor of the game application
- Descripton:
- Return:
- 1 - if failed
- 0 - if successful
- */
- gameApp::~gameApp(void)
- {
- }
- // INITIALIZATION
- /******************************************************************/
- /*
- Purpose: initializes the graphics device
- Descripton:
- Return:
- 1 - if failed
- 0 - if successful
- */
- int gameApp::initGraphics(int argc, char** argv, int winWidth, int winHeight, int winPosx, int winPosy) {
- int rc = 0;
- GLenum err;
- // initialize GLUT and pass it the command variables
- glutInit(&argc, argv);
- //glutInitDisplayMode(GLUT_DOUBLE);
- glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
- // Set the window
- // instruct openGL where to put the window on the screen
- glutInitWindowPosition(winPosx, winPosy);
- // instuct openGL what window size ot use
- glutInitWindowSize(winWidth, winHeight); // no magic numbers
- // careate the fist window and obtain a handle to it
- wId = glutCreateWindow("My First Window");
- glEnable(GL_CULL_FACE);
- glCullFace(GL_BACK);
- //glDisable(GL_CULL_FACE);
- glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // set the colour buffer to black
- glEnable(GL_DEPTH_TEST); // Enable depth ubffer testing
- glClearDepth(1.0f); // Set depth buffer
- glDepthFunc(GL_LEQUAL); // depth test operation (this is the default)
- glShadeModel(GL_SMOOTH); // smooth shading
- glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // highest quality perspective corrections
- // set the call back functions
- glutDisplayFunc(renderFrame);
- glutReshapeFunc(reshapeFun);
- glutKeyboardFunc(keyboardFun);
- glutSpecialFunc(specialKeyboardFun);
- glutTimerFunc(10, timerFun, 1);
- // initialize GLEW
- err = glewInit();
- //GLenum err = glewInit();
- if (err != GLEW_OK) fprintf(stderr, " Error initializing GLEW! \n");
- else fprintf(stderr, "Initializing GLEW succeeded!\n");
- return(0);
- }
- int initCommunication(char *serverIP, char *port) {
- unsigned short serverPort = 0;
- SOCKET clientSock = INVALID_SOCKET;
- struct sockaddr_in serverAdd;
- int clientAddLen = 0;
- u_long iMode = 0;
- // create socket
- handle = socket(AF_INET,
- SOCK_DGRAM,
- IPPROTO_UDP);
- if (handle <= 0) {
- printf("failed to create socket\n");
- return false;
- }
- serverAdd.sin_family = AF_INET;
- serverAdd.sin_addr.s_addr = INADDR_ANY; // listen to all addresses - it can be set to a specific address
- sscanf(port, "%hu", &serverPort);
- serverAdd.sin_port = htons(serverPort);
- // associate the socket to the particular address and port
- if (bind(handle, (struct sockaddr *) &serverAdd, sizeof(serverAdd))) {
- std::cout << std::endl << "Failed to bind socket! " << std::endl;
- return false;
- }
- iMode = 1; // non blocking is enabled
- if (ioctlsocket(handle, FIONBIO, &iMode) != 0) {
- printf("failed to set non-blocking\n");
- return false;
- }
- }
- /******************************************************************/
- /*
- Purpose: initialize the game
- Descripton:
- Return:
- 1 - if failed
- 0 - if successful
- */
- int gameApp::initGame(void) {
- // load game settings
- std::ifstream gameSettings;
- gameSettings.open("playerSettings.txt");
- std::string gameSettingsArgs[6];
- int argsCounter = 0;
- if (gameSettings.is_open()) {
- std::cout << "Succesfully opened file!" << std::endl;
- std::string textLine;
- while (getline(gameSettings, textLine) && argsCounter < 6) {
- if (textLine.at(0) != ':') {
- gameSettingsArgs[argsCounter] = textLine;
- argsCounter++;
- }
- }
- std::cout << "IP address was read as:" << gameSettingsArgs[0] << std::endl;
- std::cout << "Port was read as:" << gameSettingsArgs[1] << std::endl;
- std::cout << "Message delay was read as:" << gameSettingsArgs[2] << std::endl;
- if (gameSettingsArgs[3] == "1") {
- std::cout << "Role was read as: 1, player." << std::endl;
- clientRole = 1;
- } else if (gameSettingsArgs[3] == "2") {
- std::cout << "Role was read as: 2, auto chaser." << std::endl;
- clientRole = 2;
- } else if (gameSettingsArgs[3] == "3") {
- std::cout << "Role was read as: 3, manual chaser." << std::endl;
- clientRole = 3;
- } else {
- std::cout << "Error! Given number: " << gameSettingsArgs[3] << " which is not a valid role! Using default of 1!" << std::endl;
- }
- std::cout << "Max player speed was read as:" << gameSettingsArgs[4] << std::endl;
- std::cout << "Max chaser speed was read as:" << gameSettingsArgs[5] << std::endl;
- gameSettings.close();
- }
- else {
- std::cout << "File not open!" << std::endl;
- }
- // set network values
- strcpy(ipAddressString, gameSettingsArgs[0].c_str());
- strcpy(portString, gameSettingsArgs[1].c_str());
- std::cout << std::endl << "input is: Server Address " << ipAddressString << " Server Port " << portString << std::endl;
- rc = initCommunication(ipAddressString, portString);
- std::cout << "Starting thread for networking!" << std::endl;
- std::thread *networkingThread = new std::thread(&networkingCode, handle);
- // create game objects
- Car *truck = NULL;
- House *house1 = NULL, *house2 = NULL, *targetHouse = NULL; // are set as static for collision
- Shader *shader = NULL;
- fps = false;
- house1 = new House();
- house2 = new House();
- targetHouse = new House();
- truck = new Car();
- preyRedKia = new Prey();
- chaserYellowKia = new Chaser();
- // create the shader that will be shared by all objects
- shader = new Shader();
- shader->createShaderProgram("general.vert", "general.frag");
- // set truck object
- truck->setShader(shader); // use the general shader
- // load the geometry
- truck->initGeom("truck\\", "L200_OBJ_DOS.obj", MODEL_OBJ_FILE);
- truck->loadTexture("truck\\truck_color_clean_256.jpg"); // get the texture
- // set the initial position attributes - align the object wth the z-axis if needed
- truck->setScale((float) 0.05, (float) 0.05, (float) 0.05);
- truck->setPositionOrientation(Vector3f(0, 0, 0), Vector3f(0, 0, 1), Vector3f(0, 1, 0));
- // set the prey object
- preyRedKia->setShader(shader); // use the general shader
- // load the geometry
- preyRedKia->initGeom("kia\\", "kia_rio.obj", MODEL_OBJ_FILE);
- // load the textures
- preyRedKia->loadTexture("kia\\rio_red.bmp");
- // set the initial position attributes - align the object wth the z-axis if needed
- preyRedKia->setScale((float) 0.2, (float) 0.2, (float) 0.2);
- preyRedKia->setPositionOrientation(Vector3f(8, 0, 7), Vector3f(1, 0, 1), Vector3f(0, 1, 0));
- preyRedKia->mYaw = 90; // orient it so that it faces that +zaxis
- preyRedKia->maxSpeed = std::stoi(gameSettingsArgs[4]); // set player max speed from file
- // set the chaser object
- chaserYellowKia->setShader(shader); // use the general shader
- // load the geometry model
- chaserYellowKia->initGeom("kia\\", "kia_rio.obj", MODEL_OBJ_FILE);
- // load the textures
- chaserYellowKia->loadTexture("kia\\rio_yellow.bmp");
- // set the initial position attributes - align the object wth the z-axis if needed
- chaserYellowKia->setScale((float) 0.2, (float) 0.2, (float) 0.2);
- chaserYellowKia->mYaw = 90; // orient it so that it faces that +zaxis
- chaserYellowKia->setPositionOrientation(Vector3f(-5, 0, 5), Vector3f(0, 0, 1), Vector3f(0, 1, 0));
- chaserYellowKia->maxSpeed = std::stoi(gameSettingsArgs[5]); // set chaser max speed loaded from file
- if (clientRole == 3) {
- chaserYellowKia->isAnotherPlayer = true;
- }
- // set the house object
- house1->setShader(shader); // use the general shader
- house1->initGeom("house_obj\\", "house_obj.obj", MODEL_OBJ_FILE);
- // load the textures
- house1->loadTexture("house_obj\\house_diffuse_256.tga");
- // set attributes (scale, position, and initial orientation towards the (0,0,1)
- house1->setScale(0.006f, 0.006f, 0.006f);
- house1->setPositionOrientation(Vector3f(5, 0, 1.2f), Vector3f(1, 0, 1), Vector3f(0, 1, 0));
- house2->setShader(shader); // use the general shader
- house2->initGeom("house_obj\\", "house_obj.obj", MODEL_OBJ_FILE);
- // load the textures
- house2->loadTexture("house_obj\\house_diffuse_256.tga");
- // set the model transformation (scale, position, and initial orientation towards the (0,0,1)
- house2->setScale(0.006f, 0.006f, 0.006f);
- house2->setPositionOrientation(Vector3f(-15, 0, -12.2f), Vector3f(-1, 0, 1), Vector3f(0, 1, 0));
- targetHouse->createShaderProg("red.vert", "red.frag"); // target uses a different shader
- targetHouse->initGeom("targetHouse\\", "targetHouse.obj", MODEL_OBJ_FILE);
- // load the textures
- targetHouse->loadTexture("house_obj\\house_diffuse_256.tga");
- // set the model transformation (scale, position, and initial orientation towards the (0,0,1)
- targetHouse->setScale(0.01f, 0.006f, 0.01f);
- targetHouse->setPositionOrientation(Vector3f(-3, 1.0, 8.2f), Vector3f(-1, 0, 1), Vector3f(0, 1, 0));
- // set the surface
- drawSurface = new meshSurface();
- drawSurface->setParam(1, 1, 60, 60, 0, 15, 0, 15);
- //drawSurface->createShaderProg("general.vert", "general.frag");
- drawSurface->setShader(shader);
- drawSurface->initGeom();
- drawSurface->loadTexture("surface\\grass_texture_256.tga");
- //drawSurface->setPositionOrientation(Vector3f(0, 0, 0), Vector3f(1, 0, 0), Vector3f(0, 1, 0));
- // add the objects to the list of game objects
- gameDynamicEntities.push_back(chaserYellowKia);
- playerIndex = 0;
- gameDynamicEntities.push_back(preyRedKia);
- chaserIndex = 1;
- gameDynamicEntities.push_back(truck);
- // add the objects to the list of game objects
- gameStaticEntities.push_back(drawSurface);
- gameStaticEntities.push_back(house1);
- gameStaticEntities.push_back(house2);
- gameStaticEntities.push_back(targetHouse);
- // set the global camera
- cam = new Camera();
- cam->setCamera(Vector3f(0, 20, 40), Vector3f(0, 0, 0), Vector3f(0, 1, 0));
- cam->setPerspectiveView(45, 1, 0.2f, 1000);
- return 0;
- }
- // LOOPS
- /******************************************************************/
- /*
- Purpose: executes the message loop
- Descripton:
- This function is a virtual function and can be replaced by a similar function in the derived class.
- Return:
- 1 - if failed
- 0 - if successful
- */
- int gameApp::gameLoop(void) {
- // enter glut main loop
- glutMainLoop();
- return 0;
- }
- // UPDATES
- int networkAction(fd_set *master_fds) {
- int len;
- int rc = 0;
- unsigned int i, j;
- timeval timeout;
- SOCKET readSocket, writeSocket;
- fd_set read_fds, write_fds;
- char buf[MSG_LENGTH];
- timeout.tv_sec = 0;
- timeout.tv_usec = 500000; // wait for 0.5 seconds
- memset(buf, 0, MSG_LENGTH);
- // copy the master list
- read_fds = *master_fds;
- // if (read_fds.fd_count <= 0) {
- // std::cout << "FD count is less or equal to 0, was: " << read_fds.fd_count << std::endl;
- // }
- if (read_fds.fd_count > 0) {
- rc = select(0, &read_fds, NULL, NULL, &timeout); // check the status of the sockets descriptors that the server is listening to
- switch (rc) {
- case 0:
- // nothing ready for readv return
- goto err;
- break;
- case SOCKET_ERROR:
- // check what is the error
- rc = WSAGetLastError();
- goto err;
- break;
- default:
- // some sockets are ready for read
- break;
- }
- }
- // for (i = 0; i < master_fds->fd_count; i++) {
- // readSocket = master_fds->fd_array[i];
- for (i = 0; i < read_fds.fd_count; i++) {
- readSocket = read_fds.fd_array[i];
- rc = recv(readSocket, buf, MSG_LENGTH - 1, 0); // wait until something was sent
- switch (rc) {
- case 0:
- // connecion is closed
- // remove from the list
- FD_CLR(readSocket, master_fds);
- break;
- case SOCKET_ERROR:
- // error
- rc = WSAGetLastError();
- switch (rc) {
- case WSAECONNREFUSED:
- // server may not be up yet
- Sleep(1000);
- break;
- case WSAEWOULDBLOCK:
- // connection was not established yet.
- // do not call connect again on the same socket.
- break;
- case WSAECONNRESET:
- FD_CLR(readSocket, master_fds);
- break;
- default:
- rc = -1;
- goto err;
- break;
- }
- break;
- default:
- break;
- }
- std::cout << "server received -> " << buf << std::endl;
- // something was read from the connectcion
- // send it back
- len = rc;
- // write_fds = *master_fds;
- write_fds = read_fds;
- // can add some code to remove the sending socket !!!
- for (j = 0; j < write_fds.fd_count; j++) {
- // send to all the clients
- writeSocket = write_fds.fd_array[j];
- //build message to send, info delimited by ';'
- char *s;
- char buffer[64];
- // role
- strcat(s, ";");
- rc = send(writeSocket, buf, len, 0); // note the number of bytes that were sent can be smaller then
- if (rc == SOCKET_ERROR) {
- rc = WSAGetLastError();
- switch (rc) {
- case 0:
- // connecion is closed
- // remove from the list
- FD_CLR(writeSocket, master_fds);
- break;
- case WSAECONNRESET:
- // error
- FD_CLR(writeSocket, master_fds);
- rc = -1;
- break;
- default:
- closesocket(writeSocket);
- FD_CLR(writeSocket, master_fds);
- rc = -1;
- break;
- }
- }
- else {
- if (rc != len) {
- // not all bytes were sent
- // need loop
- rc = 5;
- }
- std::cout << "server sent: " << buf << std::endl;
- }
- }
- }
- rc = 0;
- err:
- return(rc);
- }
- /******************************************************************/
- /*
- Purpose: updates the game state
- Descripton:
- Return:
- 1 - if failed
- 0 - if successful
- */
- int gameApp::updateGameState(long event) {
- std::string debugString;
- bool xCollide;
- bool zCollide;
- static int frameCount = 0;
- static int dir = 1;
- static Vector3f lastPreyPos = preyRedKia->mPosition;
- static Vector3f lastChaserPos = preyRedKia->mPosition;
- unsigned int i;
- int rc;
- switch (event) {
- case GAME_UPDATE_FRAME_STATE_EVENT:
- frameCount++; // increment frame count
- bool xDetect;
- bool zDetect;
- // this section should have the game logic with respect to time.
- // Then it calls each object with updateStateFunction
- lastPreyPos = preyRedKia->mPosition;
- lastChaserPos = chaserYellowKia->mPosition;
- for (i = 0; i < gameDynamicEntities.size(); i++) {
- rc = gameDynamicEntities.at(i)->updateState(frameCount);
- if (rc == GAME_OBJECT_DELETE_ENTITY) {
- // swap current object with the last one
- gameObject *temp = gameDynamicEntities.at(i);
- gameDynamicEntities.at(i) = gameDynamicEntities.back();
- delete temp;
- gameDynamicEntities.pop_back();
- }
- }
- if (clientRole == 1) {
- // If in proximity of prey, chase
- xDetect = (((preyRedKia->mPosition.x) <= (chaserYellowKia->mPosition.x + 6))
- && ((preyRedKia->mPosition.x) >= (chaserYellowKia->mPosition.x - 6)));
- zDetect = (((preyRedKia->mPosition.z) <= (chaserYellowKia->mPosition.z + 6))
- && ((preyRedKia->mPosition.z) >= (chaserYellowKia->mPosition.z - 6)));
- // prey is in proximity of the chaser?
- if (xDetect && zDetect) {
- Vector3f directionVec = (preyRedKia->mPosition - chaserYellowKia->mPosition);
- directionVec.normalize();
- chaserYellowKia->changeLookAtVector(directionVec.x, directionVec.y, directionVec.z);
- chaserYellowKia->moveForward(0.05);
- }
- } else if (clientRole == 3) {
- // let connecting client control the car
- }
- if (fps) {
- cam->setCamera(preyRedKia->mPosition, preyRedKia->lookAtVector, preyRedKia->upVector);
- }
- break;
- case GAME_COLLISION_EVENT:
- // player collides, exclude collission with the floor
- for (i = 1; i < gameStaticEntities.size(); i++) {
- xCollide = (((preyRedKia->mPosition.x) <= (gameStaticEntities.at(i)->mPosition.x + 3))
- && ((preyRedKia->mPosition.x) >= (gameStaticEntities.at(i)->mPosition.x - 3)));
- zCollide = (((preyRedKia->mPosition.z) <= (gameStaticEntities.at(i)->mPosition.z + 3))
- && ((preyRedKia->mPosition.z) >= (gameStaticEntities.at(i)->mPosition.z - 3)));
- debugString = std::string("Prey X: ") + std::to_string(preyRedKia->mPosition.x) + std::string("Prey Z: ") + std::to_string(preyRedKia->mPosition.z)
- + 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)
- + std::string(" X Collide: ") + std::to_string(xCollide) + " Z Collide: " + std::to_string(zCollide) ;
- // std::cout << debugString << std::endl;
- if (xCollide && zCollide) {
- preyRedKia->mPosition = lastPreyPos;
- }
- }
- // chaser collides, exclude collission with the floor
- for (i = 1; i < gameStaticEntities.size(); i++) {
- xCollide = (((chaserYellowKia->mPosition.x) <= (gameStaticEntities.at(i)->mPosition.x + 3))
- && ((chaserYellowKia->mPosition.x) >= (gameStaticEntities.at(i)->mPosition.x - 3)));
- zCollide = (((chaserYellowKia->mPosition.z) <= (gameStaticEntities.at(i)->mPosition.z + 3))
- && ((chaserYellowKia->mPosition.z) >= (gameStaticEntities.at(i)->mPosition.z - 3)));
- debugString = std::string("Chaser X: ") + std::to_string(chaserYellowKia->mPosition.x) + std::string("Chaser Z: ") + std::to_string(chaserYellowKia->mPosition.z)
- + 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)
- + std::string(" X Collide: ") + std::to_string(xCollide) + " Z Collide: " + std::to_string(zCollide);
- // std::cout << debugString << std::endl;
- if (xCollide && zCollide) {
- chaserYellowKia->mPosition = lastChaserPos;
- }
- }
- break;
- default:
- printf("another event occurred \n");
- break;
- }
- return 0;
- }
- /******************************************************************/
- /*
- Purpose: renders one frame
- Description:
- Return:
- 1 - if failed
- 0 - if successful
- */
- void gameApp::renderFrame(void) {
- static int count = 0;
- static int dir = 1;
- unsigned int i;
- count++;
- glClearColor(0, 0, 0, 0.0);
- glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Clear the colour and depth buffers
- for (i = 0; i < gameDynamicEntities.size(); i++) {
- gameObject *g = gameDynamicEntities.at(i);
- gameDynamicEntities.at(i)->render(NULL, gameApp::cam);
- }
- for (i = 0; i < gameStaticEntities.size(); i++) {
- gameStaticEntities.at(i)->render(NULL, gameApp::cam);
- }
- // swap the buffers
- glutSwapBuffers();
- }
- /****************************************************************************/
- void gameApp::keyboardFun(unsigned char key, int x, int y) {
- switch (key) {
- case 033:
- case 'Q':
- case 'q':
- exit(1);
- break;
- case 'w':
- cam->moveForward(NORMAL_SPEED);
- break;
- case 'W':
- cam->moveForward(MAX_SPEED);
- break;
- case 's':
- cam->moveForward(-NORMAL_SPEED);
- break;
- case 'S':
- cam->moveForward(-MAX_SPEED);
- break;
- case 'a':
- cam->yaw((float) .2);
- break;
- case 'A':
- cam->yaw(1);
- break;
- case 'D':
- cam->yaw(-1);
- break;
- case 'd':
- cam->yaw((float)-.2);
- break;
- case 'z':
- cam->zoomIn();
- break;
- case 'Z':
- cam->zoomOut();
- break;
- }
- // Cam movmeents
- if(key == 'c'){
- // change camera view point
- } else if (key == 'C') {
- // change camera view point default
- cam->setCamera(Vector3f(0, 20, 40), Vector3f(0, 0, 0), Vector3f(0, 1, 0));
- }
- // vehicle movements
- if (clientRole == 1) {
- std::cout << "Listening to controls for prey player" << std::endl;
- // standard vehicle control
- preyRedKia->processKeys(key);
- } else if (clientRole == 3) {
- std::cout << "Listening to controls for chaser player" << std::endl;
- // if set to the chaser, proccess keys for another chaser instead.
- chaserYellowKia->processKeys(key);
- }
- }
- void gameApp::specialKeyboardFun(int key, int x, int y)
- {
- switch (key) {
- case 033:
- case 'Q':
- case 'q':
- exit(1);
- break;
- case GLUT_KEY_LEFT:
- cam->roll((float) .2);
- break;
- case GLUT_KEY_UP:
- cam->pitch((float) .2);
- break;
- case GLUT_KEY_RIGHT:
- cam->roll((float) -.2);
- break;
- case GLUT_KEY_DOWN:
- cam->pitch((float) -.2);
- break;
- }
- }
- /************************************************************************************************/
- /*
- This functions in invoked when there is a change to the window by the user
- Here a new setting of the rendering paramters are set. In most cases it consists of two things:
- a. changeing the view port dimensions
- b. changing the aspect ratio
- input
- w, h - the width and height of the new window in the pixel coordinates
- */
- void gameApp::reshapeFun(int w, int h)
- {
- float fieldOfView, aspectRatio, nearPlane, farPlane;
- // change the view port
- glViewport (0 , 0, (GLsizei) w, (GLsizei) h);
- // Set the state to accept projection information
- glMatrixMode(GL_PROJECTION); // To operate on the Projection matrix
- glLoadIdentity();
- // Enable perspective projection with fovy, aspect, zNear and zFar
- //gluPerspective(45.0f, aspect, 0.1f, 100.0f);
- cam->getPerspectiveView(&fieldOfView, &aspectRatio, &nearPlane, &farPlane);
- // Compute aspect ratio of the new window
- aspectRatio = (float)w / (float)h;
- cam->setPerspectiveView(fieldOfView, aspectRatio ,nearPlane, farPlane);
- }
- void gameApp::networkingCode (int handle) {
- // networking loop
- while (true) {
- // std::cout << "LOOPED IN NETWORKING THREAD!" << std::endl;
- unsigned char packet_data[MSG_LENGTH];
- unsigned int max_packet_size = sizeof(packet_data);
- sockaddr_in from;
- typedef int socklen_t;
- socklen_t fromLength = sizeof(from);
- int bytes = recvfrom(handle,
- (char*)packet_data,
- max_packet_size,
- 0,
- (sockaddr*)&from,
- &fromLength);
- if (!bytes)
- break;
- // where did the packet come from
- unsigned int from_address =
- ntohl(from.sin_addr.s_addr);
- unsigned int from_port =
- ntohs(from.sin_port);
- std::cout << "received this from : " << from_address << " port " << from_port << std::endl;
- }
- }
- /***************************************************************************************************/
- /*
- This function is a timer function for the update state event and redrawing the scenes.
- Here the FrameNumber does not play a role yet because there is a single event that
- the function is handling. Namely, the timerEvent is a frameNumber.
- Currently the updateGameState() is also keeping track of the frame number. This
- should be modified to either a global variable (not preferable), gameApp member variable,
- or passed in as a parameter to updateGameState() (most likely the best option).
- */
- void gameApp::timerFun(int timerEvent)
- {
- static int frameNumber = 0;
- frameNumber++;
- // renderSceneFun();
- glutPostRedisplay();
- // get next event from Queue (future implementation)
- // the queue should have return an event and the event timer
- myApp->updateGameState((long)GAME_UPDATE_FRAME_STATE_EVENT);
- myApp->updateGameState((long)GAME_COLLISION_EVENT);
- glutTimerFunc(5, timerFun, frameNumber);
- }
- boolean udpSendMssg(int handle, char* dataToSend, char* address, char* port) {
- unsigned short serverPort = 0;
- sscanf(port, "%hu", &serverPort);
- sockaddr_in addr;
- addr.sin_family = AF_INET;
- addr.sin_addr.s_addr = inet_addr(address);
- addr.sin_port = htons(serverPort);
- int sent_bytes = sendto(handle, dataToSend, MSG_LENGTH, 0, (sockaddr*)&addr, sizeof(sockaddr_in));
- if (sent_bytes != MSG_LENGTH)
- {
- printf("failed to send packet\n");
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement