Beispiel #1
0
int main(void) {
    srand(time(NULL));

    //Create init object
    Init init = Init();

    //Initialize glfw
    init.glfw(4, 1);
    //Open a window
    GLFWwindow *window = init.window(400, 400);

    //Print window info
    init.printWindowInfo(window);

    //Make opened window current context
    glfwMakeContextCurrent(window);

    init.glew();

    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    glViewport(0, 0, width, height);

    glEnable(GL_CULL_FACE);


    // Nvidia cards require a vertex array to cooperate.
    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    //Set up the initial state.
    unsigned int w = 32, h = 32, d = 32;
    State *prevState = new State(w, h, d);

    VelocityGrid *velocities = new VelocityGrid(w, h, d);
    prevState->setVelocityGrid(velocities);

    // init level set
    LevelSet *ls = factory::levelSet::ball(w, h, d);
    prevState->setLevelSet(ls);

    delete ls;

    // init simulator
    Simulator sim(*prevState, 0.1f);
    //    BubbleMaxExporter bubbleExporter;
    
    // Dark black background
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    //Load in shaders
    static ShaderProgram colorCubeProg("../vertShader.vert", "../colorCube.frag");
    static ShaderProgram rayCasterProg("../vertShader.vert", "../rayCaster.frag");
    static ShaderProgram bubbleProg("../bubbleVertShader.vert", "../bubbleFragShader.frag");

    static const GLfloat vertexBufferData[] = {
            -1.0f, -1.0f, -1.0f,
            1.0f, -1.0f, -1.0f,
            -1.0f, 1.0f, -1.0f,
            1.0f, 1.0f, -1.0f,
            -1.0f, -1.0f, 1.0f,
            1.0f, -1.0f, 1.0f,
            -1.0f, 1.0f, 1.0f,
            1.0f, 1.0f, 1.0f
    };

    static const GLuint triangleBufferData[] = {
            // xy plane (z = -1)
            0, 1, 3,
            3, 2, 0,
            // xz plane (y = -1)
            0, 5, 1,
            0, 4, 5,
            // yz plane (x = -1)
            0, 2, 4,
            2, 6, 4,
            // xy plane (z = 1)
            4, 7, 5,
            4, 6, 7,
            // xz plane (y = 1)
            2, 7, 6,
            2, 3, 7,
            // yz plane (x = 1)
            1, 5, 3,
            3, 5, 7
    };

    std::vector<GLfloat> g_bubble_buffer_data;

    //Create vertex buffer
    GLuint vertexbuffer;
    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexBufferData), vertexBufferData, GL_STATIC_DRAW);



    GLuint triangleBuffer;
    glGenBuffers(1, &triangleBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, triangleBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(triangleBufferData), triangleBufferData, GL_STATIC_DRAW);

    // Create bubble buffer
    GLuint bubbleBuffer;
    glGenBuffers(1, &bubbleBuffer);

    // Create framebuffer
    FBO *framebuffer = new FBO(width, height);

    GLuint volumeTextureId;
    glGenTextures(1, &volumeTextureId);
    glBindTexture(GL_TEXTURE_3D, volumeTextureId);

    //Object which encapsulates a texture + The destruction of a texture.
    Texture3D tex3D(w, h, d);
    double lastTime = glfwGetTime();
    int nbFrames = 0;

    float deltaT = 0.1; //First time step

    glfwSwapInterval(1);
    int i = 0;
    do {


        framebuffer->activate();

        // common for both render passes.
        sim.step(deltaT);

        // deltaT = sim.getDeltaT();

        glm::mat4 matrix = glm::mat4(1.0f);
        matrix = glm::translate(matrix, glm::vec3(0.0f, 0.0f, 2.0f));
        matrix = glm::rotate(matrix, -3.1415926535f / 4.0f, glm::vec3(1.0f, 0.0f, 0.0f));
        matrix = glm::rotate(matrix, 0.1415926535f / 4.0f * (float) glfwGetTime(), glm::vec3(0.0f, 1.0f, 0.0f));

        // Render back face of the cube.
        colorCubeProg();
        glCullFace(GL_FRONT);

        {
            GLuint tLocation = glGetUniformLocation(colorCubeProg, "time");
            glUniform1f(tLocation, glfwGetTime());

            GLuint mvLocation = glGetUniformLocation(colorCubeProg, "mvMatrix");
            glUniformMatrix4fv(mvLocation, 1, false, glm::value_ptr(matrix));
        }

        glClear(GL_COLOR_BUFFER_BIT);
        glEnableVertexAttribArray(0);

        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, triangleBuffer);
    //Triangle coordinates
    glVertexAttribPointer(
            0,                  // Location 0
            3,                  // size
            GL_FLOAT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            (void *) 0            // array buffer offset
    );

        glDrawElements(GL_TRIANGLES, 12 * 3, GL_UNSIGNED_INT, 0);
        glDisableVertexAttribArray(0);

        // Do the ray casting.
        glBindFramebuffer(GL_FRAMEBUFFER, 0); // bind the screen
        glCullFace(GL_BACK);
        rayCasterProg();

        {
            GLuint tLocation = glGetUniformLocation(rayCasterProg, "time");
            glUniform1f(tLocation, glfwGetTime());

            GLuint mvLocation = glGetUniformLocation(rayCasterProg, "mvMatrix");
            glUniformMatrix4fv(mvLocation, 1, false, glm::value_ptr(matrix));

            GLuint windowSizeLocation = glGetUniformLocation(rayCasterProg, "windowSize");
            glUniform2f(windowSizeLocation, width, height);
        }

        glClear(GL_COLOR_BUFFER_BIT);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, *(framebuffer->getTexture()));

        GLuint textureLocation = glGetUniformLocation(rayCasterProg, "backfaceTexture");
        glUniform1i(textureLocation, 0);

        State *currentState = sim.getCurrentState();

        std::vector<glm::vec3> vertexList;
        std::vector<std::vector<int> > faceIndices;
        // copy desired quantities to texture
        for (unsigned int k = 0; k < d; ++k) {
            for (unsigned int j = 0; j < h; ++j) {
                for (unsigned int i = 0; i < w; ++i) {

                    // velocity
                    //tex3D.set(i,j,k,0, 0.5 + 0.5*currentState.getVelocityGrid()->u->get(i,j,k));
                    //tex3D.set(i,j,1, 0.5 + 0.5*currentState.getVelocityGrid()->v->get(i,j));
                    //tex3D.set(i,j,2, 0.5 + currentState.getCellTypeGrid()->get(i, j));
                    //tex3D.set(i,j,2, 0.5);
                    //tex3D.set(i,j,3, 1.0f);

                    // divergence
                    //tex3D.set(i,j,0, fabs(sim.getDivergenceGrid()->get(i,j)));
                    //tex3D.set(i,j,1, fabs(sim.getDivergenceGrid()->get(i,j)));
                    //tex3D.set(i,j,2, fabs(sim.getDivergenceGrid()->get(i,j)));
                    //tex3D.set(i,j,3, 1.0f);

                    // type
                    // tex3D.set(i,j,k, 0, currentState.getCellTypeGrid()->get(i,j, k) == CellType::FLUID ? 1.0 : 0.0);
                    // tex3D.set(i,j,k, 1, currentState.getCellTypeGrid()->get(i,j, k) == CellType::FLUID ? 1.0 : 0.0);
                    // tex3D.set(i,j,k, 2, currentState.getCellTypeGrid()->get(i,j, k) == CellType::SOLID ? 1.0 : 0.0);
                    // tex3D.set(i,j,k, 3, 1.0f);

                    if(currentState->getSignedDistanceGrid()->isValid(i+1,j,k) &&
                        currentState->getSignedDistanceGrid()->isValid(i,j+1,k) &&
                        currentState->getSignedDistanceGrid()->isValid(i+1,j+1,k) &&
                        currentState->getSignedDistanceGrid()->isValid(i,j,k+1) &&
                        currentState->getSignedDistanceGrid()->isValid(i+1,j,k+1) &&
                        currentState->getSignedDistanceGrid()->isValid(i,j+1,k+1) &&
                        currentState->getSignedDistanceGrid()->isValid(i+1,j+1,k+1)){

                        marchingCubes::GRIDCELL gridcell;
                        gridcell.p[0] = glm::vec3(i,j,k);
                        gridcell.p[1] = glm::vec3(i,j+1,k);
                        gridcell.p[2] = glm::vec3(i+1,j+1,k);
                        gridcell.p[3] = glm::vec3(i+1,j,k);
                        gridcell.p[4] = glm::vec3(i,j,k+1);
                        gridcell.p[5] = glm::vec3(i,j+1,k+1);
                        gridcell.p[6] = glm::vec3(i+1,j+1,k+1);
                        gridcell.p[7] = glm::vec3(i+1,j,k+1);

                        gridcell.val[0] = currentState->getSignedDistanceGrid()->get(i, j, k);
                        gridcell.val[1] = currentState->getSignedDistanceGrid()->get(i, j+1, k);
                        gridcell.val[2] = currentState->getSignedDistanceGrid()->get(i+1, j+1, k);
                        gridcell.val[3] = currentState->getSignedDistanceGrid()->get(i+1, j, k);
                        gridcell.val[4] = currentState->getSignedDistanceGrid()->get(i, j, k+1);
                        gridcell.val[5] = currentState->getSignedDistanceGrid()->get(i, j+1, k+1);
                        gridcell.val[6] = currentState->getSignedDistanceGrid()->get(i+1, j+1, k+1);
                        gridcell.val[7] = currentState->getSignedDistanceGrid()->get(i+1, j, k+1);

                        //std::cout << gridcell.val[0] << std::endl;

                        marchingCubes::TRIANGLE *triangles = new marchingCubes::TRIANGLE[5];
                        int numTriangles = marchingCubes::PolygoniseCube(gridcell, 0.0, triangles);
                        for(int i = 0; i < numTriangles; i++){
                            int startIndex = vertexList.size()+1;
                            for(int j = 0; j < 3; j++){
                                //std::cout << triangles[i].p[j].x << " " << triangles[i].p[j].y << " " << triangles[i].p[j].z << std::endl;
                            }
                            vertexList.push_back(triangles[i].p[0]);
                            vertexList.push_back(triangles[i].p[1]);
                            vertexList.push_back(triangles[i].p[2]);

                            std::vector<int> indices = {
                                    startIndex,
                                    startIndex+1,
                                    startIndex+2
                            };

                            faceIndices.push_back(indices);
                        }

                        delete[] triangles;
                    }
                    //signed dist
                    float dist = currentState->getSignedDistanceGrid()->get(i, j, k);
                    float solid = currentState->getCellTypeGrid()->get(i, j, k) == CellType::SOLID ? 1.0f : 0.0f;
                    dist = (glm::clamp(dist + solid, -1.0f, 1.0f) + 1) / 2;

                    tex3D.set(i, j, k, 0, solid);
                    tex3D.set(i, j, k, 1, 0.0f); // not used
                    tex3D.set(i, j, k, 2, dist);
                    tex3D.set(i, j, k, 3, 1.0f);
                    //closest point
                    // tex3D.set(i,j,0, currentState.getClosestPointGrid()->get(i,j).x / 70.0);
                    // tex3D.set(i,j,1, currentState.getClosestPointGrid()->get(i,j).y / 70.0);
                    // tex3D.set(i,j,2, 0.0f);
                    // tex3D.set(i,j,3, 1.0f);
                }
            }
        }

        printObjToFile("exported_" + std::to_string(i) + ".obj", vertexList, faceIndices);
        std::ofstream fileStream("exportedState_" + std::to_string(i) + ".pf", std::ios::binary);
        currentState->write(fileStream);
        fileStream.close();


        // activate and upload texture to gpu
        tex3D(GL_TEXTURE1);
        GLuint volumeTextureLocation = glGetUniformLocation(rayCasterProg, "volumeTexture");
        glUniform1i(volumeTextureLocation, 1);

        glEnableVertexAttribArray(0);
        glDrawElements(GL_TRIANGLES, 12 * 3, GL_UNSIGNED_INT, 0);
        glDisableVertexAttribArray(0);

        FBO::deactivate();

        

        ////////////////// Start drawing bubbles //////////////////////
        
        // Draw bubbles
        const std::vector<Bubble> bubbles = currentState->getBubbles();
        g_bubble_buffer_data.clear();
        std::cout << "frame=" << i << ", nBubbles=" << bubbles.size() << std::endl;
        for (int i = 0; i < bubbles.size(); i++) {
          Bubble b = bubbles.at(i);

          //          std::cout << "bubble pos " << b.position.x << ", " << b.position.y << std::endl << b.radius << std::endl;
            
          g_bubble_buffer_data.push_back(b.position.x / (float)w * 2.0 - 1.0);
          g_bubble_buffer_data.push_back(b.position.y / (float)h * 2.0 - 1.0);
          g_bubble_buffer_data.push_back(b.position.z / (float)d * 2.0 - 1.0);
          g_bubble_buffer_data.push_back(b.radius);
        }

           
        glBindBuffer(GL_ARRAY_BUFFER, bubbleBuffer);    
        glBufferData(GL_ARRAY_BUFFER, sizeof(float) * g_bubble_buffer_data.size(), &g_bubble_buffer_data[0], GL_DYNAMIC_DRAW);
        
                
        
        bubbleProg();
        glEnable(GL_PROGRAM_POINT_SIZE);

        {
            GLuint tLocation = glGetUniformLocation(colorCubeProg, "time");
            glUniform1f(tLocation, glfwGetTime());

            GLuint mvLocation = glGetUniformLocation(colorCubeProg, "mvMatrix");
            glUniformMatrix4fv(mvLocation, 1, false, glm::value_ptr(matrix));
        }

        //        glEnable (GL_BLEND);
        //        glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
                
        glPointSize(4.0);
        
        if (g_bubble_buffer_data.size() > 0) {
          glEnable(GL_PROGRAM_POINT_SIZE);
          glEnableVertexAttribArray(0);
          glVertexAttribPointer(
                                0,                  //Location 0
                                4,                  // size
                                GL_FLOAT,           // type
                                GL_FALSE,           // normalized?
                                0,                  // stride
                                (void*)0            // array buffer offset
                                );
          
          glDrawArrays(GL_POINTS, 0, 4 * g_bubble_buffer_data.size()); // 3 indices starting at 0 -> 1 triangle
          glDisableVertexAttribArray(0);
        }
        ////////////////// End drawing bubbles //////////////////////
        




        glfwPollEvents();
        glfwSwapBuffers(window);
        double currentTime = glfwGetTime();
        nbFrames++;
        if (currentTime - lastTime >= 1.0) { // If last prinf() was more than 1 sec ago
            // printf and reset timer
            std::string title = std::to_string(1000.0 / double(nbFrames)) + "ms/frame        " + std::to_string(deltaT) + "  dt";
            glfwSetWindowTitle(window, title.c_str());
            nbFrames = 0;
            lastTime += 1.0;
        }
        i++;
        
        //        bubbleExporter.update(i, sim.getBubbleTracker());
        //        bubbleExporter.exportSnapshot(i, "bubbles_" + std::to_string(i) + ".mx");

        /*        if (i > 600) {
          bubbleExporter.exportBubbles("bubbles.mx");
          break;
          }*/
    } // Check if the ESC key was pressed or the window was closed
    while (!glfwWindowShouldClose(window));

    std::cout << "Cleaning up!" << std::endl;
    // Close OpenGL window and terminate GLFW
    glfwDestroyWindow(window);
    glfwTerminate();
    glDeleteBuffers(1, &vertexbuffer);

    glDeleteVertexArrays(1, &VertexArrayID);
    exit(EXIT_SUCCESS);
}
Beispiel #2
0
void Screen::SetTitle(const String &title) {
    glfwSetWindowTitle(title.ToCString());
}
Beispiel #3
0
void CCEGLView::setFrameSize(float width, float height)
{
	bool eResult = false;
	int u32GLFWFlags = GLFW_WINDOW;
	//create the window by glfw.

	//check
	CCAssert(width!=0&&height!=0, "invalid window's size equal 0");

	//Inits GLFW
	eResult = glfwInit() != GL_FALSE;

	if (!eResult) {
		CCAssert(0, "fail to init the glfw");
	}

	/* Updates window hint */
	glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);

	int iDepth = 16; // set default value
	/* Depending on video depth */
	switch(iDepth)
	{
		/* 16-bit */
		case 16:
		{
			/* Updates video mode */
			eResult = (glfwOpenWindow(width, height, 5, 6, 5, 0, 16, 8, (int)u32GLFWFlags) != false) ? true : false;

			break;
		}

		/* 24-bit */
		case 24:
		{
			/* Updates video mode */
			eResult = (glfwOpenWindow(width, height, 8, 8, 8, 0, 16, 8, (int)u32GLFWFlags) != false) ? true : false;

			break;
		}

		/* 32-bit */
		default:
		case 32:
		{
			/* Updates video mode */
			eResult = (glfwOpenWindow(width, height, 8, 8, 8, 8, 16, 8, (int)u32GLFWFlags) != GL_FALSE) ? true :false;
			break;
		}
	}

	/* Success? */
	if(eResult)
	{

		/* Updates actual size */
	  //		glfwGetWindowSize(&width, &height);

		CCEGLViewProtocol::setFrameSize(width, height);		

		/* Updates its title */
		glfwSetWindowTitle("Cocos2dx-Linux");

		//set the init flag
		bIsInit = true;

		//register the glfw key event
		glfwSetKeyCallback(keyEventHandle);
		//register the glfw char event
		glfwSetCharCallback(charEventHandle);
		//register the glfw mouse event
		glfwSetMouseButtonCallback(mouseButtonEventHandle);
		//register the glfw mouse pos event
		glfwSetMousePosCallback(mousePosEventHandle);

		glfwSetWindowCloseCallback(closeEventHandle);

		//Inits extensions
		eResult = initExtensions();

		if (!eResult) {
			CCAssert(0, "fail to init the extensions of opengl");
		}
		initGL();
	}
}
Beispiel #4
0
void GLFWView::setWindowTitle(const std::string& title) {
    glfwSetWindowTitle(window, (std::string { "Mapbox GL: " } + title).c_str());
}
Beispiel #5
0
int main( ) {
	config.load( "config.cfg" );
	if( config.error( ) ) {
		puts( "Error loading config." );
		return 1;
	}

	rc::MessageHandler hMessages;
	rc::registerMessageHandler( &hMessages );

	rc::init( "KakaTD", (int)config.getNum("xres"), (int)config.getNum("yres"), (int)config.getNum("zres"), config.getNum("fullscreen") > 0.01f, config.getNum("fov"), config.getNum("near"), config.getNum("far"), (int)config.getNum("depth"), (int)config.getNum("fsaa"), (int)config.getNum("stencil"), (int)config.getNum("accum") );
	handleMessages( );

	rc::Shader::global = "const vec3 lightDir = vec3( 0.5, 0.0, 0.866 );\n";
	if( (int)config.getNum("pcf") ) rc::Shader::global += "#define PCF\n";
	rc::Shader::global += "#define SHADOWMAPSIZE " + strFloat((float)config.getNum("shadowmapres")) + "\n";
	rc::Shader::global += "#line 0\n";

	culling::setup( config.getNum("fov"), config.getNum("xres") / config.getNum("yres"), 60.0f );
	camera::setup( config.getNum("heightSpeed"), config.getNum("heightMoveSmoothness"), (int)config.getNum("moveBorder"), config.getNum("moveSpeed"), config.getNum("lookAngle"), config.getNum("targetHeight") );
	map::setup( config.getString("map").c_str( ) );
	shadows::setup( (int)config.getNum("shadowmapres"), config.getNum("bilinearpcf") > 0.01f );

	rc::Object pickMarker;
	pickMarker.setMesh( rc::getRessource<rc::Mesh>( "media/cube2" ) );
	pickMarker.setTexture( rc::getRessource<rc::Texture>( "media/spawn.png" ) );
	pickMarker.scale( Eigen::Vector3f( 0.01f, 0.01f, 0.01f ) );
	pickMarker.position( Eigen::Vector3f( 0.0f, 0.0f, 0.0f ) );

	rc::Shader* towerShader = rc::getRessource<rc::Shader>( "media/tower.vert;media/tower.frag" );
	towerShader->defaultUniforms.add( rc::uniform::SAMPLER, "shadowMap", &rc::Texture::sampler1 );
	towerShader->defaultUniforms.add( rc::uniform::MAT4 | rc::uniform::FLOAT, "lightMVP", shadows::lightMVP );
	towerShader->defaultUniforms.add( rc::uniform::MAT4 | rc::uniform::FLOAT, "objectMVP", rc::Object::MVP );

	rc::Renderable::finishInitialization( );
	/*for( std::list<rc::Renderable*>::iterator i = rc::Renderable::renderables.begin( ); i != rc::Renderable::renderables.end( ); ++i) {
		printf( "%d\n", (*i)->hash( ) );
	};*/
	puts( "------------------------------------------------- Start ");

	time_t next = clock( );
	int frameCounter = 0;
	double t0 = 0.0, t1 = 0.0;
	glfwSetTime(0.0);
	Eigen::Vector2i pickPos = Eigen::Vector2i( -1, -1 );
	bool lastEnter = false;
	bool lastClick = false;
	do {
		t0 = glfwGetTime();
		//float speed = ((t0.tv_sec - t1.tv_sec) * 1000000 + (t0.tv_usec - t1.tv_usec)) * 0.0001f;
		//shaderTime = (t0.tv_sec * 1000000 + t0.tv_usec) * 0.000001f;
		float speed = (float)(t0 - t1) * 100.0f;
		shaderTime = (float)t0 * 1.0f;
		t1 = t0;

		bool click = glfwGetMouseButton( GLFW_MOUSE_BUTTON_LEFT ) == GLFW_PRESS;
		if( pickPos.x( ) != -1 ) {
			map::GridField* field = map::mapGrid + pickPos.y( )*map::width + pickPos.x( );
			Eigen::Vector3f pos = Eigen::Vector3f( (pickPos.x( ) - map::width * 0.5f) * SPACING, field->type==map::GridField::RAISED?HEIGHT:0.0f, (pickPos.y( ) - map::height * 0.5f) * SPACING );
			pickMarker.position( pos );
			if( click && !lastClick ) {
				rc::Object* temp = new rc::Object;
				temp->setMesh( rc::getRessource<rc::Mesh>( "media/Blitz" ) );
				temp->setShader( rc::getRessource<rc::Shader>( "media/tower.vert;media/tower.frag" ) );
				temp->setTexture( &shadows::shadowMap, rc::Texture::sampler1 );
				temp->position( pos );
				temp->scale( Eigen::Vector3f( 0.024f, 0.024f, 0.03f ) );
				temp->orientation(Eigen::Vector3f(-(float)M_PI / 2.0f, 0.0f, 0.0f));
			}
		}
		lastClick = click;

		camera::update( speed );
		if( rc::getKey( GLFW_KEY_SPACE ) ) {
			camera::camPos = Eigen::Vector3f( 50.0f, 50.0f, -50.0f );
			camera::targetHeight = 50.0f;
		};

		bool enter = rc::getKey( GLFW_KEY_ENTER );
		if( enter && !lastEnter ) {

		};
		lastEnter = enter;

		//puts( "--------------------------------------- Frame ");
		// Rendering
		culling::update( );
		pickPos = picking::update( );
		shadows::update( );
		rc::update( );
		frameCounter++;
		handleMessages( );

		if( next < clock( ) ) {
			char Buf[256];
			sprintf( Buf, "FPS: %d, Rendered: %d, Texture-Switches: %d, Shader-Binds: %d, Polygons: %.3d", frameCounter, rc::Renderable::rendered, rc::Texture::binds, rc::Shader::binds, rc::Mesh::polysDrawn );
			puts( Buf );
			glfwSetWindowTitle( Buf );
			frameCounter = 0;
			next = clock( ) + CLOCKS_PER_SEC;
		};
	} while( rc::windowOpen( ) && !rc::getKey( GLFW_KEY_ESC ) );

	rc::terminate( );
	return 0;
}
Beispiel #6
0
	void Window::setTitle(const std::string& title) {
		glfwSetWindowTitle(handle, title.c_str());
		this->title = title;
	}
