예제 #1
0
// threadId of ALL_THREADS means run all threads.  Otherwise, run just the 
// indicated thread.
static void runUntilInterrupt(Core *core, uint32_t threadId, bool enableFbWindow)
{
	fd_set readFds;
	int result;
	struct timeval timeout; 

	FD_ZERO(&readFds);

	while (1)
	{
		if (!executeInstructions(core, threadId, gScreenRefreshRate))
			break;

		if (enableFbWindow)
		{
			updateFramebuffer(getFramebuffer(core));
			pollEvent();
		}

		FD_SET(gClientSocket, &readFds);
		timeout.tv_sec = 0;
		timeout.tv_usec = 0;
		result = select(gClientSocket + 1, &readFds, NULL, NULL, &timeout);
		if ((result < 0 && errno != EINTR) || result == 1)
			break;
	}
}
예제 #2
0
void SDL_Controller::mainLoop()
{
	while (!quitGame)
	{
		if (stateStack.empty())
		{
			pollEvent();
		}
		else
		{
			int result = stateStack.top()->handleEvents();
			if (result == -1)
			{
				quitGame = true;
			}
			else if (result == 0)
			{
				stateStack.pop();
			}
		}
		
		bg.render(renderer, 0, 0);

		if (stateStack.empty())
		{
			snake->update();
		}
		

		if (snake->crash())
		{
			quitGame = true;
		}

		if (snake->getHeadX() == minionX && snake->getHeadY() == minionY)
		{
			snake->addTail();
			score++;
			minionAlive = false;
		}
		if (!minionAlive)
		{
			minionX = (rand() % ((SCREEN_WIDTH - ICON_SIZE) / ICON_SIZE)) * ICON_SIZE;
			minionY = (rand() % ((SCREEN_HEIGHT - ICON_SIZE) / ICON_SIZE)) * ICON_SIZE;
			minionAlive = true;
		}
		snake->draw(renderer);
		minion.render(renderer, minionX, minionY);
		if (!stateStack.empty())
		{
			stateStack.top()->drawState(renderer);
		}
		SDL_RenderPresent(renderer);
		SDL_Delay(FPS_INTERVAL);
	}
	SDL_DestroyWindow(window);
	std::cout << "Thanks for playing! Your score is : " << score << std::endl;
	system("pause");
}
예제 #3
0
파일: event.c 프로젝트: ivokosir/cogh
void pollEvents(Window* w) {
    clearAllEvents(w);

    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        pollEvent(w, event);
    }
}
예제 #4
0
void CWindow::gameTool(CGame *game)
{
    static CFrameCounter counter;
    while(!exit)
    {
        pollEvent();
        game->GameTool(); //wywoluje tylko rendering, nie moze byc w osobnym watku!!!!!!!
        window.display();
        ///counter.count();
    }
}
예제 #5
0
파일: window.cpp 프로젝트: Xackery/ZEQ
void Window::pollInput(double delta)
{
    sf::Event ev;
    
    while (pollEvent(ev))
    {
        if (!m_input.handleEvent(ev))
            m_running = false;
    }
    
    m_input.update(delta);
}
예제 #6
0
void CWindow::renderIntro(bool *done)
{
    static CPoster post(-1,1,2,2);
    post.texId = CTexture("texture/intro.bmp").texId;

    while(!*done and !exit)
    {
        post.draw();
        pollEvent();
        window.display();
    }
}
예제 #7
0
bool KeySource::flushEvents(EventStage& next)
{
    bool more(false);

    pollEvent(next);
    
    mKeyHardware.pressed(KeyHardwareEventHandler::create([&](const KeyHardwareEvent&)
    {
        more = true;
    }));

    return more;
}
예제 #8
0
파일: frame.cpp 프로젝트: silversthem/2f
void Frame::run()
{
	while(isOpen())
	{
		calculate_bounds();
		calculate_mouse_pos();
		while(pollEvent(_event))
		{
			eventHandling();
		}
		drawAll();
	}
}
예제 #9
0
/**
 * Standard event retrieval, which only returns keyboard and mouse clicks
 */
