int main(int argc, char** argv)
{



	int width = 800, height = 600;
	bool isFullscreen = false;

	if (argc > 1){
		std::cout << "Running with arguments: \n";
		int i = 1;
		while (i != argc){
			std::cout << argv[i] << '\n';
			if (strcmp(argv[i], "-setSize") == 0 && argc > (i + 2)){
				width = atoi(argv[(i + 1)]);
				height = atoi(argv[(i + 2)]);
			}
			if (strcmp(argv[i], "-setFPSLimit") == 0 && argc > (i + 1)){
				framerate = atoi(argv[(i + 1)]);
			}

			i++;
		}
	
	}
	else {
		std::cout << "Running with no extra arguments.\n";
	}

	sf::RenderWindow window(sf::VideoMode(width, height), title);
	window.setFramerateLimit(framerate);
	sf::View view;
	view.setSize(sf::Vector2f((width/2.0f), (height/2.0f)));
	view.setCenter((width/2.0f), (height/2.0f));
	window.setView(view);
	Map map("../resources/ignore/");
	Entity test;
	test.setPosition(sf::Vector2f(80.f, 80.f));
	test.loadSpritesheet("../resources/ignore/player.png", sf::Vector2i(16, 16));
	while (window.isOpen())
	{
		sf::Event event;
		if (fpsclock.getElapsedTime().asSeconds() >= 1.0f){
			window.setTitle(title + " - FPS: " + std::to_string(framerate));
			framerate = 0;
			fpsclock.restart();
		}
			framerate++;
		// End of framerate code

		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed || sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
				window.close();
			if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){
				test.move(Entity::RIGHT, &window);
			}
			if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)){
				test.move(Entity::DOWN, &window);
			}
			if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){
				test.move(Entity::LEFT, &window);
			}
			if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)){
				test.move(Entity::UP, &window);
			}
			if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift)){
				test.isMoving = true;
			}
			else
				test.isMoving = false;
		}
		// Update view to the players location.
		view.setCenter(test.getLocation().x, test.getLocation().y);
		// Update the windows view to the newly changed view.
		window.setView(view);

		window.clear(sf::Color::Black);
		window.draw(map.getSprite());
		window.draw(test.getSprite());
		window.display();
	}
	std::cout << "Closed." << std::endl;
	return 0;
}
void CaptureFilterEdit::showFilters()
{
    FilterDialog capture_filter_dlg(window(), FilterDialog::CaptureFilter);
    capture_filter_dlg.exec();
}
void InputEventHandler::removeFromWindow(){
	if(attached()) window().remove(this);
}
Exemple #4
0
ReportPart::TempData* ReportDesignView::tempData() const {
    return static_cast<ReportPart::TempData*> ( window()->data() );
}
Exemple #5
0
int main()
{
	const std::string windowTitle{ "TimestepLite example" };
	sf::RenderWindow window(sf::VideoMode(800, 600), windowTitle, sf::Style::Default);
	window.setFramerateLimit(100); // max render rate is 100 fps (different to physics timestep)

	hx::Sfml::KeyMap keyMap;
	// WASD controls movement
	keyMap.addControl("up", sf::Keyboard::W);
	keyMap.addControl("down", sf::Keyboard::S);
	keyMap.addControl("left", sf::Keyboard::A);
	keyMap.addControl("right", sf::Keyboard::D);
	// toggles timestep values of 1/5 and 1/60. 1/5 is default state
	keyMap.addControl("toggle step value", sf::Keyboard::Space);

	sf::CircleShape circle(50.f);
	circle.setOrigin(circle.getRadius(), circle.getRadius());
	circle.setFillColor(sf::Colors::Salmon);
	circle.setOutlineColor(sf::Colors::Mint);
	circle.setOutlineThickness(-5.f);
	const float movementSpeed{ 250.f }; // pixels per second
	sf::Vector2f circlePosition{ window.getSize() / 2u };

	hx::Kairos::Stopwatch clock;
	hx::Kairos::TimestepLite timestep;
	timestep.setStep(1.0 / 5.0); // 'physics' timestep is one fifth of a second, or 5 frames per second.
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed || event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape)
				window.close();
			if (event.type == sf::Event::KeyPressed)
			{
				if (event.key.code == keyMap.getKey("toggle step value"))
				{
					if (timestep.getStep() > 1.0 / 6.0)
						timestep.setStep(1.0 / 60.0);
					else
						timestep.setStep(1.0 / 5.0);
				}
			}
		}

		timestep.update(clock.restart().asSeconds()); // add frame time each cycle
		while (timestep.isTimeToIntegrate()) // this is true as long as there are unprocessed timesteps.
		{
			float dt{ static_cast<float>(timestep.getStep()) };

			if (sf::Keyboard::isKeyPressed(keyMap.getKey("up")))
				circlePosition.y -= movementSpeed * dt;
			if (sf::Keyboard::isKeyPressed(keyMap.getKey("down")))
				circlePosition.y += movementSpeed * dt;
			if (sf::Keyboard::isKeyPressed(keyMap.getKey("left")))
				circlePosition.x -= movementSpeed * dt;
			if (sf::Keyboard::isKeyPressed(keyMap.getKey("right")))
				circlePosition.x += movementSpeed * dt;

			// keep circle inside the window
			circlePosition.x = hx::clamp(circlePosition.x, circle.getRadius(), window.getSize().x - circle.getRadius());
			circlePosition.y = hx::clamp(circlePosition.y, circle.getRadius(), window.getSize().y - circle.getRadius());
		}
		circle.setPosition(circlePosition);

		// shows information in the window title bar
		std::string infoTitle{ windowTitle };
		if (timestep.getStep() > 1.0 / 6.0)
			infoTitle += " | Timestep: 5 FPS";
		else
			infoTitle += " | Timestep: 60 FPS";
		window.setTitle(infoTitle);

		window.clear();
		window.draw(circle);
		window.display();
	}

	return EXIT_SUCCESS;
}
Exemple #6
0
int main(void) {
    GlutCLWindow window(512, 512);

    Sphere sphere;
    init_sphere(&sphere);
    sphere.center.y = -4.0f;
    sphere.center.x = -2.0f;
    sphere.center.z = -2.0f;
    sphere.mat.kd = 1.0f;
    sphere.mat.diffuse.x = 0.0f;
    sphere.mat.diffuse.y = 0.7f;
    sphere.mat.diffuse.z = 0.7f;
    window.rayTracer.addSphere(sphere);

    init_sphere(&sphere);
    sphere.center.y = -3.0f;
    sphere.center.x = 2.0f;
    sphere.center.z = 2.0f;
    sphere.mat.ks = 0.2f;
    sphere.mat.kt = 0.8f;
    sphere.mat.extinction.x = 0.99f;
    sphere.mat.extinction.y = 0.95f;
    sphere.mat.extinction.z = 0.95f;
    sphere.mat.ior = 1.1f;
    window.rayTracer.addSphere(sphere);

    init_sphere(&sphere);
    sphere.center.y = -4.0f;
    sphere.center.x = 0.0f;
    sphere.center.z = 0.0f;
    sphere.mat.ks = 1.0f;
    window.rayTracer.addSphere(sphere);

    init_sphere(&sphere);
    sphere.center.y = -4.0f;
    sphere.center.x = 2.0f;
    sphere.center.z = -2.0f;
    sphere.mat.kd = 0.2f;
    sphere.mat.ks = 0.8f;
    sphere.mat.diffuse.x = 0.7f;
    sphere.mat.diffuse.y = 0.7f;
    sphere.mat.diffuse.z = 0.0f;
    sphere.mat.specExp = 100.0f;
    window.rayTracer.addSphere(sphere);

    init_sphere(&sphere);
    sphere.center.y = -4.0f;
    sphere.center.x = -2.0f;
    sphere.center.z = 2.0f;
    sphere.mat.kd = 0.6f;
    sphere.mat.ks = 0.4f;
    sphere.mat.diffuse.x = 0.7f;
    sphere.mat.diffuse.y = 0.0f;
    sphere.mat.diffuse.z = 0.8f;
    sphere.mat.specExp = 1000.0f;
    window.rayTracer.addSphere(sphere);

    init_sphere(&sphere);
    sphere.center.x = 2.2f;
    sphere.center.y = 1.0f;
    sphere.center.z = 2.0f;
    sphere.radius = 0.5f;
    sphere.mat.emission_power = 1.0;
    sphere.mat.emission.x = 1.8f;
    sphere.mat.emission.y = 1.8f;
    sphere.mat.emission.z = 1.8f;
    window.rayTracer.addSphere(sphere);

//    init_sphere(&sphere);
//    sphere.center.x = 1.0f;
//    sphere.center.y = 3.0f;
//    sphere.center.z = -2.0f;
//    sphere.radius = 0.5f;
//    sphere.mat.emission_power = 1.0;
//    sphere.mat.emission.x = 0.4f;
//    sphere.mat.emission.y = 0.1f;
//    sphere.mat.emission.z = 0.6f;
//    window.rayTracer.addSphere(sphere);

    window.rayTracer.setSampleRate(1);
    window.rayTracer.setMaxPathDepth(6);
    window.rayTracer.setCameraSpherical(gmtl::Point3f(0, -4, -0), 14.0f,
            118.0f, 5);
    window.setProgressive(20000);

    glutMainLoop();

}
Exemple #7
0
BOOL fast_tate_pairing(ECn& P,ZZn3& Qx,ZZn3& Qy,Big &x,ZZn2& X,ZZn6& res)
{ 
    int i,j,n,nb,nbw,nzs;
    ECn A,P2,t[PRECOMP];
    ZZn6 w,hc,z2n,zn[PRECOMP];
	Big q=x*x-x+1;

    res=zn[0]=1;  

    t[0]=P2=A=P;
    z2n=g(P2,P2,Qx,Qy);     // P2=P+P
    normalise(P2);
//
// Build windowing table
//
    for (i=1;i<PRECOMP;i++)
    {           
        hc=g(A,P2,Qx,Qy);     
        t[i]=A;         
        zn[i]=z2n*zn[i-1]*hc;   
    }
	
    multi_norm(PRECOMP,t);  // make t points Affine

/*
    A=P;    // reset A
    nb=bits(q);

    for (i=nb-2;i>=0;i--)
    {
		res*=res;
		res*=g(A,A,Qx,Qy);
		if (bit(q,i)==1)
			res*=g(A,P,Qx,Qy);
        if (res.iszero()) return FALSE;  
    }
*/

	A=P;    // reset A
	nb=bits(q);
    for (i=nb-2;i>=0;i-=(nbw+nzs))
    { // windowing helps a little.. 
        n=window(q,i,&nbw,&nzs,WINDOW_SIZE);  // standard MIRACL windowing
        for (j=0;j<nbw;j++)
        {
            res*=res;    
            res*=g(A,A,Qx,Qy);
        }

        if (n>0)
        {
            res*=zn[n/2]; 
            res*=g(A,t[n/2],Qx,Qy);
        }  

        for (j=0;j<nzs;j++) 
        {
            res*=res; 
            res*=g(A,A,Qx,Qy); 
        }  
        if (res.iszero()) return FALSE;  
    }

#ifdef MR_COUNT_OPS
printf("After Miller  fpc= %d fpa= %d fpx= %d\n",fpc,fpa,fpx);
#endif
  //  if (!A.iszero() || res.iszero()) return FALSE;

    w=res;   
    w.powq(X);
    res*=w;                        // ^(p+1)

    w=res;
    w.powq(X); w.powq(X); w.powq(X);
    res=w/res;                     // ^(p^3-1)

// exploit the clever "trick" for a half-length exponentiation!

    res.mark_as_unitary();

    w=res;
    res.powq(X);  // res*=res;  // res=pow(res,CF);
 
    if (x<0) res/=powu(w,-x);
    else res*=powu(w,x);

    if (res==(ZZn6)1) return FALSE;
    return TRUE;            
}
/*!
    Returns the platform screen handle corresponding to this platform window.
*/
QPlatformScreen *QPlatformWindow::screen() const
{
    return window()->screen()->handle();
}
Exemple #9
0
void initscreen()
{
	int i,j;
	char ch;
	window(1,1,80,25);
	textbackground(BLUE);
	textcolor(LIGHTGREEN); /*图象初始化*/
	clrscr();
	textcolor(MAGENTA);
	for(i=20;i<=60;i++)
	{
		for(j=4;j<=18;j+=2)
		{
			gotoxy(i,j);
			cprintf("%c",219);
		}
		gotoxy(i,21);
		cprintf("%c",219);
	}
	for(i=4;i<=21;i++)
	{
		gotoxy(19,i);
		cprintf("%c",219);
		gotoxy(61,i);
		cprintf("%c",219);
		gotoxy(62,i);
		cprintf("%c",219);
		gotoxy(18,i);
		cprintf("%c",219);
	}
	textcolor(YELLOW);
	gotoxy(20,5);
	cprintf("\1");
	textcolor(12);
	gotoxy(60,20);
	cprintf("\2");
	gotoxy(20,5);
	textcolor(WHITE);
	gotoxy(20,22);
	cprintf("Welcome to this little Saving Hostage Game!");
	gotoxy(16,23);
	cprintf("All you have to do is finding a way to the Red Person.");
	gotoxy(22,24);
	cprintf("Press any key to start, Q to quit...");
	ch=getch();
	if(ch=='Q'||ch=='q')
		quitgame(0);
	else
	{
		gotoxy(22,24);
		printf("                                    ");
	}
	textcolor(LIGHTGREEN);
	gotoxy(22,1);
	cprintf("%c(UP) %c(DOWN) %c(LEFT) %c(RIGHT) ESC(QUIT)\n",24,25,27,26);
	textcolor(YELLOW);
	gotoxy(23,2);
	cprintf("You have only %d seconds!",MAXTIME);
	gotoxy(50,2);
	cprintf("TIME:"); /*图象初始化结束*/
	x=20;
	y=5;
	t=0;
	return;	
}
/*!
  Reimplement to let Qt be able to request activation/focus for a window

  Some window systems will probably not have callbacks for this functionality,
  and then calling QWindowSystemInterface::handleWindowActivated(QWindow *w)
  would be sufficient.

  If the window system has some event handling/callbacks then call
  QWindowSystemInterface::handleWindowActivated(QWindow *w) when the window system
  gives the notification.

  Default implementation calls QWindowSystem::handleWindowActivated(QWindow *w)
*/
void QPlatformWindow::requestActivateWindow()
{
    QWindowSystemInterface::handleWindowActivated(window());
}
/*!
    Returns the parent platform window (or 0 if orphan).
*/
QPlatformWindow *QPlatformWindow::parent() const
{
    return window()->parent() ? window()->parent()->handle() : 0;
}
bool QPlatformWindow::isExposed() const
{
    return window()->isVisible();
}
Exemple #13
0
int main(){
  enum Direction {Down, Left, Right, Up};
  //lets us know where to start drawing from 
  sf::Vector2i source(1, Down);
  //accesable with source.x , source.y / Mut source.x = var ...
  int x = 0,y = 0;
  sf::RenderWindow window(sf::VideoMode(800, 600), "ANIMATION!!!!");

  //  window.setKeyRepeatEnabled(false);

  sf::Texture pTexture;
  sf::Sprite playerImage;
  //Error Check
  if(!pTexture.loadFromFile("Player.png")){
    std::cout << "Error. Could not load in Image." << std::endl;
    return 1;
  }

  playerImage.setTexture(pTexture);

  while(window.isOpen()){
    sf::Event Event;

    while(window.pollEvent(Event)){
      switch(Event.type){
      case sf::Event::Closed:
	window.close();
	break;
	/*
	  The next block of code is an implementation of the movement through
	  the sprite sheet that was handed to the texture object.
	  It's easily implemented, attempting to explain it to myself at the
	  moment. The source.y will hold the value of the starting Y location,
	  of the IntRect function. The enumerated values,0 - 3, will outline
	  which value, *32 for the sprite pack, will be the starting Y-Axis
	  at 2*32, and so forth.
	  setPosition updates the location of the image to simulate movement.
	  Not a smooth movement as of yet. Will implement this in a better 
	  manner later on.
	  There is a serious lag in the event procession.
	 */
      case sf::Event::KeyPressed:
	switch(Event.key.code){
	case sf::Keyboard::Up:
	  source.y = Up;
	  y-=5;

	  break;
	case sf::Keyboard::Down:
	  source.y = Down;
	  y+=5;

	  break;
	case sf::Keyboard::Left:
	  source.y = Left;
	  x-=5;

	  break;
	case sf::Keyboard::Right:
	  source.y = Right;
	  x+=5;

	  break;
	default:
	  break;
	}

      default:
	break;
      }
    }
    playerImage.setPosition(x,y);
    /*
      The source.x value holds the value for the starting X-Axis position
      from the input texture. Multiplying it by 32 moves down the sprite pack
      that is being brought in, and then cycles through them, as long as it 
      does not exceed the bounds of the texture that is being brought in.
    
      this will cause the image to basically move to the leftcycling until max
      X length is found, and starting over. Causing the illusion of movement.
    */
    source.x++;//Causes the image to loop along the given axis.
    if(source.x * 32 >= (signed int) pTexture.getSize().x)//Move to the next 
      source.x = 0;//Resets to the top of the cycle point.

    /*
      This is where the texture that is being printed out is updated, and moved
      through with the values that had been changed in the prior loops.
      multiplying the values in source, ranging from 0-3 multiplied by 32, to 
      accomodate the 32x32 size of the sprite to be printed.
    */
    playerImage.setTextureRect(sf::IntRect(source.x *32, source.y*32, 32, 32));
					     
    window.draw(playerImage);
    window.display();
    window.clear();
  }

  return 0;
}				 
Exemple #14
0
int main(void){
    static const int width(1280), height(720);

    sf::Window window(sf::VideoMode(width, height), "OpenGL", sf::Style::Default, sf::ContextSettings(32));
    window.setFramerateLimit(60);

    GLint error;
    if(GLEW_OK != (error = glewInit())) {
        std::cerr << "Glew init failed" << std::endl;
        return EXIT_FAILURE;
    }

    // RAW CPU DATA
    int count = 12;
    int index[] = {0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7, 8, 9, 10, 10, 9, 11, 12, 13, 14, 14, 13, 15, 16, 17, 18, 19, 17, 20, 21, 22, 23, 24, 25, 26, };
    float uv[] = {0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f,  1.f, 0.f,  1.f, 1.f,  0.f, 1.f,  1.f, 1.f,  0.f, 0.f, 0.f, 0.f, 1.f, 1.f,  1.f, 0.f,  };
    float vertices[] = {-0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5 };
    float normals[] = {0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, };
    int   quad_triangleCount = 2;
    int   quad_triangleList[] = {0, 1, 2, 2, 1, 3};
    float quad_vertices[] =  {-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0};

    // Creatin Buffer Objects
    hglt::VAO vao;
    hglt::VAO quadVAO;

    hglt::VBO quadIndexVBO;
    hglt::VBO quadVerticesVBO;
    hglt::VBO indexVBO;
    hglt::VBO verticesVBO;
    hglt::VBO normalsVBO;
    hglt::VBO uvVBO;

    // Send RAW Data from CPU to BO in GPU
    /// Quad
    quadVAO.bind();
    quadIndexVBO.bind(GL_ELEMENT_ARRAY_BUFFER);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quad_triangleList), quad_triangleList, GL_STATIC_DRAW);

    quadVerticesVBO.bind();
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(quad_vertices), quad_vertices, GL_STATIC_DRAW);
    quadVAO.unbind();

    /// Index
    indexVBO.bind(GL_ELEMENT_ARRAY_BUFFER);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index), index, GL_STATIC_DRAW);
    hglt::VBO::unbind(GL_ELEMENT_ARRAY_BUFFER);

    /// Vertices
    verticesVBO.bind();
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    hglt::VBO::unbind();

    /// Normals
    normalsVBO.bind();
    glBufferData(GL_ARRAY_BUFFER, sizeof(normals), normals, GL_STATIC_DRAW);
    hglt::VBO::unbind();

    /// UV
    uvVBO.bind();
    glBufferData(GL_ARRAY_BUFFER, sizeof(uv), uv, GL_STATIC_DRAW);
    hglt::VBO::unbind();

    // Build VAO
    vao.bind();

    // Set Index GL_ELEMENT_ARRAY_BUFFER
    indexVBO.bind(GL_ELEMENT_ARRAY_BUFFER);

    // Set Buffer Object GL_ARRAY_BUFFER
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);

    verticesVBO.bind(GL_ARRAY_BUFFER);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (const GLvoid*) (0 * sizeof(GLfloat)));
    hglt::VBO::unbind();

    normalsVBO.bind();
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (const GLvoid*) (0 * sizeof(GLfloat)));
    hglt::VBO::unbind();

    uvVBO.bind();
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (const GLvoid*) (0 * sizeof(GLfloat)));
    hglt::VBO::unbind();

    hglt::VAO::unbind();

    // LOAD SHADER
    hglt::Program geometryShader = hglt::loadProgram("shader/simple.vs.glsl", "shader/simple.fs.glsl");
    hglt::Program laccumShader = hglt::loadProgram( "shader/lightAccumulation.vs.glsl",
                                                    "shader/lightAccumulation.fs.glsl");
    hglt::Program blitShader = hglt::loadProgram( "shader/blit.vs.glsl", "shader/blit.fs.glsl");
    // LOAD TEXTURE
    hglt::Texture spec = hglt::loadTexture2D("texture/spec.tga");
    hglt::Texture diff = hglt::loadTexture2D("texture/diff.tga", GL_TEXTURE1);

    // Get Uniform Location
    GLint ksLocation = glGetUniformLocation(geometryShader.getGLId(), "uMat.ks");
    GLint kdLocation = glGetUniformLocation(geometryShader.getGLId(), "uMat.kd");
    GLint shininessLocation = glGetUniformLocation(geometryShader.getGLId(), "uMat.shininess");

    GLint laccumMaterialLocation = glGetUniformLocation(laccumShader.getGLId(), "uMaterial");
    GLint laccumNormalLocation = glGetUniformLocation(laccumShader.getGLId(), "uNormal");
    GLint laccumDepthLocation = glGetUniformLocation(laccumShader.getGLId(), "uDepth");
    GLint laccumCameraPositionLocation = glGetUniformLocation(laccumShader.getGLId(), "uCameraPosition");
    GLint laccumInverseViewProjectionLocation = glGetUniformLocation(laccumShader.getGLId(), "uInvViewProjection");
    GLint laccumLightPositionLocation = glGetUniformLocation(laccumShader.getGLId(), "uLightPosition");
    GLint laccumLightColorLocation = glGetUniformLocation(laccumShader.getGLId(), "uLightColor");
    GLint laccumLightIntensityLocation = glGetUniformLocation(laccumShader.getGLId(), "uLightIntensity");

    GLuint blitTex1Location = glGetUniformLocation(blitShader.getGLId(), "uTexture1");


    glUniform1i(kdLocation, 0);
    glUniform1i(ksLocation, 1);


    // TRANSORMATION MATRIX
    glm::mat4 model(1.0);
    glm::mat4 view(1.0);
    glm::mat4 projection(1.0);

    GLint modelLocation = glGetUniformLocation(geometryShader.getGLId(), "uModel");
    GLint viewLocation = glGetUniformLocation(geometryShader.getGLId(), "uView");
    GLint projectionLocation = glGetUniformLocation(geometryShader.getGLId(), "uProjection");

    GLint cameraPositionLocation = glGetUniformLocation(geometryShader.getGLId(), "uCameraPosition");
    GLint timeLocation = glGetUniformLocation(geometryShader.getGLId(), "uTime");

    //std::cout << glm::to_string(model) << std::endl;

    sf::Clock clock;
    sf::Clock clock2;

    // Create Camera
    hglt::Camera camera;
    glEnable(GL_DEPTH_TEST);

    // Alloc FrameBuffer
    hglt::FrameBuffer gbuffer(width, height, 2);
    if(!gbuffer.isValid()){
        std::cerr << "Can't build FrameBuffer." << std::endl;
        return EXIT_FAILURE;
    }

    // Main Loop
    while (window.isOpen()){
        sf::Time frameTime = clock.restart();
        float framerate = 1 / (frameTime.asMilliseconds() * 0.001);
        //std::cout << framerate << "FPS" << std::endl;

        // GEOMETRY PASS
        gbuffer.bind();
        glDrawBuffers(gbuffer.outCount, gbuffer.drawBuffers);

        glViewport( 0, 0, width, height  );

        glEnable(GL_DEPTH_TEST);

        // Reset
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Use Geometry Shader
        geometryShader.use();

        // Upload Uniform
        glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, glm::value_ptr(camera.getProjectionMatrix()));
        glUniformMatrix4fv(viewLocation, 1, GL_FALSE, glm::value_ptr(camera.getViewMatrix()));
        glUniformMatrix4fv(modelLocation, 1, GL_FALSE, glm::value_ptr(model));
        glUniform3fv(cameraPositionLocation, 1, glm::value_ptr(camera.getPosition()));
        glUniform1f(timeLocation, clock2.getElapsedTime().asMilliseconds()* 0.001);
        glUniform1f(shininessLocation, 1000.0f);

        // Draw
        /// Bind Texture
        diff.bind(GL_TEXTURE0);
        spec.bind(GL_TEXTURE1);

        vao.bind();
        //glDrawArrays(GL_TRIANGLES, 0, 3);
        glDrawElements(GL_TRIANGLES, count*3, GL_UNSIGNED_INT, 0);
        hglt::VAO::unbind();

        hglt::Texture::unbind();

        hglt::FrameBuffer::unbind();

        // LIGHT ACCUMULATION PASS

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        laccumShader.use();

        glUniform1i(laccumMaterialLocation, 0);
        glUniform1i(laccumNormalLocation, 1);
        glUniform1i(laccumDepthLocation, 2);
        glUniform3fv(laccumCameraPositionLocation, 1, glm::value_ptr(camera.getPosition()));
        glUniformMatrix4fv( laccumInverseViewProjectionLocation, 1, 0,
                            glm::value_ptr(glm::inverse(camera.getProjectionMatrix())));

        // Bind color to unit 0
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, gbuffer.colorTexId[0]);
        // Bind normal to unit 1
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, gbuffer.colorTexId[1]);
        // Bind depth to unit 2
        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_2D, gbuffer.depthTexId);

        // Blit above the rest
        glDisable(GL_DEPTH_TEST);

        glEnable(GL_BLEND);
        glBlendFunc(GL_ONE, GL_ONE);

        for (unsigned int i = 0; i < 10; ++i) {
            float tl = clock2.getElapsedTime().asMilliseconds()* 0.0001 * i;

            //Update light uniforms
            float lightPosition[3] = { sinf(tl) * 10.0f, 0.5f, cosf(tl) * 10.0f};
            float lightColor[3] = {sinf(tl) *  1.0f, 1.0f - cosf(tl), -sinf(tl)};
            float lightIntensity = 10.0f;

            glUniform3fv(laccumLightPositionLocation, 1, lightPosition);
            glUniform3fv(laccumLightColorLocation, 1, lightColor);
            glUniform1f(laccumLightIntensityLocation, lightIntensity);

            // Draw quad
            glBindVertexArray(quadVAO.getGLId());
            glDrawElements(GL_TRIANGLES, quad_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);
        }

        glDisable(GL_BLEND);

        // Bind blit shader
        blitShader.use();
        // Upload uniforms
        glUniform1i(blitTex1Location, 0);
        // use only unit 0
        glActiveTexture(GL_TEXTURE0);

        // Viewport
        glViewport( 0, 0, width/3, height/4  );
        // Bind texture
        glBindTexture(GL_TEXTURE_2D, gbuffer.colorTexId[0]);
        // Draw quad
        quadVAO.bind();
        glDrawElements(GL_TRIANGLES, quad_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);
        // Viewport
        glViewport( width/3, 0, width/3, height/4  );
        // Bind texture
        glBindTexture(GL_TEXTURE_2D, gbuffer.colorTexId[1]);
        // Draw quad
        quadVAO.bind();
        glDrawElements(GL_TRIANGLES, quad_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);
        // Viewport
        glViewport( width/3 * 2, 0, width/3, height/4  );
        // Bind texture
        glBindTexture(GL_TEXTURE_2D, gbuffer.depthTexId);
        // Draw quad
        quadVAO.bind();
        glDrawElements(GL_TRIANGLES, quad_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);

        // Check for OpenGL errors
        GLenum err = glGetError();
        if(err != GL_NO_ERROR)
            std::cerr << "OpenGL Error" << gluErrorString(err);

        sf::Event event;
        while(window.pollEvent(event)){
            if(event.type == sf::Event::Closed)
                window.close();

            else if(event.type == sf::Event::Resized)
                glViewport(0, 0, event.size.width, event.size.height);
        }

        { // Keyboard Manager
            static bool shiftLock(false);

            if( sf::Keyboard::isKeyPressed(sf::Keyboard::Escape) )
                window.close();

            if( sf::Keyboard::isKeyPressed(sf::Keyboard::Z) )
                camera.moveFront(-0.1);

            if( sf::Keyboard::isKeyPressed(sf::Keyboard::S) )
                camera.moveFront(0.1);

            if( sf::Keyboard::isKeyPressed(sf::Keyboard::LShift) ){
                static sf::Vector2i lockMousePos;
                if( shiftLock ){
                    sf::Vector2i mouse = sf::Mouse::getPosition(window);

                    camera.rotateLeft(float(mouse.x - lockMousePos.x) / 10.0);
                    camera.rotateUp(float(mouse.y - lockMousePos.y) / 10.0);
                    sf::Mouse::setPosition(lockMousePos, window);
                }
                else{
                    shiftLock = true;
                    lockMousePos = sf::Mouse::getPosition(window);
                    window.setMouseCursorVisible(false);
                }
            }
            else{
                shiftLock = false;
                window.setMouseCursorVisible(true);
            }
        }

        window.display();
    }

    return EXIT_SUCCESS;
}
Exemple #15
0
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
    std::srand(static_cast<unsigned int>(std::time(NULL)));

    // Define some constants
    const float pi = 3.14159f;
    const int gameWidth = 800;
    const int gameHeight = 600;
    sf::Vector2f paddleSize(25, 100);
    float ballRadius = 10.f;

    // Create the window of the application
    sf::RenderWindow window(sf::VideoMode(gameWidth, gameHeight, 32), "SFML Pong");
    window.EnableVerticalSync(true);

    // Load the sounds used in the game
    sf::SoundBuffer ballSoundBuffer;
    if (!ballSoundBuffer.LoadFromFile("resources/ball.wav"))
        return EXIT_FAILURE;
    sf::Sound ballSound(ballSoundBuffer);

    // Create the left paddle
    sf::RectangleShape leftPaddle;
    leftPaddle.SetSize(paddleSize - sf::Vector2f(3, 3));
    leftPaddle.SetOutlineThickness(3);
    leftPaddle.SetOutlineColor(sf::Color::Black);
    leftPaddle.SetFillColor(sf::Color(100, 100, 200));
    leftPaddle.SetOrigin(paddleSize / 2.f);

    // Create the right paddle
    sf::RectangleShape rightPaddle;
    rightPaddle.SetSize(paddleSize - sf::Vector2f(3, 3));
    rightPaddle.SetOutlineThickness(3);
    rightPaddle.SetOutlineColor(sf::Color::Black);
    rightPaddle.SetFillColor(sf::Color(200, 100, 100));
    rightPaddle.SetOrigin(paddleSize / 2.f);

    // Create the ball
    sf::CircleShape ball;
    ball.SetRadius(ballRadius - 3);
    ball.SetOutlineThickness(3);
    ball.SetOutlineColor(sf::Color::Black);
    ball.SetFillColor(sf::Color::White);
    ball.SetOrigin(ballRadius / 2, ballRadius / 2);

    // Load the text font
    sf::Font font;
    if (!font.LoadFromFile("resources/sansation.ttf"))
        return EXIT_FAILURE;

    // Initialize the pause message
    sf::Text pauseMessage;
    pauseMessage.SetFont(font);
    pauseMessage.SetCharacterSize(40);
    pauseMessage.SetPosition(170.f, 150.f);
    pauseMessage.SetColor(sf::Color::White);
    pauseMessage.SetString("Welcome to SFML pong!\nPress space to start the game");

    // Define the paddles properties
    sf::Clock AITimer;
    const sf::Time AITime   = sf::Seconds(0.1f);
    const float paddleSpeed = 400.f;
    float rightPaddleSpeed  = 0.f;
    const float ballSpeed   = 400.f;
    float ballAngle         = 0.f; // to be changed later

    sf::Clock clock;
    bool isPlaying = false;
    while (window.IsOpen())
    {
        // Handle events
        sf::Event event;
        while (window.PollEvent(event))
        {
            // Window closed or escape key pressed: exit
            if ((event.Type == sf::Event::Closed) || 
               ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Keyboard::Escape)))
            {
                window.Close();
                break;
            }

            // Space key pressed: play
            if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Keyboard::Space))
            {
                if (!isPlaying)
                {
                    // (re)start the game
                    isPlaying = true;

                    // Reset the position of the paddles and ball
                    leftPaddle.SetPosition(10 + paddleSize.x / 2, gameHeight / 2);
                    rightPaddle.SetPosition(gameWidth - 10 - paddleSize.x / 2, gameHeight / 2);
                    ball.SetPosition(gameWidth / 2, gameHeight / 2);

                    // Reset the ball angle
                    do
                    {
                        // Make sure the ball initial angle is not too much vertical
                        ballAngle = (std::rand() % 360) * 2 * pi / 360;
                    }
                    while (std::abs(std::cos(ballAngle)) < 0.7f);
                }
            }
        }

        if (isPlaying)
        {
            float deltaTime = clock.Restart().AsSeconds();

            // Move the player's paddle
            if (sf::Keyboard::IsKeyPressed(sf::Keyboard::Up) &&
               (leftPaddle.GetPosition().y - paddleSize.y / 2 > 5.f))
            {
                leftPaddle.Move(0.f, -paddleSpeed * deltaTime);
            }
            if (sf::Keyboard::IsKeyPressed(sf::Keyboard::Down) &&
               (leftPaddle.GetPosition().y + paddleSize.y / 2 < gameHeight - 5.f))
            {
                leftPaddle.Move(0.f, paddleSpeed * deltaTime);
            }

            // Move the computer's paddle
            if (((rightPaddleSpeed < 0.f) && (rightPaddle.GetPosition().y - paddleSize.y / 2 > 5.f)) ||
                ((rightPaddleSpeed > 0.f) && (rightPaddle.GetPosition().y + paddleSize.y / 2 < gameHeight - 5.f)))
            {
                rightPaddle.Move(0.f, rightPaddleSpeed * deltaTime);
            }

            // Update the computer's paddle direction according to the ball position
            if (AITimer.GetElapsedTime() > AITime)
            {
                AITimer.Restart();
                if (ball.GetPosition().y + ballRadius > rightPaddle.GetPosition().y + paddleSize.y / 2)
                    rightPaddleSpeed = paddleSpeed;
                else if (ball.GetPosition().y - ballRadius < rightPaddle.GetPosition().y - paddleSize.y / 2)
                    rightPaddleSpeed = -paddleSpeed;
                else
                    rightPaddleSpeed = 0.f;
            }

            // Move the ball
            float factor = ballSpeed * deltaTime;
            ball.Move(std::cos(ballAngle) * factor, std::sin(ballAngle) * factor);

            // Check collisions between the ball and the screen
            if (ball.GetPosition().x - ballRadius < 0.f)
            {
                isPlaying = false;
                pauseMessage.SetString("You lost !\nPress space to restart or\nescape to exit");
            }
            if (ball.GetPosition().x + ballRadius > 800)
            {
                isPlaying = false;
                pauseMessage.SetString("You won !\nPress space to restart or\nescape to exit");
            }
            if (ball.GetPosition().y - ballRadius < 0.f)
            {
                ballSound.Play();
                ballAngle = -ballAngle;
                ball.SetPosition(ball.GetPosition().x, ballRadius + 0.1f);
            }
            if (ball.GetPosition().y + ballRadius > gameHeight)
            {
                ballSound.Play();
                ballAngle = -ballAngle;
                ball.SetPosition(ball.GetPosition().x, gameHeight - ballRadius - 0.1f);
            }

            // Check the collisions between the ball and the paddles
            // Left Paddle
            if (ball.GetPosition().x - ballRadius < leftPaddle.GetPosition().x + paddleSize.x / 2 && 
                ball.GetPosition().x - ballRadius > leftPaddle.GetPosition().x &&
                ball.GetPosition().y + ballRadius >= leftPaddle.GetPosition().y - paddleSize.y / 2 &&
                ball.GetPosition().y - ballRadius <= leftPaddle.GetPosition().y + paddleSize.y / 2)
            {
                if (ball.GetPosition().y > leftPaddle.GetPosition().y)
                    ballAngle = pi - ballAngle + (std::rand() % 20) * pi / 180;
                else
                    ballAngle = pi - ballAngle - (std::rand() % 20) * pi / 180;

                ballSound.Play();
                ball.SetPosition(leftPaddle.GetPosition().x + ballRadius + paddleSize.x / 2 + 0.1f, ball.GetPosition().y);
            }

            // Right Paddle
            if (ball.GetPosition().x + ballRadius > rightPaddle.GetPosition().x - paddleSize.x / 2 &&
                ball.GetPosition().x + ballRadius < rightPaddle.GetPosition().x &&
                ball.GetPosition().y + ballRadius >= rightPaddle.GetPosition().y - paddleSize.y / 2 &&
                ball.GetPosition().y - ballRadius <= rightPaddle.GetPosition().y + paddleSize.y / 2)
            {
                if (ball.GetPosition().y > rightPaddle.GetPosition().y)
                    ballAngle = pi - ballAngle + (std::rand() % 20) * pi / 180;
                else
                    ballAngle = pi - ballAngle - (std::rand() % 20) * pi / 180;

                ballSound.Play();
                ball.SetPosition(rightPaddle.GetPosition().x - ballRadius - paddleSize.x / 2 - 0.1f, ball.GetPosition().y);
            }
        }

        // Clear the window
        window.Clear(sf::Color(50, 200, 50));

        if (isPlaying)
        {
            // Draw the paddles and the ball
            window.Draw(leftPaddle);
            window.Draw(rightPaddle);
            window.Draw(ball);
        }
        else
        {
            // Draw the pause message
            window.Draw(pauseMessage);
        }

        // Display things on screen
        window.Display();
    }

    return EXIT_SUCCESS;
}
Exemple #16
0
int main(int, char const**)
{
    // Create the main window
    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");

    // Set the Icon
    sf::Image icon;
    if (!icon.loadFromFile(resourcePath() + "icon.png")) {
        return EXIT_FAILURE;
    }
    window.setIcon(icon.getSize().x, icon.getSize().y, icon.getPixelsPtr());

    // Load a sprite to display
    sf::Texture texture;
    if (!texture.loadFromFile(resourcePath() + "cute_image.jpg")) {
        return EXIT_FAILURE;
    }
    sf::Sprite sprite(texture);

    // Create a graphical text to display
    sf::Font font;
    if (!font.loadFromFile(resourcePath() + "sansation.ttf")) {
        return EXIT_FAILURE;
    }
    sf::Text text("This is how you do it with sfml", font, 50);
    text.setColor(sf::Color::Black);

    // Load a music to play
    sf::Music music;
    if (!music.openFromFile(resourcePath() + "nice_music.ogg")) {
        return EXIT_FAILURE;
    }

    // Play the music
    music.play();

    // Start the game loop
    while (window.isOpen())
    {
        // Process events
        sf::Event event;
        while (window.pollEvent(event))
        {
            // Close window : exit
            if (event.type == sf::Event::Closed) {
                window.close();
            }

            // Escape pressed : exit
            if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
                window.close();
            }
        }

        // Clear screen
        window.clear();

        // Draw the sprite
        window.draw(sprite);

        // Draw the string
        window.draw(text);

        // Update the window
        window.display();
    }

    return EXIT_SUCCESS;
}
QSGNode *FrameSvgItem::updatePaintNode(QSGNode *oldNode, QQuickItem::UpdatePaintNodeData *)
{
    if (!window() || !m_frameSvg ||
        (!m_frameSvg->hasElementPrefix(m_frameSvg->actualPrefix()) && !m_frameSvg->hasElementPrefix(m_prefix))) {
        delete oldNode;
        return Q_NULLPTR;
    }

    if (m_fastPath) {
        if (m_textureChanged) {
            delete oldNode;
            oldNode = 0;
        }

        if (!oldNode) {
            QString prefix = m_frameSvg->actualPrefix();
            oldNode = new FrameNode(prefix, m_frameSvg);

            bool tileCenter = (m_frameSvg->hasElement(QStringLiteral("hint-tile-center"))
                            || m_frameSvg->hasElement(prefix % QLatin1String("hint-tile-center")));
            bool stretchBorders = (m_frameSvg->hasElement(QStringLiteral("hint-stretch-borders"))
                                || m_frameSvg->hasElement(prefix % QLatin1String("hint-stretch-borders")));
            FrameItemNode::FitMode borderFitMode = stretchBorders ? FrameItemNode::Stretch : FrameItemNode::Tile;
            FrameItemNode::FitMode centerFitMode = tileCenter ? FrameItemNode::Tile: FrameItemNode::Stretch;

            new FrameItemNode(this, FrameSvg::NoBorder, centerFitMode, oldNode);
            new FrameItemNode(this, FrameSvg::TopBorder | FrameSvg::LeftBorder, FrameItemNode::FastStretch, oldNode);
            new FrameItemNode(this, FrameSvg::TopBorder | FrameSvg::RightBorder, FrameItemNode::FastStretch, oldNode);
            new FrameItemNode(this, FrameSvg::TopBorder, borderFitMode, oldNode);
            new FrameItemNode(this, FrameSvg::BottomBorder, borderFitMode, oldNode);
            new FrameItemNode(this, FrameSvg::BottomBorder | FrameSvg::LeftBorder, FrameItemNode::FastStretch, oldNode);
            new FrameItemNode(this, FrameSvg::BottomBorder | FrameSvg::RightBorder, FrameItemNode::FastStretch, oldNode);
            new FrameItemNode(this, FrameSvg::LeftBorder,  borderFitMode, oldNode);
            new FrameItemNode(this, FrameSvg::RightBorder, borderFitMode, oldNode);

            m_sizeChanged = true;
            m_textureChanged = false;
        }

        if (m_sizeChanged) {
            FrameNode* frameNode = static_cast<FrameNode*>(oldNode);
            QSize frameSize(width(), height());
            QRect geometry = frameNode->contentsRect(frameSize);
            for(int i = 0; i<oldNode->childCount(); ++i) {
                FrameItemNode* it = static_cast<FrameItemNode*>(oldNode->childAtIndex(i));
                it->reposition(geometry, frameSize);
            }

            m_sizeChanged = false;
        }
    } else {
        ManagedTextureNode *textureNode = dynamic_cast<ManagedTextureNode *>(oldNode);
        if (!textureNode) {
            delete oldNode;
            textureNode = new ManagedTextureNode;
            textureNode->setFiltering(QSGTexture::Nearest);
            m_textureChanged = true; //force updating the texture on our newly created node
            oldNode = textureNode;
        }

        if ((m_textureChanged || m_sizeChanged) || textureNode->texture()->textureSize() != m_frameSvg->size()) {
            QImage image = m_frameSvg->framePixmap().toImage();
            textureNode->setTexture(s_cache->loadTexture(window(), image));
            textureNode->setRect(0, 0, width(), height());

            m_textureChanged = false;
            m_sizeChanged = false;
        }
    }

    return oldNode;
}
Exemple #18
0
bool QISplitter::eventFilter(QObject *pWatched, QEvent *pEvent)
{
    if (pWatched == handle(1))
    {
        switch (pEvent->type())
        {
            case QEvent::MouseButtonDblClick:
                restoreState(m_baseState);
                break;
            default:
                break;
        }
    }
#ifdef Q_WS_MAC
    /* Special handling on the Mac. Cause there the horizontal handle is only 1
     * pixel wide, its hard to catch. Therefor we make some invisible area
     * around the handle and forwarding the mouse events to the handle, if the
     * user presses the left mouse button. */
    else if (   m_type == Native
             && orientation() == Qt::Horizontal
             && count() > 1
             && qApp->activeWindow() == window())
    {
        switch (pEvent->type())
        {
            case QEvent::MouseButtonPress:
            case QEvent::MouseMove:
            {
                const int margin = 3;
                QMouseEvent *pMouseEvent = static_cast<QMouseEvent*>(pEvent);
                for (int i=1; i < count(); ++i)
                {
                    QWidget *pHandle = handle(i);
                    if (   pHandle
                        && pHandle != pWatched)
                    {
                        /* Create new mouse event with translated mouse positions. */
                        QMouseEvent newME(pMouseEvent->type(),
                                          pHandle->mapFromGlobal(pMouseEvent->globalPos()),
                                          pMouseEvent->button(),
                                          pMouseEvent->buttons(),
                                          pMouseEvent->modifiers());
                        /* Check if we hit the handle */
                        bool fMarginHit = QRect(pHandle->mapToGlobal(QPoint(0, 0)), pHandle->size()).adjusted(-margin, 0, margin, 0).contains(pMouseEvent->globalPos());
                        if (pEvent->type() == QEvent::MouseButtonPress)
                        {
                            /* If we have a handle position hit and the left
                             * button is pressed, start the grabbing. */
                            if (   fMarginHit
                                && pMouseEvent->buttons().testFlag(Qt::LeftButton))
                            {
                                m_fHandleGrabbed = true;
                                setCursor(Qt::SplitHCursor);
                                qApp->postEvent(pHandle, new QMouseEvent(newME));
                                return true;
                            }
                        }
                        else if(pEvent->type() == QEvent::MouseMove)
                        {
                            /* If we are in the near of the handle or currently
                             * dragging, forward the mouse event. */
                            if (   fMarginHit
                                || (   m_fHandleGrabbed
                                    && pMouseEvent->buttons().testFlag(Qt::LeftButton)))
                            {
                                setCursor(Qt::SplitHCursor);
                                qApp->postEvent(pHandle, new QMouseEvent(newME));
                                return true;
                            }
                            else
                            {
                                /* If not, reset the state. */
                                m_fHandleGrabbed = false;
                                setCursor(Qt::ArrowCursor);
                            }
                        }
                    }
                }
                break;
            }
            case QEvent::WindowDeactivate:
            case QEvent::MouseButtonRelease:
            {
                m_fHandleGrabbed = false;
                setCursor(Qt::ArrowCursor);
                break;
            }
            default:
                break;
        }
    }
#endif /* Q_WS_MAC */

    return QSplitter::eventFilter(pWatched, pEvent);
}
// This is a simple example of building and running a simulation
// using Box2D. Here we create a large ground box and a small dynamic
// box.
int main(int argc, char** argv)
{
  //Setup SFML
  sf::RenderWindow window( sf::VideoMode( WWIDTH,WHEIGHT), "It really is Box2D");

  B2_NOT_USED(argc);
  B2_NOT_USED(argv);

  // Textures
  sf::Texture GroundTexture;
  sf::Texture BoxTexture;
  GroundTexture.loadFromFile("grass.png");
  BoxTexture.loadFromFile("wood.png");
  // Sprites
  sf::Sprite GroundSprite;
  sf::Sprite BodySprite;
  GroundSprite.setTexture(GroundTexture);
  GroundSprite.setTextureRect(sf::IntRect(0, 0, 10 * SCALE, 2 * SCALE));
  GroundSprite.setOrigin(5 * SCALE, 1 * SCALE); // origin in middle

  BodySprite.setTexture( BoxTexture);
  BodySprite.setTextureRect(sf::IntRect(0, 0, 2 * SCALE, 2 * SCALE));
  BodySprite.setOrigin( 1 * SCALE, 1 * SCALE); //origin in middle

  // Define the gravity vector.
  b2Vec2 gravity(0.0f, -1.0f);

  // Construct a world object, which will hold and simulate the rigid bodies.
  b2World world(gravity);

  // Define the ground body.
  b2BodyDef groundBodyDef;
  groundBodyDef.position.Set(0.0f, -12.0f);


  // Call the body factory which allocates memory for the ground body
  // from a pool and creates the ground box shape (also from a pool).
  // The body is also added to the world.
  b2Body* groundBody = world.CreateBody(&groundBodyDef);

  // Define the ground box shape.
  b2PolygonShape groundBox;

  // The extents are the half-widths of the box.
  groundBox.SetAsBox(5.0f, 1.0f);

  // Add the ground fixture to the ground body.
  groundBody->CreateFixture(&groundBox, 0.0f);

  // Define the dynamic body. We set its position and call the body factory.
  b2BodyDef bodyDef;
  bodyDef.type = b2_dynamicBody;
  bodyDef.position.Set(3.0f, 8.0f);
  b2Body* body = world.CreateBody(&bodyDef);
  body->SetTransform( body->GetPosition(), 1.2); //rotate

  // Define another box shape for our dynamic body.
  b2PolygonShape dynamicBox;
  dynamicBox.SetAsBox(1.0f, 1.0f); //Half widths. so actually 2x2 box

  // Define the dynamic body fixture.
  b2FixtureDef fixtureDef;
  fixtureDef.shape = &dynamicBox;

  // Set the box density to be non-zero, so it will be dynamic.
  fixtureDef.density = 1.0f;

  // Override the default friction.
  fixtureDef.friction = 0.3f;

  // Add the shape to the body.
  body->CreateFixture(&fixtureDef);

  // Prepare for simulation. Typically we use a time step of 1/60 of a
  // second (60Hz) and 10 iterations. This provides a high quality simulation
  // in most game scenarios.
  float32 timeStep = 1.0f / 60.0f;
  int32 velocityIterations = 6;
  int32 positionIterations = 2;

  // This is our little game loop.
  while (window.isOpen())
  {
    // Check if it's time to go
    sf::Event event;
    while (window.pollEvent( event))
    {
      if( event.type == sf::Event::Closed)
        window.close();
    }
    window.clear();
    // Instruct the world to perform a single step of simulation.
    // It is generally best to keep the time step and iterations fixed.
    world.Step(timeStep, velocityIterations, positionIterations);

    // Draw it
    // get the position and angle of the body
    b2Vec2 pos = body->GetPosition();
    float32 angle = body->GetAngle();
    pos = convertWorldToScreen( pos);

    BodySprite.setPosition(pos.x, pos.y);
    BodySprite.setRotation(180/b2_pi * angle);
    window.draw(BodySprite);

    // get the position and angle of the ground
    pos = groundBody->GetPosition();
    angle = groundBody->GetAngle();
    pos = convertWorldToScreen( pos);

    GroundSprite.setPosition(pos.x, pos.y);
    GroundSprite.setRotation(180/b2_pi * angle);
    window.draw(GroundSprite);


    window.display();
  }

  // When the world destructor is called, all bodies and joints are freed. This can
  // create orphaned pointers, so be careful about your world management.

  return 0;
}
Exemple #20
0
// The start of the Application
int App::start(const std::vector<std::string> &args)
{
	clan::DisplayWindowDescription win_desc;
	win_desc.set_allow_resize(true);
	win_desc.set_stencil_size(8);
	// For simplicity this example does not use the depth components
	//win_desc.set_depth_size(16);
	win_desc.set_title("Stencil Example");
	win_desc.set_size(clan::Size( 900, 570 ), false);

	clan::DisplayWindow window(win_desc);
	clan::Slot slot_quit = window.sig_window_close().connect(this, &App::on_window_close);
	clan::Slot slot_input_up = (window.get_ic().get_keyboard()).sig_key_up().connect(this, &App::on_input_up);

	std::string theme;
	if (clan::FileHelp::file_exists("../../../Resources/GUIThemeAero/theme.css"))
		theme = "../../../Resources/GUIThemeAero";
	else if (clan::FileHelp::file_exists("../../../Resources/GUIThemeBasic/theme.css"))
		theme = "../../../Resources/GUIThemeBasic";
	else
		throw clan::Exception("No themes found");

	clan::GUIWindowManagerTexture wm(window);
	clan::GUIManager gui(wm, theme);
	
	clan::Canvas canvas(window);

	// Deleted automatically by the GUI
	Options *options = new Options(gui, clan::Rect(0, 0, canvas.get_size()));

	clan::Image image_grid(canvas, "../Blend/Resources/grid.png");
	clan::Image image_ball(canvas, "../Blend/Resources/ball.png");
	grid_space = (float) (image_grid.get_width() - image_ball.get_width());

	setup_balls();

	options->request_repaint();

	clan::Font font(canvas, "Tahoma", 20);

	clan::BlendStateDescription blend_desc;
	blend_desc.enable_color_write(false, false, false, false);
	clan::BlendState blend_state_no_color_write(canvas, blend_desc);

	clan::GameTime game_time;

	while (!quit)
	{
		game_time.update();
	
		wm.process();
		wm.draw_windows(canvas);

		int num_balls = options->num_balls;
		if (num_balls > max_balls)
			num_balls = max_balls;

		if (options->is_moveballs_set)
			move_balls(game_time.get_time_elapsed(), num_balls);

		canvas.clear_stencil(0);

		// Draw the grid
		const float grid_xpos = 10.0f;
		const float grid_ypos = 10.0f;
		image_grid.draw(canvas, grid_xpos, grid_ypos);

		clan::DepthStencilStateDescription stencil_desc;

		// Draw the circle onto the stencil
		if (options->is_circle_set)
		{
			stencil_desc.enable_stencil_test(true);

			stencil_desc.set_stencil_compare_front(clan::compare_always, 255, 255);
			stencil_desc.set_stencil_compare_back(clan::compare_always, 255, 255);
			stencil_desc.set_stencil_op_front(clan::stencil_incr_wrap, clan::stencil_incr_wrap, clan::stencil_incr_wrap);
			stencil_desc.set_stencil_op_back(clan::stencil_incr_wrap, clan::stencil_incr_wrap, clan::stencil_incr_wrap);
			stencil_desc.enable_depth_write(false);
			stencil_desc.enable_depth_test(false);

			clan::DepthStencilState stencil_state(canvas, stencil_desc);
			canvas.set_depth_stencil_state(stencil_state);
			canvas.set_blend_state(blend_state_no_color_write);

			canvas.fill_circle(grid_xpos + image_grid.get_width()/2, grid_ypos + image_grid.get_height()/2, 100, clan::Colorf::white);
			canvas.reset_blend_state();

		}

		stencil_desc.enable_stencil_test(true);
		stencil_desc.set_stencil_compare_front(options->compare_function, options->compare_reference, 255);
		stencil_desc.set_stencil_compare_back(options->compare_function, options->compare_reference, 255);
		stencil_desc.set_stencil_op_front(options->stencil_fail, options->stencil_pass, options->stencil_pass);
		stencil_desc.set_stencil_op_back(options->stencil_fail, options->stencil_pass, options->stencil_pass);

		// Note, depth testing disabled for this example
		stencil_desc.enable_depth_write(false);
		stencil_desc.enable_depth_test(false);
		
		clan::BlendState blend_state(canvas, blend_desc);
		clan::DepthStencilState stencil_state(canvas, stencil_desc);
		canvas.set_depth_stencil_state(stencil_state);

		for (int cnt=0; cnt<num_balls; cnt++)
		{
			image_ball.draw(canvas, grid_xpos + balls[cnt].xpos, grid_ypos + balls[cnt].ypos);
		}

		canvas.reset_depth_stencil_state();

		clan::Image stencil_image = get_stencil(canvas, 
			clan::Rect(grid_xpos, grid_ypos, image_grid.get_width(), image_grid.get_height()));

		const float stencil_image_xpos = 400.0f;
		const float stencil_image_ypos = 30.0f;
		const float stencil_image_scale = 0.5f;
		stencil_image.set_scale(stencil_image_scale, stencil_image_scale);
		stencil_image.draw(canvas, stencil_image_xpos, stencil_image_ypos);
		canvas.draw_box(clan::Rectf(stencil_image_xpos, stencil_image_ypos, clan::Sizef(stencil_image.get_width() * stencil_image_scale, stencil_image.get_height() * stencil_image_scale)), clan::Colorf::white);
		font.draw_text(canvas, stencil_image_xpos, stencil_image_ypos - 4.0f, "Stencil", clan::Colorf::black);

		// Add a note to avoid confusion
		font.draw_text(canvas, 10.0f, 500.0, "(This example does not use the stencil depth buffer comparison or the stencil bitmask)", clan::Colorf::black);

		window.flip(1);

		clan::KeepAlive::process();
	}

	return 0;
}
Exemple #21
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    database::dataCreate("cartoPoints");

