static void onIdle() { updateWorld(); // fps checker static long fps_start_time = glutGet(GLUT_ELAPSED_TIME); static int frame_cnt = 0; ++frame_cnt; long now = glutGet(GLUT_ELAPSED_TIME); if (now - fps_start_time > 1000) { current_fps = frame_cnt * 1000.0f / (now - fps_start_time); frame_cnt = 0; fps_start_time = now; } // timer control long elapsed_time = timer_draw + timer_update; if (elapsed_time < time_slice) { long sleep_time = (time_slice - elapsed_time); #ifdef __APPLE__ usleep((useconds_t)sleep_time * 1000); #else Sleep(sleep_time); #endif } glutPostRedisplay(); }
virtual void onTargetSelectorInvoked(wyTargetSelector* ts) { switch (ts->getId()) { case TS_UPDATE: updateWorld(ts->getDelta()); break; } }
WorldMap::WorldMap() : mWorld(0), mSub(0), mLevelCount(0), mSection(0), mCount(0), mNewWorld(false), //fult mWorldMax(3) { readButtons(); mMusic = "Resources/Sound/Music/Title_Screen_"; mSprite.setTexture(*ResourceManager::getInst().getTexture("Resources/Menu/WorldMenu/WorldmapBG.png")); mSprite.setPosition(0,0); readSave(); readWorld(); updateWorld(); readAnimals(); LevelManager::getInst().setDeadAnimalCollection(mDeadAnimalVector); mCurrentWorld = mWorld; mCurrentSection = mSection; mFactButton = new FactButton(sf::Vector2f(20,20), "addAnimalipedia", "Resources/Menu/AchievementMenu/faktaknapp.png", "Resources/Sound/Menu/Menu_forward.wav"); mCutscenes.push_back("Resources/Data/Cutscenes/Cutscene_2.xml"); mCutscenes.push_back("Resources/Data/Cutscenes/Cutscene_3.xml"); mCutscenes.push_back("Resources/Data/Cutscenes/Cutscene_ending.xml"); }
//run simulation for 10000 void runSimulation(int *world, int worldsize, player *people, int players, int numSteps){ for (int i = 0; i < numSteps; i++){ CheckTag(world, worldsize, people, players); MoveZombies(world, worldsize, people, players); updateWorld(world, worldsize, people, players); CheckTag(world, worldsize, people, players); MoveZombies(world, worldsize, people, players); updateWorld(world, worldsize, people, players); CheckTag(world, worldsize, people, players); MoveZombies(world, worldsize, people, players); updateWorld(world, worldsize, people, players); CheckTag(world, worldsize, people, players); MoveHumans(world, worldsize, people, players); updateWorld(world, worldsize, people, players); CheckTag(world, worldsize, people, players); } }
Game::Game(CommWindow* comm) : mComm(comm) { mTimer = new QTimer(this); connect(mTimer, SIGNAL(timeout()), this, SLOT(updateWorld())); mTimer->setInterval(1000 / fps); mElapsed.start(); mTimer->start(); }
Brick::Brick(Vec3 _pos) { position = _pos; scale = Vec3(1,1,1); rotation = Vec3(0,0,0); alive = true; #ifdef _WIN32 shaderTechniqueID = GraphicsDX11::getInstance()->getTechIDByName("techSimple"); #endif updateWorld(); }
void Antimony::step() { timer.catchTime(TIMER_FRAME_GLOBAL); delta = timer.getDelta(); double fstep = delta * worldSpeed; cpuUsage.GetUsage(0); if (GetForegroundWindow() == window_main.hWnd && mouse.isExclusive()) { mouse.acquire(false); } else { mouse.release(false); /*SetCursor(arrow); SetClassLong(window_main.hWnd, GCL_HCURSOR, (DWORD)arrow);*/ } updateGameState(); if (ifGameState(GAMESTATE_INGAME)) // In-game (non-paused, non-menu etc.) { if (devConsole.isOpen()) { player.lock(); camera_main.lock(); } else { player.unlock(); camera_main.unlock(); } updateAI(fstep); // update AI/scripts etc. (TBI) updateWorld(fstep); // update moving objects, triggers etc. (TBI) player.update(delta, m_objectsCollisions); updatePlayerControls(&keys, &controller[0], fstep); // update player inputs updatePhysics(fstep); // btWorld step updateCameraControls(&mouse, &keys, &controller[0], fstep); // update camera (--> mat_view) } else if (ifGameState(GAMESTATE_PAUSED) && devConsole.isClosed()) // Game is paused { camera_main.unlock(); updateCameraControls(&mouse, &keys, &controller[0], fstep); // update camera (--> mat_view) } prepareFrame(); // prepare the frame for rendering }
bool World::handleEvents(SDL_Event *event) { switch (event->type) { case SDL_KEYDOWN: // keyDown[event->key.keysym.sym](); // break; switch( event->key.keysym.sym ) { case SDLK_w: map->adjustPlayer(0,-1); // map->visibleRect.Y -= 1; break; case SDLK_a: map->adjustPlayer(-1,0); // map->visibleRect.X -= 1; break; case SDLK_s: map->adjustPlayer(0,1); // map->visibleRect.Y += 1; break; case SDLK_d: map->adjustPlayer(1,0); // map->visibleRect.X += 1; break; case SDLK_f: // add range overlay, which takes key presses return false; break; case SDLK_PERIOD: break; default: return false; } break; default: return false; } turn.playerCount++; updateWorld(); return true; }
void OpenGlApplication::process() { glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); updateCamera(); updateWorld(); draw(); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); updateProjection(); mWindow->swapBuffers(); }
void runGame() { hideCursor(); initWorld(); unsigned long curtime = ccTimeMilliseconds(); double acctime = 0.0; while(true){ ccEvent event = updateWindow(); if(event.type == CC_EVENT_WINDOW_QUIT){ break; }else if(event.type == CC_EVENT_KEY_DOWN){ handleKeyDownWorld(event.keyCode); }else if(event.type == CC_EVENT_KEY_UP){ handleKeyUpWorld(event.keyCode); } unsigned long newtime = ccTimeMilliseconds(); double frametime = (newtime - curtime) * 0.001; curtime = newtime; if(frametime > FRAME_CAP){ frametime = FRAME_CAP; } acctime += frametime; bool redraw = false; while(acctime >= FRAME_DELTA){ acctime -= FRAME_DELTA; redraw = updateWorld(); } if(redraw){ renderWorld(2, 1, getWidth() - getGuiWidth() - 3, getHeight() - 8); renderGui(getWidth() - getGuiWidth(), 0); } renderWindow(2); } }
void world::GameLoop() { //checking the keyboard events while(GameWindow.pollEvent(GameWindowEvent)) { if(GameWindowEvent.type==sf::Event::EventType::KeyPressed && (GameWindowEvent.key.code == sf::Keyboard::Left|| GameWindowEvent.key.code == sf::Keyboard::Right)) { PlayerPadel.timerStart(); } if(GameWindowEvent.type==sf::Event::EventType::KeyReleased && (GameWindowEvent.key.code == sf::Keyboard::Left|| GameWindowEvent.key.code == sf::Keyboard::Right)) { PlayerPadel.stop(); } } //making the changes per frame to the world updateWorld(); }
void World::updateWorld() { turn.count++; int turnCurrent = turn.count % turn.orderCount; Speed turnSpeed = turn.order[turnCurrent]; // printf("Turn %d speed=%s\n",turnCurrent,stringForSpeed(turnSpeed).c_str()); map->update(turnSpeed); if(map->getPlayer()->speed == turnSpeed) { map->getPlayer()->calculateSight(); LOG("<([ - - - - - - Turn End - - - - - - - ])>"); return; } updateWorld(); }
void WorldMap::setCurrentWorldOrSub(std::string currentLevel){ if(mWorldVector[mWorld][mSub].size() > mLevelCount){ for(std::vector<std::string>::iterator i = mWorldVector.at(mWorld).at(mSub).begin(); i != mWorldVector.at(mWorld).at(mSub).end(); i++){ if((*i) == currentLevel){ mLevelCount++; mCurrentSection++; } } } if(mWorldVector[mWorld][mSub].size() <= mLevelCount){ //anger plats i vectorn. mSub++; mLevelCount = 0; } if(mWorldVector[mWorld].size() <= mSub){ mWorld++; mSub = 0; mNewWorld = true; } for(ButtonVector::iterator i = mButtonVector.begin(); i != mButtonVector.end(); i++){ if((*i)->getLevel() == currentLevel){ //alive är korrekt här (*i)->setAlive(false); } } //så endgame funakr, hååårdkod if(mWorld <= 2){ updateWorld(); } saveToFile(currentLevel); }
bool HelloPolycodeApp::Update() { updateWorld(core->getElapsed()); infoLabel->setText("Example server. ["+String::IntToString(players.size())+" Players]"); return core->Update(); }
bool GStillEntity::checkIntersect ( const D3DXVECTOR4& vPos, /*世界坐标系中的点 */ const D3DXVECTOR4& vDir, /*世界坐标系中的向量 */ bool bInsectInfo /*是 裥枰鲎残畔?*/ ) { HRESULT hr = S_FALSE; //将Pos和Dir转换到物体本地坐标系中 D3DXMATRIX matWorld = getTrans()->getLocalD3D(); D3DXMatrixInverse ( &matWorld, NULL, &matWorld ); D3DXVec4Transform ( ( D3DXVECTOR4 * ) &vDir, ( D3DXVECTOR4 * ) &vDir, &matWorld ); D3DXVec3Normalize ( ( D3DXVECTOR3* ) &vDir, ( D3DXVECTOR3* ) &vDir ); D3DXVec4Transform ( ( D3DXVECTOR4 * ) &vPos, ( D3DXVECTOR4 * ) &vPos, &matWorld ); if ( mMeshForInsect == NULL ) { recreateInsectMesh(); } BOOL bHit = FALSE; hr = D3DXIntersect ( mMeshForInsect, ( D3DXVECTOR3* ) &vPos, ( D3DXVECTOR3* ) &vDir, &bHit, &m_InsectInfo.dwFaceIndex, &m_InsectInfo.u, &m_InsectInfo.v, &m_InsectInfo.fDist, NULL, NULL ); mNodeState.setBit ( eObjState_Picked, ( bool ) bHit ); dDebugMsgBox ( hr, "碰撞失败!" ); if ( FAILED ( hr ) ) { return false; } if ( bInsectInfo && mNodeState[eObjState_Picked] ) { D3DXVECTOR3 v[3]; DWORD dwIndex[3]; //先要获取索引缓冲区格式 LPDIRECT3DINDEXBUFFER9 pI = NULL; mMeshForInsect->GetIndexBuffer ( &pI ); D3DINDEXBUFFER_DESC indexDesc; dMemoryZero ( &indexDesc, sizeof ( D3DINDEXBUFFER_DESC ) ); if ( pI != NULL ) { pI->GetDesc ( &indexDesc ); } if ( indexDesc.Format== D3DFMT_INDEX16 ) { WORD *pIndexData16; hr = mMeshForInsect->LockIndexBuffer ( D3DLOCK_READONLY, ( void** ) &pIndexData16 ); dwIndex[0] = pIndexData16[m_InsectInfo.dwFaceIndex * 3 + 0]; dwIndex[1] = pIndexData16[m_InsectInfo.dwFaceIndex * 3 + 1]; dwIndex[2] = pIndexData16[m_InsectInfo.dwFaceIndex * 3 + 2]; } else { DWORD *pIndexData32; hr = mMeshForInsect->LockIndexBuffer ( D3DLOCK_READONLY, ( void** ) &pIndexData32 ); dwIndex[0] = pIndexData32[m_InsectInfo.dwFaceIndex * 3 + 0]; dwIndex[1] = pIndexData32[m_InsectInfo.dwFaceIndex * 3 + 1]; dwIndex[2] = pIndexData32[m_InsectInfo.dwFaceIndex * 3 + 2]; } mMeshForInsect->UnlockIndexBuffer(); D3DXVECTOR3 *pVertexData; hr = mMeshForInsect->LockVertexBuffer ( D3DLOCK_READONLY, ( void** ) &pVertexData ); v[0] = pVertexData[dwIndex[0]]; v[1] = pVertexData[dwIndex[1]]; v[2] = pVertexData[dwIndex[2]]; mMeshForInsect->UnlockVertexBuffer(); D3DXVECTOR4 vNormal ( ZEROFLOAT, ZEROFLOAT, ZEROFLOAT, ZEROFLOAT ); D3DXVECTOR4 vHitPos ( ZEROFLOAT, ZEROFLOAT, ZEROFLOAT, ZEROFLOAT ); D3DXVECTOR3 vTmp1, vTmp2; vTmp1 = v[1] - v[0]; vTmp2 = v[2] - v[0]; vHitPos = ( D3DXVECTOR4 ) v[0] + m_InsectInfo.u * ( D3DXVECTOR4 ) vTmp1 + m_InsectInfo.v * ( D3DXVECTOR4 ) vTmp2; vHitPos.w = 1; updateWorld (); D3DXVec4Transform ( &vHitPos, &vHitPos, &getTrans()->getLocalD3D() ); m_InsectInfo.vHitPos = D3DXVECTOR3 ( vHitPos.x, vHitPos.y, vHitPos.z ); D3DXVec3Cross ( ( D3DXVECTOR3* ) &vNormal, &vTmp1, &vTmp2 ); vNormal.w = 0; D3DXVec4Transform ( &vNormal, &vNormal, &matWorld ); D3DXVec3Normalize ( ( D3DXVECTOR3* ) &vNormal, ( D3DXVECTOR3* ) &vNormal ); m_InsectInfo.vNormal = D3DXVECTOR3 ( vNormal.x, vNormal.y, vNormal.z ); } return mNodeState[eObjState_Picked]; }
void PhysicsHandler::handleUpdate(EventDetails* const details) { commitChanges(); //Start the physics timing statistic StatTimeElem *PhysicsTimeStatElem = StatCollector::getGlobalElem(statPhysicsTime); if(PhysicsTimeStatElem) { PhysicsTimeStatElem->start(); } _TimeSinceLast += dynamic_cast<UpdateEventDetails* const>(details)->getElapsedTime(); if(osgFloor(_TimeSinceLast/getStepSize()) > getMaxStepsPerUpdate()) { SWARNING << "Physics Simulation slowing: dropping " << osgFloor(_TimeSinceLast/getStepSize())-getMaxStepsPerUpdate() << " steps" << std::endl; _TimeSinceLast = getMaxStepsPerUpdate()*getStepSize(); } StatIntElem *NPhysicsStepsStatElem = StatCollector::getGlobalElem(statNPhysicsSteps); StatTimeElem *CollisionTimeStatElem = StatCollector::getGlobalElem(statCollisionTime); StatTimeElem *DynamicsTimeStatElem = StatCollector::getGlobalElem(statSimulationTime); while(_TimeSinceLast > getStepSize()) { //Increment the steps statistic if(NPhysicsStepsStatElem) { NPhysicsStepsStatElem->inc(); } //*********** Collision Checks ************* //Start the collision timing statistic if(CollisionTimeStatElem) { CollisionTimeStatElem->start(); } //Do collision checks for(UInt32 i(0) ; i<getMFSpaces()->size() ; ++i) { getSpaces(i)->Collide(getWorld()); } //Stop the collision timing statistic if(CollisionTimeStatElem) { CollisionTimeStatElem->stop(); } //*********** Simulation step ************* //Start the simulation timing statistic if(DynamicsTimeStatElem) { DynamicsTimeStatElem->start(); } //Step the dynamics simulation getWorld()->worldQuickStep(getStepSize()); //Stop the simulation timing statistic if(DynamicsTimeStatElem) { DynamicsTimeStatElem->stop(); } //Decrease the time since last simulation step _TimeSinceLast -= getStepSize(); } StatRealElem *NCollisionTestsStatElem = StatCollector::getGlobalElem(statNCollisionTests); if(NCollisionTestsStatElem) { NCollisionTestsStatElem->set(NCollisionTestsStatElem->get()/static_cast<Real32>(NPhysicsStepsStatElem->get())); } StatRealElem *NCollisionsStatElem = StatCollector::getGlobalElem(statNCollisions); if(NCollisionsStatElem) { NCollisionsStatElem->set(NCollisionsStatElem->get()/static_cast<Real32>(NPhysicsStepsStatElem->get())); } StatTimeElem *TransformUpdateTimeStatElem = StatCollector::getGlobalElem(statTransformUpdateTime); //Start the transform update timing statistic if(TransformUpdateTimeStatElem) { TransformUpdateTimeStatElem->start(); } //update matrices updateWorld(getUpdateNode()); //Start the transform update timing statistic if(TransformUpdateTimeStatElem) { TransformUpdateTimeStatElem->stop(); } //Stop the physics timing statistic if(PhysicsTimeStatElem) { PhysicsTimeStatElem->stop(); } }
int main() { GLFWwindow* window; if (!glfwInit()) { printf("Error initializing GLFW\n"); return -1; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, GL_VERSION_MAJOR); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, GL_VERSION_MINOR); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); //glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_SAMPLES, 8); window = glfwCreateWindow(1920, 1080, "Test Window", glfwGetPrimaryMonitor(), NULL); if (!window) { printf("Error creating GLFW window\n"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetCursorPosCallback(window, cursor_position_callback); glfwSetScrollCallback(window, scroll_callback); if (gl3wInit()) { printf("Error initializing OpenGL\n"); glfwTerminate(); return -1; } printf("OpenGL %s GLSL %s\n", glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)); if (!gl3wIsSupported(GL_VERSION_MAJOR, GL_VERSION_MINOR)) { printf("OpenGL %i.%i is not supported\n", GL_VERSION_MAJOR, GL_VERSION_MINOR); glfwTerminate(); return -1; } glViewport(0, 0, 1920, 1080); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); GLuint programID = loadShadersvf("shaders/simple.vsh", "shaders/simple.fsh"); GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); //glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data), vertex_buffer_data, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(sphere_model), sphere_model, GL_STATIC_DRAW); GLuint ibo; glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(sphere_indices), sphere_indices, GL_STATIC_DRAW); //glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index_buffer_data), index_buffer_data, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glDisableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); double timesteps[] = {1, 60, 60 * 60, 60 * 60 * 24, 60 * 60 * 24 * 7, 60 * 60 * 24 * 30, 60 * 60 * 24 * 365}; int timestepCounter = 0; World world; world.num_functions = 0; //Add the functions for gravitational attraction to the world's object list, and have it execute when updateWorld() is called addFunction(&world, attract, COMPONENT_POSITION | COMPONENT_VELOCITY); addFunction(&world, move, COMPONENT_POSITION | COMPONENT_VELOCITY); unsigned int bodies[11]; //Create all the planets with the correct masses, sizes, and velocities bodies[0] = createStar(&world, "Sun", 0, 0, 0, 0, 0, 0, 1.989 * pow(10, 30), 6.963 * pow(10,8), 1); bodies[1] = createPlanet(&world, "Mercury", -0.35790 * AU, -0.04240 * AU, -0.11618 * AU, -0.00000004 * AU, 0.00000003 * AU, 0.00000031 * AU, 3.285 * pow(10,23), 2.44 * pow(10,6), 0.4549, 0.4509, 0.4705); bodies[2] = createPlanet(&world, "Venus", -0.46075 * AU, -0.03422 * AU, -0.56289 * AU, -0.00000017 * AU, -0.00000001 * AU, 0.00000014 * AU, 4.867 * pow(10, 24), 6.052 * pow(10,6), 0.4627, 0.568, 0.380); bodies[3] = createPlanet(&world, "Earth", 0.99542 * AU, 0, 0.01938 * AU, 0.00000001 * AU, 0, -0.00000019 * AU, 5.972 * pow(10, 24), 6.371 * pow(10,6), 0, 0.4, 0.6); bodies[4] = createPlanet(&world, "Moon", 0.99708 * AU, -0.00016 * AU, 0.02141 * AU, 0.00000001 * AU + 722.66, 0, -0.00000019 * AU - 722.66, 7.348 * pow(10, 22), 1.737 * pow(10,6), 0.4, 0.4, 0.4); bodies[5] = createPlanet(&world, "Mars", 1.38763 * AU, 0.01755 * AU, -0.79510 * AU, -0.00000009 * AU, -0.00000001 * AU, -0.00000013 * AU, 6.39 * pow(10, 23), 3.39 * pow(10,6), 0.8157, 0.5294, 0.3922); bodies[6] = createPlanet(&world, "Jupiter", 5.32462 * AU, 0.11488 * AU, 1.04223 * AU, 0.00000002 * AU, 0, -0.00000008 * AU, 1.898 * pow(10,27), 69.911 * pow(10,6), 0.8824, 0.7961, 0.7412); bodies[7] = createPlanet(&world, "Saturn", 3.30063 * AU, 0.29595 * AU, -9.47771 * AU, -0.00000006 * AU, 0, -0.00000002 * AU, 5.683 * pow(10,26), 58.232 * pow(10,6), 0.7843, 0.6392, 0.4314); bodies[8] = createPlanet(&world, "Uranus", -18.76415 * AU, -0.21783 * AU, 6.83528 * AU, 0.00000002 * AU, 0, 0.00000004 * AU, 8.681 * pow(10,25), 25.362 * pow(10,6), 0.8314, 0.9804, 0.9922); bodies[9] = createPlanet(&world, "Neptune", -28.07048 * AU, -0.42924 * AU, -10.42730 * AU, -0.00000002 * AU, 0, 0.0000003 * AU, 1.024 * pow(10,26), 24.622 * pow(10,6), 0.2, 0.2902, 0.7451); bodies[10] = createPlanet(&world, "Pluto", -8.88081 * AU, 0.86973 * AU, -31.76914 * AU, -0.00000003 * AU, -0.00000001 * AU, 0.0000001 / 41.0 * AU, 1.309 * pow(10,22), 1.186 * pow(10, 6), 0.7137, 0.6824, 0.6314); double mat4d_projection[4][4] = MATRIX_IDENTITY_4; mat4dProjection(M_PI / 2.0, 16.0/9.0, pow(10,6), pow(10,13), mat4d_projection); unsigned int parent = 3; Camera camera; makeCamera(&camera, 0, 0, pow(10, 9), &world, bodies[parent]); double mat4d_camera[4][4] = MATRIX_IDENTITY_4; float mat4_camera[4][4]; double sensitivity = 0.005; printf("Starting main loop\n"); while (!glfwWindowShouldClose(window)) { clearInput(); glfwPollEvents(); //rotate or zoom out the camera depending on camera movement and scrolling double dx, dy, dz; getMouseDelta(&dx, &dy, &dz); updateCamera(&camera, dx * sensitivity, dy * sensitivity, dz); if (getClicked()) { if(++parent > 10) parent = 0; changeCameraParent(&camera, pow(10, 9), &world, bodies[parent]); } timestepCounter += getTimeStepChange(); if (timestepCounter > 6) timestepCounter = 0; else if (timestepCounter < 0) timestepCounter = 6; setTimeStep(timesteps[timestepCounter]); //get the time since the last frame to do proper delta-timing for the gravitational attraction and movement double delta = timeTick(); updateWorld(&world, delta); getCameraMatrix(&camera, mat4d_camera); double modelView[4][4]; mat4dMlt(mat4d_projection, mat4d_camera, modelView); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(programID); glBindVertexArray(vao); glEnableVertexAttribArray(0); //For each of the objects in the world, loop through them and render them if they have a position and radius, //rendering works by rendering the same sphere over and over, with a different translation and scale //because all objects in this program are spheres for (int i = 0; i < WORLD_MAX_ENTITIES; ++i) { if (isEntity(&world, i, COMPONENT_POSITION | COMPONENT_RADIUS)) { /*double pos[4] = {world.position[i].position[0], world.position[i].position[1], world.position[i].position[2], 1}; vec4dMltMat(mat4d_camera, pos, pos); double distance = vec3dLength(pos); printf("%i: %f\n", i, distance); double mat4d_model[4][4] = MATRIX_IDENTITY_4; double radius = world.radius[i].radius; double scaleFactor = distance * (1 / pow(radius,2)); printf("Scale factor: %f\n", scaleFactor); if (scaleFactor > pow(10,-3)) { printf("Has been scaled\n"); radius = radius / scaleFactor; } printf("Radius: %f\n", radius);*/ double mat4d_model[4][4] = MATRIX_IDENTITY_4; double radius = world.radius[i].radius; double scale[3] = {radius, radius, radius}; mat4dGenScale(scale, mat4d_model); mat4dTranslate(world.position[i].position, mat4d_model); double modelViewProjection[4][4]; mat4dMlt(modelView, mat4d_model, modelViewProjection); float modelViewProjectionf[4][4]; doubleToSingle(modelViewProjection[0], modelViewProjectionf[0], 16); double color[3] = {1,1,1}; if (isEntity(&world, i, COMPONENT_COLOR)) { vec3dSetEqual(world.color[i].color, color); } float colorf[3]; doubleToSingle(color, colorf, 3); GLint colorLoc = glGetUniformLocation(programID, "in_color"); glUniform3fv(colorLoc, 1, colorf); GLint mvpLoc = glGetUniformLocation(programID, "mvp"); glUniformMatrix4fv(mvpLoc, 1, GL_FALSE, modelViewProjectionf[0]); glDrawElements(GL_TRIANGLES, sphere_num_indices, GL_UNSIGNED_INT, 0); } } glDisableVertexAttribArray(0); glBindVertexArray(0); glfwSwapBuffers(window); } glfwDestroyWindow(window); glfwTerminate(); return 0; }
void GameScene::initGame() { blockVertexShader=new QGLShader(QGLShader::Vertex); blockVertexShader->compileSourceFile(QLatin1String(":/res/divinecraft/shader/block.vsh")); blockFragmentShader=new QGLShader(QGLShader::Fragment); blockFragmentShader->compileSourceFile(QLatin1String(":/res/divinecraft/shader/block.fsh")); blockProgram=new QGLShaderProgram; blockProgram->addShader(blockVertexShader); blockProgram->addShader(blockFragmentShader); if(!blockProgram->link()){ qWarning("Failed to compile and link shader program"); qWarning("Vertex shader log:"); qWarning() << blockVertexShader->log(); qWarning() << blockFragmentShader->log(); qWarning("Shader program log:"); qWarning() << blockProgram->log(); QMessageBox::warning(0,tr("错误"),tr("着色器程序加载失败造成游戏无法正常启动\n" "请联系开发者寻求解决方案"),QMessageBox::Ok); exit(1); } lineVertexShader=new QGLShader(QGLShader::Vertex); lineVertexShader->compileSourceFile(QLatin1String(":/res/divinecraft/shader/line.vsh")); lineFragmentShader=new QGLShader(QGLShader::Fragment); lineFragmentShader->compileSourceFile(QLatin1String(":/res/divinecraft/shader/line.fsh")); lineProgram=new QGLShaderProgram; lineProgram->addShader(lineVertexShader); lineProgram->addShader(lineFragmentShader); if(!lineProgram->link()){ qWarning("Failed to compile and link shader program"); qWarning("Vertex shader log:"); qWarning() << lineVertexShader->log(); qWarning() << lineFragmentShader->log(); qWarning("Shader program log:"); qWarning() << lineProgram->log(); QMessageBox::warning(0,tr("错误"),tr("着色器程序加载失败造成游戏无法正常启动\n" "请联系开发者寻求解决方案"),QMessageBox::Ok); exit(1); } //////////////////////////// camera=new Camera(QVector3D(0,4,0),QPointF(180.0,0.0)); world=new World; wThread=new QThread; world->moveToThread(wThread); connect(wThread,SIGNAL(finished()),world,SLOT(deleteLater())); //线程被销毁的同时销毁world connect(this,SIGNAL(reloadWorld()),world,SLOT(forcedUpdateWorld())); //强制进行世界刷新 connect(camera,SIGNAL(cameraMove(QVector3D)),world,SLOT(changeCameraPosition(QVector3D))); //连接camera移动与世界相机位移的槽 connect(this,SIGNAL(resetRenderLen()),world,SLOT(updateWorld())); connect(this,SIGNAL(addBlock()),camera,SLOT(addBlock())); connect(this,SIGNAL(removeBlock()),camera,SLOT(removeBlock())); connect(world,SIGNAL(loadOver()),this,SLOT(loadOverSlot())); wThread->start(); // world->setMaxRenderLen(maxRenderLen); world->setWorldName("new_world"); camera->setWorld(world); //传递世界指针 /////////////////////////// //这里是一个规定的加载顺序,后步骤会依赖于前步骤 world->loadBlockIndex(); //加载方块属性列表 loadTexture(); //加载纹理 //====================== line=new LineMesh(2); //十字准心 float lineLen=0.0004; line->addLine(QVector3D(-lineLen,0,-0.02),QVector3D(lineLen,0,-0.02)); line->addLine(QVector3D(0,-lineLen,-0.02),QVector3D(0,lineLen,-0.02)); lineQua=new LineMesh(12); //被选方块的包围线框 //======================= //数据面板 dataPanel=new DataPanel(0,0,200,100); addItem(dataPanel); glFps=0; drawCount=0; dataPanel->setRenderLen(maxRenderLen); connect(camera,SIGNAL(getPositions(QVector3D,QVector3D)),this,SLOT(dataShowPosition(QVector3D,QVector3D))); // dataPanel->hide(); //背包物品栏 backPackBar=new BackPackBar(this); hideBackPackBar(); backPackBar->setWorld(world); //传递world指针 //物品栏 itemBar=new ItemBar(this); connect(itemBar,SIGNAL(thingIndexChange(int)),camera,SLOT(setBlockId(int))); backPackBar->setPocket(itemBar); //======================= //消息面板 messagePanel=new MessagePanel; addItem(messagePanel); //=========================== //选项菜单 opWidget=new OptionsWidget(); opWidgetProxy=new QGraphicsProxyWidget(0); opWidgetProxy->setWidget(opWidget); this->addItem(opWidgetProxy); opWidgetProxy->hide(); inOpWidget=false; connect(opWidget,SIGNAL(continueGame()),this,SLOT(continueGame())); connect(opWidget,SIGNAL(mouseLevelValueChange(int)),camera,SLOT(setMouseLevel(int))); connect(opWidget,SIGNAL(renderValueChange(int)),this,SLOT(setRenderLen(int))); connect(opWidget,SIGNAL(quitClick()),gView,SLOT(close())); //============================= loadSettings(); camera->loadPosRot(); //加载位置视角信息 setRenderLen(maxRenderLen); //设置渲染距离并刷新整个世界 opWidget->setRenderLen(maxRenderLen); opWidget->setMouseLevel(camera->getMouseLevel()); }
void CMapWidget::updateTile(int x, int y, CEditableMap::UpdateType type) { if (m_map == 0) return; // This is a bit messy and not very DRY ... int screenX = screenXForPos(x, y); int screenY = screenYForPos(y); CMap::ObjectType toPreview = m_currentTool->typesToPreview(); if (type & CEditableMap::HighlightUpdate) { updateWorld(screenX + 2, screenY + 63, 62, 32); } // Get the floor in one place int floorNum = -1; int offsetX = 0, offsetY = 0; if (type & (CEditableMap::FloorUpdate | CEditableMap::ItemUpdate)) { floorNum = m_map->floors[x][y]; if (toPreview & CMap::Floor) floorNum = m_currentTool->whatThingFor(CMap::Floor, x, y, floorNum); floorNum = m_map->randomisedFloor(x, y, floorNum); if (m_patches->floors.exists(floorNum)) { const CShape &shape = m_patches->floors[floorNum]; const CFrame &frame = shape.frames.first(); offsetX = frame.furrePosX; offsetY = frame.furrePosY; } } if (type & CEditableMap::FloorUpdate) { if (m_patches->floors.exists(floorNum)) { const CShape &shape = m_patches->floors[floorNum]; const CFrame &frame = shape.frames.first(); updateWorld(screenX + frame.posX, screenY + frame.posY, frame.pixmap.width(), frame.pixmap.height()); } // As it turns out, if we refresh the floor, it's a good idea to // also refresh the item... because its position could have changed // if the floor had a furrepos set. type = (CEditableMap::UpdateType)(type | CEditableMap::ItemUpdate); } if (type & CEditableMap::ItemUpdate) { int num = m_map->items[x][y]; if (toPreview & CMap::Item) num = m_currentTool->whatThingFor(CMap::Item, x, y, num); num = m_map->randomisedItem(x, y, num); if (num > 0 && m_patches->items.exists(num)) { const CShape &shape = m_patches->items[num]; const CFrame &frame = shape.frames.first(); updateWorld(screenX + frame.posX + offsetX, screenY + frame.posY + offsetY, frame.pixmap.width(), frame.pixmap.height()); } } if (type & CEditableMap::LeftWallUpdate) { int num = m_map->walls[x*2][y]; if (toPreview & CMap::LeftWall) num = m_currentTool->whatThingFor(CMap::LeftWall, x*2, y, num); num = m_patches->wallIndexer.imageNumForShape(num) + 1; if (num >= 1 && m_patches->walls.exists(num)) { const CShape &shape = m_patches->walls[num]; const CFrame &frame = shape.frames.first(); updateWorld(screenX + frame.posX - 16, screenY + frame.posY - 8, frame.pixmap.width(), frame.pixmap.height()); } } if (type & CEditableMap::RightWallUpdate) { int num = m_map->walls[x*2+1][y]; if (toPreview & CMap::RightWall) num = m_currentTool->whatThingFor(CMap::RightWall, x*2+1, y, num); num = m_patches->wallIndexer.imageNumForShape(num); if (num >= 0 && m_patches->walls.exists(num)) { const CShape &shape = m_patches->walls[num]; const CFrame &frame = shape.frames.first(); updateWorld(screenX + frame.posX + 16, screenY + frame.posY - 8, frame.pixmap.width(), frame.pixmap.height()); } } if (type & CEditableMap::RegionUpdate) { int num = m_map->regions[x][y]; if (toPreview & CMap::Region) num = m_currentTool->whatThingFor(CMap::Region, x, y, num); num = m_patches->regionIndexer.imageNumForShape(num); if (num >= 0 && m_patches->regions.exists(num)) { const CShape &shape = m_patches->regions[num]; const CFrame &frame = shape.frames.first(); updateWorld(screenX + frame.posX, screenY + frame.posY, frame.pixmap.width(), frame.pixmap.height()); } } if (type & CEditableMap::EffectUpdate) { int num = m_map->effects[x][y]; if (toPreview & CMap::Effect) num = m_currentTool->whatThingFor(CMap::Effect, x, y, num); if (num > 0 && m_patches->effects.exists(num)) { const CShape &shape = m_patches->effects[num]; const CFrame &frame = shape.frames.first(); updateWorld(screenX + frame.posX, screenY + frame.posY, frame.pixmap.width(), frame.pixmap.height()); } } }