bool EventsClass::getEvent(Event &evt, int eventMask) {
	while (pollEvent() && !_vm->getEventManager()->shouldQuit()) {
		evt.handled = false;
		evt.eventType = EVENT_NONE;
		evt.mousePos = _event.mouse;
		evt.kbd = _event.kbd;

		switch (_event.type) {
		case Common::EVENT_MOUSEMOVE:
			evt.eventType = EVENT_MOUSE_MOVE;
			break;
		case Common::EVENT_LBUTTONDOWN:
			evt.eventType = EVENT_BUTTON_DOWN;
			evt.btnState = BTNSHIFT_LEFT;
			break;
		case Common::EVENT_RBUTTONDOWN:
			evt.eventType = EVENT_BUTTON_DOWN;
			evt.btnState = BTNSHIFT_RIGHT;
			break;
		case Common::EVENT_MBUTTONDOWN:
			evt.eventType = EVENT_BUTTON_DOWN;
			evt.btnState = BTNSHIFT_MIDDLE;
			break;
		case Common::EVENT_LBUTTONUP:
		case Common::EVENT_RBUTTONUP:
		case Common::EVENT_MBUTTONUP:
			evt.eventType = EVENT_BUTTON_UP;
			evt.btnState = 0;
			break;
		case Common::EVENT_KEYDOWN:
			evt.eventType = EVENT_KEYPRESS;
			evt.kbd = _event.kbd;
			break;
		default:
			break;
		}

		if (evt.eventType & eventMask)
			return true;
	}

	evt.handled = false;
	evt.eventType = EVENT_NONE;

	return false;
}
예제 #10
0
int main ( int argc, char * argv[] ) {
	Uint32 time = SDL_GetTicks();
	init();
	loadData();
	long long iterator = 0;

	while ( !quit ) {
		printf( "\tLoop start {\n " );
		Uint32 timePre = time;
		time = SDL_GetTicks();
		dt = ((double)( time - timePre )) / 1000.0;
		printf( "\tEvents\n " );
		pollEvent();
		printf( "\tUpdate\n " );
		update();
		printf( "\tRender\n " );
		render();
		printf( "%i\t} Loop end\n ", iterator++ );
		
	}

	return 0x127;
}
예제 #11
0
void CAppWindow::EnterLoop()
{
    while (isOpen())
    {
        sf::Event event;
        while (pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
            {
                close();
                return;
            }
            m_menu->OnEvent(event);
        }

        clear(sf::Color::Black);
        if (m_state != State::WaitingInput)
        {
            OnRunningDemo();
        }
        draw(*m_menu);
        display();
    }
}
예제 #12
0
int Game::run() {
    while (isOpen() && !mvStates.empty()) {
        sf::Event event;
        while (pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                close();                
            }
        }
        
        if (isOpen()) {
            mvFrameTime = mvFrameClock.restart();
            
            std::deque<StatePtr>::iterator iter;
            for (iter = mvStates.begin(); iter != mvStates.end(); iter++) {
                try {
                    (*iter)->update();
                    if (!mvStates.empty()) {
                        clear();
                        (*iter)->draw();
                        display();
                    }
                } catch (DAException &e) {
                    // If an exception manages to propagate to this level of
                    // operation, we can assume it's pretty severe and we'll
                    // just let ourselves crash.
                    std::cerr << e.message();
                    close();
                    
                    return EXIT_FAILURE;
                }
            }
        }
    }
    
    return EXIT_SUCCESS;
}
예제 #13
0
파일: window.cpp 프로젝트: Zaela/ZEQ-API
bool zeq_window_t::pollInput(zeq_input_t* input)
{
    sf::Event ev;
    
    if (pollEvent(ev))
    {
        memcpy(input, &ev, sizeof(zeq_input_t));
        
        zeq_input_event_t t;
        
        switch (ev.type)
        {
        case sf::Event::Closed:
            t = ZEQ_INPUT_WINDOW_CLOSE;
            break;
        case sf::Event::Resized:
            t = ZEQ_INPUT_WINDOW_RESIZE;
            break;
        case sf::Event::LostFocus:
            t = ZEQ_INPUT_WINDOW_LOSE_FOCUS;
            break;
        case sf::Event::GainedFocus:
            t = ZEQ_INPUT_WINDOW_GAIN_FOCUS;
            break;
        case sf::Event::TextEntered:
            t = ZEQ_INPUT_TEXT_ENTRY;
            break;
        case sf::Event::KeyPressed:
            t = ZEQ_INPUT_KEY_PRESS;
            break;
        case sf::Event::KeyReleased:
            t = ZEQ_INPUT_KEY_RELEASE;
            break;
        case sf::Event::MouseWheelScrolled:
            t = ZEQ_INPUT_MOUSE_WHEEL;
            break;
        case sf::Event::MouseButtonPressed:
            t = ZEQ_INPUT_MOUSE_CLICK;
            break;
        case sf::Event::MouseButtonReleased:
            t = ZEQ_INPUT_MOUSE_RELEASE;
            break;
        case sf::Event::MouseMoved:
            t = ZEQ_INPUT_MOUSE_MOVE;
            break;
        case sf::Event::MouseEntered:
            t = ZEQ_INPUT_MOUSE_ENTER_WINDOW;
            break;
        case sf::Event::MouseLeft:
            t = ZEQ_INPUT_MOUSE_LEAVE_WINDOW;
            break;
        default:
            t = ZEQ_INPUT_UNKNOWN;
            break;
        }
        
        input->event = t;
        return true;
    }
    
    return false;
}
예제 #14
0
파일: tankdrive.c 프로젝트: balty/ftc
task main()
{
	waitForStart();

	StartTask(safeGuard);

	eventengine_t engine;
	event_t event;
	eventengine_init(&engine);

	engine.eventNone = true;
	engine.joysticks = false;
	engine.controller1 = true;
	engine.controller2 = false;

	float driveSpeed = 1.0;
	int controllerPov;

	memset(&state, 0, sizeof(state));

	// Reset servo values
	bFloatDuringInactiveMotorPWM = false; // the motors will NOT coast when power is not applied
	nMotorEncoder[motorARM1] = 0; // reset the Motor Encoder of Motor ARM 1
	nMotorEncoder[motorARM2] = 0; // reset the Motor Encoder of Motor ARM 2
	servo[clawservo1] = 180; // set servo to zero
	servo[clawservo2] = 180; // set servo to zero
	servo[sweeper] = 0;
	wait1Msec(500);

	while (true)
	{
		// Set wheel speeds
		motor[leftWheels] = (float) controllerValue(1, 1, 2) * driveSpeed;
		motor[rightWheels] = (float) controllerValue(1, 2, 2) * driveSpeed;

		// First, update states
		state.arm1_state = nMotorEncoder[motorARM1];
		state.arm2_state = nMotorEncoder[motorARM2];
		controllerPov = joystick.joy1_TopHat;

		// Manual joint and servo controls
		{
			// Lower joint controls
			if (joy1Btn(CONTROLLER_L1))
			{
				state.arm1_manual_lock = true;
				state.arm1_target = state.arm1_state;
				motor[motorARM1] = ARM_SPEED_LOWER;
			}
			else if (joy1Btn(CONTROLLER_L2))
			{
				state.arm1_manual_lock = true;
				state.arm1_target = state.arm1_state;
				motor[motorARM1] = -ARM_SPEED_LOWER;
			}
			else
			{
				// If it is locked, this means we can set speed to zero
				// without disrupting auto-rotation
				if (state.arm1_manual_lock)
					motor[motorARM1] = 0;

				// Don't disengage the lock - we don't want auto-adjust until
				// we hit the button
			}

			// Upper joint controlls
			if (joy1Btn(CONTROLLER_R1))
			{
				state.arm2_manual_lock = true;
				state.arm2_target = state.arm2_state;
				motor[motorARM2] = ARM_SPEED_UPPER;
			}
			else if (joy1Btn(CONTROLLER_R2))
			{
				state.arm2_manual_lock = true;
				state.arm2_target = state.arm2_state;
				motor[motorARM2] = -ARM_SPEED_UPPER;
			}
			else
			{
				if (state.arm2_manual_lock)
					motor[motorARM2] = 0;
			}

			// Manual servo controls
			if (controllerPov == DPAD_UP)
			{
				servo[clawservo1] = ServoValue[clawservo1] - 2;
				servo[clawservo2] = ServoValue[clawservo2] - 2;
			}
			else if (controllerPov == DPAD_DOWN)
			{
				servo[clawservo1] = ServoValue[clawservo1] + 2;
				servo[clawservo2] = ServoValue[clawservo2] + 2;
			}
			else if (controllerPov == DPAD_LEFT)
			{
				servo[sweeper] = ServoValue[sweeper] + 3;
			}
			else if (controllerPov == DPAD_RIGHT)
			{
				servo[sweeper] = ServoValue[sweeper] - 3;
			}
		}

		// Button press events
		pollEvent(&engine, &event);
		if (event.type == EVENT_TYPE_CONTROLLER_1_BUTTON_DOWN)
		{
			if (event.data == CONTROLLER_X)
			{
				// Middle row
				state.arm1_target = ARM_1_COUNT_1;
				state.arm2_target = ARM_2_COUNT_1;

				state.arm1_manual_lock = false;
				state.arm2_manual_lock = false;

				servo[clawservo1] = SERVO_ANGLE_1;
				servo[clawservo2] = SERVO_ANGLE_1;

				PlaySound(soundBeepBeep);
			}
			else if (event.data == CONTROLLER_A)
			{
				// Bottom row
				state.arm1_target = ARM_1_COUNT_2;
				state.arm2_target = ARM_2_COUNT_2;

				state.arm1_manual_lock = false;
				state.arm2_manual_lock = false;

				servo[clawservo1] = SERVO_ANGLE_2;
				servo[clawservo2] = SERVO_ANGLE_2;
			}
			else if (event.data == CONTROLLER_Y)
			{
				// Top row
				state.arm1_target = ARM_1_COUNT_4;
				state.arm2_target = ARM_2_COUNT_4;

				state.arm1_manual_lock = false;
				state.arm2_manual_lock = false;

				servo[clawservo1] = SERVO_ANGLE_4;
				servo[clawservo2] = SERVO_ANGLE_4;
			}
			else if (event.data == CONTROLLER_B)
			{
				// Pick-up position
				state.arm1_target = ARM_1_COUNT_3;
				state.arm2_target = ARM_2_COUNT_3;

				state.arm1_manual_lock = false;
				state.arm2_manual_lock = false;

				servo[clawservo1] = SERVO_ANGLE_3;
				servo[clawservo2] = SERVO_ANGLE_3;
			}
			else if (event.data == CONTROLLER_JOYCLICK_RIGHT)
			{
				// Sweep position
				state.arm1_target = ARM_1_COUNT_5;
				state.arm2_target = ARM_2_COUNT_5;

				state.arm1_manual_lock = false;
				state.arm2_manual_lock = false;

				servo[clawservo1] = SERVO_ANGLE_5;
				servo[clawservo2] = SERVO_ANGLE_5;
			}
			else if (event.data == CONTROLLER_JOYCLICK_LEFT)
			{
				driveSpeed = driveSpeed == SLOW_CONSTANT ? 1.0 : SLOW_CONSTANT;
			}
		}

		// Refresh some values for important accuracy
		state.arm1_state = nMotorEncoder[motorARM1];
		state.arm2_state = nMotorEncoder[motorARM2];

		// Rotate to the target locations if things arent locked
		if (!state.arm1_manual_lock)
		{
			if (abs(state.arm1_target - state.arm1_state) > 100)
				motor[motorARM1] = state.arm1_target > state.arm1_state ? ARM_SPEED_LOWER : -ARM_SPEED_LOWER;
			else
				motor[motorARM1] = 0;
		}

		if (!state.arm2_manual_lock)
		{
			if (abs(state.arm2_target - state.arm2_state) > 100)
				motor[motorARM2] = state.arm2_target > state.arm2_state ? ARM_SPEED_UPPER : -ARM_SPEED_UPPER;
			else
				motor[motorARM2] = 0;
		}

		// Display encoder values on the screen
		nxtDisplayTextLine(0, "L:%d", nMotorEncoder[motorARM1]);
		nxtDisplayTextLine(1, "U:%d", nMotorEncoder[motorARM2]);
		nxtDisplayTextLine(2, "S:%d", ServoValue[clawservo1]);
		nxtDisplayTextLine(3, "S2:%d", ServoValue[sweeper]);
	}
}
예제 #15
0
파일: main.cpp 프로젝트: thecoshman/sandbox
    int Main() {
        run = true;
        //Peanuts::WindowOptions windowOptions("GL test", Peanuts::Windowed(Peanuts::size(640,480), Peanuts::position(100,100)), Peanuts::OpenGLVersion(3, 1));
        Peanuts::WindowOptions windowOptions("GL test", Peanuts::Windowed(Peanuts::size(640,480), Peanuts::Centered()), Peanuts::OpenGLVersion(3, 1));
        //Peanuts::WindowOptions windowOptions("GL test", Peanuts::Windowed(Peanuts::size(640,480), Peanuts::Centered(), Peanuts::Borders::Off), Peanuts::OpenGLVersion(3, 1));
        //Peanuts::WindowOptions windowOptions("GL test", Peanuts::Windowed(Peanuts::Maximised()), Peanuts::OpenGLVersion(3, 1));
        //Peanuts::WindowOptions windowOptions("GL test", Peanuts::Windowed(Peanuts::Maximised(), Peanuts::Borders::Off), Peanuts::OpenGLVersion(3, 1));
        //Peanuts::WindowOptions windowOptions("GL test", Peanuts::FullScreen(), Peanuts::OpenGLVersion(3, 1));
        auto win  = Peanuts::Window::create(windowOptions);
        EventHandler eventHandler;

        gl::ClearColor(1.0f, 0.0f, 0.0f, 0.0f);
        gl::Enable(gl::GL_DEPTH_TEST);
        gl::DepthFunc(gl::GL_LEQUAL);
        gl::Enable(gl::GL_CULL_FACE);
        gl::CullFace(gl::GL_BACK);
        gl::PolygonMode(gl::GL_FRONT, gl::GL_FILL);

        gldr::VertexArray vao;
        vao.bind();
        gldr::Texture2d tex;
        gldr::Program program;
        {
            gldr::VertexShader vertexShader(util::loadShader("resource/shaders/basic.vert"));
            gldr::FragmentShader fragmentShader(util::loadShader("resource/shaders/basic.frag"));
            program.attach(vertexShader, fragmentShader);
            program.link();
        }
        GLint modelview, projection;

        
        gldr::indexVertexBuffer indexBuffer;
        gldr::dataVertexBuffer vertexBuffer;
        gldr::dataVertexBuffer colorBuffer;
        gldr::dataVertexBuffer textureCoordBuffer;
        {
            std::vector<GLfloat> vertexData = {
                -0.5, -0.5, -0.5,
                0.5, -0.5, -0.5,
                0.5, 0.5, -0.5,
                -0.5, 0.5, -0.5,
            };
            std::vector<GLuint> indexdata = {
                0, 1, 2,
                2, 3, 0
            };
            std::vector<GLfloat> colors = {
                1.0,0.0,0.0,
                0.0,1.0,0.0,
                0.0,0.0,1.0,
                0.0,1.0,1.0
            };
            std::vector<GLfloat> textureCoord = {
                0.0, 1.0,
                1.0, 1.0,
                1.0, 0.0,
                0.0, 0.0,
            };
            vertexBuffer.bufferData(vertexData);
            colorBuffer.bufferData(colors);
            indexBuffer.bufferData(indexdata);
            textureCoordBuffer.bufferData(textureCoord);

            tex.setFiltering(gldr::textureOptions::FilterDirection::Minification, gldr::textureOptions::FilterMode::Linear);
            tex.setFiltering(gldr::textureOptions::FilterDirection::Magnification, gldr::textureOptions::FilterMode::Linear);
            auto image = loadImage("resource/images/pheonixflames.png");
            tex.imageData(image.width, image.height,
                gldr::textureOptions::Format::RGBA,
                gldr::textureOptions::InternalFormat::RGB,
                gldr::textureOptions::DataType::UnsignedByte,
                image.data.data()
            );

            program.use();
            GLint position_attribute = program.getAttribLocation("position");
            GLint color_attribute = program.getAttribLocation("color");
            GLint texture_coord_attribute = program.getAttribLocation("texture_coord"); 
            modelview = program.getUniformLocation("ModelView");
            projection = program.getUniformLocation("Projection");

            vertexBuffer.bind();
            gl::VertexAttribPointer(position_attribute, 3, gl::GL_FLOAT, gl::GL_FALSE, 0, 0);
            gl::EnableVertexAttribArray(position_attribute);
            colorBuffer.bind();
            gl::VertexAttribPointer(color_attribute, 3, gl::GL_FLOAT, gl::GL_FALSE, 0, 0);
            gl::EnableVertexAttribArray(color_attribute);
            textureCoordBuffer.bind();
            gl::VertexAttribPointer(texture_coord_attribute, 2, gl::GL_FLOAT, gl::GL_FALSE, 0, 0);
            gl::EnableVertexAttribArray(texture_coord_attribute);
        }

        projectionMat = cam.projection();
        cam.pos = glm::vec3(0.0f, 0.0f, -2.0f);
        cam.dir = glm::vec3(0.0f, 0.0f, 1.0f);

        Crate crate;

        while (run) {
            gl::Clear(gl::GL_COLOR_BUFFER_BIT);
            gl::Clear(gl::GL_DEPTH_BUFFER_BIT);
            gl::UniformMatrix4fv(modelview, 1, gl::GL_FALSE, glm::value_ptr(cam.modelView()));
            gl::UniformMatrix4fv(projection, 1, gl::GL_FALSE, glm::value_ptr(projectionMat));
            vao.bind();
            tex.bind();
            program.use();
            gl::DrawElements(gl::GL_TRIANGLES, 6, gl::GL_UNSIGNED_INT, 0);
            crate.projectWith(projectionMat);
            crate.draw();

            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            win->pumpEvents();
            while(auto event = win->pollEvent()){
                boost::apply_visitor(eventHandler, *event);
            }
            win->swapBuffers();
            update();
        }
        return 0;
    }