/*
    QVector<POI> tabdatas;
    QVector<heure> tabheure;

    qDebug() <<"> ajout de point 1 : " <<addPoint("test1", "test4",  (float)3.1234, (float)2.67890);
    qDebug() <<"> ajout de point 2 : " <<addPoint("test2", "test2",  (float)3.1234, (float)2.67890);
    qDebug() <<"> ajout de point 3 : " <<addPoint("test3", "test1",  (float)3.1234, (float)2.67890);

    qDebug() <<"> ajout d'heure 1 : " <<addHeur(2,1, "11:13:14", "13:13:14");
    qDebug() <<"> ajout d'heure 2 : " <<addHeur(1,2, "12:13:14", "14:13:14");
    qDebug() <<"> ajout d'heure 3 : " <<addHeur(3,3, "13:13:14", "15:13:14");

    qDebug() <<"> ajout d'heure 1 : " <<addHeur(3,1, "11:13:14", "13:13:14");
    qDebug() <<"> ajout d'heure 2 : " <<addHeur(2,2, "12:13:14", "14:13:14");
    qDebug() <<"> ajout d'heure 3 : " <<addHeur(1,3, "13:13:14", "15:13:14");

    qDebug() <<"> ajout d'heure 1 : " <<addHeur(1,1, "11:13:14", "13:13:14");
    qDebug() <<"> ajout d'heure 2 : " <<addHeur(3,2, "12:13:14", "14:13:14");
    qDebug() <<"> ajout d'heure 3 : " <<addHeur(2,3, "13:13:14", "15:13:14");

    qDebug("> getpointByName : test2");
    tabdatas = getPointByName("test2");
    qDebug() << "nb table avec test2 comme nom" << tabdatas.size();

    qDebug("> getpointByName : test1");
    tabdatas = getPointByName("test1");
    qDebug() << ">> nb table : " << tabdatas.size();

    qDebug() << "> getPoint((float)3.1234, (float)2.67890, test2)";
    tabdatas = getPoint((float)3.1234, (float)2.67890, "test2");
    qDebug() << ">> nb table : " << tabdatas.size();

    qDebug() << "> getPoint((float)3.1234, (float)2.67890)";
    tabdatas = getPoint((float)3.1234, (float)2.67890);
    qDebug() << ">> nb table : " << tabdatas.size();

    qDebug() << "> heure du point 0 ";
    tabheure = getHeureByPoint(0);
    qDebug() << ">> nb table : " << tabheure.size();

    qDebug() << "> heure du point 1 ";
    tabheure = getHeureByPoint(1);
    qDebug() << ">> nb table : " << tabheure.size();

    qDebug() << "> heure du point 3 ";
    tabheure = getHeureByPoint(3);
    qDebug() << ">> nb table : " << tabheure.size();

    qDebug() << "> id point 1 : " << getIdPoint("test3", "test1",  (float)3.1234, (float)2.67890);
*/
    edit_point_gui window(1);
    //window.exec();

    return window.exec();
}
Exemple #22
0
int main()
{
  std::cout << appName << " Version " << Arkanoid11_VERSION_MAJOR << "." << Arkanoid11_VERSION_MINOR << std::endl;


  // setup game objects
  Ball ball{windowWidth / 2, windowHeight / 2};
  Paddle paddle{windowWidth / 2, windowHeight - paddleHeight * 2};
  std::vector<Brick> bricks;
  bricks.reserve(countBlocksX * countBlocksY);

  for(int ix{0}; ix < countBlocksX; ++ix)
    for(int iy{0}; iy < countBlocksY; ++iy)
      bricks.emplace_back( (ix + 1) * (brickWidth + 4) + 20,
                           (iy + 1) * (brickHeight + 4),
                           brickColors[iy / 2]);


  sf::VideoMode vmode(windowWidth, windowHeight);
  sf::RenderWindow window(vmode, appName);
  window.setFramerateLimit(60);

  while(window.isOpen())
  {
    window.clear();

    if(sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Escape))
        window.close();

    sf::Event event;
    while(window.pollEvent(event))
    {
      if(event.type == sf::Event::Closed)
          window.close();
    }

    // update
    ball.update();
    paddle.update();
    testCollision(paddle, ball);

    for(auto& brick : bricks) 
        testCollision(brick, ball);

    // remove all destroyed bricks
    bricks.erase(std::remove_if(std::begin(bricks), std::end(bricks),
                 [](const Brick& brick) { return brick.destroyed; }),
                 std::end(bricks));

    // winning conditions
    bool won = std::all_of(std::begin(bricks), std::end(bricks), 
            [](const Brick& brick) { return brick.destroyed; });

    if(won)
        window.close();

    // Draw
    window.draw(paddle.shape);
    window.draw(ball.shape);
    for(auto& brick : bricks)
        window.draw(brick.shape);

    window.display();
  }

  return 0;
}
int main()
{
	// Create resource cache for both sf::Texture and sf::SoundBuffer
	thor::MultiResourceCache cache;

	// Create sf::Image to load texture from
	sf::Image image;
	image.create(529, 100, sf::Color(130, 70, 0));

	// Create keys to load resources
	thor::ResourceKey<sf::Texture>		textureKey1 = thor::Resources::fromImage<sf::Texture>(image);
	thor::ResourceKey<sf::Texture>		textureKey2 = thor::Resources::fromFile<sf::Texture>("Media/image.jpg");
	thor::ResourceKey<sf::SoundBuffer>	soundKey	= thor::Resources::fromFile<sf::SoundBuffer>("Media/click.wav");
	thor::ResourceKey<sf::Font>			fontKey		= thor::Resources::fromFile<sf::Font>("Media/sansation.ttf");

	// Create resource pointers to access the resources
	std::shared_ptr<sf::Texture>		texture1, texture2;
	std::shared_ptr<sf::SoundBuffer>	soundBuffer;
	std::shared_ptr<sf::Font>			font;

	// Actually load resources, store them in resource pointers and react to loading errors
	try
	{
		texture1    = cache.acquire(textureKey1);
		texture2    = cache.acquire(textureKey2);
		soundBuffer = cache.acquire(soundKey);
		font        = cache.acquire(fontKey);
	}
	catch (thor::ResourceLoadingException& e)
	{
		std::cout << e.what() << std::endl;
		return 1;
	}

	// Create instances that use the resources
	sf::Sprite sprite1(*texture1);
	sf::Sprite sprite2(*texture2);
	sf::Sound sound(*soundBuffer);
	sf::Text instructions("Press return to play sound, escape to quit", *font, 14u);

	// Move second sprite so that the sprites don't overlap
	sprite2.move( 0.f, static_cast<float>(texture1->getSize().y) );

	// Create render window
	sf::RenderWindow window(sf::VideoMode(800, 600), "Thor Resources");
	window.setVerticalSyncEnabled(true);

	for (;;)
	{
		// Handle events
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
			{
				return 0;
			}
			else if (event.type == sf::Event::KeyPressed)
			{
				switch (event.key.code)
				{
					case sf::Keyboard::Escape:
						return 0;

					case sf::Keyboard::Return:
						sound.play();
						break;
				}
			}
		}

		// Draw sprites of the loaded textures
		window.clear();
		window.draw(sprite1);
		window.draw(sprite2);
		window.draw(instructions);
		window.display();
	}
}
Exemple #24
0
// ----------------------------------------------------------------------------
int main(int argc, char **argv)
{
	 aiLogStream stream;

	//glutInitWindowSize(900,600);
	//glutInitWindowPosition(100,100);
	//glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
	//glutInit(&argc, argv);

	//glutCreateWindow("Assimp - Very simple OpenGL sample");
	//glutDisplayFunc(display);
	//glutReshapeFunc(reshape);

	sf::IntRect viewport(0,0,800,600);
	sf::RenderWindow window(sf::VideoMode(viewport.width,viewport.height,32), "SFML Window");

	reshape(viewport.width,viewport.height);
	// get a handle to the predefined STDOUT log stream and attach
	// it to the logging system. It remains active for all further
	// calls to aiImportFile(Ex) and aiApplyPostProcessing.
	stream = aiGetPredefinedLogStream(aiDefaultLogStream_STDOUT,NULL);
	aiAttachLogStream(&stream);

	// ... same procedure, but this stream now writes the
	// log messages to assimp_log.txt
	stream = aiGetPredefinedLogStream(aiDefaultLogStream_FILE,"assimp_log.txt");
	aiAttachLogStream(&stream);

	// the model name can be specified on the command line. If none
	// is specified, we try to locate one of the more expressive test 
	// models from the repository (/models-nonbsd may be missing in 
	// some distributions so we need a fallback from /models!).
	std::string assimp_models = getenv("ASSIMP");
	std::string dwarf, testMod;
	dwarf=assimp_models+"/test/models-nonbsd/MD5/Bob.md5mesh";
	testMod=assimp_models+ "/test/models/X/Testwuson.X";
	if( 0 != loadasset( argc >= 2 ? argv[1] : dwarf.c_str())) {
		if( argc != 1 || (0 != loadasset( dwarf.c_str()) && 0 != loadasset( testMod.c_str()))) { 
			//return -1;
			;
		}
	}

	glClearColor(0.1f,0.1f,0.1f,1.f);

	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);    // Uses default lighting parameters

	glEnable(GL_DEPTH_TEST);

	glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
	glEnable(GL_NORMALIZE);

	// XXX docs say all polygons are emitted CCW, but tests show that some aren't.
	if(getenv("MODEL_IS_BROKEN"))  
		glFrontFace(GL_CW);

	glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);

	//glutGet(GLUT_ELAPSED_TIME);
	//glutMainLoop();
	while (window.isOpen())
    {

        // Process events
        sf::Event Event;
        while (window.pollEvent(Event))
        {
            // Close window : exit
            if (Event.type == sf::Event::Closed)
                window.close();

            // Escape key : exit
            if ((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::Escape))
                window.close();

            // Resize event : adjust viewport
			if (Event.type == sf::Event::Resized){
				reshape(Event.size.width, Event.size.height);
			}

		}

		//draw/update
		
		display();

		window.display();
	}

	// cleanup - calling 'aiReleaseImport' is important, as the library 
	// keeps internal resources until the scene is freed again. Not 
	// doing so can cause severe resource leaking.
	aiReleaseImport(scene);

	// We added a log stream to the library, it's our job to disable it
	// again. This will definitely release the last resources allocated
	// by Assimp.
	aiDetachAllLogStreams();
	return 0;
}
void CaptureFilterEdit::saveFilter()
{
    FilterDialog capture_filter_dlg(window(), FilterDialog::CaptureFilter, text());
    capture_filter_dlg.exec();
}
Exemple #26
0
int main(int argc, const char *argv[])
{
    if (argc < 2)
    {
        std::cout << "Usage: " << std::string(argv[0]) << " movie_path" << std::endl;
        my_pause();
        return 1;
    }
    
    std::string mediaFile = std::string(argv[1]);
    std::cout << "Going to open movie file \"" << mediaFile << "\"" << std::endl;
    
    sfe::Movie movie;
    if (!movie.openFromFile(mediaFile))
    {
        my_pause();
        return 1;
    }
    
    bool fullscreen = false;
    sf::VideoMode desktopMode = sf::VideoMode::getDesktopMode();
    float width = std::min(static_cast<float>(desktopMode.width), movie.getSize().x);
    float height = std::min(static_cast<float>(desktopMode.height), movie.getSize().y);
    
    // For audio files, there is no frame size, set a minimum:
    if (width * height < 1.f)
    {
        width = std::max(width, 250.f);
        height = std::max(height, 40.f);
    }
    
    // Create window
    sf::RenderWindow window(sf::VideoMode(width, height), "sfeMovie Player",
                            sf::Style::Close | sf::Style::Resize);
    
    // Scale movie to the window drawing area and enable VSync
    window.setFramerateLimit(60);
    window.setVerticalSyncEnabled(true);
    movie.fit(0, 0, width, height);
    
    UserInterface ui(window, movie);
    StreamSelector selector(movie);
    displayShortcuts();

    movie.play();
    
    while (window.isOpen())
    {
        sf::Event ev;
        while (window.pollEvent(ev))
        {
            // Window closure
            if (ev.type == sf::Event::Closed ||
                (ev.type == sf::Event::KeyPressed &&
                 ev.key.code == sf::Keyboard::Escape))
            {
                window.close();
            }
            
            if (ev.type == sf::Event::KeyPressed)
            {
                switch (ev.key.code)
                {
                    case sf::Keyboard::Space:
                        if (movie.getStatus() == sfe::Playing)
                            movie.pause();
                        else
                            movie.play();
                        break;
                        
                    case sf::Keyboard::A:
                        if (ev.key.alt)
                            selector.selectNextStream(sfe::Audio);
                        break;
                        
                    case sf::Keyboard::F:
                        fullscreen = !fullscreen;
                        
                        if (fullscreen)
                            window.create(desktopMode, "sfeMovie Player", sf::Style::Fullscreen);
                        else
                            window.create(sf::VideoMode(width, height), "sfeMovie Player",
                                          sf::Style::Close | sf::Style::Resize);
                        
                        window.setFramerateLimit(60);
                        window.setVerticalSyncEnabled(true);
                        movie.fit(0, 0, (float)window.getSize().x, (float)window.getSize().y);
                        ui.applyProperties();
                        break;
                        
                    case sf::Keyboard::H:
                        ui.toggleVisible();
                        break;
                        
                    case sf::Keyboard::I:
                        displayMediaInfo(movie);;
                        break;
                        
                    case sf::Keyboard::S:
                        if (ev.key.alt)
                            selector.selectNextStream(sfe::Subtitle);
                        else
                            movie.stop();
                        break;
                        
                    case sf::Keyboard::V:
                        if (ev.key.alt)
                            selector.selectNextStream(sfe::Video);
                    default:
                        break;
                }
            }
            else if (ev.type == sf::Event::MouseWheelMoved)
            {
                float volume = movie.getVolume() + 10 * ev.mouseWheel.delta;
                volume = std::min(volume, 100.f);
                volume = std::max(volume, 0.f);
                movie.setVolume(volume);
                std::cout << "Volume changed to " << int(volume) << "%" << std::endl;
            }
            else if (ev.type == sf::Event::Resized)
            {
                movie.fit(0, 0, window.getSize().x, window.getSize().y);
                window.setView(sf::View(sf::FloatRect(0, 0, (float)window.getSize().x, (float)window.getSize().y)));
            }
            else if (ev.type == sf::Event::MouseButtonPressed ||
                     (ev.type == sf::Event::MouseMoved && sf::Mouse::isButtonPressed(sf::Mouse::Left)))
            {
                int xPos = 0;
                
                if (ev.type == sf::Event::MouseButtonPressed)
                    xPos = ev.mouseButton.x;
                else if (ev.type == sf::Event::MouseMoved)
                    xPos = ev.mouseMove.x;
                
                float ratio = static_cast<float>(xPos) / window.getSize().x;
                sf::Time targetTime = ratio * movie.getDuration();
                movie.setPlayingOffset(targetTime);
            }
        }
        
        movie.update();
        
        // Render movie
        window.clear();
        window.draw(movie);
        ui.draw();
        window.display();
    }
    
    return 0;
}
Exemple #27
0
int main()
{
    int winWidth = 500;
    int winHeight = 500;

    // create the window
    sf::Window window(sf::VideoMode(winWidth, winHeight), "Fluid Simulation", sf::Style::Default, sf::ContextSettings(32));
    window.setVerticalSyncEnabled(true);

    // Limit to 60 fps
    window.setFramerateLimit(60);

    // Fluid sim init
    
#ifndef FLUID3D
    FluidSim2D simulator(192 / 2, 108 / 2, 0.1, 0.0, 0.0);
#else
    FluidSim3D simulator(24, 24, 24, 0.1, 0.0, 0.0, false);
#endif

    // OpenGL initialization
    glClearColor(0, 0, 0, 0);
    glEnable(GL_TEXTURE_3D);

    // run the main loop
    bool running = true;
    while (running)
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // handle events
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
            {
                // end the program
                running = false;
            }
            else if (event.type == sf::Event::Resized)
            {
                // adjust the viewport when the window is resized
            }
            else if (event.type == sf::Event::MouseWheelMoved)
            {
#ifdef FLUID3D
                simulator.dist += event.mouseWheel.delta * -0.1;
#endif
            }
        }

        simulator.reinit();

        // Collect UI events
        if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
            simulator.setSource(sf::Mouse::getPosition(window), winWidth, winHeight);
        if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
            simulator.setVelocity(sf::Mouse::getPosition(window), winWidth, winHeight, 5.0f);