Beispiel #7
0
void OpenWindow(int width, int height)
{
	int i = 0;
	std::cout << "OpenWindow\n";

	// (1) init glfw
	if (!glfwInit())
	{
		std::cout << "Failed to init glfw" << std::endl;
		system("PAUSE");
		exit(-1);
	}

	///*
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	//*/

	Util::DebugInit();

	// Open window
	if(!glfwOpenWindow(
		width, height,      // Width and height of window
		8, 8, 8,			// Number of red, green, and blue bits for color buffer
		8,					// Number of bits for alpha buffer
		24,					// Number of bits for depth buffer (Z-buffer)
		0,					// Number of bits for stencil buffer
		GLFW_WINDOW))		// GLFW_FULLSCREEN / GLFW_WINDOW
	{
		glfwTerminate();
		std::cout << "Failed to open window" << std::endl;
		system("PAUSE");
		exit(-1);
	} 

	// Set window title
	glfwSetWindowTitle("Mad Mummies");

	// Enable sticky keys
	glfwEnable(GLFW_STICKY_KEYS);

	// Disable mouse cursor
	glfwDisable(GLFW_MOUSE_CURSOR);

	// glGenVertexArrays is not working otherwise
	glewExperimental = GL_TRUE;

	GLenum err = glewInit();
	if (err != GLEW_OK) {
		std::cout << glewGetErrorString(err);
	}
	if (glewIsSupported("GL_VERSION_3_3")) {
		std::cout << "OpenGL version 3.3 is supported." << std::endl;
	}
	if(GLEW_ARB_geometry_shader4) {
		std::cout << "Geometry shader are supported." << std::endl;
	}

	Util::DebugRegisterCallback();

}
Beispiel #8
0
void outPut::init_outPut()
{
    ///Initialisation OpenGL
    glfwInit();

    loadConfig();

    glfwOpenWindowHint(GLFW_OPENGL_CORE_PROFILE, GL_TRUE);
    glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
    assert(glfwOpenWindow( _reg.WIDTH, _reg.HEIGHT, 0,0,0,0,0,0, GLFW_WINDOW ));
    std::string window_title = "";
    window_title = window_title + __WINDOW_TITLE +" compilé le "+__DATE__+ " à " + __TIME__;
    glfwSetWindowTitle(window_title.c_str() );

    glewInit();

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluPerspective(70,(double)_reg.WIDTH/_reg.HEIGHT,1,1000);

    glEnable(GL_DEPTH_TEST);
    //glEnable(GL_CULL_FACE);

    glEnable(GL_COLOR_MATERIAL);
    glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
    glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
    glClearColor(119.0/255.0, 181.0/255.0, 254.0/255.0,1.0);

    _sNolight.loadProgram("Ressources/shaders/simple.vs","Ressources/shaders/simple.fs");
    _sNolight.linkProgram();
    _sLight.loadProgram("Ressources/shaders/light.vs","Ressources/shaders/light.fs");
    glBindAttribLocation(_sLight.getProgramID(), aID_position, "a_position");
    glBindAttribLocation(_sLight.getProgramID(), aID_normal, "a_normal");
    glBindAttribLocation(_sLight.getProgramID(), aID_cost, "a_cost");
    _sLight.linkProgram();
    uid_maxCost = glGetUniformLocation(_sLight.getProgramID(), "maxCost");
    uid_defaultColor = glGetUniformLocation(_sLight.getProgramID(), "defaultColor");

    {
        //float lightPos[4] = {200.0,200.0,50.0,1.0};
        float lightD[4] = {0.0f,0.0f,0.0f,0.0f};
        float lightA[4] = {1.0f,1.0f,1.0f,1.0f};
        float lightS[4] = {1.0f,1.0f,1.0f,1.0f};

        float materialD[4] = {0.23f, 0.23f, 0.3f, 1.0f };
        float materialA[4] = {0.27f, 0.27f, 0.27f, 1.0f };
        float materialS[4] = {0.7f, 0.7f, 0.7f, 1.0f };


    _sLight.initCommunication();
//    _sLight.setLightPos(lightPos);
    _sLight.setLightMaterial(lightD, lightA,lightS);
    _sLight.setMaterial(materialD, materialA,materialS,200.0);

    }

    _postProcess.loadProgram("Ressources/shaders/postprocess.vs","Ressources/shaders/postprocess.fs");
    //glBindAttribLocation(_postProcess.getProgramID(), aID_UV, "uv_fbo");
    _postProcess.linkProgram();
    uid_pp_colors = glGetUniformLocation(_postProcess.getProgramID(), "fbo_texture");
    uid_pp_offset = glGetUniformLocation(_postProcess.getProgramID(), "u_offset");
    uid_pp_effect = glGetUniformLocation(_postProcess.getProgramID(), "effect");

    frameBuffer.genFBO(_reg.WIDTH, _reg.HEIGHT);

    GLuint idUniformResolution = glGetUniformLocation(_sNolight.getProgramID(), "resolution");
    glUniform2f(idUniformResolution, (float)_reg.WIDTH, (float)_reg.HEIGHT);
    idUniformResolution = glGetUniformLocation(_sLight.getProgramID(), "resolution");
    glUniform2f(idUniformResolution, (float)_reg.WIDTH, (float)_reg.HEIGHT);

    glUseProgram(_sNolight.getProgramID());

    init_Tw();
    init_Bars();

    _reg.MULTIPLIER = 5;
    //_reg.UNIFORM_COLOR = {0.5,0.5,0.5};
    _reg.UNIFORM_COLOR[0]=_reg.UNIFORM_COLOR[1]=_reg.UNIFORM_COLOR[2]=0.5;

    _status.running = true;
    _status.pause = false;
    _status.maxDiff = 50;
    _status.drawDelay = 75;
    _valueChanges.reserve(_dimensions.x*_dimensions.y);

    _reg.WIREFRAME = false;
}
Beispiel #9
0
int main(int argc, char* argv[])
{
  app_argc = argc;
  app_argv = argv;
  int     width, height, running, frames, x, y;
  double  t, t1;
  char    titlestr[ 200 ];

  // Initialise GLFW
  glfwInit();

  bool start_fullscreen = false;
  int x_res = 1280;
  int y_res = 720;
  bool manual_resolution_set = false;
  for (int i = 1; i < argc; i++)
  {
    vsx_string arg1 = argv[i];
    if (arg1 == "--help" || arg1 == "/?" || arg1 == "-help" || arg1 == "-?")
    {
      printf(
             "Usage:\n"
          "  vsxu_player [path_to_vsx_file]\n"
          "\n"
          "Flags: \n"
          "  -pl        Preload all visuals on start \n"
          "  -dr        Disable randomizer     \n"
          "  -p [x,y]   Set window position x,y \n"
          "  -s [x,y]   Set window size x,y \n\n\n"
            );
      exit(0);
    } else
    if (arg1 == "-f") {
      start_fullscreen = true;
    } else
    if (arg1 == "-pl") {
      option_preload_all = true;
    } else
    if (arg1 == "-dr") {
      disable_randomizer = true;
    } else
    if (arg1 == "-no") {
      no_overlay = true;
    } else
    if (arg1 == "-s")
    {
      if (i+1 < argc)
      {
        i++;
        vsx_string arg2 = argv[i];
        vsx_avector<vsx_string> parts;
        vsx_string deli = ",";
        explode(arg2, deli, parts);
        if (parts.size() == 2)
        {
          x_res = vsx_string_helper::s2i(parts[0]);
          y_res = vsx_string_helper::s2i(parts[1]);
          manual_resolution_set = true;
        } else
        {
          deli = "x";
          explode(arg2, deli, parts);
          if ( parts.size() == 2 )
          {
            x_res = vsx_string_helper::s2i(parts[0]);
            y_res = vsx_string_helper::s2i(parts[1]);
            manual_resolution_set = true;
          }
        }
      }
    }
  }
  if (start_fullscreen && !manual_resolution_set)
  {
    // try to get the resolution from the desktop for fullscreen
    GLFWvidmode video_mode;
    glfwGetDesktopMode(&video_mode);
    x_res = video_mode.Height;
    y_res = video_mode.Width;
  }
  
  // Open OpenGL window
  glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4);
  if( !glfwOpenWindow( x_res, y_res, 0,0,0,0,16,0, start_fullscreen?GLFW_FULLSCREEN:GLFW_WINDOW ) ) // GLFW_FULLSCREEN
  {
    printf("Error! Could not create an OpenGL context. Please check your GPU drivers...\n");
    glfwTerminate();
    return 0;
  }
  if (start_fullscreen) glfwEnable( GLFW_MOUSE_CURSOR );
  app_init(0);

  glfwEnable(GLFW_AUTO_POLL_EVENTS);

  for (int i = 1; i < argc; i++) {
    vsx_string arg1 = argv[i];
    if (arg1 == "-p") {
      if (i+1 < argc)
      {
        i++;
        vsx_string arg2 = argv[i];
        vsx_avector<vsx_string> parts;
        vsx_string deli = ",";
        explode(arg2, deli, parts);
        glfwSetWindowPos( vsx_string_helper::s2i(parts[0]), vsx_string_helper::s2i(parts[1]) );
      }
    }
  }

  glfwSetKeyCallback(&key_event);
  glfwSetMouseButtonCallback(&mouse_button_event);
  glfwSetMousePosCallback(&mouse_pos_event);
  glfwSetCharCallback(&key_char_event);
  glfwSetMouseWheelCallback(&mouse_wheel);
  // set window size callback function
  glfwSetWindowSizeCallback(window_size);

  // Enable sticky keys
  glfwEnable( GLFW_STICKY_KEYS );
  glfwSwapInterval(1);

  // Main loop
  running = GL_TRUE;
  frames = 0;

  #if PLATFORM_FAMILY == PLATFORM_FAMILY_UNIX
    sprintf( titlestr, "Vovoid VSXu Player %s [GNU/Linux %d-bit]", vsxu_ver, PLATFORM_BITS);
  #endif
  #if PLATFORM_FAMILY == PLATFORM_FAMILY_WINDOWS
    sprintf( titlestr, "Vovoid VSXu Player %s [Windows %d-bit]", vsxu_ver, PLATFORM_BITS);
  #endif
  glfwSetWindowTitle( titlestr );


  while( running )
  {
    if (mouse_pos_type)
    {
      if (mouse_pos_type == 1) app_mouse_move(last_x,last_y);
      else app_mouse_move_passive(last_x,last_y);
      mouse_pos_type = 0;
    }

    app_pre_draw();

    // Get time and mouse position
    t = glfwGetTime();
    glfwGetMousePos( &x, &y );
    float delta = t-t1;
    t1 = t;
    if (key_pressed != -1)
    {
          //printf("%f\n", delta);
      key_time += delta;
      if (key_time > 0.3f)
      {
        key_repeat_time += delta;
        if (key_repeat_time > initial_key_delay)
        {
          key_repeat_time = 0.0f;
          if (key_character != -1)
            app_char(key_character);
          app_key_down((long)key_pressed);
          initial_key_delay *= 0.99f;
              //printf("repeating key: %d\n", key_character);
        }
      }
    }
    frames ++;

    // Get window size (may be different than the requested size)
    glfwGetWindowSize( &width, &height );
    height = height > 0 ? height : 1;

    // Set viewport
    vsx_gl_state::get_instance()->viewport_set( 0, 0, width, height );

    // Clear color buffer
    glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
    glClear( GL_COLOR_BUFFER_BIT );
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    app_draw(0);

    glfwSwapBuffers();

    // Check if the ESC key was pressed or the window was closed
    running = /*!glfwGetKey( GLFW_KEY_ESC ) &&*/
    glfwGetWindowParam( GLFW_OPENED );
  }

  // Close OpenGL window and terminate GLFW
  glfwTerminate();

  return 0;
}
Beispiel #10
0
int main()
{
    GLFWwindow *window;
    char *userptr = "userptr";

    glfwSetErrorCallback(errorcb);
    assert(glfwInit() == GL_TRUE);
    assert(!strcmp(glfwGetVersionString(), "3.2.1 JS WebGL Emscripten"));
    assert(glfwGetCurrentContext() == NULL);

    {
        int major, minor, rev;
        glfwGetVersion(&major, &minor, &rev);
        assert(major == 3);
        assert(minor == 2);
        assert(rev == 1);
    }

    {
        int count, x, y, w, h;
        GLFWmonitor **monitors = glfwGetMonitors(&count);
        assert(count == 1);
        for (int i = 0; i < count; ++i) {
            assert(monitors[i] != NULL);
        }

        assert(glfwGetPrimaryMonitor() != NULL);
        glfwGetMonitorPos(monitors[0], &x, &y);
        glfwGetMonitorPhysicalSize(monitors[0], &w, &h);
        assert(glfwGetMonitorName(monitors[0]) != NULL);
        glfwSetMonitorCallback(monitcb);

        // XXX: not implemented
        // assert(glfwGetVideoModes(monitors[0], &count) != NULL);
        // assert(glfwGetVideoMode(monitors[0]) != NULL);
        // glfwSetGamma(monitors[0], 1.0f);
        // assert(glfwGetGammaRamp(monitors[0]) != NULL);
        // glfwSetGammaRamp(monitors[0], ramp);
    }

    {
        int x, y, w, h;
        glfwDefaultWindowHints();
        glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);

        window = glfwCreateWindow(640, 480, "glfw3.c", NULL, NULL);
        assert(window != NULL);

        glfwSetWindowPosCallback(window, wposicb);
        glfwSetWindowSizeCallback(window, wsizecb);
        glfwSetWindowCloseCallback(window, wcloscb);
        glfwSetWindowRefreshCallback(window, wrfrscb);
        glfwSetWindowFocusCallback(window, wfocucb);
        glfwSetWindowIconifyCallback(window, wiconcb);
        glfwSetFramebufferSizeCallback(window, wfsizcb);

        assert(glfwWindowShouldClose(window) == 0);
        glfwSetWindowShouldClose(window, 1);
        assert(glfwWindowShouldClose(window) == 1);

        glfwSetWindowTitle(window, "test");
        glfwSetWindowTitle(window, "glfw3.c");

        // XXX: not implemented
        // glfwSetWindowPos(window, 1, 1);

        glfwGetWindowPos(window, &x, &y); // stub
        glfwGetWindowSize(window, &w, &h);
        assert(w == 640 && h == 480);

        glfwSetWindowSize(window, 1, 1);
        glfwGetWindowSize(window, &w, &h);
        assert(w == 1 && h == 1);

        glfwSetWindowSize(window, 640, 480);
        glfwGetFramebufferSize(window, &w, &h);

        // XXX: not implemented
        // glfwIconifyWindow(window);
        // glfwRestoreWindow(window);
        // glfwShowWindow(window);
        // glfwHideWindow(window);

        assert(glfwGetWindowMonitor(window) == NULL);
        glfwDestroyWindow(window);

        window = glfwCreateWindow(640, 480, "glfw3.c", glfwGetPrimaryMonitor(), NULL);
        assert(window != NULL);
        assert(glfwGetWindowMonitor(window) == glfwGetPrimaryMonitor());
        glfwDestroyWindow(window);

        window = glfwCreateWindow(640, 480, "glfw3.c", NULL, NULL);
        assert(window != NULL);

        assert(glfwGetWindowAttrib(window, GLFW_CLIENT_API) == GLFW_OPENGL_ES_API);

        assert(glfwGetWindowUserPointer(window) == NULL);
        glfwSetWindowUserPointer(window, userptr);
        assert(glfwGetWindowUserPointer(window) == userptr);
    }

    {
        double x, y;

        glfwSetKeyCallback(window, wkeypcb);
        glfwSetCharCallback(window, wcharcb);
        glfwSetMouseButtonCallback(window, wmbutcb);
        glfwSetCursorPosCallback(window, wcurpcb);
        glfwSetCursorEnterCallback(window, wcurecb);
        glfwSetScrollCallback(window, wscrocb);

        // XXX: stub, events come immediatly
        // glfwPollEvents();
        // glfwWaitEvents();

        assert(glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_NORMAL);

        // XXX: not implemented
        // glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);

        glfwGetKey(window, GLFW_KEY_A);
        glfwGetMouseButton(window, 0);
        glfwGetCursorPos(window, &x, &y);

        // XXX: not implemented
        // glfwSetCursorPos(window, 0, 0);
    }

    {
        // XXX: not implemented
        // glfwJoystickPresent(joy);
        // glfwGetJoystickAxes(joy, &count);
        // glfwGetJoystickButtons(joy, &count);
        // glfwGetJoystickName(joy);
    }

    {
        // XXX: not implemented
        // glfwSetClipboardString(window, "string");
        // glfwGetClipboardString(window);
    }

    {
        glfwGetTime();
        glfwSetTime(0);
    }

    {
        glfwMakeContextCurrent(window); // stub
        assert(glfwGetCurrentContext() == window);
        glfwSwapBuffers(window); // stub
        glfwSwapInterval(0); // stub
    }

    {
        assert(glfwExtensionSupported("nonexistant") == 0);
        assert(glfwGetProcAddress("nonexistant") == NULL);
    }

    glfwTerminate();