예제 #16
0
bool NWindow::depilerPileEvenement(NEvent evenement) {
	pollEvent(evenement);
	return true;
}
예제 #17
0
파일: main.c 프로젝트: jonvaldes/handmade
int main() {
    createWindow(640, 480);
    int framecnt = 0;

    Image* img = loadTGAImage("cat.tga");
    if(img == NULL) {
        printf("ERROR: Could not open image file\n");
        exit(1);
    }
    Image* font = loadTGAImage("font.tga");
    if(font == NULL) {
        printf("ERROR: Could not load font file\n");
        exit(1);
    }

    int mousePos[2] = {0, 0};

    while(1) {
        KeyEvent ev;
        profileBlockStart("eventHandling");
        while(pollEvent(&ev)) {
            switch(ev.type) {
            case KEY_DOWN:
                printf("Keycode: %d\n", ev.key);
                if(ev.key == 53) {
                    goto endGame;
                }
                break;
            case MOUSE_MOVE:
                mousePos[0] = ev.posx;
                mousePos[1] = ev.posy;
                break;
            }
        }
        profileBlockEnd("eventHandling");
        Image* fb = getFramebuffer();
        profileBlockStart("clearFramebuffer");
        Color backColor = color(0, 30, 140, 40);
        clear(fb, &backColor);
        profileBlockEnd("clearFramebuffer");

        profileBlockStart("paintCats");
        for(int i = 0; i < 300; i++) {
            paint(PAINT_OVER, img, fb, (int)(fb->width / 2 + (i * 0.7) * sin(i * 1.221 + framecnt * 0.004)),
                  (int)(fb->height / 2 + (i * 0.7) * cos(i * 1.221 + framecnt * 0.004)));
        }
        profileBlockEnd("paintCats");

        profileBlockStart("paintText");
        Color textColor = color(255, 200, 250, 255);
        textColor.a = (framecnt * 32) % 256;
        drawText(fb, font, &textColor, "Hello world!", mousePos[0], mousePos[1]);
        drawButton(fb, font, "Click here!", 120, 200);

        profileBlockEnd("paintText");

        profileBlockStart("flush");
        flushFramebuffer();
        profileBlockEnd("flush");
        framecnt++;
    }

endGame:
    saveProfile("_profile.json");
    deleteImage(img);
    closeWindow();
}
예제 #18
0
파일: Mesh.cpp 프로젝트: mfichman/sfr
int main() {
    auto window = makeWindow();

    // Asset loader setup
    auto assets = std::make_shared<sfr::AssetTable>();
    auto assetLoader = std::make_shared<sfr::AssetLoader>(assets);

    // Renderer setup
    auto deferredRenderer = std::make_shared<sfr::DeferredRenderer>(assets);
    auto transformUpdater = std::make_shared<sfr::TransformUpdater>();

    // Scene setup
    auto scene = std::make_shared<sfr::Scene>();

    // Set up a camera positioned at (1, 0, 1) and looking at (0, 0, 0). The
    // camera's up vector is the y-axis.
    auto up = sfr::Vector(0, 1.f, 0);
    auto origin = sfr::Vector(1.f, 0, 1.f);
    auto target = sfr::Vector(0, 0, 0);
    auto cameraNode = scene->root()->childIs<sfr::Transform>("camera");
    cameraNode->transformIs(sfr::Matrix::look(origin, target, up));

    auto camera = cameraNode->childIs<sfr::Camera>();
    camera->viewportWidthIs(window->getSize().x);
    camera->viewportWidthIs(window->getSize().y);
    scene->cameraIs(camera); // set this camera to the active camera

    // Place the car mesh (loaded from the asset loader) at (0, 0, 0)
    auto car = assets->assetIs<sfr::Transform>("meshes/Lexus.obj");
    scene->root()->childIs(car);

    // Place a spotlight at (0, 16, 0) and point it down towards the car.  The
    // spotlight's position is determined from the parent transform.
    auto lightNode = scene->root()->childIs<sfr::Transform>("light");
    lightNode->positionIs(sfr::Vector(0, 16.f, 0));
    
    auto light = lightNode->childIs<sfr::SpotLight>();
    light->spotCutoffIs(20.f); // set spot light to spread by 20 degrees
    light->spotPowerIs(40.f); // larger spotPower results in sharper beam edges
    light->constantAttenuationIs(1.f);
    light->linearAttenuationIs(0);
    light->quadraticAttenuationIs(0);
    light->specularColorIs(sfr::Color(1.f, 1.f, 1.f, 1.f));
    light->diffuseColorIs(sfr::Color(3.f, 3.f, 3.f, 3.f)); // really bright light
    light->directionIs(sfr::Vector(0, -1.f, 0)); // point the light down the y-axis

    // Enable shadows for the light
    light->shadowMapIs(std::make_shared<sfr::DepthRenderTarget>(1024, 1024));


    // Run the render loop. This code differs depending on what windowing
    // library you use. The parts that will always remain the same are:
    // 1. glClear
    // 2. transformUpdater->operator(): Updates the scene graph world transforms
    // 3. deferredRenderer->operator()): Renders the scene
    while (window->isOpen()) {
        sf::Event evt;
        while (window->pollEvent(evt)) {
            switch (evt.type) {
            case sf::Event::Closed:
                exit(0);
                break;
            default:
                break;
            }
        }

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
        transformUpdater->operator()(scene);
        deferredRenderer->operator()(scene);
        
        window->display();
    }

    return 0;
}
예제 #19
0
bool NWindow::depilerPileEvenement(NEvent evenement) {
	pollEvent(evenement);
}
예제 #20
0
Common::Error TinselEngine::run() {
	// Initialize backend
	if (getGameID() == GID_DW2) {
#ifndef DW2_EXACT_SIZE
		initGraphics(640, 480, true);
#else
		initGraphics(640, 432, true);
#endif
		_screenSurface.create(640, 432, 1);
	} else {
		initGraphics(320, 200, false);
		_screenSurface.create(320, 200, 1);
	}

	g_system->getEventManager()->registerRandomSource(_random, "tinsel");

	_console = new Console();

	_scheduler = new Scheduler();

	InitSysVars();

	// init memory manager
	MemoryInit();

	// load user configuration
	ReadConfig();

#if 1
	// FIXME: The following is taken from RestartGame().
	// It may have to be adjusted a bit
	CountOut = 1;

	RebootCursor();
	RebootDeadTags();
	RebootMovers();
	resetUserEventTime();
	RebootTimers();
	RebootScalingReels();

	DelayedScene.scene = HookScene.scene = 0;
#endif

	// Load in text strings
	ChangeLanguage(g_language);

	// Init palette and object managers, scheduler, keyboard and mouse
	RestartDrivers();

	// load in graphics info
	SetupHandleTable();

	// Actors, globals and inventory icons
	LoadBasicChunks();

	// Continuous game processes
	CreateConstProcesses();

	// allow game to run in the background
	//RestartBackgroundProcess();	// FIXME: is this still needed?

	//dumpMusic();	// dumps all of the game's music in external XMIDI files

	// Load game from specified slot, if any
	//
	// TODO: We might want to think about properly taking care of possible
	// errors when loading the save state.

	if (ConfMan.hasKey("save_slot")) {
		if (loadGameState(ConfMan.getInt("save_slot")) == Common::kNoError)
			loadingFromGMM = true;
	}

	// Foreground loop
	uint32 timerVal = 0;
	while (!shouldQuit()) {
		assert(_console);
		if (_console->isAttached())
			_console->onFrame();

		// Check for time to do next game cycle
		if ((g_system->getMillis() > timerVal + GAME_FRAME_DELAY)) {
			timerVal = g_system->getMillis();
			AudioCD.updateCD();
			NextGameCycle();
		}

		if (bRestart) {
			RestartGame();
			bRestart = false;
			bHasRestarted = true;	// Set restarted flag
		}

		// Save/Restore scene file transfers
		ProcessSRQueue();

		// Handle any playing movie
		FettleBMV();

#ifdef DEBUG
		if (bFast)
			continue;		// run flat-out
#endif
		// Loop processing events while there are any pending
		while (pollEvent())
			;

		DoCdChange();

		if (MoviePlaying() && NextMovieTime())
			g_system->delayMillis(MAX<int>(NextMovieTime() - g_system->getMillis() + MovieAudioLag(), 0));
		else
			g_system->delayMillis(10);
	}

	// Write configuration
	WriteConfig();

	return Common::kNoError;
}
예제 #21
0
    int Main() {
        run = true;
        Peanuts::WindowOptions windowOptions("GL test", Peanuts::Windowed(std::pair<int,int>(640,480),Peanuts::Centered()), Peanuts::OpenGLVersion(1, 4));
        auto win  = Peanuts::Window::create(windowOptions);
        EventHandler eventHandler;
        gl::ClearColor(1.0f, 0.0f, 0.0f, 0.0f);
        std::chrono::milliseconds dura( 2000 );

        GLfloat vertices_position[24] = {
            0.0, 0.0,
            0.5, 0.0,
            0.5, 0.5,
        
            0.0, 0.0,
            0.0, 0.5,
            -0.5, 0.5,
        
            0.0, 0.0,
            -0.5, 0.0,
            -0.5, -0.5,     

            0.0, 0.0,
            0.0, -0.5,
            0.5, -0.5,
        };

        // Create a Vector Buffer Object that will store the vertices on video memory
        GLuint vbo;
        gl::GenBuffers(1, &vbo);
        gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
        gl::BufferData(gl::ARRAY_BUFFER, sizeof(vertices_position), vertices_position, gl::STATIC_DRAW);

        std::string vert_shader_code = (
            "#version 150\n"
            "\n"
            "in vec4 position;\n"
            "\n"
            "void main() {\n"
            "    gl_Position = position;\n"
            "}\n"
        );
        std::string frag_shader_code = (
            "#version 150\n"
            "\n"
            "out vec4 out_color;\n"
            "\n"
            "void main() {\n"
            "    out_color = vec4(0.0, 1.0, 1.0, 1.0);\n"
            "}\n"
        );
        auto program = create_program(vert_shader_code, frag_shader_code);

        GLuint vao;
        gl::GenVertexArrays(1, &vao);
        gl::BindVertexArray(vao);

        GLint position_attribute = gl::GetAttribLocation(program, "position");

        // Specify how the data for position can be accessed
        gl::VertexAttribPointer(position_attribute, 2, gl::FLOAT, false, 0, 0);
        // Enable the attribute
        gl::EnableVertexAttribArray(position_attribute);

        while (run) {
            gl::Clear(gl::COLOR_BUFFER_BIT);
            gl::BindVertexArray(vao);
            gl::DrawArrays(gl::TRIANGLES, 0, 12);

            std::this_thread::sleep_for(dura);
            win->pumpEvents();
            while(auto event = win->pollEvent()){
                boost::apply_visitor(eventHandler, *event);
            }
            win->swapBuffers();
        }
        return 0;
    }