#ifdef FLUID3D
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
            simulator.yrot += 1;
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
            simulator.yrot -= 1;
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
            simulator.xrot += 1;
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
            simulator.xrot -= 1;
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::B))
            simulator.bounds = !simulator.bounds;
#endif

        simulator.simulate();

        simulator.draw(winWidth, winHeight);

        // end the current frame (internally swaps the front and back buffers)
        window.display();
    }

    // release resources...

    return 0;
}
int main()
{
    srand(time(NULL));

    bool storyPane = false;
    std::string txt[200];
    std::string line;

    int incre=0;
    std::ifstream file;

    file.open("options.txt");

    if (file.is_open())
    {
        while (!file.eof())
        {
            std::getline(file,line);
            txt[incre]=line;
            incre++;
        }
    }

    file.close();

    sf::RenderWindow window(sf::VideoMode(1024,600), "GameJam", sf::Style::Close);

    std::string tempTxt = txt[1];

    if(txt[1] == "1")
        window.create(sf::VideoMode(1024,600), "GameJam", sf::Style::Fullscreen);

    sf::View view;

    view.reset(sf::FloatRect(0, 0, 1920, 1080));

    if(!mainmenu(window,view))
		return 0;

    incre=0;

    file.open("options.txt");

    if (file.is_open())
    {
        while (!file.eof())
        {
            std::getline(file,line);
            txt[incre]=line;
            incre++;
        }
    }

    file.close();

    window.setFramerateLimit(60);
    window.setVerticalSyncEnabled(true);

    if(txt[1] == "1" && tempTxt == "0")
        window.create(sf::VideoMode(1024, 600), "GameJam", sf::Style::Fullscreen);
    else if(txt[1] == "0" && tempTxt == "1")
        window.create(sf::VideoMode(1024, 600), "GameJam", sf::Style::Close);

    int level = 1;
    int storySection = 1;

    //Story story(1);
    //story.update(window);
    sf::Texture storyPanelTexture[7];
    storyPanelTexture[0].loadFromFile("data/story/comic_page1_clean.png");
    storyPanelTexture[1].loadFromFile("data/story/comic_page2a_clean.png");
    storyPanelTexture[2].loadFromFile("data/story/comic_page2b_clean.png");
    storyPanelTexture[3].loadFromFile("data/story/comic_page3_clean.png");
    storyPanelTexture[4].loadFromFile("data/story/comic_page4_clean.png");
    storyPanelTexture[5].loadFromFile("data/story/comic_page5_clean.png");
    storyPanelTexture[6].loadFromFile("data/story/comic_page6_clean.png");

    sf::Sprite storyPanelSprite;
    sf::Clock scrollingClock;
    sf::Time scrollingTime;

    sf::Vector2f velocity;

    if(storySection == 1)
    {
        storyPanelSprite.setTexture(storyPanelTexture[0]);
        storyPanelSprite.setPosition(0,0);
        velocity = sf::Vector2f(-2.25,-0.03);
    }
    else if(storySection == 2)
    {
        storyPanelSprite.setTexture(storyPanelTexture[1]);
        storyPanelSprite.setOrigin(sf::Vector2f(975,540));
        storyPanelSprite.setPosition(960,540);

        velocity = sf::Vector2f(0,0);
    }
    else if(storySection == 3)
        storyPanelSprite.setTexture(storyPanelTexture[3]);
    else if(storySection == 4)
        storyPanelSprite.setTexture(storyPanelTexture[4]);
    else if(storySection == 5)
        storyPanelSprite.setTexture(storyPanelTexture[5]);
    else if(storySection == 6)
        storyPanelSprite.setTexture(storyPanelTexture[6]);

    int nextStory = 1;

    sf::Texture endingPanelTexture[4];
    sf::Sprite endingPanelSprite[4];

    sf::Music introMusic;
    introMusic.openFromFile("data/sound/comic.ogg");
    introMusic.setPlayingOffset(sf::Time(sf::seconds(7)));

    endingPanelTexture[0].loadFromFile("data/story/finalBoss_BG_idle.png");
    endingPanelTexture[1].loadFromFile("data/story/finalBoss_BG_blink.png");
    endingPanelTexture[2].loadFromFile("data/story/finalBoss_BG_roar.png");
    endingPanelTexture[3].loadFromFile("data/story/credit_screen.png");

    if(level == 1)
    {
        storyPane = true;

    }

    introMusic.play();
    if(window.isOpen())
    {
        //Map map(level);
        Map* map;
        map = new Map(level);

        //Player player(level);
        Player* player;
        player = new Player(level);
        player->initilize();
        player->platformAmoumt = map->platformsToDraw;

        sf::Clock clock;
        sf::Time dt;

        bool currentLevel = true;

        for(int i = 0; i < map->platformsToDraw; i++)
        {
            player->setPlatformBB(map->getSprite(i),i);
        }

        scrollingClock.restart();

        while (currentLevel)
        {
            window.setView(view);
            dt = clock.getElapsedTime();
            scrollingTime = scrollingClock.getElapsedTime();

            sf::Event event;
            while (window.pollEvent(event))
            {
                if (event.type == sf::Event::Closed)
                    return 0;//window.close();

                if(event.key.code == sf::Keyboard::Escape)
                {
                    return 0;
                }
                if(event.key.code == sf::Keyboard::S)
                {
                    if(storyPane)
                        storyPane = false;

                    introMusic.stop();
                }

            }

            if(!storyPane)
            {
                for(int i = 0; i < map->platformsToDraw; i++)
                {
                    player->setPlatformBB(map->getSprite(i),i);
                }

                player->update();
                player->updateAnimation(dt,clock);

                if(!map->headCollected && player->collide(map->getHeadPosition()))
                {
                    map->headCollected = true;
                    map->exitLocked = false;
                    player->headCount++;
                }

                if(map->update(*player))
                {
                    if(level == 1)
                    {
                        level++;
                        map = new Map(level);
                        player = new Player(level);

                        player->initilize();
                        player->platformAmoumt = map->platformsToDraw;
                    }
                    else return 0;

                    //currentLevel = false;
                }
            }

            window.clear();

            if(!storyPane)
            {
                map->drawBG(window);
                map->draw(window,*player);
            }

            if(player->getY() > 2090)
            {
                std::cout << "you fell off the screen :'(";
                currentLevel = false;
                window.close(); //doesn't close the program
            }

            window.setView(view);

            if(storyPane)
            {
                window.clear();
                window.draw(storyPanelSprite);
                //storyPanelSprite.move(velocity);

                scrollingTime = scrollingClock.getElapsedTime();

                if(storySection == 1)
                {
                    //storyPanelSprite.setScale(1 + scrollingTime.asSeconds() * .05,
                      //                        1 + scrollingTime.asSeconds() * .05);

                    if(scrollingTime.asSeconds() > 7)
                    {
                        scrollingClock.restart();
                        scrollingTime = scrollingClock.getElapsedTime();
                        storyPanelSprite.setTexture(storyPanelTexture[1]);
                        storySection = 2;
                    }

                }

                else if(storySection == 2)
                {

                    if(scrollingTime.asSeconds() < 3)
                        //storyPanelSprite.setScale(1 + scrollingTime.asSeconds() * .05,
                          //                        1 + scrollingTime.asSeconds() * .05);

                    if(scrollingTime.asSeconds() > 4)
                        storyPanelSprite.setTexture(storyPanelTexture[2]);

                    if(scrollingTime.asSeconds() > 5)
                    {
                        scrollingClock.restart();
                        scrollingTime = scrollingClock.getElapsedTime();
                        storyPanelSprite.setTexture(storyPanelTexture[3]);
                        storySection = 3;
                    }
                }

                else if(storySection == 3)
                {
                    if(scrollingTime.asSeconds() > 4)
                    {
                        scrollingClock.restart();
                        scrollingTime = scrollingClock.getElapsedTime();
                        storyPanelSprite.setTexture(storyPanelTexture[4]);
                        storySection = 4;
                    }
                }

                else if(storySection == 4)
                {
                    if(scrollingTime.asSeconds() > 3)
                    {
                        scrollingClock.restart();
                        scrollingTime = scrollingClock.getElapsedTime();
                        storyPanelSprite.setTexture(storyPanelTexture[5]);
                        storySection = 5;
                    }
                }

                else if(storySection == 5)
                {
                    if(scrollingTime.asSeconds() > 3)
                    {
                        scrollingClock.restart();
                        scrollingTime = scrollingClock.getElapsedTime();
                        storyPanelSprite.setTexture(storyPanelTexture[6]);
                        storySection = 6;
                    }
                }

                else if(storySection == 6)
                {
                    if(scrollingTime.asSeconds() > 6)
                    {
                        scrollingClock.restart();
                        scrollingTime = scrollingClock.getElapsedTime();
                        storyPanelSprite.setTexture(storyPanelTexture[7]);
                        storyPane = false;
                    }
                }

            }


            window.display();
        }
    }

    return 0;
}
void WindowEventHandler::removeFromWindow(){
	if(attached()){
		window().remove(this); // Window::remove calls onResize
	}
}
Exemple #30
0
// The start of the Application
int Particle::start(const std::vector<std::string> &args)
{
	quit = false;

	// Set the window
	clan::DisplayWindow window("LinearParticle Example - Main Menu", 640, 480, false);

	// Connect the Window close event
    clan::SlotContainer cc;
	cc.connect(window.sig_window_close(), clan::bind_member(this, &Particle::on_window_close));

	// Get the graphic context
	clan::Canvas canvas(window);

	clan::Font font(canvas, "tahoma", 20);

	// Run until someone presses escape
	while (!quit)
	{
		canvas.clear(clan::Colorf(0.0f,0.0f,0.2f));

		int ypos = 32;
		const int ygap = 24;
		font.draw_text(canvas, 32, ypos, "Linear Particle Example - Main Menu");
		ypos += ygap*2;
		font.draw_text(canvas, 32, ypos, "1) Simple"); ypos += ygap;
		font.draw_text(canvas, 32, ypos, "2) Circle"); ypos += ygap;
		font.draw_text(canvas, 32, ypos, "3) Circle2"); ypos += ygap;
		font.draw_text(canvas, 32, ypos, "4) MSmall"); ypos += ygap;
		font.draw_text(canvas, 32, ypos, "5) Shooting"); ypos += ygap;
		font.draw_text(canvas, 32, ypos, "6) Explosion"); ypos += ygap;
		font.draw_text(canvas, 32, ypos, "7) CMotion"); ypos += ygap;
		font.draw_text(canvas, 32, ypos, "8) UserCollision"); ypos += ygap;

		ypos += ygap;
		font.draw_text(canvas, 32, ypos, "Press Escape to exit the example and return to this screen."); ypos += ygap;

		clan::InputDevice keyboard = window.get_ic().get_keyboard();
		if (keyboard.get_keycode(clan::keycode_escape))
			break;

		bool reset_title_flag = false;
		if (keyboard.get_keycode(clan::keycode_1))
		{
			DemoSimple demo; demo.run(window); reset_title_flag = true;
		}
		else if (keyboard.get_keycode(clan::keycode_2))
		{
			DemoCircle demo; demo.run(window); reset_title_flag = true;
		}
		else if (keyboard.get_keycode(clan::keycode_3))
		{
			DemoCircle2 demo; demo.run(window); reset_title_flag = true;
		}
		else if (keyboard.get_keycode(clan::keycode_4))
		{
			DemoMSmall demo; demo.run(window); reset_title_flag = true;
		}
		else if (keyboard.get_keycode(clan::keycode_5))
		{
			DemoShooting demo; demo.run(window); reset_title_flag = true;
		}
		else if (keyboard.get_keycode(clan::keycode_6))
		{
			DemoExplosion demo; demo.run(window); reset_title_flag = true;
		}
		else if (keyboard.get_keycode(clan::keycode_7))
		{
			DemoCMotion demo; demo.run(window); reset_title_flag = true;
		}
		else if (keyboard.get_keycode(clan::keycode_8))
		{
			DemoUserCollision demo; demo.run(window); reset_title_flag = true;
		}

		if (reset_title_flag)
			window.set_title("LinearParticle Example - Main Menu");

		window.flip(1);

		clan::KeepAlive::process(0);
	}

	return 0;
}