#ifdef REPORT_RESULT
    REPORT_RESULT(1);
#endif
    return 0;
}
Beispiel #11
0
bool SetupScene(int texBase, GLuint *textures) {
    if (!glfwInit()) {
        printf("glfwInit() failed\n");
        return false;
    }

    if( !glfwOpenWindow(640, 480, 0, 0, 0, 0, 0, 0, GLFW_WINDOW))
    {
        printf("glfwOpenWindow() failed\n");
        return false;
    }

    glfwSetWindowTitle("Heavy Metal");

    glGenTextures(NUM_TEXTURES, textures);
    glBindTexture(GL_TEXTURE_2D, textures[BLOCK_TEXTURE]);

    if (!glfwLoadTexture2D("block.tga", GLFW_BUILD_MIPMAPS_BIT)) {
        printf("Texture load failed.\n");
        //return false;
    }
    else {
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                     GL_LINEAR );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
                     GL_LINEAR );
    }

    glBindTexture(GL_TEXTURE_2D, textures[BG_TEXTURE]);
    if (!glfwLoadTexture2D("bg.tga", GLFW_BUILD_MIPMAPS_BIT)) {
        printf("Texture load failed.\n");
        //return false;
    }
    else {
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                        GL_LINEAR );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
                        GL_LINEAR );

    }

    glBindTexture(GL_TEXTURE_2D, textures[FONT_TEXTURE]);
    if (!glfwLoadTexture2D("font.tga", GLFW_BUILD_MIPMAPS_BIT)) {
        printf("Texture load failed.\n");
    }
    else {
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                        GL_LINEAR );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
                        GL_LINEAR );
    }

    glBindTexture(GL_TEXTURE_2D, textures[MAIN_BG_TEXTURE]);
    if (!glfwLoadTexture2D("main_bg.tga", GLFW_BUILD_MIPMAPS_BIT)) {
        printf("Texture load failed.\n");
    }
    else {
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                        GL_LINEAR );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
                        GL_LINEAR );
    }

    glEnable(GL_TEXTURE_2D);

    glViewport(0, 0, 640, 480);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0f, 640, 480, 0.0f, -1.0f, 1.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);							    // The Type Of Depth Test To Do
	glShadeModel(GL_SMOOTH);

    /*glCullFace( GL_FRONT );
    glEnable( GL_CULL_FACE );*/

    //load the font into the calllists for later use
    GenerateFont(texBase, textures);

    game->CaptureKeys(true);

    return true;
}
Beispiel #12
0
int main(int argc, char **argv)
{
	if (argc != 2)
	{
		std::cerr << "Usage: " << argv[0] << " <game directory>" << std::endl;
		return -1;
	}
	// Create window
	glfwInit();
	if (!glfwOpenWindow(1024, 768, 8, 8, 8, 8, 24, 8, GLFW_WINDOW))
	{
		glfwTerminate();
		std::cerr << "Could not create render window." << std::endl;
		return -1;
	}
	glfwGetMousePos(&oldx, &oldy);
	glfwSetMousePosCallback(mouseInput);
	glfwSetMouseButtonCallback(mouseButtonInput);
	glfwSetKeyCallback(keyboardInput);
	glfwSetCharCallback(charInput);
	glfwDisable(GLFW_MOUSE_CURSOR);
	// Create engine
	peak::Engine engine;
	engine.setDirectory(argv[1]);
	// Initialize graphics
	graphics.setEngine(&engine);
	if (!graphics.init(1024, 768))
	{
		glfwTerminate();
		std::cerr << "Could not initialize graphics." << std::endl;
		return -1;
	}
	/*peak::graphics::CameraSceneNode *camera = new peak::graphics::CameraSceneNode(&graphics,
		"pipelines/deferred.pipeline.xml");
	camera->setParent(graphics.getRootSceneNode());
	camera->setPosition(peak::Vector3F(0, 0, 10));
	camera->setRotation(peak::Vector3F(0, 10, 0));
	graphics.setDefaultCamera(camera);*/
	// Create game
	peak::XMLGame *game = new peak::XMLGame();
	network.registerComponents(game);
	graphics.registerComponents(game);
	physics.registerComponents(game);
	engine.setGame(game);
	if (!game->load())
	{
		std::cerr << "Could not load the game." << std::endl;
		return -1;
	}
	/*// Initialize networking
	peak::WorldComponent *worldcomponent = 0;
	bool isserver = false;
	bool isclient = false;
	peak::network::ClientWorldComponent *client = 0;
	peak::network::ServerWorldComponent *server = new peak::network::ServerWorldComponent(0);
	if (server->init(new peak::Buffer()))
	{
		worldcomponent = server;
		isserver = true;
	}
	else
	{
		delete server;
		client = new peak::network::ClientWorldComponent(0);
		if (!client->init("localhost", 27272))
		{
			delete client;
			glfwTerminate();
			std::cerr << "Could not initialize networking." << std::endl;
			return -1;
		}
		worldcomponent = client;
		isclient = true;
	}
	peak::XMLWorld *world = new peak::XMLWorld(&engine,
		engine.getDirectory() + "/Data/Worlds/Test.xml");
	worldcomponent->setWorld(world);
	world->addComponent(worldcomponent);
	if (!world->load())
	{
		delete world;
		std::cerr << "Could not create world." << std::endl;
		return -1;
	}
	if (isclient)
		client->setReady();*/
	// Create initial world
	peak::World *world = game->createInitialWorld();
	if (!world)
	{
		std::cerr << "Could not create world." << std::endl;
		return -1;
	}
	engine.addWorld(world);
	world->start();
	/*if (isserver)
	{
		peak::Entity *entity = game->getEntityFactory("Player")->createEntity(world,
			(1 << peak::EEF_Server) | (1 << peak::EEF_Local));
		world->addEntity(entity);
	}*/
	// Wait for engine to stop
	unsigned int frames = 0;
	uint64_t lasttime = peak::OS::getSystemTime();
	peak::FrameLimiter limiter(20000);
	while (true)
	{
		engine.update();
		if (!engine.isRunning())
			break;
		if (!graphics.render())
			break;
		glfwSwapBuffers();
		if (glfwGetWindowParam(GLFW_OPENED) != GL_TRUE)
			break;
		// Update frame counter
		frames++;
		if (frames == 10)
		{
			uint64_t time = peak::OS::getSystemTime();
			unsigned int dt = time - lasttime;
			float fps = 1000000.0f / ((float)(time - lasttime) / 10);
			lasttime = time;
			frames = 0;
			char title[64];
			snprintf(title, 64, "PeakEngine - %d fps (%d ms)", (int)fps, dt / 1000);
			glfwSetWindowTitle(title);
		}
		// Only render at 50 fps
		limiter.wait();
	}
	// Destroy the engine
	engine.stop(true);
	if (!game->shutdown())
	{
		std::cerr << "Could not destroy the game." << std::endl;
	}
	delete game;
	// Close graphics
	graphics.shutdown();
	glfwEnable(GLFW_MOUSE_CURSOR);
	glfwTerminate();
	return 0;
}
Beispiel #13
0
int main(int argc, char **argv)
{
    glfwSetErrorCallback(error_callback);

    /* Initialize the library */
    if (!glfwInit()){
        fprintf(stderr, "Initialization failed.\n");
        return 1;
    }

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(width, height, "Hello World", NULL, NULL);
    if (!window) {
        glfwTerminate();
        fprintf(stderr, "Error creating window.\n");
        return 1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);
    glfwSetInputMode(window, GLFW_STICKY_MOUSE_BUTTONS, 1);
    glfwSetKeyCallback(window, key_callback);
    glfwSetMouseButtonCallback(window, mouse_button_callback);
    glfwSetCursorPosCallback(window, cursor_pos_callback);

    //**************************** generowanie przykładowych piksli
    hs_init(&argc, &argv);
    initOctTree();
    hs_exit();
    float *piksele = malloc(height*width*3*sizeof(*piksele));

    printf("sizeof(OctTreeNode)=%d\n", (int)sizeof(OctTreeNode));

    //****************************

    init_cl();
    turnCamera(0.f,0.f,0.f); // Calculates initial camera direction
    fflush(stderr);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        for (int i = 0; i < height * width * 3; i++)
            piksele[i] = 0.0;

        clock_t start = clock();
        captureOctTree(camera_pos, camera_target, up, width, height, piksele);
        clock_t end = clock();

        // show render time in window title
        char title[16];
        snprintf(title, 16, "%d ms", (int)((end - start) / (CLOCKS_PER_SEC / 1000)));
        glfwSetWindowTitle(window, title);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    if (num_platforms > 0) {
        clReleaseMemObject(mainOctCL);
        clReleaseMemObject(image);
        clReleaseKernel(kernel);
        clReleaseCommandQueue(queue);
    }
    glfwDestroyWindow(window);

    glfwTerminate();
    return 0;
}
Beispiel #14
0
void boot_init(int* argc, char** argv) {

  int error;

  fail_if(glfwInit() == false);

  // OpenGL version 3
  glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
  glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 0);

  // No window resize
  glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, true);
  // 400% gameboy scale, 5 bit rgb with 1 bit alpha, 8 bit z buffer
  fail_if(glfwOpenWindow(160 * 4, 144 * 4, 5, 5, 5, 1, 8, 0, GLFW_WINDOW) == false);

  glfwSetWindowTitle("");

  glfwEnable(GLFW_AUTO_POLL_EVENTS); // Automatically poll input on swap
  glfwSwapInterval(1); // 0: vsync off, 1: vsync on 

  printf("Renderer: %s\n", glGetString(GL_RENDERER));
  printf("GL Version: %s\n", glGetString(GL_VERSION));
  printf("Using GLSL: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));

  error = glewInit();

  if (error != GLEW_OK) {
    fprintf(stderr, "GLEW error: %s\n", glewGetErrorString(error));
  }

  printf("GL Extension Wrangler: %s\n", glewGetString(GLEW_VERSION));

  // Load audio
  fail_if(alutInit(argc, argv) == false);

  glClearColor(206.0/255.0, 230.0/255.0, 165.0/255.0, 1.0f);
  glEnable(GL_SCISSOR_TEST); // For geom culling
  
  // transparency
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  // z-buffer
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);

  // Set up perspective
  glOrtho(0, 160, 144, 0, -1.0, 1.0);
  glDepthRange(-1.0f, 1.0f);
  glViewport(0, 0, 160 * 4, 144 * 4);

  // This is where Ill put the logo thing
  unsigned logo = bitmap_load("bmp/logo.bmp");
  unsigned logo_vbo;
  float t0, t1, dt;
  float logo_x = 16, logo_y = -80;
  float logo_v[] = {
    0,     0, 0, 1.0 - 0,
    0,   128, 0, 1.0 - 1,
    128, 128, 1, 1.0 - 1,
    128,   0, 1, 1.0 - 0,
  };

  glGenBuffers(1, &logo_vbo);
  glBindBuffer(GL_ARRAY_BUFFER, logo_vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(logo_v)*sizeof(float), logo_v, GL_STATIC_DRAW);
 
  Pipeline* logo_program = pipeline_new(
    shader_new(SHADER_VERTEX, "shader/logo.vert"),
    shader_new(SHADER_FRAGMENT, "shader/logo.frag"));

  pipeline_attribute(logo_program, "coord", 0);
  pipeline_attribute(logo_program, "st", 1);
  pipeline_uniform(logo_program, "pos", 0);
  pipeline_uniform(logo_program, "tex", 1);

  glUseProgram(logo_program->id);

  // Bind the logo to texture 0
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, logo);
  glUniform1i(logo_program->uniform[1], 0);

  // Bind logo vbo
  glBindBuffer(GL_ARRAY_BUFFER, logo_vbo);
  glEnableVertexAttribArray(logo_program->attribute[0]);
  glVertexAttribPointer(logo_program->attribute[0], 2, GL_FLOAT, false, 4*sizeof(float), (void*)0);
  glEnableVertexAttribArray(logo_program->attribute[1]);
  glVertexAttribPointer(logo_program->attribute[1], 2, GL_FLOAT, false, 4*sizeof(float), (void*)(2 * sizeof(float)));

  // load sound
  unsigned sound_source;
  alGenSources(1, &sound_source);
  Sound* ding = sound_load("sound/ding.ogg");

  alSourcei(sound_source, AL_BUFFER, ding->buffer);
  
  glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
  glfwSwapBuffers();

  sleep(1);

  t0 = glfwGetTime();
  while (logo_y < 8) {
    t1 = glfwGetTime();
    dt = t1 - t0;
    t0 = t1;

    logo_y += 50 * dt;

    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

    glUniform2f(logo_program->uniform[0], roundf(logo_x), roundf(logo_y));

    // Render logo
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

    glfwSwapBuffers();
  }

  alSourcePlay(sound_source);

  glDisableVertexAttribArray(logo_program->attribute[0]);
  glDisableVertexAttribArray(logo_program->attribute[1]);

  sleep(1);
}
Beispiel #15
0
void glfwWindow::setWindowTitle(const std::string& title)
{
  glfwSetWindowTitle(title.c_str());
}
Beispiel #16
0
int main( void )
{
    int     running;

    // Initialise GLFW
    glfwInit();

    // Open OpenGL window
    if( !glfwOpenWindow( 500, 500, 0,0,0,0, 16,0, GLFW_WINDOW ) )
    {
        glfwTerminate();
        return 0;
    }

    // Set window title
    glfwSetWindowTitle( "Split view demo" );

    // Enable sticky keys
    glfwEnable( GLFW_STICKY_KEYS );

    // Enable mouse cursor (only needed for fullscreen mode)
    glfwEnable( GLFW_MOUSE_CURSOR );

    // Disable automatic event polling
    glfwDisable( GLFW_AUTO_POLL_EVENTS );

    // Set callback functions
    glfwSetWindowSizeCallback( WindowSizeFun );
    glfwSetWindowRefreshCallback( WindowRefreshFun );
    glfwSetMousePosCallback( MousePosFun );
    glfwSetMouseButtonCallback( MouseButtonFun );

    // Main loop
    do
    {
        // Only redraw if we need to
        if( do_redraw )
        {
            // Draw all views
            DrawAllViews();

            // Swap buffers
            glfwSwapBuffers();

            do_redraw = 0;
        }

        // Wait for new events
        glfwWaitEvents();

        // Check if the ESC key was pressed or the window was closed
        running = !glfwGetKey( GLFW_KEY_ESC ) &&
                  glfwGetWindowParam( GLFW_OPENED );
    }
    while( running );

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    return 0;
}
Beispiel #17
0
int main( void )
{
    int     width, height, running, x;
    double  t;

    // Initialise GLFW
    if( !glfwInit() )
    {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        exit( EXIT_FAILURE );
    }

    // Open OpenGL window
    if( !glfwOpenWindow( 640, 480, 0,0,0,0, 0,0, GLFW_WINDOW ) )
    {
        fprintf( stderr, "Failed to open GLFW window\n" );

        glfwTerminate();
        exit( EXIT_FAILURE );
    }

    glfwSetWindowTitle( "Spinning Triangle" );

    // Enable sticky keys
    glfwEnable( GLFW_STICKY_KEYS );

    // Enable vertical sync (on cards that support it)
    glfwSwapInterval( 1 );

    // Main loop
    running = GL_TRUE;
    while( running )
    {
        // Get time and mouse position
        t = glfwGetTime();
        glfwGetMousePos( &x, NULL );

        // Get window size (may be different than the requested size)
        glfwGetWindowSize( &width, &height );
        height = height > 0 ? height : 1;

        // Set viewport
        glViewport( 0, 0, width, height );

        // Clear color buffer
        glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
        glClear( GL_COLOR_BUFFER_BIT );

        // Select and setup the projection matrix
        glMatrixMode( GL_PROJECTION );
        glLoadIdentity();
        gluPerspective( 65.0f, (GLfloat)width/(GLfloat)height, 1.0f, 100.0f );

        // Select and setup the modelview matrix
        glMatrixMode( GL_MODELVIEW );
        glLoadIdentity();
        gluLookAt( 0.0f, 1.0f, 0.0f,    // Eye-position
                   0.0f, 20.0f, 0.0f,   // View-point
                   0.0f, 0.0f, 1.0f );  // Up-vector

        // Draw a rotating colorful triangle
        glTranslatef( 0.0f, 14.0f, 0.0f );
        glRotatef( 0.3f*(GLfloat)x + (GLfloat)t*100.0f, 0.0f, 0.0f, 1.0f );
        glBegin( GL_TRIANGLES );
          glColor3f( 1.0f, 0.0f, 0.0f );
          glVertex3f( -5.0f, 0.0f, -4.0f );
          glColor3f( 0.0f, 1.0f, 0.0f );
          glVertex3f( 5.0f, 0.0f, -4.0f );
          glColor3f( 0.0f, 0.0f, 1.0f );
          glVertex3f( 0.0f, 0.0f, 6.0f );
        glEnd();

        // Swap buffers
        glfwSwapBuffers();

        // Check if the ESC key was pressed or the window was closed
        running = !glfwGetKey( GLFW_KEY_ESC ) &&
                  glfwGetWindowParam( GLFW_OPENED );
    }

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    exit( EXIT_SUCCESS );
}
Beispiel #18
0
int main(int argc, char** argv)
{
    bool run = GL_TRUE;

    if(!glfwInit())
    {
        exit(EXIT_FAILURE);
    }

    if(!glfwOpenWindow(windows_width, windows_height, 8, 8, 8, 8, 24, 0, GLFW_WINDOW))
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glewInit();
    if (!glewIsSupported( "GL_VERSION_2_0 "
                          "GL_ARB_pixel_buffer_object"
                        )) {
        fprintf( stderr, "ERROR: Support for necessary OpenGL extensions missing.");
        fflush( stderr);
        return false;
    }

    //glfwSetKeyCallback(Viewer::keyCallback);
    //glfwSetMouseButtonCallback(Viewer::mouseButtonCallback);
    //glfwSetMousePosCallback(Viewer::mousePosCallback);
    //glfwSetMouseWheelCallback(Viewer::mouseWheelCallback);

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);

    FluidSim sph;
    sph.initialize();
    sph.resetFrameNum();
    sph.outputObj(true);

    vec3 center(0.0f, -0.15f, 0.0f);
    Viewer::camera()->setFocal(center.x, center.y, center.z);
    Viewer::camera()->resetLookAt();

    old_now = glfwGetTime();
    while(run)
    {
        unsigned int frame_num = sph.getFrameNum();
        if(frame_num > 450)
            exit(0);
        Viewer::camera()->aim();

        printf("frame number: %d\n", frame_num);
        sph.compute(0.004);
        sph.draw();

        utils::drawAxis();
        utils::grabScreen(windows_width, windows_height, sph.getFrameNum());
        now = glfwGetTime();
        char fpsInfo[256];
        sprintf(fpsInfo, "Frame: %u. Time cost per frame: %f", frame_num, now - old_now);
        old_now = now;
        glfwSetWindowTitle(fpsInfo);

        glfwSwapBuffers();

        run = !glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam(GLFW_OPENED);
    }

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Beispiel #19
0
int main() {
	int running = GL_TRUE;
	int width = 640;
	int height = 480;
	int x = 50;
	int y = 50;
	int w = 10;
	int h = 10;
	/*
	Window *win = check_malloc (sizeof(Window));
	win->width = 640;
	win->height = 480;
	*/

	// Initialize GLFW, create a ShivaVG context, open a window

	if( !glfwInit() )
	{
		return 1; // Couldn't initialize GLFW
	}

	int n = glfwOpenWindow(width, height, 0,0,0,0,0,0, GLFW_WINDOW);
	if (!n) {
		glfwTerminate(); // Cleanup GLFW
		return 1; // Couldn't create a window
	}

	glfwSetWindowCloseCallback(window_close_callback);

	glfwSetWindowTitle("Shiva test");

	vgCreateContextSH(width, height); // XXX: TODO: handle errors!!!!
	
	/*
	Rect *r = make_rect(0,0,100,100,0,1,1,1);
	win->rect = r;
	*/
	
	//make color
	VGPaint paint;
	VGfloat paint_array[] = {1,0,1,1};
	paint = vgCreatePaint();
    vgSetParameterfv(paint, VG_PAINT_COLOR, 4, paint_array);
	
	//make rect

	VGPath path = vgCreatePath(VG_PATH_FORMAT_STANDARD, VG_PATH_DATATYPE_F,
								1,0,0,0, VG_PATH_CAPABILITY_ALL);
	vguRect(path, 0, 0, w, h);


	VGfloat magenta[] = {0.9,0,0,1};
	

	while (running) {
			
		vgSetfv(VG_CLEAR_COLOR, 4, magenta);
		vgClear(0, 0, width, height);
		
		vgLoadIdentity();

		vgTranslate(x, y);
		vgSetPaint(paint, VG_FILL_PATH);
		vgDrawPath(path, VG_FILL_PATH);

		glfwSwapBuffers();	

		// Terminate when ESC is pressed or the window is closed
		running = !glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam(GLFW_OPENED);
	}

	// Close the window, clean up the ShivaVG context, and clean up GLFW
	vgDestroyContextSH();

	// Close window and terminate GLFW
	glfwTerminate();

	
	return 0;
}
Beispiel #20
0
	void VehicleSim::update(double dt)
	{
		for (b2Body* body = _physWorld.GetBodyList(); body; body = body->GetNext())
		{
			// Simulate rolling resistance
			// Simple version of rolling resistance using formula given by spec
			// Frr = -Crr * v
			// A better implementation of rolling resistance would
			// counteract the movement due to other forces
			// such that a coefficient of 1 would equal no movement
			// To calculate this, you could resolve the forces on the body into the direction of
			// the vector perpendicular to the normal of the contact and then multiply that
			// by the coefficient of friction of the contact
			for (b2ContactEdge* contactEdge = body->GetContactList(); contactEdge; contactEdge = contactEdge->next)
			{ 
				b2Contact* contact = contactEdge->contact;

				// Get fixtures
				b2Fixture* fixA = contact->GetFixtureA();
				b2Fixture* fixB = contact->GetFixtureB();

				b2Fixture* bodyFix = (fixA->GetBody() == body ? fixA : fixB);

				if (bodyFix->GetShape()->GetType() == b2Shape::e_circle)
				{
					// Get friction of fixtures
					float ca = fixA->GetFriction();
					float cb = fixB->GetFriction();

					// Calculate coefficient of friction for this contact
					// (average of both coefficients of friction)
					float c = contact->GetFriction();

					// Calculate force due to rolling resistance
					// F_rr = v * -c_rr
					b2Vec2 F_rr = -c * body->GetLinearVelocity();

					// Apply rolling resistance
					body->ApplyForceToCenter(F_rr, true);
				}
			}

			// Simple aerodynamic drag, calculated using the formula
			// Fad = -Cad * v|v|
			// Where Cad = the cross sectional area of the car
			// And v is the velocity
			// The cross sectional area is scaled down from world coordinates
			// by a factor of 1000 to produce nice results
			// A more complicated form of aerodynamic drag can be calculated
			// the mass density p of the air (dependent on its temperature and pressure),
			// and the drag coefficient Cd calculated using the object's geometry
			// The formula for this would be Fd = 0.5 * p * v|v| * Cd * Cad
			// But this is beyond the scope of this simulation
			b2Fixture* fixtures = body->GetFixtureList();
			if (fixtures != nullptr)
			{
				b2AABB aabb = fixtures->GetAABB(0);

				for (b2Fixture* fix = fixtures; fix; fix = fix->GetNext())
				{
					// The cross sectional area is estimated using the AABB of each shape
					aabb.Combine(fix->GetAABB(0));
				}

				b2Vec2 size = 0.001f * (aabb.upperBound - aabb.lowerBound);

				// Reverse size to get an approximation of cross sectional area
				float temp = size.x;
				size.x = size.y;
				size.y = temp;

				// Calculate v|v|
				b2Vec2 vsquared = body->GetLinearVelocity().Length() * body->GetLinearVelocity();

				// Calculate force of aerodynamic drag
				b2Vec2 Fad(-size.x * vsquared.x, -size.y * vsquared.y);

				// Apply force to body
				body->ApplyForceToCenter(Fad, true);
			}
		}

		// Update physics system
		double time = glfwGetTime();
		float stepTime = (1.0f / _timeStep);
		while (_lastPhysicsUpdate + stepTime < time)
		{
			if (_simulationRunning)
				doStep();

			_lastPhysicsUpdate += stepTime;
		}

		// Update options
		if (!_worldOptionsTabButton->Hidden())
		{
			for (auto it = _updatableOptions.begin(); it != _updatableOptions.end(); ++it)
			{
				(*it)->update();
			}
		}

		// Do frame update
		doFrameInput(dt);

		// Get inner area of dock
		Gwen::Rect innerBounds = _guiDock->GetInnerBounds();

		// Update camera's viewport
		_camera.setViewport(innerBounds.x, innerBounds.y, innerBounds.w, innerBounds.h);

		// Update camera's matrix
		if (innerBounds.h > 0)
		{
			float aspect = (float)innerBounds.w / innerBounds.h;
			_camera.orthographic(_orthoScale, aspect);
		}

		// Handle motor for each joint
		for (auto joint = _physWorld.GetJointList(); joint; joint = joint->GetNext())
		{
			MotorInput* motorInput = (MotorInput*)joint->GetUserData();

			if (motorInput != nullptr)
			{
				motorInput->update(_window, joint);
			}
		}

		// Set window title
		const int TITLE_LEN = 1024;
		char title[1024];
		sprintf(title, VEHICLESIM_TITLE_FORMAT, getFPS());
		glfwSetWindowTitle(_window, title);
	}