예제 #22
0
파일: AsyncCopier.cpp 프로젝트: 2php/fbcunn
void AsyncCopier::copyHtoD(void* dest, const void* src, size_t size) {
  VLOG(1) << "copyHtoD " << size;
  auto pdest = static_cast<uint8_t*>(dest);
  auto psrc = static_cast<const uint8_t*>(src);

  unsigned int flags;
  auto err = cudaHostGetFlags(&flags, const_cast<void*>(src));
  if (err == cudaSuccess) {
    // Page-locked using cudaHostAlloc / cudaHostRegister, copy directly.
    checkCudaError(cudaMemcpyAsync(dest, src, size, cudaMemcpyHostToDevice),
                   "cudaMemcpyAsync");
    return;
  } else if (err != cudaErrorInvalidValue) {
    checkCudaError(err, "invalid return code from cudaMemcpyAsync");
  }
  cudaGetLastError();  // reset last error
  // This is dicey -- what if another kernel has completed with an error?
  // But there's nothing else we can do, as any cuda function may return an
  // error from a previous kernel launch.

  if (size > bufferSize_) {
    // Copy synchronously.
    checkCudaError(cudaMemcpy(dest, src, size, cudaMemcpyHostToDevice),
                   "cudaMemcpy");
    return;
  }

  Event* eventToWait = nullptr;

  auto copyRange = [this, &size, &pdest, &psrc] (AllocatedBlock& range) {
    size_t n = std::min(size, range.length);
    range.length = n;
    VLOG(1) << "Copy " << range.start << " + " << n;
    auto bufPtr = buffer_.get() + range.start;
    memcpy(bufPtr, psrc, n);
    checkCudaError(cudaMemcpyAsync(pdest, bufPtr, n, cudaMemcpyHostToDevice),
                   "cudaMemcpyAsync");
    pdest += n;
    psrc += n;
    size -= n;
    checkCudaError(cudaEventRecord(*range.event->event), "cudaEventRecord");
    allocated_.push_back(range);
  };

  for (;;) {
    {
      std::lock_guard<std::mutex> lock(mutex_);

      if (eventToWait) {
        releaseEventLocked(eventToWait);
        eventToWait = nullptr;
      }

      // Always reap
      while (!allocated_.empty() && pollEvent(allocated_.front().event)) {
        releaseEventLocked(allocated_.front().event);
        allocated_.pop_front();
      }

      auto ranges = getRangesLocked();
      if (!ranges.empty()) {
        auto ev = getEventLocked();
        for (auto it = ranges.begin(); size != 0 && it != ranges.end(); ++it) {
          auto& range = *it;
          ++ev->refCount;
          range.event = ev;
          copyRange(range);
        }
        releaseEventLocked(ev);
        if (size == 0) {
          break;
        }
      }
      // Sigh, we have to wait.
      eventToWait = allocated_.front().event;
      ++eventToWait->refCount;
    }

    DCHECK(eventToWait);
    VLOG(1) << "Waiting, remaining " << size;
    waitEvent(eventToWait);
  }
  VLOG(1) << "End copyHtoD";

  DCHECK(!eventToWait);
}
예제 #23
0
int main(int argc, char* argv[]) {
	printf("SimpleDS\n");
	printf("Build: " VERSION_STR " (" SYSTEM_NAME " " SYSTEM_PROCESSOR ")");
#ifdef SDL_HAPTIC_DISABLED
	printf(" - No Haptic");
#endif
	printf("\nAuthors: " VERSION_AUTHORS "\n");

	args = std::vector<const char*>(argv, argv + argc);
	int offset = 1;

	std::string configFile = "./simpleds.conf";
	if (hasOpt("-c") || hasOpt("--config")) {
		configFile = getOpt("-c");
		if (configFile.size() == 0) {
			configFile = getOpt("--config");
		}
		offset += 2;
	}
	config = new Config(configFile);
	if (config->loaded) {
		printf("Config: %s\n", configFile.c_str());
		if (config->has("DS.foo")) {
			printf("Foo: %s\n", config->getString("DS.foo").c_str());
		}
	} else {
		printf("Config file couldn't be loaded, won't be able to save\n");
	}

	uint16_t teamNum = (uint16_t)config->getInt32("DS.team");

	verbose = (hasOpt("-v") || hasOpt("--verbose"));

	if (hasOpt("-V") || hasOpt("--version")) {
		return 0;
	}

	if (hasOpt("-h") || hasOpt("--help")) {
		printUsage();
		printf("Options:\n");
		printf(" -h, --help      Prints this message\n");
		printf(" -v, --verbose   Output debugging information\n");
		printf(" -V, --version   Prints version info and exits\n");
		printf(" -c, --config    Sets the config file to use [default: ./simpleds.conf]\n");
		printf(" teamNum         The team number to use, must be provided here or in configuration file\n");
		return 0;
	}

	if (teamNum == 0 && args.begin() + offset == args.end()) { // We're out of arguments
		printUsage();
		return 1;
	} else {
		char* endptr;
		uint16_t argTeamNum = (uint16_t)std::strtol(args[offset], &endptr, 10);

		if (endptr == args[offset] || *endptr != '\0') { // No team number in config, and none provided
			if (teamNum == 0) {
				printUsage();
				return 1;
			}
		} else {
			teamNum = argTeamNum;
		}
	}

	printf("Team Number: %d\n", teamNum);

	bool quit = false;
	SDL_Event e;

	auto gui = new GUI();
	if (!gui->isValid()) {
		return 1;
	}

	config->setInt32("DS.team", teamNum);
	config->initInt32("DS.alliance", Alliance::RED);
	config->initInt32("DS.position", 1);

	DS::initialize(teamNum);
	auto ds = DS::getInstance();

	enum GUIMode { MAIN, INFO, JOYSTICKS, CONTROL, HELP, COUNT };
	GUIMode mode = GUIMode::MAIN;

	auto runner = std::async(std::launch::async, &DS::run, ds);
	std::map<GUIMode, Screen*> screens;
	screens[MAIN] = new ScreenMain();
	screens[INFO] = new ScreenInfo();
	screens[JOYSTICKS] = new ScreenJoysticks();
	screens[CONTROL] = new ScreenControl();
	screens[HELP] = new ScreenHelp();

	while (!quit) {
		while (gui->pollEvent(&e) != 0) {
			if (e.type == SDL_QUIT) {
				quit = true;
			} else if (e.type == SDL_JOYDEVICEREMOVED || e.type == SDL_JOYDEVICEADDED) {
				ds->setEnable(false);
				ds->loadJoysticks();
			} else if (e.type == SDL_KEYDOWN && e.key.repeat == 0) {
				auto key = e.key.keysym;
				if (key.sym == SDLK_e) {
					ds->toggleEnable();
				} else if (key.sym == SDLK_SPACE) {
					ds->setEnable(false);
				} else if (key.sym == SDLK_0) {
					ds->setEStop();
				} else if (key.sym == SDLK_q) {
					quit = true;
				} else if (key.sym == SDLK_r) {
					if (key.mod & KMOD_SHIFT) {
						ds->reboot();
					} else {
						ds->restartCode();
					}
				} else if (key.sym == SDLK_BACKQUOTE) {
					ds->setAlliance(ds->getAlliance() == Alliance::BLUE ? Alliance::RED : Alliance::BLUE);
				} else if (key.sym >= SDLK_1 && key.sym <= SDLK_9) {
					uint8_t keyNum = (uint8_t)(1 + key.sym - SDLK_1);
					if (key.mod & KMOD_CTRL && keyNum >= 1 && keyNum <= 3) {
						ds->setPosition(keyNum);
					} else if (key.mod & KMOD_SHIFT && keyNum >= 1 && keyNum <= 3) {
						ds->setEnable(false);
						ds->setMode((Mode)(keyNum - 1));
					} else if (keyNum >= 1 && keyNum <= GUIMode::COUNT) {
						mode = (GUIMode)(keyNum - 1);
					}
				}
			}
			screens[mode]->update(e);
		}
		if (gui->readyToDraw()) {
			gui->setOffset(10, 10);
			gui->clear();
			gui->drawScreen(screens[mode]);

			gui->setOffset(10, gui->getHeight() - gui->getCharSize().y);
			gui->drawText(0, 0, "1: Main", mode == GUIMode::MAIN ? Colors::BLACK : Colors::DISABLED);
			gui->drawTextRel(9, 0, "2: Info", mode == GUIMode::INFO ? Colors::BLACK : Colors::DISABLED);
			gui->drawTextRel(9, 0, "3: Joysticks", mode == GUIMode::JOYSTICKS ? Colors::BLACK : Colors::DISABLED);
			gui->drawTextRel(14, 0, "4: Control", mode == GUIMode::CONTROL ? Colors::BLACK : Colors::DISABLED);
			gui->drawTextRel(12, 0, "5: Help", mode == GUIMode::HELP ? Colors::BLACK : Colors::DISABLED);

			gui->render();
		}

		std::string s = narf::util::format("Team %d", teamNum);
		if (ds->isConnected()) {
			auto rio = ds->getRoboRIO();
			s += " - ";
			if (rio->getEStop()) {
				s += "E-Stopped";
			} else {
				s += narf::util::format("%s %s", modeNames[rio->getMode()].c_str(), rio->getEnable() ? "Enabled" : "Disabled");
			}
			s += narf::util::format(" - %s %d", allianceNames[ds->getAlliance()].c_str(), ds->getPosition());
			if (!rio->getCode()) {
				s += " - No Code";
			}
		} else {
			s += " - No Comms";
		}
		gui->setTitle(s);

		ds->updateJoysticks();
		SDL_Delay(25);
	}

	ds->saveJoysticks();
	ds->stop();
	SDL_Quit();
	return 0;
}
예제 #24
0
void Fenettre::RenderMe()
{
   #if FRAME_TIME <= 0
    sf::Clock clock;
    #endif
    bool run = false;
    PositionCamera();
    while(isOpen())
	{
        sf::Event event;
        while(pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
            {
                close();
            }
            else if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
            {
                close();
            }
            else if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Space))
            {
                run = !run;
            }
            else if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::R))
            {
                camera->setPosition(btVector3(-100,50,0));
            }
            // Adjust the viewport when the window is resized
            else if (event.type == sf::Event::Resized)
            {
                glViewport(0, 0, event.size.width, event.size.height);
            }
            else if (run && event.type == sf::Event::MouseMoved)
            {
                camera->MouseMoved();
            }
            else if (run && event.type == sf::Event::MouseWheelMoved)
            {
                camera->MouseWheelMoved(event);
            }
            else if (run && event.type == sf::Event::MouseButtonPressed)
            {
                shootBox(camera->GetCible());
            }

        }

		// Clear color and depth buffer
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		// Update dynamics
		if (run)
		{
           #if FRAME_TIME <= 0
            World->stepSimulation(clock.GetElapsedTime());
            camera->animate(clock.GetElapsedTime());
            #else
            World->stepSimulation(1.0f/FRAME_TIME);
            camera->animate(1.0f/FRAME_TIME);
            #endif

            PositionCamera();
		}

		RenderScene();
		glFlush();
		display();
	}
};
예제 #25
0
파일: android.c 프로젝트: jacereda/glcv
void android_main(struct android_app* app) {
    char * argv[] = {"cvandroid"};
    const EGLint attr[] = {
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_BLUE_SIZE, 8,
        EGL_GREEN_SIZE, 8,
        EGL_RED_SIZE, 8,
        EGL_NONE
    };
    EGLint ncfg;
    EGLint fmt;
    EGLint w;
    EGLint h;
    EGLConfig cfg;
    EGLDisplay dpy;
    EGLSurface surf;
    EGLContext ctx;
    app_dummy();
    app->userData = 0;
    app->onAppCmd = handle;
    app->onInputEvent = input;
    dbg("wait\n");
    while (!app->userData)
        pollEvent(app);
    g_app = app;
    cvInject(CVE_INIT, 1, (intptr_t)argv);
    dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    if (!eglInitialize(dpy, 0, 0))
        err("initialize display");
    eglChooseConfig(dpy, attr, &cfg, 1, &ncfg);
    eglGetConfigAttrib(dpy, cfg, EGL_NATIVE_VISUAL_ID, &fmt);
    ANativeWindow_setBuffersGeometry(app->window, 0, 0, fmt);
    surf = eglCreateWindowSurface(dpy, cfg, app->window, 0);
    ctx = eglCreateContext(dpy, cfg, 0, 0);
    eglMakeCurrent(dpy, surf, surf, ctx);
    eglQuerySurface(dpy, surf, EGL_WIDTH, &w);
    eglQuerySurface(dpy, surf, EGL_HEIGHT, &h);
    if (!eglSwapInterval(dpy, 1))
        err("setting swap interval");
    cvInject(CVE_RESIZE, w, h);
    cvInject(CVE_GLINIT, 0, 0);
    app->userData = 0;
    while (!app->userData && !app->destroyRequested) {
        cvInject(CVE_UPDATE, 0, 0);
        if (!eglSwapBuffers(dpy, surf))
            err("swapbuffers failed");
        pollEvent(app);
    }
    if (app->destroyRequested)
        cvInject(CVE_CLOSE, 0, 0);
    dbg("terminated");
    cvInject(CVE_GLTERM, 0, 0);
    if (!eglMakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))
        err("clearing current");
    if (!eglDestroyContext(dpy, ctx))
        err("destroying context");
    if (!eglDestroySurface(dpy, surf))
        err("destroying surface");
    if (!eglTerminate(dpy))
        err("terminating");
}