mat33 sprite::transformation_matrix() const { if (shape::has_transformation_matrix()) return shape::transformation_matrix(); auto az = physics().angle_radians()[2]; auto pos = physics().position(); return mat33{ { std::cos(az), -std::sin(az), 0.0 },{ std::sin(az), std::cos(az), 0.0 },{ pos[0], pos[1], 1.0 } }; }
std::array<rocks_in_space::physics, 2> rocks_in_space::physics::divide(std::mt19937& gen, std::uniform_real_distribution<float>& zero_to_one) const { auto polar = car_to_pol(m_velocity); auto r = polar.r(); auto r1 = r * (1.2F + zero_to_one(gen)); auto r2 = r * (1.2F + zero_to_one(gen)); auto theta1 = polar.theta() + (zero_to_one(gen) - eighth_tau<float>); auto theta2 = polar.theta() + (zero_to_one(gen) - eighth_tau<float>); return{ { physics(m_position, pol_to_car({r1, theta1})), physics(m_position, pol_to_car({r2, theta2})) } }; }
bullet(const ng::i_sprite& aParent) : ng::sprite(aParent.container(), ng::colour::Pink2) { shape::set_size(ng::size{ 3.0, 3.0 }); ng::vec3 relativePos = aParent.physics().origin(); relativePos[1] += 18.0; auto tm = aParent.transformation_matrix(); physics().set_position(aParent.physics().position() + tm * relativePos); physics().set_mass(0.016); physics().set_angle_radians(aParent.physics().angle_radians()); physics().set_velocity(tm * ng::vec3{0.0, 360.0, 0.0} + aParent.physics().velocity()); }
int main() { if(!Window::Initialise("Game Technologies", 1280,800,false)) { return Quit(true, "Window failed to initialise!"); } if(!Renderer::Initialise()) { return Quit(true, "Renderer failed to initialise!"); } PhysicsSystem::Initialise(); MyGame* game = new MyGame(); Window::GetWindow().LockMouseToWindow(true); Window::GetWindow().ShowOSPointer(false); bool running = true; std::thread physics(physicsLoop, game, std::ref(running)); while(Window::GetWindow().UpdateWindow() && !Window::GetKeyboard()->KeyDown(KEYBOARD_ESCAPE)){ float msec = Window::GetWindow().GetTimer()->GetTimedMS(); //How many milliseconds since last update? game->UpdateRendering(msec); //Update our 'sybsystem' logic (renderer and physics!) game->UpdateGame(msec); //Update our game logic } running = false; physics.join(); delete game; //Done with our game now...bye bye! return Quit(); }
bool BlockLiquid::onPlace(User* user, int16_t newblock, int32_t x, int8_t y, int32_t z, int map, int8_t direction) { uint8_t oldblock; uint8_t oldmeta; if (!Mineserver::get()->map(map)->getBlock(x, y, z, &oldblock, &oldmeta)) return true; /* move the x,y,z coords dependent upon placement direction */ if (!this->translateDirection(&x,&y,&z,map,direction)) return true; if (!this->isBlockEmpty(x,y,z,map)) return true; direction = user->relativeToBlock(x, y, z); int block = newblock; if (block == ITEM_WATER_BUCKET) newblock = BLOCK_STATIONARY_WATER; if (block == ITEM_LAVA_BUCKET) newblock = BLOCK_STATIONARY_LAVA; Mineserver::get()->map(map)->setBlock(x, y, z, (char)newblock, 0); Mineserver::get()->map(map)->sendBlockChange(x, y, z, (char)newblock, 0); physics(x,y,z,map); return false; }
int main(void) { logOpen(); initXWindows(); init_opengl(); Game game; init(&game); srand(time(NULL)); clock_gettime(CLOCK_REALTIME, &timePause); clock_gettime(CLOCK_REALTIME, &timeStart); int done=0; while (!done) { while (XPending(dpy)) { XEvent e; XNextEvent(dpy, &e); check_resize(&e); check_mouse(&e); done = check_keys(&e); } clock_gettime(CLOCK_REALTIME, &timeCurrent); timeSpan = timeDiff(&timeStart, &timeCurrent); timeCopy(&timeStart, &timeCurrent); physicsCountdown += timeSpan; while (physicsCountdown >= physicsRate) { physics(&game); physicsCountdown -= physicsRate; } render(&game); glXSwapBuffers(dpy, win); } cleanupXWindows(); cleanup_fonts(); logClose(); return 0; }
int main(int argc, char* argv[]) { SceneGraph world(800,600); Physics physics(world); Graphics graphics("Fun with Shapes",800,600,world); EventHandler event_handler(physics,graphics,world); PMovingObject* object = new PElipse(300,100,40, 60, 10); object->set_ay(-150); object->set_vx(40); object->set_vy(300); object->set_dtheta(.2); world.addObject(object); object = new PEquilateralTriangle(400,100,50); object->set_ay(-150); object->set_vx(-40); object->set_vy(300); object->set_dtheta(.1); world.addObject(object); event_handler.startThread(); event_handler.waitForStop(); return 0; }
int play(t_game *game) { Uint8 *keys; int key; char finish; Uint32 timer, elapsed; finish = 1; music(game, "sprites/demacia.mp3"); while (finish) { timer = SDL_GetTicks(); SDL_FillRect(game->sdl.screen, NULL, 0); SDL_PumpEvents(); keys = SDL_GetKeyState(&key); if (physics(&game->darien.darien, game) == 0) gere_key(game, &game->darien.darien.sprite, keys); aff_screen(game); elapsed = SDL_GetTicks() - timer; if (elapsed < 20) SDL_Delay(20 - elapsed); if (keys[SDLK_ESCAPE]) finish = 0; } exit(0); }
static void physics_thread() { /* Now initialize the physics engine. */ cpInitChipmunk(); space = cpSpaceNew(); do { /* But here we do care about the elapsed time. */ synchronize(&oldtime /*,&server_elapsed*/); simple_lock(&physics_lock); physics(world, space); cpSpaceHashEach(space->activeShapes, &draw_player, NULL); //cpSpaceHashEach(space->staticShapes, &draw_static, NULL); simple_unlock(&physics_lock); if(to_remove_array.length > 0) lDestroy(&to_remove_array, remove_unused); } while(!physics_exit_time); lFree(&to_remove_array); cpSpaceFreeChildren(space); cpSpaceFree(space); }
void deriv(double *y ,double *dydx, double t) { state current_state; // To solve for acceleration build a state struct to send to physics engine current_state.x.v.i = y[0]; current_state.v.v.i = y[1]; current_state.x.v.j = y[2]; current_state.v.v.j = y[3]; current_state.x.v.k = y[4]; current_state.v.v.k = y[5]; current_state.a.v.i = dydx[1]; current_state.a.v.j = dydx[3]; current_state.a.v.k = dydx[5]; current_state.m = y[6]; // Do Physics to current state: state_change deriv_state = physics(current_state, t, physics_model); // Build RK vectors from state change // Velocity is single integration of acceleration dydx[0] = y[1]; dydx[2] = y[3]; dydx[4] = y[5]; // Acceleration is from physics model dydx[1] = deriv_state.acc.v.i; dydx[3] = deriv_state.acc.v.j; dydx[5] = deriv_state.acc.v.k; dydx[6] = deriv_state.m_dot; }
Box::Box(b2World& world, float x, float y) { std::shared_ptr<DrawableComponent> drawable(new DrawableComponent(this, "box.png")); components.push_back(drawable); std::shared_ptr<PhysicsComponent> physics(new PhysicsComponent(this, world, x, y)); components.push_back(physics); }
int main(void) { logOpen(); initXWindows(); init_opengl(); init(); init_sounds(); clock_gettime(CLOCK_REALTIME, &timePause); clock_gettime(CLOCK_REALTIME, &timeStart); while(!done) { while(XPending(dpy)) { XEvent e; XNextEvent(dpy, &e); check_resize(&e); check_mouse(&e); check_keys(&e); } // //Below is a process to apply physics at a consistent rate. //1. Get the time right now. clock_gettime(CLOCK_REALTIME, &timeCurrent); //2. How long since we were here last? timeSpan = timeDiff(&timeStart, &timeCurrent); //3. Save the current time as our new starting time. timeCopy(&timeStart, &timeCurrent); //4. Add time-span to our countdown amount. physicsCountdown += timeSpan; //5. Has countdown gone beyond our physics rate? // if yes, // In a loop... // Apply physics // Reducing countdown by physics-rate. // Break when countdown < physics-rate. // if no, // Apply no physics this frame. while(physicsCountdown >= physicsRate) { //6. Apply physics physics(); //7. Reduce the countdown by our physics-rate physicsCountdown -= physicsRate; } //Always render every frame. render(); glXSwapBuffers(dpy, win); } cleanupXWindows(); cleanup_fonts(); #ifdef USE_SOUND fmod_cleanup(); #endif //USE_SOUND logClose(); return 0; }
PhysicsInterface::BodyObject PhysicsInterface::createGeometryBodyFrom2DLineStrip(const Vector<Vec2>& points, float mass, bool fixed, const Entity* entity, const SimpleTransform& initialTransform) { auto vertices = Vector<Vec3>(); auto triangles = Vector<RawIndexedTriangle>(); // Convert 2D line strip to an actual triangle mesh usable as a collision hull for (auto i = 0U; i < points.size(); i++) { vertices.emplace(points[i].x, points[i].y, -10.0f); vertices.emplace(points[i].x, points[i].y, 10.0f); triangles.emplace(i * 2 + 0, i * 2 + 1, ((i + 1) % points.size()) * 2 + 0); triangles.emplace(i * 2 + 1, ((i + 1) % points.size()) * 2 + 1, ((i + 1) % points.size()) * 2 + 0); } return physics().createGeometryBodyFromTemplate( physics().createBodyTemplateFromGeometry(vertices, triangles, true, 0.5f), mass, fixed, nullptr, initialTransform); }
int main(void) { int done=0; srand(time(NULL)); initXWindows(); init_opengl(); //declare game object Game game; game.n=0; clock_gettime(CLOCK_REALTIME, &timePause); clock_gettime(CLOCK_REALTIME, &timeStart); //declare a box shape for(int i = 0; i<5; i++) { game.box[i].width = 100; game.box[i].height = 15; game.box[i].center.x = 120 + (60*i); game.box[i].center.y = 500 - (100*i); } game.circle.radius = .5; game.circle.center.x = 60 + 9*65; game.circle.center.y = 450- 8*60; //start animation while(!done) { while(XPending(dpy)) { XEvent e; XNextEvent(dpy, &e); check_mouse(&e, &game); done = check_keys(&e, &game); } clock_gettime(CLOCK_REALTIME, &timeCurrent); timeSpan = timeDiff(&timeStart, &timeCurrent); timeCopy(&timeStart, &timeCurrent); physicsCountdown += timeSpan; while(physicsCountdown >= physicsRate) { physics(&game); physicsCountdown -= physicsRate; } movement(&game); render(&game); glXSwapBuffers(dpy, win); } cleanupXWindows(); return 0; }
// FUNCTION ====== draw void draw(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); Vec3d oldPos; oldPos.set( body.pos ); //printVec( oldPos ); printf(" // oldPos \n"); /* printf("invIbody\n"); printMat(rbody.invIbody); printf("invI\n"); printMat(rbody.invI); printf("rotMat\n"); printMat(rbody.rotMat); printQuat(rbody.qrot ); printf("qrot\n"); printVec(rbody.L ); printf("L\n"); printVec(rbody.omega); printf("omega\n"); printVec(rbody.pos ); printf("pos\n"); */ physics(); // ALL PHYSICS COMPUTATION DONE HERE camera (); //drawLine( oldPos, body.pos ); glEnable (GL_LIGHTING); glShadeModel(GL_FLAT); rbody.render(); rbody2.render(); glColor3f( 0, 0, 0); constrain1->render(); /* printf("invI\n"); printMat(rbody.invI); printf("rotMat\n"); printMat(rbody.rotMat); printQuat(rbody.qrot ); printf("qrot\n"); printVec(rbody.L ); printf("L\n"); printVec(rbody.omega); printf("omega\n"); printVec(rbody.pos ); printf("pos\n"); quit(); */ drawAxis( 5 ); glFinish(); SDL_GL_SwapBuffers(); }
void play(void) // Our Budding Game Engine { uint16_t i; i = 100; enSet(0, 500, 1, 1, enNONCIRC, enU16, &i); while(1){ // Check wether key press is Q if so exit loop moveball(); physics(); enGet(); //EN delay_ms(i); // Reduce game speed to human playable level } }
nxBaseGameLogic::nxBaseGameLogic(nxGameOptions const &options) { m_LastActorId = 0; m_pProcessManager = NX_NEW nxProcessManager; m_State = NX_GS_Initializing; m_bProxy = false; m_RenderDiagnostics = false; m_NRemotePlayers = 0; m_ExpectedRemotePlayers = options.nNetPlayers; m_ExpectedAI = 0; shared_ptr<nxIPhysics> physics(NX_NEW nxPhysics()); m_pPhysics = physics; //TODO : AI // m_pAiEventListener = nxEventListenerPtr (NX_NEW nxAiEventListener ( )); // safeAddListener(m_pAiEventListener, nxEvtData_AiSteer::sk_EventType); }
int main() { Verlet v; Physics physics(&v); // Design some behaviours for particles Attraction avoidMouse; Attraction pullToCenter; pullToCenter.target._x = 50.0; pullToCenter.target._y = 50.0; pullToCenter.setStrength(120); avoidMouse.setRadius(60); avoidMouse.setStrength(-1000); // Allow particle collisions to make things interesting Collision collision; for (int i = 0; i < 20; i++) { //Create a particle Particle* particle = new Particle(); Vector position(i, 2*i); particle->setRadius(particle->_mass * 10); particle->moveTo(position); // Make it collidable collision.pool.append(particle); // Apply behaviours particle->behaviours.append(&avoidMouse); particle->behaviours.append(&pullToCenter); particle->behaviours.append(&collision); // Add to the simulation physics.particles.append(particle); } while(1) physics.step(); return 0; }
bool PlatformerEntityController::jump(float height, float time) { if (isJumping() || !getEntity() || !getEntity()->hasCharacterController()) return false; // Can only jump when there is a surface beneath the player auto collisionNormal = Vec3(); if (!physics().getCharacterControllerDownAxisCollision(getEntity()->characterController_, collisionNormal)) return false; // Can't launch off surfaces steeper than 45 degrees if (collisionNormal.dot(Vec3::UnitY) < 0.707f) return false; isJumping_ = true; jumpStartTime_ = platform().getTime(); jumpHeight_ = height; jumpTime_ = time; return true; }
int main(void) { logOpen(); initXWindows(); init_opengl(); init(); //buttonsInit();------------------------------------------------------------------ init_sounds(); clock_gettime(CLOCK_REALTIME, &timePause); clock_gettime(CLOCK_REALTIME, &timeStart); while(!done) { while(XPending(dpy)) { XEvent e; XNextEvent(dpy, &e); check_resize(&e); check_mouse(&e); GOcheck_mouse(&e); check_keys(&e); } clock_gettime(CLOCK_REALTIME, &timeCurrent); timeSpan = timeDiff(&timeStart, &timeCurrent); timeCopy(&timeStart, &timeCurrent); physicsCountdown += timeSpan; while(physicsCountdown >= physicsRate) { physics(); physicsCountdown -= physicsRate; } render(); glXSwapBuffers(dpy, win); } cleanupXWindows(); cleanup_fonts(); #ifdef USE_SOUND fmod_cleanup(); #endif //USE_SOUND logClose(); return 0; }
void RDSolver::config_mesh() { if( is_null(m_mesh) ) return; Mesh& mesh = *(m_mesh); physics::PhysModel& pm = physics(); // physcial model must have already been configured if( pm.ndim() != mesh.dimension() ) throw SetupError( FromHere(), "Dimensionality mismatch. Loaded mesh ndim " + to_str(mesh.dimension()) + " and physical model dimension " + to_str(pm.ndim()) ); // setup the fields prepare_mesh().configure_option_recursively( RDM::Tags::mesh(), m_mesh ); // trigger config_mesh() prepare_mesh().execute(); // configure all other subcomponents with the mesh boost_foreach( Component& comp, find_components(*this) ) comp.configure_option_recursively( RDM::Tags::mesh(), m_mesh ); }
void bubblesTask(void *pvParameters){ uint16_t old_val_encoder = enGeReg(); uiGraphicsColor = black; uiTextColor = RGB; lcd_Clear(); initialize(); while(1){ moveball(); physics(); //======== обработка кнопок ========// if(BtScan() || (old_val_encoder != enGeReg())){ // BeepTime(100); xTaskCreate(baseTSK, "baseTSK", BASE_TSK_SZ_STACK, NULL, 2, NULL); vTaskDelete(NULL); //”дал¤ем текущую задачу } vTaskDelay(60); } }
void RDSolver::config_physics() { try { PhysModel& pm = physics(); std::string user_vars = options().option( RDM::Tags::update_vars() ).value<std::string>(); if( user_vars.empty() ) return; Handle< Variables > upv(find_component_ptr_with_tag(pm, RDM::Tags::update_vars())); if( is_not_null(upv) ) // if exits insure is the good one { if( upv->type() != user_vars ) { pm.remove_component(upv->name() ); upv.reset(); } } if( is_null(upv) ) pm.create_variables( user_vars, RDM::Tags::update_vars() ); boost_foreach( Component& comp, find_components(*this) ) comp.configure_option_recursively( RDM::Tags::physical_model(), pm.handle<PhysModel>() ); // load the library which has the correct RDM physics std::string modeltype = pm.model_type(); boost::to_lower( modeltype ); OSystem::instance().lib_loader()->load_library( "coolfluid_rdm_" + modeltype ); } catch(SetupError&) { // Do nothing if physmodel is not configured } }
int main(void) { initXWindows(); srand(time(NULL)); clock_gettime(CLOCK_REALTIME, &timePause); clock_gettime(CLOCK_REALTIME, &timeStart); init_opengl(); init_ship(); //Do this to allow fonts glEnable(GL_TEXTURE_2D); initialize_fonts(); init_textures(); while(!done) { while(XPending(dpy)) { XEvent e; XNextEvent(dpy, &e); check_resize(&e); check_mouse(&e); check_keys(&e); } clock_gettime(CLOCK_REALTIME, &timeCurrent); timeSpan = timeDiff(&timeStart, &timeCurrent); timeCopy(&timeStart, &timeCurrent); physicsCountdown += timeSpan; while (physicsCountdown >= physicsRate) { physics(); physicsCountdown -= physicsRate; render(); } //physics(); //render(); glXSwapBuffers(dpy, win); } cleanupXWindows(); cleanup_fonts(); return 0; }
void Game::run() { sf::Clock clock; sf::Time timeSinceLastUpdate = sf::Time::Zero; while (mWindow.isOpen()) { sf::Time elapsedTime = clock.restart(); timeSinceLastUpdate += elapsedTime; while (timeSinceLastUpdate > TimePerFrame) { timeSinceLastUpdate -= TimePerFrame; if (use_gp) processGamepad(); processEvents(); update(TimePerFrame); physics(TimePerFrame); animator(TimePerFrame); } render(); } }
void player1::update() { if (_pause == false) { if (_isDamaged == false) control(); physics(); pixelCollision(); control2(); attack(); invincibilityCount(); CAMERAMANAGER->setSingleFocus(_x, _y, WINSIZEX); } if (_currentHP <= 0 && _isDead == false) { _frameX = 0; _isDead = true; } if (_downwardThrust == true) _playerRC = RectMake(_x - HIT_BOX_WIDTH / 2, _y - HIT_BOX_HEIGHT, HIT_BOX_WIDTH, HIT_BOX_HEIGHT - 5); else _playerRC = RectMake(_x - HIT_BOX_WIDTH / 2, _y - HIT_BOX_HEIGHT, HIT_BOX_WIDTH, HIT_BOX_HEIGHT); if (KEYMANAGER->isOnceKeyDown('R')) { if (_isDead == true) SCENEMANAGER->changeScene("GameTitleScene"); } }
// FUNCTION ====== draw void draw() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); //glDepthMask(0); glDisable (GL_LIGHTING); glShadeModel(GL_SMOOTH); float skysz = 5000.0; glBegin(GL_QUADS); glColor3f( 0.1, 0.1, 0.5 ); glVertex3f( -skysz, skysz, -skysz ); glColor3f( 0.1, 0.1, 0.5 ); glVertex3f( -skysz, skysz, +skysz ); glColor3f( 0.1, 0.1, 0.5 ); glVertex3f( +skysz, skysz, +skysz ); glColor3f( 0.1, 0.1, 0.5 ); glVertex3f( +skysz, skysz, -skysz ); glColor3f( 0.3, 0.5, 0.5 ); glVertex3f( -skysz, 0, -skysz ); glColor3f( 0.3, 0.5, 0.5 ); glVertex3f( -skysz, 0, +skysz ); glColor3f( 0.1, 0.1, 0.5 ); glVertex3f( -skysz, skysz, +skysz ); glColor3f( 0.1, 0.1, 0.5 ); glVertex3f( -skysz, skysz, -skysz ); glColor3f( 0.3, 0.5, 0.5 ); glVertex3f( +skysz, 0, -skysz ); glColor3f( 0.3, 0.5, 0.5 ); glVertex3f( +skysz, 0, +skysz ); glColor3f( 0.1, 0.1, 0.5 ); glVertex3f( +skysz, skysz, +skysz ); glColor3f( 0.1, 0.1, 0.5 ); glVertex3f( +skysz, skysz, -skysz ); glColor3f( 0.3, 0.5, 0.5 ); glVertex3f( -skysz, 0, -skysz ); glColor3f( 0.3, 0.5, 0.5 ); glVertex3f( +skysz, 0, -skysz ); glColor3f( 0.1, 0.1, 0.5 ); glVertex3f( +skysz, skysz, -skysz ); glColor3f( 0.1, 0.1, 0.5 ); glVertex3f( -skysz, skysz, -skysz ); glColor3f( 0.3, 0.5, 0.5 ); glVertex3f( -skysz, 0, +skysz ); glColor3f( 0.3, 0.5, 0.5 ); glVertex3f( +skysz, 0, +skysz ); glColor3f( 0.1, 0.1, 0.5 ); glVertex3f( +skysz, skysz, +skysz ); glColor3f( 0.1, 0.1, 0.5 ); glVertex3f( -skysz, skysz, +skysz ); glEnd(); //glDepthMask(1); physics(); // ALL PHYSICS COMPUTATION DONE HERE /* printQuat( myCraft.qrot ); printf("qrot\n"); printVec( myCraft.force ); printf("force\n"); printVec( myCraft.torq ); printf("torq\n"); printVec( myCraft.L ); printf("L\n"); printVec( myCraft.omega ); printf("omega\n"); printf("invI\n"); printMat( myCraft.invI ); printf("rotMat\n"); printMat( myCraft.rotMat ); */ camera (); glEnable (GL_LIGHTING); glShadeModel(GL_FLAT); myCraft.render(); // terrain float groundsz = 10000.0; glBegin(GL_QUADS); glColor3f( 0.3, 0.6, 0.1 ); glNormal3f(0,1,0); glVertex3f( -groundsz, 0, -groundsz ); glVertex3f( +groundsz, 0, -groundsz ); glVertex3f( +groundsz, 0, +groundsz ); glVertex3f( -groundsz, 0, +groundsz ); glEnd(); if (buildings>0) glCallList( buildings ); drawAxis( 5 ); glFinish(); SDL_GL_SwapBuffers(); }
int main(int argc, char *argv[]) { if(argc > 1) { if(argv[1] != NULL) { beginTesting(); } return 0; } logOpen(); initXWindows(); init_opengl(); Game game; init(&game); srand(time(NULL)); clock_gettime(CLOCK_REALTIME, &timePause); clock_gettime(CLOCK_REALTIME, &timeStart); hud = new Hud(xres ,yres); if (TEST_Hud){ hud->testHUDAll(); return 0; } //DEFUALT IS LEVEL 1 SELECTED: selected_screen = LEFT; level =1; //-------------- is_gameover = false; high_score = 0; gameStarted = false; lastPaddleHit = 'N';//'N' means no paddle hit bombBegin = time(NULL); bombRandom = random(7); beginSmallLeftPaddle = time(NULL); smallLeftPaddleTime = 7; beginSmallRightPaddle = time(NULL); smallRightPaddleTime = 7; hud->setAI(false);//DEFAULT: player2 is human ball_saved_X_velocity = 8.0f * cos(30); ball_saved_Y_velocity = 8.0f * sin(90); obstacle_saved_Y_velocity = -5.0; int min; if (xres<yres){ min=xres; } else{ min=yres; } bomb_radius = ((int)(3*min)/10); //MAIN MENU LOOP while(intro != 0) { while (XPending(dpy)) { XEvent e; XNextEvent(dpy, &e); check_resize(&e); intro = check_keys(&e, &game); } render(&game); glXSwapBuffers(dpy, win); } //BEGIN MAIN GAME LOOP int done=0; while (!done) { while (XPending(dpy)) { XEvent e; XNextEvent(dpy, &e); check_resize(&e); done = check_keys(&e, &game); } clock_gettime(CLOCK_REALTIME, &timeCurrent); timeSpan = timeDiff(&timeStart, &timeCurrent); timeCopy(&timeStart, &timeCurrent); physicsCountdown += timeSpan; while (physicsCountdown >= physicsRate) { physics(&game); physicsCountdown -= physicsRate; } render(&game); glXSwapBuffers(dpy, win); } cleanupXWindows(); cleanup_fonts(); logClose(); return 0; }
bool Mineserver::run() { uint32_t starttime = (uint32_t)time(0); uint32_t tick = (uint32_t)time(0); // load plugins if (config()->has("system.plugins") && (config()->type("system.plugins") == CONFIG_NODE_LIST)) { std::list<std::string> tmp = config()->mData("system.plugins")->keys(); for (std::list<std::string>::const_iterator it = tmp.begin(); it != tmp.end(); ++it) { std::string path = config()->sData("system.path.plugins"); std::string name = config()->sData("system.plugins." + (*it)); std::string alias = *it; if (name[0] == '_') { path = ""; alias = name; name = name.substr(1); } plugin()->loadPlugin(name, path, alias); } } // Initialize map for (int i = 0; i < (int)m_map.size(); i++) { physics(i)->enabled = (config()->bData("system.physics.enabled")); m_map[i]->init(i); if (config()->bData("map.generate_spawn.enabled")) { LOG2(INFO, "Generating spawn area..."); int size = config()->iData("map.generate_spawn.size"); bool show_progress = config()->bData("map.generate_spawn.show_progress"); #ifdef __FreeBSD__ show_progress = false; #endif #ifdef WIN32 DWORD t_begin = 0, t_end = 0; #else clock_t t_begin = 0, t_end = 0; #endif for (int x = -size; x <= size; x++) { if (show_progress) { #ifdef WIN32 t_begin = timeGetTime(); #else t_begin = clock(); #endif } for (int z = -size; z <= size; z++) { m_map[i]->loadMap(x, z); } if (show_progress) { #ifdef WIN32 t_end = timeGetTime(); LOG2(INFO, dtos((x + size + 1) *(size * 2 + 1)) + "/" + dtos((size * 2 + 1) *(size * 2 + 1)) + " done. " + dtos((t_end - t_begin) / (size * 2 + 1)) + "ms per chunk"); #else t_end = clock(); LOG2(INFO, dtos((x + size + 1) *(size * 2 + 1)) + "/" + dtos((size * 2 + 1) *(size * 2 + 1)) + " done. " + dtos(((t_end - t_begin) / (CLOCKS_PER_SEC / 1000)) / (size * 2 + 1)) + "ms per chunk"); #endif } } } #ifdef DEBUG LOG(DEBUG, "Map", "Spawn area ready!"); #endif } // Initialize packethandler packetHandler()->init(); // Load ip from config const std::string ip = config()->sData("net.ip"); // Load port from config const int port = config()->iData("net.port"); #ifdef WIN32 WSADATA wsaData; int iResult; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { LOG2(ERROR, std::string("WSAStartup failed with error: " + iResult)); return false; } #endif struct sockaddr_in addresslisten; int reuse = 1; m_eventBase = reinterpret_cast<event_base*>(event_init()); #ifdef WIN32 m_socketlisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); #else m_socketlisten = socket(AF_INET, SOCK_STREAM, 0); #endif if (m_socketlisten < 0) { LOG2(ERROR, "Failed to create listen socket"); return false; } memset(&addresslisten, 0, sizeof(addresslisten)); addresslisten.sin_family = AF_INET; addresslisten.sin_addr.s_addr = inet_addr(ip.c_str()); addresslisten.sin_port = htons(port); setsockopt(m_socketlisten, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse)); // Bind to port if (bind(m_socketlisten, (struct sockaddr*)&addresslisten, sizeof(addresslisten)) < 0) { LOG2(ERROR, "Failed to bind to " + ip + ":" + dtos(port)); return false; } if (listen(m_socketlisten, 5) < 0) { LOG2(ERROR, "Failed to listen to socket"); return false; } setnonblock(m_socketlisten); event_set(&m_listenEvent, m_socketlisten, EV_WRITE | EV_READ | EV_PERSIST, accept_callback, NULL); event_add(&m_listenEvent, NULL); LOG2(INFO, "Listening on: "); if (ip == "0.0.0.0") { // Print all local IPs char name[255]; gethostname(name, sizeof(name)); struct hostent* hostinfo = gethostbyname(name); int ipIndex = 0; while (hostinfo && hostinfo->h_addr_list[ipIndex]) { const std::string ip(inet_ntoa(*(struct in_addr*)hostinfo->h_addr_list[ipIndex++])); LOG2(INFO, ip + ":" + dtos(port)); } } else { LOG2(INFO, ip + ":" + dtos(port)); } timeval loopTime; loopTime.tv_sec = 0; loopTime.tv_usec = 200000; // 200ms m_running = true; event_base_loopexit(m_eventBase, &loopTime); // Create our Server Console user so we can issue commands time_t timeNow = time(NULL); while (m_running && event_base_loop(m_eventBase, 0) == 0) { event_base_loopexit(m_eventBase, &loopTime); // Run 200ms timer hook static_cast<Hook0<bool>*>(plugin()->getHook("Timer200"))->doAll(); // Alert any block types that care about timers for (size_t i = 0 ; i < plugin()->getBlockCB().size(); ++i) { const BlockBasicPtr blockcb = plugin()->getBlockCB()[i]; if (blockcb != NULL) { blockcb->timer200(); } } //Update physics every 200ms for (std::vector<Map*>::size_type i = 0 ; i < m_map.size(); i++) { physics(i)->update(); } //Every 10 seconds.. timeNow = time(0); if (timeNow - starttime > 10) { starttime = (uint32_t)timeNow; //Map saving on configurable interval if (m_saveInterval != 0 && timeNow - m_lastSave >= m_saveInterval) { //Save for (std::vector<Map*>::size_type i = 0; i < m_map.size(); i++) { m_map[i]->saveWholeMap(); } m_lastSave = timeNow; } // If users, ping them if (!User::all().empty()) { // Send server time Packet pkt; pkt << (int8_t)PACKET_TIME_UPDATE << (int64_t)m_map[0]->mapTime; (*User::all().begin())->sendAll(pkt); } //Check for tree generation from saplings for (size_t i = 0; i < m_map.size(); ++i) { m_map[i]->checkGenTrees(); } // TODO: Run garbage collection for chunk storage dealie? // Run 10s timer hook static_cast<Hook0<bool>*>(plugin()->getHook("Timer10000"))->doAll(); } // Every second if (timeNow - tick > 0) { tick = (uint32_t)timeNow; // Loop users for (std::set<User*>::const_iterator it = users().begin(); it != users().end(); ++it) { // No data received in 30s, timeout if ((*it)->logged && timeNow - (*it)->lastData > 30) { LOG2(INFO, "Player " + (*it)->nick + " timed out"); delete *it; } else if (!(*it)->logged && timeNow - (*it)->lastData > 100) { delete (*it); } else { if (m_damage_enabled) { (*it)->checkEnvironmentDamage(); } (*it)->pushMap(); (*it)->popMap(); } } for (std::vector<Map*>::size_type i = 0 ; i < m_map.size(); i++) { m_map[i]->mapTime += 20; if (m_map[i]->mapTime >= 24000) { m_map[i]->mapTime = 0; } } for (std::set<User*>::const_iterator it = users().begin(); it != users().end(); ++it) { (*it)->pushMap(); (*it)->popMap(); } // Check for Furnace activity furnaceManager()->update(); // Run 1s timer hook static_cast<Hook0<bool>*>(plugin()->getHook("Timer1000"))->doAll(); } // Underwater check / drowning // ToDo: this could be done a bit differently? - Fador // -- User::all() == users() - louisdx for (std::set<User*>::const_iterator it = users().begin(); it != users().end(); ++it) { (*it)->isUnderwater(); if ((*it)->pos.y < 0) { (*it)->sethealth((*it)->health - 5); } } } #ifdef WIN32 closesocket(m_socketlisten); #else close(m_socketlisten); #endif saveAll(); event_base_free(m_eventBase); return true; }
btTypedConstraint* ObjectConstraintSlider::getConstraint() { btSliderConstraint* constraint { nullptr }; QUuid otherEntityID; glm::vec3 pointInA; glm::vec3 axisInA; glm::vec3 pointInB; glm::vec3 axisInB; withReadLock([&]{ constraint = static_cast<btSliderConstraint*>(_constraint); pointInA = _pointInA; axisInA = _axisInA; otherEntityID = _otherID; pointInB = _pointInB; axisInB = _axisInB; }); if (constraint) { return constraint; } static int repeatMessageID = LogHandler::getInstance().newRepeatedMessageID(); btRigidBody* rigidBodyA = getRigidBody(); if (!rigidBodyA) { HIFI_FCDEBUG_ID(physics(), repeatMessageID, "ObjectConstraintSlider::getConstraint -- no rigidBodyA"); return nullptr; } if (glm::length(axisInA) < FLT_EPSILON) { qCWarning(physics) << "slider axis cannot be a zero vector"; axisInA = DEFAULT_SLIDER_AXIS; } else { axisInA = glm::normalize(axisInA); } if (!otherEntityID.isNull()) { // This slider is between two entities... find the other rigid body. if (glm::length(axisInB) < FLT_EPSILON) { qCWarning(physics) << "slider axis cannot be a zero vector"; axisInB = DEFAULT_SLIDER_AXIS; } else { axisInB = glm::normalize(axisInB); } glm::quat rotA = glm::rotation(DEFAULT_SLIDER_AXIS, axisInA); glm::quat rotB = glm::rotation(DEFAULT_SLIDER_AXIS, axisInB); btTransform frameInA(glmToBullet(rotA), glmToBullet(pointInA)); btTransform frameInB(glmToBullet(rotB), glmToBullet(pointInB)); btRigidBody* rigidBodyB = getOtherRigidBody(otherEntityID); if (!rigidBodyB) { HIFI_FCDEBUG_ID(physics(), repeatMessageID, "ObjectConstraintSlider::getConstraint -- no rigidBodyB"); return nullptr; } constraint = new btSliderConstraint(*rigidBodyA, *rigidBodyB, frameInA, frameInB, true); } else { // This slider is between an entity and the world-frame. glm::quat rot = glm::rotation(DEFAULT_SLIDER_AXIS, axisInA); btTransform frameInA(glmToBullet(rot), glmToBullet(pointInA)); constraint = new btSliderConstraint(*rigidBodyA, frameInA, true); } withWriteLock([&]{ _constraint = constraint; }); // if we don't wake up rigidBodyA, we may not send the dynamicData property over the network forceBodyNonStatic(); activateBody(); updateSlider(); return constraint; }