bool CApplication::OpenWindow(size_t iWidth, size_t iHeight, bool bFullscreen, bool bResizeable)
{
#ifdef __APPLE__
	// On macOS, glfwInit() can change the current directory.
	// See http://www.glfw.org/docs/latest/group__init.html
	char *cwd = getcwd(0, 0);
	int ret = glfwInit();
	chdir(cwd);
	free(cwd);
#else
	int ret = glfwInit();
#endif
	if (!ret) {
		printf("glfwInit failed\n");
		exit(1);
	}

	m_bFullscreen = bFullscreen;

	if (HasCommandLineSwitch("--fullscreen"))
		m_bFullscreen = true;

	if (HasCommandLineSwitch("--windowed"))
		m_bFullscreen = false;

	m_iWindowWidth = iWidth;
	m_iWindowHeight = iHeight;

    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
    glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

	if (m_bMultisampling)
		glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4);

	glfwOpenWindowHint(GLFW_DEPTH_BITS, 16);
	glfwOpenWindowHint(GLFW_RED_BITS, 8);
	glfwOpenWindowHint(GLFW_GREEN_BITS, 8);
	glfwOpenWindowHint(GLFW_BLUE_BITS, 8);
	glfwOpenWindowHint(GLFW_ALPHA_BITS, 8);

	if (!(m_pWindow = (size_t)glfwOpenWindow(iWidth, iHeight, 8, 8, 8, 8, 16, 0, GLFW_WINDOW)))
	{
		glfwTerminate();
		return false;
	}

	glfwSetWindowTitle((char*)L"Math for Game Developers");

	int iScreenWidth;
	int iScreenHeight;

	GetScreenSize(iScreenWidth, iScreenHeight);

	if (!m_bFullscreen)
	{
		// The taskbar is at the bottom of the screen. Pretend the screen is smaller so the window doesn't clip down into it.
		// Also the window's title bar at the top takes up space.
		iScreenHeight -= 70;

		int iWindowX = (int)(iScreenWidth/2-m_iWindowWidth/2);
		int iWindowY = (int)(iScreenHeight/2-m_iWindowHeight/2);
		iWindowY -= 40;    // Move it a tad so that we can see it better in the videos.
		iWindowX -= 80;
		glfwSetWindowPos(iWindowX, iWindowY);
	}

	glfwSetWindowCloseCallback(&CApplication::WindowCloseCallback);
	glfwSetWindowSizeCallback(&CApplication::WindowResizeCallback);
	glfwSetKeyCallback(&CApplication::KeyEventCallback);
	glfwSetCharCallback(&CApplication::CharEventCallback);
	glfwSetMousePosCallback(&CApplication::MouseMotionCallback);
	glfwSetMouseButtonCallback(&CApplication::MouseInputCallback);
	glfwSwapInterval( 1 );
	glfwSetTime( 0.0 );

	SetMouseCursorEnabled(true);

	GLenum err = gl3wInit();
	if (0 != err)
		exit(0);

	glEnable(GL_CULL_FACE);
	glEnable(GL_DEPTH_TEST);
	glLineWidth(1.0);

	m_bIsOpen = true;

	m_pRenderer = CreateRenderer();
	m_pRenderer->Initialize();

	return true;
}
Beispiel #22
0
	void Engine::setWindowTitle(const char* title)
	{
		glfwSetWindowTitle(window, title);
	}
Beispiel #23
0
int main()
{
  srand(time(0));

  s_settings settings;
  settings.mode = MODE_AUTO;
  settings.w = 960;
  settings.h = 480;
  settings.tiled_view = true;
  settings.paused = false;

  if(glfwInit() == GL_FALSE)
  {
    std::cerr << "Failed to init GLFW" << std::endl;
    return 1;
  }

  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

  GLFWwindow *window;
  if((window = glfwCreateWindow(settings.w, settings.h, "Painting Evolution", 0, 0)) == 0)
  {
    std::cerr << "Failed to open window" << std::endl;
    glfwTerminate();
    return 1;
  }

  glfwSetWindowUserPointer(window, &settings);

  glfwMakeContextCurrent(window);
  glfwSetWindowSizeCallback(window, glfw_window_size_callback);
  glfwSetCursorPosCallback(window, glfw_cursor_position_callback);
  glfwSetScrollCallback(window, glfw_mouse_scroll_callback);
  glfwSetKeyCallback(window, glfw_keyboard_callback);
  glfwSetMouseButtonCallback(window, glfw_mouse_button_callback);

  // start GLEW extension handler
  glewExperimental = GL_TRUE;
  GLenum err = glewInit();
  while((err = glGetError()) != GL_NO_ERROR)
  {
    std::cout << "glewInit error: " << err << std::endl;
    std::cout << std::endl;
  }
  
  #ifndef NDEBUG
  const GLubyte* renderer = glGetString(GL_RENDERER);
  const GLubyte* version = glGetString(GL_VERSION);
  
  std::cout << "Debug info:" << std::endl;
  std::cout << " Date: " << __DATE__ << std::endl;
  std::cout << " Time: " << __TIME__ << std::endl;
  std::cout << " Renderer: " << renderer << std::endl;
  std::cout << " OpenGL version supported: " << version << std::endl; 
  std::cout << " Max textures: " << GL_MAX_TEXTURE_UNITS << std::endl;
  std::cout << std::endl;
  #endif

  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);


  bool r;
  
  GLuint vertex_shader, fragment_shader, compute_shader;

  r = vertex_shader_load(&vertex_shader, "shaders\\vertex_shader.glsl");
  if(r == false)
  {
    glfwDestroyWindow(window);
    glfwTerminate();
  }

  r = fragment_shader_load(&fragment_shader, "shaders\\fragment_shader.glsl");
  if(r == false)
  {
    glfwDestroyWindow(window);
    glfwTerminate();
  }

  r = compute_shader_load(&compute_shader, "shaders\\compute_shader.glsl");
  if(r == false)
  {
    glfwDestroyWindow(window);
    glfwTerminate();
  }


  GLuint shader_program, similarity_program;

  // create program
  shader_program = glCreateProgram();
  glAttachShader(shader_program, vertex_shader);
  glAttachShader(shader_program, fragment_shader);
  glLinkProgram(shader_program);
  check_program_link_status(shader_program);
  
  // create program
  similarity_program = glCreateProgram();
  glAttachShader(similarity_program, compute_shader);
  glLinkProgram(similarity_program);
  check_program_link_status(similarity_program);
  

  /**** side by side view ****/
  GLuint vao, vbo, cbo, uvbo;
  
  glGenVertexArrays(1, &vao);
  glBindVertexArray(vao);
  
  // Vertices
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (char*)0 + 0*sizeof(GLfloat));
  
  // Colours
  glGenBuffers(1, &cbo);
  glBindBuffer(GL_ARRAY_BUFFER, cbo);
  glEnableVertexAttribArray(1);
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (char*)0 + 0*sizeof(GLfloat));
  
  // uvs
  glGenBuffers(1, &uvbo);
  glBindBuffer(GL_ARRAY_BUFFER, uvbo);
  glEnableVertexAttribArray(2);
  glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, (char*)0 + 0*sizeof(GLfloat));
  /**** side by side view ****/
  

  s_sim sim;
  bmp_load(&sim.target, "input.bmp");
  
  sim.grid_pos = 0;
  sim.grid_w = 8;
  sim.grid_h = 8;
  sim.tile_w = sim.target.w/sim.grid_w;
  sim.tile_h = sim.target.h/sim.grid_h;

  settings.sim = &sim;

  assert(sim.target.w%16 == 0);
  assert(sim.target.h%16 == 0);
  assert(sim.tile_w%16 == 0);
  assert(sim.tile_h%16 == 0);
  
  s_painting temp;
  for(int p = 0; p < 36; ++p)
  {
    sim.paintings.push_back(temp);
    painting_init(&sim.paintings[p], sim.tile_w, sim.tile_h);
  }
  for(int p = 0; p < sim.grid_w*sim.grid_h; ++p)
  {
    sim.grid_paintings.push_back(temp);
    painting_init(&sim.grid_paintings[p], sim.tile_w, sim.tile_h);
  }
  
  int num_workgroups = sim.tile_w*sim.tile_h/16/16;
  std::vector<GLfloat> scores(num_workgroups);
  

  // generate vao_compute and scores_bo
  GLuint vao_compute, scores_bo;
  
  glGenVertexArrays(1, &vao_compute);
  glBindVertexArray(vao_compute);
  
  glGenBuffers(1, &scores_bo);
  glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, scores_bo);
  glBufferData(GL_SHADER_STORAGE_BUFFER, num_workgroups*sizeof(scores[0]), &scores[0], GL_DYNAMIC_DRAW); // GL_STATIC_DRAW
  
  glGenTextures(1, &sim.target_id);
  glBindTexture(GL_TEXTURE_2D, sim.target_id);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // GL_LINEAR
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // GL_LINEAR
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

  glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, sim.target.w, sim.target.h, 0, GL_RGB, GL_UNSIGNED_BYTE, sim.target.data);

  glGenTextures(1, &sim.result_id);
  glBindTexture(GL_TEXTURE_2D, sim.result_id);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // GL_LINEAR
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // GL_LINEAR
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, sim.target.w, sim.target.h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);

  std::vector<GLubyte> emptyData(3 * sim.target.w * sim.target.h, 0);
  glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, sim.target.w, sim.target.h, GL_RGB, GL_UNSIGNED_BYTE, &emptyData[0]);
  
  
  GLuint highres_texture_id = 0;
  glGenTextures(1, &highres_texture_id);
  glBindTexture(GL_TEXTURE_2D, highres_texture_id);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // GL_LINEAR
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // GL_LINEAR
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, sim.tile_w, sim.tile_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);

  // create a framebuffer object
  GLuint highres_fbo = 0;
  glGenFramebuffers(1, &highres_fbo);
  glBindFramebuffer(GL_FRAMEBUFFER, highres_fbo);
  
  // attach the texture to FBO color attachment point
  glFramebufferTexture2D(GL_FRAMEBUFFER,        // 1. fbo target: GL_FRAMEBUFFER 
                         GL_COLOR_ATTACHMENT0,  // 2. attachment point
                         GL_TEXTURE_2D,         // 3. tex target: GL_TEXTURE_2D
                         highres_texture_id,    // 4. tex ID
                         0);                    // 5. mipmap level: 0(base)

  glClearColor(0.0, 0.0, 0.0, 1.0);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  
  glBindTexture(GL_TEXTURE_2D, 0);
  
  // check FBO status
  GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  if(status != GL_FRAMEBUFFER_COMPLETE)
  {
    std::cout << "Framebuffer error:" << status<< std::endl;
    return -1;
  }

  GLuint texture_slice = 0;
  glGenTextures(1, &texture_slice);
  glActiveTexture(GL_TEXTURE0 + texture_slice);
  glBindTexture(GL_TEXTURE_2D, texture_slice);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // GL_LINEAR
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // GL_LINEAR
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, sim.tile_w, sim.tile_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
  glBindTexture(GL_TEXTURE_2D, 0);

  glPointSize(2.0);

  GLuint query;
  glGenQueries(1, &query);


  GLubyte *data = new GLubyte[3*sim.tile_w*sim.tile_h];

  unsigned int parent1_id = 0;
  unsigned int parent2_id = 0;
  float parent1_score = FLT_MIN;
  float parent2_score = FLT_MIN;

  int x_offset = 0;
  int y_offset = 0;
  int tile_x = 0;
  int tile_y = 0;
  int last_grid_pos = -1;
  int auto_generation = 0;
  float start_score = 0.0;

  while(!glfwWindowShouldClose(window))
  {
    glBeginQuery(GL_TIME_ELAPSED, query);

    if(settings.paused == false)
    {
      // Auto mode will spend a set number of generations per grid position and then move to the new lowest scoring
      if(settings.mode == MODE_AUTO && auto_generation >= AUTO_GENERATIONS)
      {
        // Set score rate
        sim.grid_paintings[sim.grid_pos].score_rate = (sim.grid_paintings[sim.grid_pos].score - start_score)/AUTO_GENERATIONS;

        assert(sim.grid_paintings[sim.grid_pos].score_rate >= 0.0);
        assert(sim.grid_paintings[sim.grid_pos].score_rate <= 1.0/AUTO_GENERATIONS);

        float fastest = FLT_MIN;
        for(unsigned int p = 0; p < sim.grid_paintings.size(); ++p)
        {
          if(sim.grid_paintings[p].score_rate > fastest)
          {
            sim.grid_pos = p;
            fastest = sim.grid_paintings[p].score_rate;
          }
        }

        start_score = sim.grid_paintings[sim.grid_pos].score;
        auto_generation = 0;
      }

      // Next tile
      if(last_grid_pos != sim.grid_pos)
      {
        if(last_grid_pos != -1)
        {
          // Update results texture - do all grid paintings because new ones might've been loaded in
          for(unsigned int p = 0; p < sim.grid_paintings.size(); ++p)
          {
            if(sim.grid_paintings[p].generation == 0) {continue;}

            tile_x = p%sim.grid_w;
            tile_y = p/sim.grid_w;
            
            x_offset = tile_x * sim.tile_w;
            y_offset = tile_y * sim.tile_h;
        
            // Save current best paiting to the results
            glViewport(0, 0, sim.tile_w, sim.tile_h);

            // Redraw
            glBindFramebuffer(GL_FRAMEBUFFER, highres_fbo);
            glClearColor(sim.grid_paintings[p].r, sim.grid_paintings[p].g, sim.grid_paintings[p].b, 1.0);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
            
            // Bind the current vao
            glBindVertexArray(vao);
            
            // Vertices
            glBindBuffer(GL_ARRAY_BUFFER, vbo);
            glBufferData(GL_ARRAY_BUFFER, 2 * 3 * sim.grid_paintings[p].num_triangles * sizeof(GLfloat), &sim.grid_paintings[p].positions[0], GL_STATIC_DRAW);
            
            // Colours
            glBindBuffer(GL_ARRAY_BUFFER, cbo);
            glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sim.grid_paintings[p].num_triangles * sizeof(GLfloat), &sim.grid_paintings[p].colours[0], GL_STATIC_DRAW);
            
            // Texture coords
            glBindBuffer(GL_ARRAY_BUFFER, uvbo);
            glBufferData(GL_ARRAY_BUFFER, 2 * 3 * sim.grid_paintings[p].num_triangles * sizeof(GLfloat), &sim.grid_paintings[p].uvs[0], GL_STATIC_DRAW);
            
            glUseProgram(shader_program);
            
            // Set the uniforms
            glm::mat4 view = glm::ortho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
            glUniformMatrix4fv(0, 1, GL_FALSE, glm::value_ptr(view));
            
            // Draw
            glDrawArrays(GL_TRIANGLES, 0, 3*sim.grid_paintings[p].num_triangles);


            // Get tile data
            glBindTexture(GL_TEXTURE_2D, highres_texture_id);
            glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, data);

            // Write tile to result texture
            glBindTexture(GL_TEXTURE_2D, sim.result_id);
            glTexSubImage2D(GL_TEXTURE_2D, 0, x_offset, y_offset, sim.tile_w, sim.tile_h, GL_RGB, GL_UNSIGNED_BYTE, data);
          }

          glBindFramebuffer(GL_FRAMEBUFFER, 0);
          glViewport(0, 0, settings.w, settings.h);
        }
        
        
        // If we've never been at this grid position before, we should start with some random paintings
        // If we have been here before, just copy the painting in storage
        if(sim.grid_paintings[sim.grid_pos].generation == 0)
        {
          for(unsigned int p = 0; p < sim.paintings.size(); ++p)
          {
            painting_randomise(&sim.paintings[p]);
          }
        }
        else
        {
          for(unsigned int p = 0; p < sim.paintings.size(); ++p)
          {
            painting_copy(&sim.paintings[p], &sim.grid_paintings[sim.grid_pos]);
          }
        }
        
        tile_x = sim.grid_pos%sim.grid_w;
        tile_y = sim.grid_pos/sim.grid_w;
        
        x_offset = tile_x * sim.tile_w;
        y_offset = tile_y * sim.tile_h;
        
        for(int y = 0; y < sim.tile_h; ++y)
        {
          for(int x = 0; x < sim.tile_w; ++x)
          {
            data[3*y*sim.tile_w + 3*x + 0] = sim.target.data[3*(y + y_offset) *sim.target.w + 3*(x + x_offset) + 0];
            data[3*y*sim.tile_w + 3*x + 1] = sim.target.data[3*(y + y_offset) *sim.target.w + 3*(x + x_offset) + 1];
            data[3*y*sim.tile_w + 3*x + 2] = sim.target.data[3*(y + y_offset) *sim.target.w + 3*(x + x_offset) + 2];
          }
        }
        
        glBindTexture(GL_TEXTURE_2D, texture_slice);
        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, sim.tile_w, sim.tile_h, GL_RGB, GL_UNSIGNED_BYTE, data);
        
        std::cout << std::endl;
        std::cout << "Pos: " << tile_x << " " << tile_y << std::endl;
        std::cout << "Score: " << sim.grid_paintings[sim.grid_pos].score << std::endl;
        std::cout << "Rate: " << sim.grid_paintings[sim.grid_pos].score_rate << std::endl;
        std::cout << "Gen: " << sim.grid_paintings[sim.grid_pos].generation << std::endl;
        std::cout << std::endl;

        last_grid_pos = sim.grid_pos;
      }
      
      
      // Draw paintings
      glViewport(0, 0, sim.tile_w, sim.tile_h);
      for(unsigned int p = 0; p < sim.paintings.size(); ++p)
      {
        glBindFramebuffer(GL_FRAMEBUFFER, sim.paintings[p].fbo);
        glClearColor(sim.paintings[p].r, sim.paintings[p].g, sim.paintings[p].b, 1.0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        
        // bind the current vao
        glBindVertexArray(vao);
        
        // Vertices
        glBindBuffer(GL_ARRAY_BUFFER, vbo);
        glBufferData(GL_ARRAY_BUFFER, 2 * 3 * sim.paintings[p].num_triangles * sizeof(GLfloat), &sim.paintings[p].positions[0], GL_STATIC_DRAW);
        
        // Colours
        glBindBuffer(GL_ARRAY_BUFFER, cbo);
        glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sim.paintings[p].num_triangles * sizeof(GLfloat), &sim.paintings[p].colours[0], GL_STATIC_DRAW);
        
        // Texture coords
        glBindBuffer(GL_ARRAY_BUFFER, uvbo);
        glBufferData(GL_ARRAY_BUFFER, 2 * 3 * sim.paintings[p].num_triangles * sizeof(GLfloat), &sim.paintings[p].uvs[0], GL_STATIC_DRAW);
        
        glUseProgram(shader_program);
        
        // Set the uniforms
        glm::mat4 view = glm::ortho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
        glUniformMatrix4fv(0, 1, GL_FALSE, glm::value_ptr(view));
        
        // Draw
        glDrawArrays(GL_TRIANGLES, 0, 3*sim.paintings[p].num_triangles);
      }
      glBindFramebuffer(GL_FRAMEBUFFER, 0);
      glViewport(0, 0, settings.w, settings.h);

      // Comparisons
      for(unsigned int p = 0; p < sim.paintings.size(); ++p)
      {
        glUseProgram(similarity_program);

        glActiveTexture(GL_TEXTURE0 + texture_slice);
        glBindTexture(GL_TEXTURE_2D, texture_slice);

        glActiveTexture(GL_TEXTURE0 + sim.paintings[p].texture_id);
        glBindTexture(GL_TEXTURE_2D, sim.paintings[p].texture_id);

        // Setup uniforms
        glUniform1i(0, texture_slice);
        glUniform1i(1, sim.paintings[p].texture_id);
        glUniform1i(2, p);
    
        // Compute
        int groups_x = sim.tile_w/16;
        int groups_y = sim.tile_h/16;
    
        glDispatchCompute(groups_x, groups_y, 1);

        // Get scores
        glBindBuffer(GL_SHADER_STORAGE_BUFFER, scores_bo);
        glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, num_workgroups*sizeof(scores[0]), &scores[0]);

        // Calculate similarity percentage
        sim.paintings[p].score = 0.0;
        for(int n = 0; n < num_workgroups; ++n)
        {
          sim.paintings[p].score += scores[n];
        }
        sim.paintings[p].score = 1.0 - sim.paintings[p].score/(3*sim.tile_w*sim.tile_h);
      }
      glActiveTexture(GL_TEXTURE0);
      
      // Find best painting
      parent1_id = sim.paintings.size();
      parent1_score = FLT_MIN;
      parent2_id = sim.paintings.size();
      parent2_score = FLT_MIN;

      for(unsigned int p = 0; p < sim.paintings.size(); ++p)
      {
        if(sim.paintings[p].score >= parent1_score)
        {
          parent2_id = parent1_id;
          parent2_score = parent1_score;

          parent1_id = p;
          parent1_score = sim.paintings[p].score;
          continue;
        }
        if(sim.paintings[p].score >= parent2_score)
        {
          parent2_id = p;
          parent2_score = sim.paintings[p].score;
        }
      }

      assert(parent1_id != sim.paintings.size());
      assert(parent2_id != sim.paintings.size());
      assert(parent1_id != parent2_id);
      assert(parent1_score >= 0.0);
      assert(parent2_score >= 0.0);
      

      // To be used when a screenshot is taken
      settings.best_painting = sim.result_id;


      // Create new sim.paintings from best
      for(unsigned int p = 0; p < sim.paintings.size(); ++p)
      {
        if(p == parent1_id || p == parent2_id) {continue;}

        paintings_breed(&sim.paintings[p], &sim.paintings[parent1_id], &sim.paintings[parent2_id]);
      }
      
      
      // Mutate sim.paintings
      for(unsigned int p = 0; p < sim.paintings.size(); ++p)
      {
        if(p == parent1_id || p == parent2_id) {continue;}

        painting_jiggle(&sim.paintings[p]);
      }
      

      // Print scores occasionally
      if(sim.grid_paintings[sim.grid_pos].generation%250 == 0)
      {
        //std::cout << "Gen " << sim.grid_paintings[sim.grid_pos].generation << ": " << parent1_id << " - " << sim.grid_paintings[sim.grid_pos].score*100.0 << "% " << std::endl;
        //std::cout << "Gen " << sim.grid_paintings[sim.grid_pos].generation << ": " << parent1_id << " - " << sim.grid_paintings[sim.grid_pos].score*100.0 << "% " << sim.grid_paintings[sim.grid_pos].score_rate << std::endl;
      }


      // Save best painting if it's an improvement
      if(sim.paintings[parent1_id].score > sim.grid_paintings[sim.grid_pos].score)
      {
        int temp = sim.grid_paintings[sim.grid_pos].generation;
        painting_copy(&sim.grid_paintings[sim.grid_pos], &sim.paintings[parent1_id]);
        sim.grid_paintings[sim.grid_pos].generation = temp;
      }
      

      // Count generations
      sim.grid_paintings[sim.grid_pos].generation++;
      if(settings.mode == MODE_AUTO)
      {
        auto_generation++;
      }
    }


    // Render target and best sim.paintings
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    glBindVertexArray(vao);
    
    glUseProgram(shader_program);
    
    glm::mat4 view = glm::ortho(-1.0, 1.0, 0.0, 1.0, -1.0, 1.0);
    glUniformMatrix4fv(0, 1, GL_FALSE, glm::value_ptr(view));
    
    // Render target to the screen
    glBindTexture(GL_TEXTURE_2D, sim.target_id);
    GLfloat positions[8] = {-1.0, 0.0,
                            -1.0, 1.0,
                             0.0, 1.0,
                             0.0, 0.0};
    GLfloat colours[12] = {0.0, 0.0, 0.0,
                           0.0, 0.0, 0.0,
                           0.0, 0.0, 0.0,
                           0.0, 0.0, 0.0};
    GLfloat uvs[8] = {0.0, 0.0,
                      0.0, 1.0,
                      1.0, 1.0,
                      1.0, 0.0};
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), &positions, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, cbo);
    glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(GLfloat), &colours, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, uvbo);
    glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), &uvs, GL_STATIC_DRAW);
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
    
    if(settings.tiled_view == true)
    {
      unsigned int x_num = ceil(sqrt(sim.paintings.size()));
      unsigned int y_num = ceil(sqrt(sim.paintings.size()));

      if(x_num*(y_num-1) >= sim.paintings.size())
      {
        y_num -= 1;
      }

      float width  = 1.0/x_num;
      float height = 1.0/y_num;
      
      for(unsigned int y = 0; y < y_num; ++y)
      {
        for(unsigned int x = 0; x < x_num; ++x)
        {
          if(y*x_num + x >= sim.paintings.size()) {break;}
          
          glBindTexture(GL_TEXTURE_2D, sim.paintings[y*y_num + x].texture_id);
          positions[0] = x*width;     positions[1] = y*height;
          positions[2] = x*width;     positions[3] = (y+1)*height;
          positions[4] = (x+1)*width; positions[5] = (y+1)*height;
          positions[6] = (x+1)*width; positions[7] = y*height;
          glBindBuffer(GL_ARRAY_BUFFER, vbo);
          glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), &positions, GL_STATIC_DRAW);
          glBindBuffer(GL_ARRAY_BUFFER, cbo);
          glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(GLfloat), &colours, GL_STATIC_DRAW);
          glBindBuffer(GL_ARRAY_BUFFER, uvbo);
          glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), &uvs, GL_STATIC_DRAW);
          glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
        }
      }
    }
    else
    {
      // Draw the results texture
      glBindTexture(GL_TEXTURE_2D, sim.result_id);
      positions[0] = 0.0; positions[1] = 0.0;
      positions[2] = 0.0; positions[3] = 1.0;
      positions[4] = 1.0; positions[5] = 1.0;
      positions[6] = 1.0; positions[7] = 0.0;

      glBindBuffer(GL_ARRAY_BUFFER, vbo);
      glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), &positions, GL_STATIC_DRAW);
      glBindBuffer(GL_ARRAY_BUFFER, cbo);
      glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(GLfloat), &colours, GL_STATIC_DRAW);
      glBindBuffer(GL_ARRAY_BUFFER, uvbo);
      glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), &uvs, GL_STATIC_DRAW);
      glDrawArrays(GL_TRIANGLE_FAN, 0, 4);


      // Draw current best over the top of the results texture
      glBindTexture(GL_TEXTURE_2D, sim.paintings[parent1_id].texture_id);

      float x_gap = 1.0/sim.grid_w;
      float y_gap = 1.0/sim.grid_h;

      positions[0] = x_gap*tile_x;     positions[1] = y_gap*tile_y;
      positions[2] = x_gap*tile_x;     positions[3] = y_gap*(tile_y+1);
      positions[4] = x_gap*(tile_x+1); positions[5] = y_gap*(tile_y+1);
      positions[6] = x_gap*(tile_x+1); positions[7] = y_gap*tile_y;

      glBindBuffer(GL_ARRAY_BUFFER, vbo);
      glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), &positions, GL_STATIC_DRAW);
      glBindBuffer(GL_ARRAY_BUFFER, cbo);
      glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(GLfloat), &colours, GL_STATIC_DRAW);
      glBindBuffer(GL_ARRAY_BUFFER, uvbo);
      glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), &uvs, GL_STATIC_DRAW);
      glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
    }

    glfwSwapBuffers(window);
    

    // check for errors
    GLenum error = glGetError();
    if(error != GL_NO_ERROR)
    {
      std::cout << "Error: " << error << std::endl;
    }

    // FPS
    glEndQuery(GL_TIME_ELAPSED);
    GLuint64 result;
    glGetQueryObjectui64v(query, GL_QUERY_RESULT, &result);
    std::stringstream tmp;
    tmp << "Painting Evolution: " << int(1e9/result) << " FPS";
    glfwSetWindowTitle(window, tmp.str().c_str());


    glfwPollEvents();
  }

  delete[] data;

  // delete the created objects
  glDeleteVertexArrays(1, &vao);
  glDeleteBuffers(1, &scores_bo);

  glDetachShader(shader_program, vertex_shader);
  glDetachShader(shader_program, fragment_shader);
  glDeleteShader(vertex_shader);
  glDeleteShader(fragment_shader);
  glDeleteProgram(shader_program);

  glDetachShader(similarity_program, compute_shader);
  glDeleteShader(compute_shader);
  glDeleteProgram(similarity_program);

  glfwDestroyWindow(window);
  glfwTerminate();
  return 0;
}
Beispiel #24
0
void Init(){
	for (int i = 0; i < 50; i++){
		Gesture_ g;
		g_gestureManager.gestures.push_back(g);
	}

	DBConnect();
	DBLoadAllGestures();
	loadFTable();
	// Initialise GLFW
	if (!glfwInit())
	{
		fprintf(stderr, "Failed to initialize GLFW\n");
		exit(1);
	}

	glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	// Open a window and create its OpenGL context
	if (!glfwOpenWindow(1050, 690, 0, 0, 0, 0, 32, 0, GLFW_WINDOW))
	{
		fprintf(stderr, "Failed to open GLFW window.\n");
		glfwTerminate();
		exit(1);
	}

	// Initialize GLEW
	glewExperimental = true; // Needed for core profile
	if (glewInit() != GLEW_OK) {
		fprintf(stderr, "Failed to initialize GLEW\n");
		exit(1);
	}

	glfwSetWindowTitle("Gesture Recognition");

	glfwDisable(GLFW_STICKY_KEYS);

	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
	
	// Init AntTweakBar
	if (!TwInit(TW_OPENGL_CORE, NULL)){
		fprintf(stderr, "Failed to initialize AntTweakBar\n");
		exit(1);
	}

	TwWindowSize(1050, 690);

	CreateBar();

	
	
	//leap init
	if (g_leapController.isConnected()) {
		if (!g_leapController.addListener(g_leapListener))
			std::cout << "Leap controller isnt accepting the listener" << std::endl;
	}
	else
		std::cout << "Leap controller isnt connected" << std::endl;
		
}
Beispiel #25
0
void Window::set_title(const String& title)
{
	glfwSetWindowTitle(glfw, title.c_str());
}
Beispiel #26
0
void Application::setTitle(const std::string& title)
{
    glfwSetWindowTitle(title.c_str());
}
Beispiel #27
0
//------------------------------------------------------------------------------
int main(int argc, char ** argv)
{
    bool fullscreen = false;
    std::string str;
    for (int i = 1; i < argc; ++i) {
        if (!strcmp(argv[i], "-d"))
            g_level = atoi(argv[++i]);
        else if (!strcmp(argv[i], "-c"))
            g_repeatCount = atoi(argv[++i]);
        else if (!strcmp(argv[i], "-f"))
            fullscreen = true;
        else {
            std::ifstream ifs(argv[1]);
            if (ifs) {
                std::stringstream ss;
                ss << ifs.rdbuf();
                ifs.close();
                str = ss.str();
                g_defaultShapes.push_back(SimpleShape(str.c_str(), argv[1], kCatmark));
            }
        }
    }
    initializeShapes();
    OsdSetErrorCallback(callbackError);

    if (not glfwInit()) {
        printf("Failed to initialize GLFW\n");
        return 1;
    }

    static const char windowTitle[] = "OpenSubdiv glBatchViewer";
    
#define CORE_PROFILE
#ifdef CORE_PROFILE
    setGLCoreProfile();
#endif

#if GLFW_VERSION_MAJOR>=3
    if (fullscreen) {
    
        g_primary = glfwGetPrimaryMonitor();

        // apparently glfwGetPrimaryMonitor fails under linux : if no primary,
        // settle for the first one in the list    
        if (not g_primary) {
            int count=0;
            GLFWmonitor ** monitors = glfwGetMonitors(&count);

            if (count)
                g_primary = monitors[0];
        }
        
        if (g_primary) {
            GLFWvidmode const * vidmode = glfwGetVideoMode(g_primary);
            g_width = vidmode->width;
            g_height = vidmode->height;
        }
    }

    if (not (g_window=glfwCreateWindow(g_width, g_height, windowTitle, 
                                       fullscreen and g_primary ? g_primary : NULL, NULL))) {
        printf("Failed to open window.\n");
        glfwTerminate();
        return 1;
    }
    glfwMakeContextCurrent(g_window);
    glfwSetKeyCallback(g_window, keyboard);
    glfwSetCursorPosCallback(g_window, motion);
    glfwSetMouseButtonCallback(g_window, mouse);
    glfwSetWindowSizeCallback(g_window, reshape);
    glfwSetWindowCloseCallback(g_window, windowClose);
#else
    if (glfwOpenWindow(g_width, g_height, 8, 8, 8, 8, 24, 8,
                       fullscreen ? GLFW_FULLSCREEN : GLFW_WINDOW) == GL_FALSE) {
        printf("Failed to open window.\n");
        glfwTerminate();
        return 1;
    }
    glfwSetWindowTitle(windowTitle);
    glfwSetKeyCallback(keyboard);
    glfwSetMousePosCallback(motion);
    glfwSetMouseButtonCallback(mouse);
    glfwSetWindowSizeCallback(reshape);
    glfwSetWindowCloseCallback(windowClose);
#endif

#if defined(OSD_USES_GLEW)
#ifdef CORE_PROFILE
    // this is the only way to initialize glew correctly under core profile context.
    glewExperimental = true;
#endif
    if (GLenum r = glewInit() != GLEW_OK) {
        printf("Failed to initialize glew. Error = %s\n", glewGetErrorString(r));
        exit(1);
    }
#ifdef CORE_PROFILE
    // clear GL errors which was generated during glewInit()
    glGetError();
#endif
#endif

    // activate feature adaptive tessellation if OSD supports it
    g_adaptive = OpenSubdiv::OsdGLDrawContext::SupportsAdaptiveTessellation();

    initGL();

    glfwSwapInterval(0);

    initHUD();
    callbackModel(g_currentShape);

    g_fpsTimer.Start();
    while (g_running) {
        idle();
        display();
        
#if GLFW_VERSION_MAJOR>=3
        glfwPollEvents();
        glfwSwapBuffers(g_window);
#else
        glfwSwapBuffers();
#endif
    }

    uninitGL();
    glfwTerminate();
}
Beispiel #28
0
void Game::Create()
{
	// Set the platform
	ApConfig::SetPlatform( ApPlatform_WinGL );
	ApConfig::SetDevice( ApDevice_WIN );

	GLFWvidmode dvm;

	// Initialise GLFW
	if(!glfwInit())
	{
		fprintf(stderr, "Failed to initialize GLFW\n");
		exit(EXIT_FAILURE);
	}

	glfwGetDesktopMode(&dvm);

	project->Init();

	// Frame counter and window settings variables
	int frame = 0;
	int redBits = 8, greenBits = 8, blueBits = 8;
	int alphaBits = 8, depthBits = 24, stencilBits = 8;
	m_width = RsUtil::GetWidth();
	m_height = RsUtil::GetHeight();

	glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);

	// Create a window
	if(!glfwOpenWindow(m_width, m_height, redBits, greenBits, blueBits, alphaBits, depthBits, stencilBits, GLFW_WINDOW))
	{
		fprintf(stderr, "Failed to open GLFW window\n");

		glfwTerminate();
		exit(EXIT_FAILURE);
	}

	// Set listeners
	glfwSetWindowCloseCallback(windowCloseListener);

	int width, height;
	GetDesktopResolution(width, height);
	glfwSetWindowPos((width / 2) - (RsUtil::GetWidth() / 2), (height / 2) - (RsUtil::GetHeight() / 2));

	// Cache the window handle
	int handle = glfwGetWindowParam( -1 );

	// Create the game mouse
	m_gameMouse.Setup( (HWND)handle );
	m_gameMouse.CreateOnDevice();

	// Create the render system
	RsImpl::pInstance()->Create();

	SdSoundWinGL::CreateManager();

	BtTimeDX11::Init();

	//glfwOpenWindowHint( GLFW_REFRESH_RATE, 1.0f / 30.0f );

	glfwSetWindowTitle( ApConfig::GetTitle() );

	// Ensure we can capture the escape key being pressed below
	glfwEnable(GLFW_STICKY_KEYS);

	// Enable vertical sync (on cards that support it)
	glfwSwapInterval(1);

	// Hide the cursor
	glfwDisable(GLFW_MOUSE_CURSOR);

	project->Create();
	project->Reset();
	do
	{
		// Get window size (may be different than the requested size)
		glfwGetWindowSize(&m_width, &m_height);

		// Set the window size
		glViewport(0, 0, m_width, m_height);

		BtFloat dt = BtTime::GetTick();
		BtFloat elapsedTime = BtTime::GetElapsedTimeInSeconds();
		BtFloat deltaTime = elapsedTime - m_lastGameLogic;

		m_lastGameLogic = elapsedTime;

		// Add the excess
		m_frameRemainder += deltaTime;

		// Cap the frame
		m_frameRemainder = BtClamp(m_frameRemainder, (BtFloat)0, 1.0f);

		BtBool isExiting = BtFalse;

		//while( m_frameRemainder >= dt )
		{
			// Update the keys
			input.Update();

			// Update the game logic
			GameUpdate();

			// Remove the dt from the frame remainder
			m_frameRemainder -= dt;
		}

		if((isClosing == BtFalse) && (project->IsClosing() == BtFalse))
		{
			// Render
			project->Render();

			// Render
			RsImpl::pInstance()->Render();
		}

		// Swap buffers
		glfwSwapBuffers();
	} // Check if the ESC key was pressed or the window was closed
	while(project->IsClosed() == BtFalse);

	// Destroy the renderer
	RsImpl::pInstance()->Destroy();

	// Destroy the sound
	SdSoundWinGL::DestroyManager();

	// Remove the game mouse
	m_gameMouse.RemoveFromDevice();

	// Destroy the project
	project->Destroy();

	// Close OpenGL window and terminate GLFW
	glfwTerminate();
}
Beispiel #29
0
int main(void)
{
	//Set the error callback
	glfwSetErrorCallback(error_callback);

	//Initialize GLFW
	if (!glfwInit())
	{
		exit(EXIT_FAILURE);
	}

	//Set the GLFW window creation hints - these are optional
	//glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //Request a specific OpenGL version
	//glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //Request a specific OpenGL version
	//glfwWindowHint(GLFW_SAMPLES, 4); //Request 4x antialiasing
	//glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);


	//Create a window and create its OpenGL context
	window = glfwCreateWindow(960, 720, "Test Window", NULL, NULL);

	//If the window couldn't be created
	if (!window)
	{
		fprintf(stderr, "Failed to open GLFW window.\n");
		glfwTerminate();
		//exit(EXIT_FAILURE);
	}

	//This function makes the context of the specified window current on the calling thread. 
	glfwMakeContextCurrent(window);

	//Sets the key callback
	glfwSetKeyCallback(window, key_callback);

	//Initialize GLEW
	GLenum err = glewInit();

	//If GLEW hasn't initialized
	if (err != GLEW_OK)
	{
		fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
		return -1;
	}

	//Set a background color
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glfwSetCursorPos(window, 1024 / 2, 768 / 2);

	GLuint VertexArrayID;
	glGenVertexArrays(1, &VertexArrayID);
	glBindVertexArray(VertexArrayID);

	// Create and compile our GLSL program from the shaders
	GLuint red = LoadShaders("SimpleTransform.vertexshader", "SingleColorRed.fragmentshader");
	GLuint grid = LoadShaders("SimpleTransform.vertexshader", "SingleColorGrid.fragmentshader");
	glBindFragDataLocation(red, 0, "red");
	glBindFragDataLocation(grid, 1, "grid");
	// Get a handle for our "MVP" uniform
	GLuint MatrixID = glGetUniformLocation(red, "MVP");

	// Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
	glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 1000.0f);
	// Or, for an ortho camera :
	//glm::mat4 Projection = glm::ortho(-10.0f,10.0f,-10.0f,10.0f,0.0f,100.0f); // In world coordinates

	// Camera matrix
	glm::mat4 View = glm::lookAt(
		glm::vec3(4, 3, 3), // Camera is at (4,3,3), in World Space
		glm::vec3(0, 0, 0), // and looks at the origin
		glm::vec3(0, 1, 0)  // Head is up (set to 0,-1,0 to look upside-down)
		);


	static const GLfloat g_vertex_buffer_data[] = {
		-1.0f, -1.0f, 0.0f,
		1.0f, -1.0f, 0.0f,
		0.0f, 1.0f, 0.0f,
	};

	static const GLushort g_element_buffer_data[] = { 0, 1, 2 };

	GLuint vertexbuffer;
	glGenBuffers(1, &vertexbuffer);
	glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

	static const GLfloat g_triangle_buffer_data[] = {
		-1.0f, -1.0f, -1.0f,
		1.0f, -1.0f, -1.0f,
		0.0f, 1.0f, -1.0f,
	};

	GLuint triangle;
	glGenBuffers(1, &triangle);
	glBindBuffer(GL_ARRAY_BUFFER, triangle);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_triangle_buffer_data), g_triangle_buffer_data, GL_STATIC_DRAW);

	// Enable depth test
	glEnable(GL_DEPTH_TEST);
	// Accept fragment if it closer to the camera than the former one
	glDepthFunc(GL_LESS);
	glEnable(GL_CULL_FACE);
	glEnable(GL_LIGHTING);
	glEnable(GL_SMOOTH);//OPENGL INSTANTIATION
	HRESULT hr;
	NUI_IMAGE_FRAME depthFrame;
	HANDLE hDepth;
	INuiSensor* pNuiSensor = NULL;
	int iSensorCount = 0;
	hr = NuiGetSensorCount(&iSensorCount);

	if (FAILED(hr))
		return hr;

	for (int i = 0; i < iSensorCount; i++)
	{
		INuiSensor* tempSensor;
		hr = NuiCreateSensorByIndex(i, &tempSensor);

		if (FAILED(hr))
			continue;

		hr = tempSensor->NuiStatus();
		if (S_OK == hr)
		{
			pNuiSensor = tempSensor;
			break;
		}

		tempSensor->Release();
	}

	for (int i = 0; i < 2048; i++) {
		depthLookUp[i] = rawDepthToMeters(i);
	}

	rotation = getRotationMatrix(theta, psi, fi);

	pNuiSensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_DEPTH);
	pNuiSensor->NuiImageStreamOpen(
		NUI_IMAGE_TYPE_DEPTH,
		NUI_IMAGE_RESOLUTION_320x240,
		0,
		2,
		NULL,
		&hDepth);//KINECT INSTANTIATION

	cout << "Starting Main Loop";

	static double lastTime = glfwGetTime();
	//Main Loop
	do
	{
		double currentTime = glfwGetTime();
		float deltaTime = float(currentTime - lastTime);
		//Clear color buffer
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glUseProgram(grid);
		modelMatrix(MatrixID);


		hr = pNuiSensor->NuiImageStreamGetNextFrame(hDepth, 0, &depthFrame);
		if (!FAILED(hr))
		{

			INuiFrameTexture* pTexture;
			NUI_LOCKED_RECT LockedRect;

			hr = pNuiSensor->NuiImageFrameGetDepthImagePixelFrameTexture(
				hDepth, &depthFrame, false, &pTexture);

			if (FAILED(hr))
			{
				pNuiSensor->NuiImageStreamReleaseFrame(hDepth, &depthFrame);
				continue;
			}

			pTexture->LockRect(0, &LockedRect, NULL, 0);//Kinect Image Grab
			int skipX = 1;
			int skipY = 1;
			float scalar = 4.0f;

			if (LockedRect.Pitch != 0)
			{
				for (int x = 0; x < width; x += skipX)
				{
					for (int y = 0; y < height; y += skipY)
					{
						const NUI_DEPTH_IMAGE_PIXEL * pBufferRun = reinterpret_cast<const NUI_DEPTH_IMAGE_PIXEL *>(LockedRect.pBits) + x + y * width;
						
						//float depth = (float)(pBufferRun->depth);
						//glm::vec3 location = realWorld(depth, height - y, x, 500.0f, 1000.0f);
						//createCube(0.006f, location);
						Vector4 locationDepth = NuiTransformDepthImageToSkeleton(x, y, (short)(pBufferRun->depth << 3));
						glm::vec3 locationDepthxyz = glm::vec3(locationDepth.x * scalar, locationDepth.y * scalar, locationDepth.z * scalar);
						createCube(0.009f, locationDepthxyz);
					}
				}
			}

			pTexture->UnlockRect(0);
			pTexture->Release();

			pNuiSensor->NuiImageStreamReleaseFrame(hDepth, &depthFrame);
		}

		createGrid();

		//Test drawings
		/*
		glUseProgram(red);
		modelMatrix(MatrixID);
		//createCube(0.05f, glm::vec3(1.0f,1.0f,1.0f));
		// 1rst attribute buffer : vertices
		glEnableVertexAttribArray(0);
		//createObject(vertexbuffer, GL_TRIANGLES, 3);
		//createObject(triangle, GL_TRIANGLES, 3);
		glDisableVertexAttribArray(0);
		*/

		//Swap buffers
		glfwSwapBuffers(window);
		//Get and organize events, like keyboard and mouse input, window resizing, etc...
		glfwPollEvents();

		std::string title = "Title | DELTA TIME " + std::to_string(1.0f/deltaTime);
		const char* pszConstString = title.c_str();
		glfwSetWindowTitle(window, pszConstString);

		lastTime = currentTime;
	} //Check if the ESC key had been pressed or if the window had been closed
	while (!glfwWindowShouldClose(window));


	//Close OpenGL window and terminate GLFW
	glfwDestroyWindow(window);
	//Finalize and clean up GLFW
	glfwTerminate();

	exit(EXIT_SUCCESS);
}
Beispiel #30
0
void init(void)
{
  srand(time(0));

  const int window_width = 800,
    window_height = 600;

  int x = NUM_POINTS_X;
  int y = NUM_POINTS_Y;
 
  if (glfwInit() != GL_TRUE)
    shut_down(1);

  // 800 x 600, 16 bit color, no depth, alpha or stencil buffers, windowed
  if (glfwOpenWindow(window_width, window_height, 5, 6, 5,
                     0, 0, 0, GLFW_WINDOW) != GL_TRUE)
    shut_down(1);
  glfwSetWindowTitle("Cloth");
 
  // set the projection matrix to a normal frustum with a max depth of 50
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  float aspect_ratio = ((float)window_height) / window_width;
  glFrustum(.5, -.5, -.5 * aspect_ratio, .5 * aspect_ratio, 1, 50);
  glMatrixMode(GL_MODELVIEW);

  //create the Point grid
  for(int i = 0; i < y; i++) {
    for(int j = 0; j < x; j++) {
      Point *p = malloc(sizeof(Point));
      p->x = j*LINK_DIST;
      p->y = i*LINK_DIST + 5;//put them off the ground a bit
      p->z = 0.0;
      p->vel_x = 0.0;
      p->vel_y = 0.0;
      p->vel_z = 0.0;
      p->prev_x = p->x;
      p->prev_y = p->y;
      p->prev_z = p->z;
      p->anchor = 0;
      int invert = y-i-1; //inverts y axis
      if(invert == 0) {
	p->anchor = 1;
      }
      point_array[(invert*x)+j] = p;
    }
  }

  //link the points together in a mesh
  int q = 0;
  for(int i = 0; i < y; i++) {
    for(int j = 0; j < x; j++) {
      int invert = y-i-1;
      
      //link upward
      if(i != 0) { //not top row
	Link *l1 = malloc(sizeof(Link));
	l1->resting_distance = LINK_DIST;//10.0/x;
	l1->tear_distance = 15*LINK_DIST;
	l1->stiffness = 1;

	l1->a = point_array[invert*x+j];
	l1->b = point_array[(invert+1)*x+j];
	l1->broken = 0;
	link_array[q] = l1;
	q++;
      }

      //link leftward (is that a word?)
      if(j != 0) { //not left edge
	Link *l2 = malloc(sizeof(Link));
	l2->resting_distance = LINK_DIST;//10.0/x;
	l2->tear_distance = 15*LINK_DIST;
	l2->stiffness = 1;
      
	l2->a = point_array[invert*x+j];
	l2->b = point_array[invert*x+j-1];
	l2->broken = 0;
	link_array[q] = l2;
	q++;
      }
    }
  }

  //make an invisible barrier for the mouse to click on
  Point *p0 = malloc(sizeof(Point));
  p0->x = -100;
  p0->y = -100;
  p0->z = 0;

  Point *p1 = malloc(sizeof(Point));
  p1->x = -100;
  p1->y = 100;
  p1->z = 0;

  Point *p2 = malloc(sizeof(Point));
  p2->x = 100;
  p2->y = 100;
  p2->z = 0;

  Point *p3 = malloc(sizeof(Point));
  p3->x = 100;
  p3->y = -100;
  p3->z = 0;

  barrier_array[0] = p0;
  barrier_array[1] = p1;
  barrier_array[2] = p2;
  barrier_array[3] = p3;
}