// --------------------------------------------------------------------------------------------------------------------
bool TexturedQuadsGLTextureArray::Init(const std::vector<TexturedQuadsProblem::Vertex>& _vertices,
                                       const std::vector<TexturedQuadsProblem::Index>& _indices,
                                       const std::vector<TextureDetails*>& _textures,
                                       size_t _objectCount)
{
    if (!TexturedQuadsSolution::Init(_vertices, _indices, _textures, _objectCount)) {
        return false;
    }

    // Prerequisites
    auto numTextures = _textures.size();
    if (!mTexManager.Init(false, numTextures)) {
        return false;
    }

    // Program
    const char* kUniformNames[] = { "ViewProjection", "TexContainer", nullptr };

    mProgram = CreateProgramT("textures_gl_texture_array_vs.glsl",
                              "textures_gl_texture_array_fs.glsl",
                              kUniformNames, &mUniformLocation);

    if (mProgram == 0) {
        console::warn("Unable to initialize solution '%s', shader compilation/linking failed.", GetName().c_str());
        return false;
    }

    // Textures
    for (auto it = _textures.begin(); it != _textures.end(); ++it) {
        mTextures.push_back(mTexManager.newTexture2DFromDetails(*it));
    }

    GLint lastTexId = -1;
    GLint lastTexUnit = -1;
    std::vector<DenseTexAddress> texAddress(numTextures);
    for (size_t i = 0; i < numTextures; ++i) {
        auto texture = mTextures[i];
        auto texId = texture->GetTexId();
        if (lastTexId != texId) {
            lastTexId = texId;
            lastTexUnit = (GLint) mTexUnits.size();

            glActiveTexture(GL_TEXTURE0 + lastTexUnit);
            glBindTexture(GL_TEXTURE_2D_ARRAY, texId);
            mTexUnits.push_back(lastTexUnit);
        }

        texAddress[i].m_container_index = lastTexUnit;
        texAddress[i].m_layer = ((float) texture->getSliceNum() + 0.5f) / numTextures;
    }

    std::vector<DenseTexAddress> texAddressContents(_objectCount);
    for (uint32_t i = 0; i < _objectCount; ++i) {
        texAddressContents[i] = texAddress[i % numTextures];
    }

    mTexAddressBuffer = NewBufferFromVector(GL_SHADER_STORAGE_BUFFER, texAddressContents, GL_DYNAMIC_DRAW);
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, mTexAddressBuffer);

    // Buffers
    glGenVertexArrays(1, &mVertexArray);
    glBindVertexArray(mVertexArray);

    mVertexBuffer = NewBufferFromVector(GL_ARRAY_BUFFER, _vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(TexturedQuadsProblem::Vertex), (void*)offsetof(TexturedQuadsProblem::Vertex, pos));
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(TexturedQuadsProblem::Vertex), (void*)offsetof(TexturedQuadsProblem::Vertex, tex));
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    std::vector<uint32_t> drawids(_objectCount);
    for (uint32_t i = 0; i < _objectCount; ++i) {
        drawids[i] = i;
    }

    mDrawIDBuffer = NewBufferFromVector(GL_ARRAY_BUFFER, drawids, GL_STATIC_DRAW);
    glVertexAttribIPointer(2, 1, GL_UNSIGNED_INT, sizeof(uint32_t), 0);
    glVertexAttribDivisor(2, 1);
    glEnableVertexAttribArray(2);

    mIndexBuffer = NewBufferFromVector(GL_ELEMENT_ARRAY_BUFFER, _indices, GL_STATIC_DRAW);

    glGenBuffers(1, &mTransformBuffer);
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, mTransformBuffer);

    return GLRenderer::GetApiError() == GL_NO_ERROR;
}
Beispiel #2
0
bool GLUniform::CreateUBO(GLuint program, GLuint location, GLenum draw)
{
    GLint size;
    GLint type;
    GLint offset;
    std::string uname;
    GLsizei dataSize = 0;
    GLsizeiptr uniformSize;
    Uniform unif;
    this->location = location;
    GLint numUniforms;
    GLuint index;
    GLint padding = 0;
      
    this->block = glGetUniformBlockIndex(program, this->name.c_str());
    std::cout<<"Block index "<<block<< " and location "<<location<<std::endl;
    glGetActiveUniformBlockiv( program, this->block, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &numUniforms );
    GLint *indices = new GLint[numUniforms];
    glGetActiveUniformBlockiv( program, this->block, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, indices );

    for( int i = 0; i < numUniforms; i++)
    {
        index = (GLuint)indices[i];

        glGetActiveUniformName(program, index, 256, 0, &uname[0]);
        glGetActiveUniformsiv(program, 1, &index, GL_UNIFORM_TYPE, &type);
        glGetActiveUniformsiv(program, 1, &index, GL_UNIFORM_OFFSET, &offset);
        glGetActiveUniformsiv(program, 1, &index, GL_UNIFORM_SIZE, &size);

        if(type == GL_FLOAT_VEC3)
            uniformSize = sizeof(glm::vec3);
        else if(type == GL_FLOAT_VEC2)
             uniformSize = sizeof(glm::vec2);
        else if(type == GL_FLOAT_VEC4)
            uniformSize = sizeof(glm::vec4);
        else if(type == GL_FLOAT_MAT4)
            uniformSize = sizeof(glm::mat4);
        else if(type == GL_FLOAT_MAT3)
            uniformSize = sizeof(glm::mat3);
        else if(type == GL_INT)
        {
            uniformSize = sizeof(int);
            padding += 3*sizeof(int);
        }
        else if(type == GL_FLOAT)
        {
            uniformSize = sizeof(float);
            padding += 3*sizeof(float);
        }
        else 
            uniformSize = 0.0f;

        dataSize += size*uniformSize;

        unif = {&uname[0], static_cast<GLint>(size*uniformSize), index, offset};
		this->uniforms[&uname[0]] = unif;

        std::cout << "Uniform <" << unif.name << "> (offset): " << unif.offset <<", (size): " <<unif.size<< ", (index): "<<unif.index<< std::endl;
    }

    GLBufferObject ubo(name.c_str(), dataSize + padding, (GLuint)1, GL_UNIFORM_BUFFER, draw); 
    if( ubo.Status(GL_UNIFORM_BUFFER, dataSize) )
    {
            std::cerr << "[E] Buffer " << name << " not created."<<std::endl;
            return false;
    }

    glBindBufferBase(ubo.Type(), location, ubo.Buffer());

    this->block = glGetUniformBlockIndex(program, this->name.c_str());
    std::cout<<"Block index "<<this->block<< " after bind "<<std::endl;
    ubo.SetBlockIndex(this->block); 
    
    this->id = ubo.Buffer();

	glBindBuffer(GL_UNIFORM_BUFFER, 0);

    delete [] indices;

    return true;
}
void Initialize()
{
	printf("Version Pilote OpenGL : %s\n", glGetString(GL_VERSION));
	printf("Type de GPU : %s\n", glGetString(GL_RENDERER));
	printf("Fabricant : %s\n", glGetString(GL_VENDOR));
	printf("Version GLSL : %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
	int numExtensions;
	glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);
	
	GLenum error = glewInit();
	if (error != GL_NO_ERROR) {
		// TODO
	}

#if LIST_EXTENSIONS
	for (int index = 0; index < numExtensions; ++index)
	{
		printf("Extension[%d] : %s\n", index, glGetStringi(GL_EXTENSIONS, index));
	}
#endif
	
#ifdef _WIN32
	// on coupe la synchro vertical pour voir l'effet du delta time
	wglSwapIntervalEXT(0);
#endif

	// render states par defaut
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
	glEnable(GL_CULL_FACE);	

	// AntTweakBar
	
	TwInit(TW_OPENGL, NULL); // ou TW_OPENGL_CORE selon le cas de figure
	objTweakBar = TwNewBar("Multiple Point Lights");
	TwAddVarRW(objTweakBar, "Num Point Lights", TW_TYPE_UINT32, &g_NumPointLights, "");	
	TwAddButton(objTweakBar, "Quitter", &ExitCallbackTw, nullptr, "");
	
	// Objets OpenGL

	glGenBuffers(1, &g_Camera.UBO);
	glBindBuffer(GL_UNIFORM_BUFFER, g_Camera.UBO);
	glBufferData(GL_UNIFORM_BUFFER, sizeof(glm::mat4) * 2, nullptr, GL_STREAM_DRAW);
	

	glGenBuffers(1, &PointLight::UBO);
	glBindBuffer(GL_UNIFORM_BUFFER, PointLight::UBO);
	glBufferData(GL_UNIFORM_BUFFER, sizeof(PointLight) * MAX_POINT_LIGHTS, nullptr, GL_STREAM_DRAW);
	

	glGenBuffers(1, &Material::UBO);
	glBindBuffer(GL_UNIFORM_BUFFER, Material::UBO);
	glBufferData(GL_UNIFORM_BUFFER, sizeof(Material), &g_ShinyMaterial, GL_STATIC_DRAW);
	
	error = glGetError(); assert(error == GL_NO_ERROR);

	g_AmbientShader.LoadVertexShader("ambient.vs");
	g_AmbientShader.LoadFragmentShader("ambient.fs");
	g_AmbientShader.Create();
	auto program = g_AmbientShader.GetProgram();

	glBindBufferBase(GL_UNIFORM_BUFFER, 0, g_Camera.UBO);
	auto blockIndex = glGetUniformBlockIndex(program, "ViewProj");
	glUniformBlockBinding(program, blockIndex, 0);

	error = glGetError(); assert(error == GL_NO_ERROR);

	g_BlinnPhongShader.LoadVertexShader("blinnPhong.vs");
	g_BlinnPhongShader.LoadFragmentShader("blinnPhong.fs");
	g_BlinnPhongShader.Create();
	program = g_BlinnPhongShader.GetProgram();

	//glBindBufferBase(GL_UNIFORM_BUFFER, 0, g_Camera.UBO); // deja bound
	blockIndex = glGetUniformBlockIndex(program, "ViewProj");
	glUniformBlockBinding(program, blockIndex, 0);

	glBindBufferBase(GL_UNIFORM_BUFFER, 1, PointLight::UBO);
	blockIndex = glGetUniformBlockIndex(program, "Lights");
	glUniformBlockBinding(program, blockIndex, 1);

	glBindBufferBase(GL_UNIFORM_BUFFER, 2, Material::UBO);
	blockIndex = glGetUniformBlockIndex(program, "Material");
	glUniformBlockBinding(program, blockIndex, 2);

	// Setup
	error = glGetError(); assert(error == GL_NO_ERROR);

	previousTime = glutGet(GLUT_ELAPSED_TIME);

	LoadMesh(g_WallMesh, g_Room);

	LoadAndCreateTextureRGBA("wall_color_map.jpg", g_Walls.textures[Walls::gWallTexture]);
	glBindTexture(GL_TEXTURE_2D, g_Walls.textures[Walls::gWallTexture]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	LoadAndCreateTextureRGBA("floor_color_map.jpg", g_Walls.textures[Walls::gFloorTexture]);
	glBindTexture(GL_TEXTURE_2D, g_Walls.textures[Walls::gFloorTexture]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	LoadAndCreateTextureRGBA("ceiling_color_map.jpg", g_Walls.textures[Walls::gCeilingTexture]);
	glBindTexture(GL_TEXTURE_2D, g_Walls.textures[Walls::gCeilingTexture]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	const std::string inputFile = "sphere.obj";
	LoadOBJ(g_SphereMesh, inputFile);

	g_Spheres.resize(g_NumPointLights);
	for (uint32_t index = 0; index < g_NumPointLights; ++index)
	{
		g_Spheres[index].initialize(index);
	}

	error = glGetError(); assert(error == GL_NO_ERROR);
}
void ViewportArrayApplication::Initialize(const char * title)
{
    int i;

    base::Initialize(title);

    glGenTransformFeedbacks(1, &xfb);
    glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, xfb);

    sort_prog = glCreateProgram();

    static const char sort_vs_source[] =
            "#version 410\n"
            "\n"
            "uniform mat4 model_matrix;\n"
            "\n"
            "layout (location = 0) in vec4 position;\n"
            "layout (location = 1) in vec3 normal;\n"
            "\n"
            "out vec3 vs_normal;\n"
            "\n"
            "void main(void)\n"
            "{\n"
            "    vs_normal = (model_matrix * vec4(normal, 0.0)).xyz;\n"
            "    gl_Position = model_matrix * position;\n"
            "}\n";

    static const char sort_gs_source[] =
        "#version 410\n"
        "\n"
        "layout (triangles) in;\n"
        "layout (points, max_vertices = 3) out;\n"
        "\n"
        "uniform mat4 projection_matrix;\n"
        "\n"
        "in vec3 vs_normal[];\n"
        "\n"
        "layout (stream = 0) out vec4 rf_position;\n"
        "layout (stream = 0) out vec3 rf_normal;\n"
        "\n"
        "layout (stream = 1) out vec4 lf_position;\n"
        "layout (stream = 1) out vec3 lf_normal;\n"
        "\n"
        "void main(void)\n"
        "{\n"
        "    vec4 A = gl_in[0].gl_Position;\n"
        "    vec4 B = gl_in[1].gl_Position;\n"
        "    vec4 C = gl_in[2].gl_Position;\n"
        "    vec3 AB = (B - A).xyz;\n"
        "    vec3 AC = (C - A).xyz;\n"
        "    vec3 face_normal = cross(AB, AC);\n"
        "    int i;\n"
        "\n"
        "    if (face_normal.x < 0.0)\n"
        "    {\n"
        "        for (i = 0; i < gl_in.length(); i++)\n"
        "        {\n"
        "            rf_position = projection_matrix * (gl_in[i].gl_Position - vec4(30.0, 0.0, 0.0, 0.0));\n"
        "            rf_normal = vs_normal[i];\n"
        "            EmitStreamVertex(0);\n"
        "        }\n"
        "        EndStreamPrimitive(0);\n"
        "    }\n"
        "    else\n"
        "    {\n"
        "        for (i = 0; i < gl_in.length(); i++)\n"
        "        {\n"
        "            lf_position = projection_matrix * (gl_in[i].gl_Position + vec4(30.0, 0.0, 0.0, 0.0));\n"
        "            lf_normal = vs_normal[i];\n"
        "            EmitStreamVertex(1);\n"
        "        }\n"
        "        EndStreamPrimitive(1);\n"
        "    }\n"
        "}\n";

    vglAttachShaderSource(sort_prog, GL_VERTEX_SHADER, sort_vs_source);
    vglAttachShaderSource(sort_prog, GL_GEOMETRY_SHADER, sort_gs_source);

    static const char * varyings[] =
    {
        "rf_position", "rf_normal",
        "gl_NextBuffer",
        "lf_position", "lf_normal"
    };

    glTransformFeedbackVaryings(sort_prog, 5, varyings, GL_INTERLEAVED_ATTRIBS);

    glLinkProgram(sort_prog);
    glUseProgram(sort_prog);

    model_matrix_pos = glGetUniformLocation(sort_prog, "model_matrix");
    projection_matrix_pos = glGetUniformLocation(sort_prog, "projection_matrix");

    glGenVertexArrays(2, vao);
    glGenBuffers(2, vbo);

    for (i = 0; i < 2; i++)
    {
        glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, vbo[i]);
        glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, 1024 * 1024 * sizeof(GLfloat), NULL, GL_DYNAMIC_COPY);
        glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, i, vbo[i]);

        glBindVertexArray(vao[i]);
        glBindBuffer(GL_ARRAY_BUFFER, vbo[i]);
        glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(vmath::vec4) + sizeof(vmath::vec3), NULL);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(vmath::vec4) + sizeof(vmath::vec3), (GLvoid *)(sizeof(vmath::vec4)));
        glEnableVertexAttribArray(0);
        glEnableVertexAttribArray(1);
    }

    render_prog = glCreateProgram();

    static const char render_vs_source[] =
        "#version 410\n"
        "\n"
        "layout (location = 0) in vec4 position;\n"
        "layout (location = 1) in vec3 normal;\n"
        "\n"
        "out vec3 vs_normal;\n"
        "\n"
        "void main(void)\n"
        "{\n"
        "    vs_normal = normal;\n"
        "    gl_Position = position;\n"
        "}\n";

    static const char render_fs_source[] =
        "#version 410\n"
        "\n"
        "layout (location = 0) out vec4 color;\n"
        "\n"
        "uniform vec4 pass_color;\n"
        "\n"
        "in vec3 vs_normal;\n"
        "\n"
        "void main(void)\n"
        "{\n"
        "    color = pass_color * (0.2 + pow(abs(vs_normal.z), 4.0)) + vec4(1.0, 1.0, 1.0, 0.0) * pow(abs(vs_normal.z), 37.0);\n"
        "}\n";

    vglAttachShaderSource(render_prog, GL_VERTEX_SHADER, render_vs_source);
    vglAttachShaderSource(render_prog, GL_FRAGMENT_SHADER, render_fs_source);

    glLinkProgram(render_prog);

    object.LoadFromVBM("D:/svn/Vermilion-Book/trunk/Code/media/ninja.vbm", 0, 1, 2);
}
Beispiel #5
0
	void DeferredPainter::Initialize(GLuint FBO, GLuint dummyVAO)
	{
		BasePainter::Initialize(FBO, dummyVAO);

		//TODO: CHANGE THIS INTO A PROPER STATIC SHADER
		m_shaderManager->CreateProgram("StaticMesh");
		m_shaderManager->LoadShader("shaders/geometry/SimpleGeometryVS.glsl", "StaticMeshVS", GL_VERTEX_SHADER);
		m_shaderManager->LoadShader("shaders/geometry/SimpleGeometryFS.glsl", "StaticMeshFS", GL_FRAGMENT_SHADER);
		m_shaderManager->AttachShader("StaticMeshVS", "StaticMesh");
		m_shaderManager->AttachShader("StaticMeshFS", "StaticMesh");
		m_shaderManager->LinkProgram("StaticMesh");

		//Normal mapped, non-animated shader
		m_shaderManager->CreateProgram("NormalMappedStatic");
		m_shaderManager->LoadShader("shaders/geometry/StaticNormalVS.glsl", "NormalMappedStaticVS", GL_VERTEX_SHADER);
		m_shaderManager->LoadShader("shaders/geometry/NormalMappedFS.glsl", "NormalMappedStaticFS", GL_FRAGMENT_SHADER);
		m_shaderManager->AttachShader("NormalMappedStaticVS", "NormalMappedStatic");
		m_shaderManager->AttachShader("NormalMappedStaticFS", "NormalMappedStatic");
		m_shaderManager->LinkProgram("NormalMappedStatic");

		// Normal map shaders
		m_shaderManager->CreateProgram("StaticNormal");
		m_shaderManager->LoadShader("shaders/geometry/StaticNormalVS.glsl", "StaticNormalVS", GL_VERTEX_SHADER);
		m_shaderManager->LoadShader("shaders/geometry/StaticNormalFS.glsl", "StaticNormalFS", GL_FRAGMENT_SHADER);
		m_shaderManager->AttachShader("StaticNormalVS", "StaticNormal");
		m_shaderManager->AttachShader("StaticNormalFS", "StaticNormal");
		m_shaderManager->LinkProgram("StaticNormal");

		m_staticNormal = m_shaderManager->GetShaderProgramID("StaticNormal");

		m_shaderManager->CreateProgram("AnimatedNormal");
		m_shaderManager->LoadShader("shaders/geometry/AnimatedNormalVS.glsl", "AnimatedNormalVS", GL_VERTEX_SHADER);
		m_shaderManager->LoadShader("shaders/geometry/StaticNormalFS.glsl", "AnimatedNormalFS", GL_FRAGMENT_SHADER);
		m_shaderManager->AttachShader("AnimatedNormalVS", "AnimatedNormal");
		m_shaderManager->AttachShader("AnimatedNormalFS", "AnimatedNormal");
		m_shaderManager->LinkProgram("AnimatedNormal");

		m_animatedNormal = m_shaderManager->GetShaderProgramID("AnimatedNormal");

		// Blend map shaders
		m_shaderManager->CreateProgram("StaticBlend");
		m_shaderManager->LoadShader("shaders/geometry/StaticBlendVS.glsl", "StaticBlendVS", GL_VERTEX_SHADER);
		m_shaderManager->LoadShader("shaders/geometry/StaticBlendFS.glsl", "StaticBlendFS", GL_FRAGMENT_SHADER);
		m_shaderManager->AttachShader("StaticBlendVS", "StaticBlend");
		m_shaderManager->AttachShader("StaticBlendFS", "StaticBlend");
		m_shaderManager->LinkProgram("StaticBlend");

		m_staticBlend = m_shaderManager->GetShaderProgramID("StaticBlend");

		m_shaderManager->CreateProgram("AnimatedBlend");
		m_shaderManager->LoadShader("shaders/geometry/AnimatedBlendVS.glsl", "AnimatedBlendVS", GL_VERTEX_SHADER);
		m_shaderManager->LoadShader("shaders/geometry/StaticBlendFS.glsl", "AnimatedBlendFS", GL_FRAGMENT_SHADER);
		m_shaderManager->AttachShader("AnimatedBlendVS", "AnimatedBlend");
		m_shaderManager->AttachShader("AnimatedBlendFS", "AnimatedBlend");
		m_shaderManager->LinkProgram("AnimatedBlend");

		m_animatedBlend = m_shaderManager->GetShaderProgramID("AnimatedBlend");

		m_shaderManager->CreateProgram("AnimatedOutline");
		m_shaderManager->LoadShader("shaders/Outline/AnimatedOutlineVS.glsl", "AnimatedOutlineVS", GL_VERTEX_SHADER);
		m_shaderManager->LoadShader("shaders/Outline/OutlineFS.glsl", "AnimatedOutlineFS", GL_FRAGMENT_SHADER);
		m_shaderManager->AttachShader("AnimatedOutlineVS", "AnimatedOutline");
		m_shaderManager->AttachShader("AnimatedOutlineFS", "AnimatedOutline");
		m_shaderManager->LinkProgram("AnimatedOutline");

		m_shaderManager->CreateProgram("StaticOutline");
		m_shaderManager->LoadShader("shaders/Outline/StaticOutlineVS.glsl", "StaticOutlineVS", GL_VERTEX_SHADER);
		m_shaderManager->LoadShader("shaders/Outline/OutlineFS.glsl", "StaticOutlineFS", GL_FRAGMENT_SHADER);
		m_shaderManager->AttachShader("StaticOutlineVS", "StaticOutline");
		m_shaderManager->AttachShader("StaticOutlineFS", "StaticOutline");
		m_shaderManager->LinkProgram("StaticOutline");
		
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("StaticMesh"),			"PerFrameBlock", UniformBufferManager::CAMERA_BINDING_INDEX);
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("NormalMappedStatic"),	"PerFrameBlock", UniformBufferManager::CAMERA_BINDING_INDEX);
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("StaticNormal"),		"PerFrameBlock", UniformBufferManager::CAMERA_BINDING_INDEX);
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("AnimatedNormal"),		"PerFrameBlock", UniformBufferManager::CAMERA_BINDING_INDEX);
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("StaticBlend"),			"PerFrameBlock", UniformBufferManager::CAMERA_BINDING_INDEX);
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("AnimatedBlend"),		"PerFrameBlock", UniformBufferManager::CAMERA_BINDING_INDEX);
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("AnimatedOutline"),		"PerFrameBlock", UniformBufferManager::CAMERA_BINDING_INDEX);
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("StaticOutline"),		"PerFrameBlock", UniformBufferManager::CAMERA_BINDING_INDEX);
		
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("StaticMesh"),			"instanceBufferOffset", UniformBufferManager::INSTANCE_ID_OFFSET_INDEX);
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("NormalMappedStatic"),	"instanceBufferOffset", UniformBufferManager::INSTANCE_ID_OFFSET_INDEX);
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("StaticNormal"),		"instanceBufferOffset", UniformBufferManager::INSTANCE_ID_OFFSET_INDEX);
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("AnimatedNormal"),		"instanceBufferOffset", UniformBufferManager::INSTANCE_ID_OFFSET_INDEX);
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("StaticBlend"),			"instanceBufferOffset", UniformBufferManager::INSTANCE_ID_OFFSET_INDEX);
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("AnimatedBlend"),		"instanceBufferOffset", UniformBufferManager::INSTANCE_ID_OFFSET_INDEX);
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("AnimatedOutline"),		"instanceBufferOffset", UniformBufferManager::INSTANCE_ID_OFFSET_INDEX);
        m_uniformBufferManager->SetUniformBlockBindingIndex(m_shaderManager->GetShaderProgramID("StaticOutline"),		"instanceBufferOffset", UniformBufferManager::INSTANCE_ID_OFFSET_INDEX);

		m_outlineThickness = 2;
		m_staticInstances = new InstanceData[MAX_INSTANCES];
		

		glGenBuffers(1, &m_instanceBuffer);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_instanceBuffer);
		glBufferData(GL_SHADER_STORAGE_BUFFER, MAX_INSTANCES * sizeof(InstanceData), NULL, GL_STREAM_COPY);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, 0);

		glGenBuffers(1, &m_instanceOffsetBuffer);
		glBindBuffer(GL_UNIFORM_BUFFER, m_instanceOffsetBuffer);
		glBufferData(GL_UNIFORM_BUFFER, 4*sizeof(unsigned int), NULL, GL_DYNAMIC_DRAW);
		glBindBufferBase(GL_UNIFORM_BUFFER, UniformBufferManager::INSTANCE_ID_OFFSET_INDEX, 0);

	}
GLuint
OpenSubdivPtexShader::bindProgram(const MHWRender::MDrawContext &     mDrawContext,
                                        OpenSubdiv::OsdGLDrawContext *osdDrawContext,
                                  const OpenSubdiv::OsdPatchArray &   patch)
{

    CHECK_GL_ERROR("bindProgram begin\n");

    // Build shader
    Effect effect;
    effect.color = _enableColor;
    effect.occlusion = _enableOcclusion;
    effect.displacement = _enableDisplacement;
    effect.normal = _enableNormal;
    EffectDesc effectDesc( patch.desc, effect );
    EffectDrawRegistry::ConfigType *
        config = effectRegistry.GetDrawConfig(effectDesc);

    // Install shader
    GLuint program = config->program;
    glUseProgram(program);

    // Update and bind transform state
    struct Transform {
        float ModelViewMatrix[16];
        float ProjectionMatrix[16];
        float ModelViewProjectionMatrix[16];
    } transformData;
    setMatrix(mDrawContext.getMatrix(MHWRender::MDrawContext::kWorldViewMtx),
              transformData.ModelViewMatrix);
    setMatrix(mDrawContext.getMatrix(MHWRender::MDrawContext::kProjectionMtx),
              transformData.ProjectionMatrix);
    setMatrix(mDrawContext.getMatrix(MHWRender::MDrawContext::kWorldViewProjMtx),
              transformData.ModelViewProjectionMatrix);

    if (!g_transformUB) {
        glGenBuffers(1, &g_transformUB);
        glBindBuffer(GL_UNIFORM_BUFFER, g_transformUB);
        glBufferData(GL_UNIFORM_BUFFER,
                sizeof(transformData), NULL, GL_STATIC_DRAW);
    };
    glBindBuffer(GL_UNIFORM_BUFFER, g_transformUB);
    glBufferSubData(GL_UNIFORM_BUFFER,
                0, sizeof(transformData), &transformData);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);

    glBindBufferBase(GL_UNIFORM_BUFFER, g_transformBinding, g_transformUB);

    // Update and bind tessellation state
    struct Tessellation {
        float TessLevel;
        int GregoryQuadOffsetBase;
        int LevelBase;
    } tessellationData;

    tessellationData.TessLevel = static_cast<float>(1 << _tessFactor);
    tessellationData.GregoryQuadOffsetBase = patch.gregoryQuadOffsetBase;
    tessellationData.LevelBase = patch.levelBase;

    if (!g_tessellationUB) {
        glGenBuffers(1, &g_tessellationUB);
        glBindBuffer(GL_UNIFORM_BUFFER, g_tessellationUB);
        glBufferData(GL_UNIFORM_BUFFER,
                sizeof(tessellationData), NULL, GL_STATIC_DRAW);
    };
    glBindBuffer(GL_UNIFORM_BUFFER, g_tessellationUB);
    glBufferSubData(GL_UNIFORM_BUFFER,
                0, sizeof(tessellationData), &tessellationData);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);

    glBindBufferBase(GL_UNIFORM_BUFFER,
                     g_tessellationBinding,
                     g_tessellationUB);


#ifdef USE_NON_IMAGE_BASED_LIGHTING
    // Update and bind lighting state
    int numLights = mDrawContext.numberOfActiveLights();
    struct Lighting {
        struct Light {
            float position[4];
            float diffuse[4];
            float ambient[4];
            float specular[4];
        } lightSource[2];
    } lightingData;
    memset(&lightingData, 0, sizeof(lightingData));

    for (int i = 0; i < numLights && i < 1; ++i) {
        MFloatPointArray positions;
        MFloatVector direction;
        float intensity;
        MColor color;
        bool hasDirection, hasPosition;
        mDrawContext.getLightInformation(i, positions, direction, intensity,
                                    color, hasDirection, hasPosition);

        Lighting::Light &light = lightingData.lightSource[i];
        if (hasDirection) {
            light.position[0] = -direction[0];
            light.position[1] = -direction[1];
            light.position[2] = -direction[2];

            for (int j = 0; j < 4; ++j) {
                light.diffuse[j] = color[j] * intensity;
                light.ambient[j] = color[j] * intensity;
                light.specular[j] = color[j] * intensity;
            }
        }
    }

    if (!g_lightingUB) {
        glGenBuffers(1, &g_lightingUB);
        glBindBuffer(GL_UNIFORM_BUFFER, g_lightingUB);
        glBufferData(GL_UNIFORM_BUFFER,
                sizeof(lightingData), NULL, GL_STATIC_DRAW);
    };
    glBindBuffer(GL_UNIFORM_BUFFER, g_lightingUB);
    glBufferSubData(GL_UNIFORM_BUFFER,
                0, sizeof(lightingData), &lightingData);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);

    glBindBufferBase(GL_UNIFORM_BUFFER, g_lightingBinding, g_lightingUB);
#endif

    GLint eye = glGetUniformLocation(program, "eyePositionInWorld");
    MPoint e = MPoint(0, 0, 0) *
        mDrawContext.getMatrix(MHWRender::MDrawContext::kWorldViewInverseMtx);
    glProgramUniform3f(program, eye,
                       static_cast<float>(e.x),
                       static_cast<float>(e.y),
                       static_cast<float>(e.z));

    // update other uniforms
    float color[4] = { 0, 0, 0, 1 };
    _diffuse.get(color);
    glProgramUniform4fv(program,
                        glGetUniformLocation(program, "diffuseColor"),
                        1, color);
    _ambient.get(color);
    glProgramUniform4fv(program,
                        glGetUniformLocation(program, "ambientColor"),
                        1, color);
    _specular.get(color);
    glProgramUniform4fv(program,
                        glGetUniformLocation(program, "specularColor"),
                        1, color);

    glProgramUniform1f(program,
                       glGetUniformLocation(program, "fresnelBias"),
                       _fresnelBias);
    glProgramUniform1f(program,
                       glGetUniformLocation(program, "fresnelScale"),
                       _fresnelScale);
    glProgramUniform1f(program,
                       glGetUniformLocation(program, "fresnelPower"),
                       _fresnelPower);


    // Ptex bindings 
    // color ptex
    if (effectRegistry.getPtexColorValid()) {
        GLint texData = glGetUniformLocation(program, "textureImage_Data");
        glProgramUniform1i(program, texData, CLR_TEXTURE_UNIT + 0);
        GLint texPacking = glGetUniformLocation(program, "textureImage_Packing");
        glProgramUniform1i(program, texPacking, CLR_TEXTURE_UNIT + 1);
        GLint texPages = glGetUniformLocation(program, "textureImage_Pages");
        glProgramUniform1i(program, texPages, CLR_TEXTURE_UNIT + 2);
    }

    // displacement ptex
    if (effectRegistry.getPtexDisplacementValid()) {
        GLint texData = glGetUniformLocation(program, "textureDisplace_Data");
        glProgramUniform1i(program, texData, DISP_TEXTURE_UNIT + 0);
        GLint texPacking = glGetUniformLocation(program, "textureDisplace_Packing");
        glProgramUniform1i(program, texPacking, DISP_TEXTURE_UNIT + 1);
        GLint texPages = glGetUniformLocation(program, "textureDisplace_Pages");
        glProgramUniform1i(program, texPages, DISP_TEXTURE_UNIT + 2);
    }

    // occlusion ptex
    if (effectRegistry.getPtexOcclusionValid()) {
        GLint texData = glGetUniformLocation(program, "textureOcclusion_Data");
        glProgramUniform1i(program, texData, OCC_TEXTURE_UNIT + 0);
        GLint texPacking = glGetUniformLocation(program, "textureOcclusion_Packing");
        glProgramUniform1i(program, texPacking, OCC_TEXTURE_UNIT + 1);
        GLint texPages = glGetUniformLocation(program, "textureOcclusion_Pages");
        glProgramUniform1i(program, texPages, OCC_TEXTURE_UNIT + 2);
    }

    // diffuse environment map
    if (effectRegistry.getDiffuseEnvironmentId() != 0) {
        GLint difmap = glGetUniformLocation(program, "diffuseEnvironmentMap");
        glProgramUniform1i(program, difmap, DIFF_TEXTURE_UNIT);
    }

    // specular environment map
    if (effectRegistry.getSpecularEnvironmentId() != 0) {
        GLint envmap = glGetUniformLocation(program, "specularEnvironmentMap");
        glProgramUniform1i(program, envmap, ENV_TEXTURE_UNIT);
    }

    glActiveTexture(GL_TEXTURE0);

    CHECK_GL_ERROR("bindProgram leave\n");

    return program;
}
Beispiel #7
0
void Render(float alpha, float elapsedtime)
{
	float tmp[16];
	float texmat[16];
	float view[16];
	float viewinv[16];
	float proj[16];
	float viewproj[16];
	float lightview[16];
	float lightproj[16];
	float lightviewproj[16];

	float globalambient[4]	= { 0.01f, 0.01f, 0.01f, 1.0f };
	float moonlight[]		= { -0.25f, 0.65f, -1, 0 };
	float mooncolor[]		= { 0.6f, 0.6f, 1, 1 };

	float eye[3]			= { 0, 0, 8 };
	float look[3]			= { 0, 0, 0 };
	float up[3]				= { 0, 1, 0 };

	float screensize[2]		= { (float)screenwidth, (float)screenheight };
	float lightclip[2];
	float clipplanes[2];
	float orient[2];

	// setup camera
	cameraangle.smooth(orient, alpha);

	GLMatrixRotationAxis(view, orient[1], 1, 0, 0);
	GLMatrixRotationAxis(tmp, orient[0], 0, 1, 0);
	GLMatrixMultiply(view, view, tmp);

	GLVec3Transform(eye, eye, view);

	GLFitToBox(clipplanes[0], clipplanes[1], eye, look, scenebox);
	GLMatrixPerspectiveFovRH(proj, (60.0f * 3.14159f) / 180.f,  (float)screenwidth / (float)screenheight, clipplanes[0], clipplanes[1]);

	GLMatrixLookAtRH(view, eye, look, up);
	GLMatrixMultiply(viewproj, view, proj);

	// setup moonlight
	GLMatrixInverse(viewinv, view);
	GLVec3Transform(moonlight, moonlight, viewinv);
	GLVec3Normalize(moonlight, moonlight);

	// should be that value in view space (background is fix)
	// but let y stay in world space, so we see shadow
	moonlight[1] = 0.65f;

	GLMatrixViewVector(lightview, moonlight);
	GLFitToBox(lightproj, lightclip, lightview, scenebox);
	GLMatrixMultiply(lightviewproj, lightview, lightproj);

	// render shadow map
	glClearColor(0, 0, 0, 1);

	varianceshadow->SetMatrix("matViewProj", lightviewproj);
	varianceshadow->SetVector("clipPlanes", lightclip);

	shadowmap->Set();
	{
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

		varianceshadow->Begin();
		{
			RenderScene(varianceshadow);
		}
		varianceshadow->End();
	}
	shadowmap->Unset();

	// blur it
	float texelsize[] = { 1.0f / SHADOWMAP_SIZE, 1.0f / SHADOWMAP_SIZE };

	glDepthMask(GL_FALSE);
	glBindTexture(GL_TEXTURE_2D, shadowmap->GetColorAttachment(0));

	boxblur3x3->SetVector("texelSize", texelsize);

	blurredshadow->Set();
	{
		boxblur3x3->Begin();
		{
			screenquad->Draw();
		}
		boxblur3x3->End();
	}
	blurredshadow->Unset();

	glDepthMask(GL_TRUE);

	// STEP 1: z pass
	ambient->SetMatrix("matViewProj", viewproj);
	ambient->SetVector("matAmbient", globalambient);

	framebuffer->Set();
	{
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

		// draw background first
		glDisable(GL_DEPTH_TEST);
		glDepthMask(GL_FALSE);
		glBindTexture(GL_TEXTURE_2D, texture3);

		float scaledx = 1360.0f * (screenheight / 768.0f);
		float scale = screenwidth / scaledx;

		GLMatrixTranslation(tmp, -0.5f, 0, 0);
		GLMatrixScaling(texmat, scale, 1, 1);
		GLMatrixMultiply(texmat, tmp, texmat);

		GLMatrixTranslation(tmp, 0.5f, 0, 0);
		GLMatrixMultiply(texmat, texmat, tmp);

		GLMatrixRotationAxis(tmp, M_PI, 0, 0, 1);
		GLMatrixMultiply(texmat, texmat, tmp);

		basic2D->SetMatrix("matTexture", texmat);
		basic2D->Begin();
		{
			screenquad->Draw();
		}
		basic2D->End();

		glEnable(GL_DEPTH_TEST);
		glDepthMask(GL_TRUE);

		// then fill zbuffer
		ambient->Begin();
		{
			RenderScene(ambient);
		}
		ambient->End();
	}
	framebuffer->Unset();

	// STEP 2: cull lights
	if( lightcull && timeout > DELAY )
	{
		lightcull->SetFloat("alpha", alpha);
		lightcull->SetVector("clipPlanes", clipplanes);
		lightcull->SetVector("screenSize", screensize);
		lightcull->SetMatrix("matProj", proj);
		lightcull->SetMatrix("matView", view);
		lightcull->SetMatrix("matViewProj", viewproj);

		glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, counterbuffer);
		GLuint* counter = (GLuint*)glMapBuffer(GL_ATOMIC_COUNTER_BUFFER, GL_WRITE_ONLY);
	
		*counter = 0;
		glUnmapBuffer(GL_ATOMIC_COUNTER_BUFFER);

		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, headbuffer);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, nodebuffer);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, lightbuffer);
		glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, 0, counterbuffer);
		glBindTexture(GL_TEXTURE_2D, framebuffer->GetDepthAttachment());

		lightcull->Begin();
		{
			glDispatchCompute(workgroupsx, workgroupsy, 1);
		}
		lightcull->End();

		glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, 0, 0);
		glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0);
		glBindTexture(GL_TEXTURE_2D, 0);
	}

	// STEP 3: add some moonlight with shadow
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE);
	glDepthMask(GL_FALSE);

	framebuffer->Set();

	shadowedlight->SetMatrix("matViewProj", viewproj);
	shadowedlight->SetMatrix("lightViewProj", lightviewproj);
	shadowedlight->SetVector("eyePos", eye);
	shadowedlight->SetVector("lightPos", moonlight);
	shadowedlight->SetVector("lightColor", mooncolor);
	shadowedlight->SetVector("clipPlanes", lightclip);

	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, blurredshadow->GetColorAttachment(0));
	glActiveTexture(GL_TEXTURE0);

	shadowedlight->Begin();
	{
		RenderScene(shadowedlight);
	}
	shadowedlight->End();

	// STEP 4: accumulate lighting
	if( lightaccum && timeout > DELAY )
	{
		lightaccum->SetMatrix("matViewProj", viewproj);
		lightaccum->SetVector("eyePos", eye);
		lightaccum->SetFloat("alpha", alpha);
		lightaccum->SetInt("numTilesX", workgroupsx);

		lightaccum->Begin();
		{
			RenderScene(lightaccum);
		}
		lightaccum->End();
		
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0);
	}

	framebuffer->Unset();

	glDisable(GL_BLEND);
	glDepthMask(GL_TRUE);

	// STEP 4: gamma correct
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
	glBindTexture(GL_TEXTURE_2D, framebuffer->GetColorAttachment(0));

	gammacorrect->Begin();
	{
		screenquad->Draw();
	}
	gammacorrect->End();

#ifdef _DEBUG
	// check errors
	GLenum err = glGetError();

	if( err != GL_NO_ERROR )
		std::cout << "Error\n";
#endif

	SwapBuffers(hdc);
	mousedx = mousedy = 0;
}
// --------------------------------------------------------------------------------------------------------------------
bool TexturedQuadsGLBindlessMultiDraw::Init(const std::vector<TexturedQuadsProblem::Vertex>& _vertices,
                                            const std::vector<TexturedQuadsProblem::Index>& _indices,
                                            const std::vector<TextureDetails*>& _textures,
                                            size_t _objectCount)
{
    if (!TexturedQuadsSolution::Init(_vertices, _indices, _textures, _objectCount)) {
        return false;
    }

    // Prerequisites
    if (glGetTextureHandleARB == nullptr) {
        console::warn("Unable to initialize solution '%s', requires support for bindless textures (not present).", GetName().c_str());
        return false;
    }

    // Programs
    mProgram = CreateProgram("textures_gl_bindless_multidraw_vs.glsl",
                             "textures_gl_bindless_multidraw_fs.glsl");

    if (mProgram == 0) {
        console::warn("Unable to initialize solution '%s', shader compilation/linking failed.", GetName().c_str());
        return false;
    }

    // Textures
    for (auto it = _textures.begin(); it != _textures.end(); ++it) {
        GLuint tex = NewTex2DFromDetails(*(*it));
        if (!tex) {
            console::warn("Unable to initialize solution '%s', texture creation failed.", GetName().c_str());
            return false;
        }

        // Needs to be freed later.
        mTextures.push_back(tex);

        GLuint64 texHandle = glGetTextureHandleARB(tex);
        if (texHandle == 0) {
            console::warn("Unable to initialize solution '%s', couldn't get texture handle.", GetName().c_str());
        }
        mTexHandles.push_back(texHandle);
    }

    // Buffers
    mVertexBuffer = NewBufferFromVector(GL_ARRAY_BUFFER, _vertices, GL_STATIC_DRAW);
    mIndexBuffer = NewBufferFromVector(GL_ELEMENT_ARRAY_BUFFER, _indices, GL_STATIC_DRAW);

    glGenBuffers(1, &mTransformBuffer);
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, mTransformBuffer);

    auto srcIt = mTexHandles.cbegin();
    std::vector<GLuint64> texAddressContents(_objectCount);
    for (auto dstIt = texAddressContents.begin(); dstIt != texAddressContents.end(); ++dstIt) {
        if (srcIt == mTexHandles.cend()) {
            srcIt = mTexHandles.cbegin();
        }

        (*dstIt) = *srcIt;
        ++srcIt;
    }

    mTexAddressBuffer = NewBufferFromVector(GL_SHADER_STORAGE_BUFFER, texAddressContents, GL_STATIC_DRAW);
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, mTexAddressBuffer);

    mCommands.resize(_objectCount);

    return GLRenderer::GetApiError() == GL_NO_ERROR;
}
void renderScene(void)
{
	int i;
	int count;

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	setCamera(1.5,1.5,3.5,1.5,1.5,0);
	glUseProgram(p);
	setUniforms();

	for (count = 0; count < 3; ++count)
	{
		glBindVertexArray(vao[count]);
		glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfbuf[count]);

		glEnable(GL_RASTERIZER_DISCARD);
		glBeginTransformFeedback(GL_TRIANGLES);
			glDrawArrays(GL_TRIANGLES, 0, 3);
		glEndTransformFeedback();
		glDisable(GL_RASTERIZER_DISCARD);

		glBindBuffer(GL_ARRAY_BUFFER, tfbuf[count]);
		glDrawArrays(GL_TRIANGLES, 0, 3);
		glBindBuffer(GL_ARRAY_BUFFER, 0);

		glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, tfbuf[count]);

		float *pos = (float *)glMapBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, GL_READ_WRITE);

		int i;
		if (pos != NULL)
		{
			printf("Triangle #%d\n", count + 1);
			for (i = 0; i < 3; ++i)
			{
				printf("    Vertex #%d\n", i);
				printf("      Color: \t%f %f %f %f\n", pos[8 * i], pos[8 * i + 1], pos[8 * i + 2], pos[8 * i + 3]);
				printf("      Pos: \t%f %f %f %f\n", pos[8 * i + 4], pos[8 * i + 5], pos[8 * i + 6], pos[8 * i + 7]);
			}
		}

		if (pos != NULL && dump_vertex)
		{
			FILE * pFile;
			int n;

			pFile = fopen ("glsl_solid_triangles_overlap_vertex.txt","w");
			fprintf(pFile, "Triangle #%d\n", count + 1);			
			for (n=0 ; n<3 ; n++)
			{
				fprintf(pFile, "    Vertex #%d\n", i);
				fprintf(pFile, "      Color: \t%f %f %f %f\n", pos[8 * i], pos[8 * i + 1], pos[8 * i + 2], pos[8 * i + 3]);
				fprintf(pFile, "      Pos: \t%f %f %f %f\n", pos[8 * i + 4], pos[8 * i + 5], pos[8 * i + 6], pos[8 * i + 7]);
			}
			fclose (pFile);
		}
	
	}

	glutSwapBuffers();
}
void indexed_buffer_target_t::reset_binding( )
{
    reset_current_buffer();
    glBindBufferBase(gl_target_type(type()), idx_, 0);
}
void indexed_buffer_target_t::bind_buffer( buffer_ptr buffer )
{
    set_current_buffer(buffer);
    glBindBufferBase(gl_target_type(type()), idx_, buffer->gl_id());
}
Beispiel #12
0
GLUSboolean init(GLUSvoid)
{
	GLUStextfile vertexSource;
	GLUStextfile fragmentSource;
	GLUStextfile computeSource;

	glusLoadTextFile("../Example30/shader/fullscreen.vert.glsl", &vertexSource);
	glusLoadTextFile("../Example30/shader/texture.frag.glsl", &fragmentSource);

	glusBuildProgramFromSource(&g_program, (const GLchar**)&vertexSource.text, 0, 0, 0, (const GLchar**)&fragmentSource.text);

	glusDestroyTextFile(&vertexSource);
	glusDestroyTextFile(&fragmentSource);

	glusLoadTextFile("../Example30/shader/raytrace.comp.glsl", &computeSource);

	glusBuildComputeProgramFromSource(&g_computeProgram, (const GLchar**)&computeSource.text);

	glusDestroyTextFile(&computeSource);

	//

	// Retrieve the uniform locations in the program.
	g_textureLocation = glGetUniformLocation(g_program.program, "u_texture");

	//

	// Generate and bind a texture.
	glGenTextures(1, &g_texture);
	glBindTexture(GL_TEXTURE_2D, g_texture);

	// Create an empty image.
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, g_imageWidth, g_imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

	// Setting the texture parameters.
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	glBindTexture(GL_TEXTURE_2D, 0);

	//
	//

	glUseProgram(g_program.program);

	glGenVertexArrays(1, &g_vao);
	glBindVertexArray(g_vao);

	//

	// Also bind created texture ...
	glBindTexture(GL_TEXTURE_2D, g_texture);

	// ... and bind this texture as an image, as we will write to it. see binding = 0 in shader.
	glBindImageTexture(0, g_texture, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA8);

	// ... and as this is texture number 0, bind the uniform to the program.
	glUniform1i(g_textureLocation, 0);

	//
	//

	glUseProgram(g_computeProgram.program);

	//

	// Generate the ray directions depending on FOV, width and height.
	if (!glusRaytracePerspectivef(g_directionBuffer, PADDING, 30.0f, WIDTH, HEIGHT))
	{
		printf("Error: Could not create direction buffer.\n");

		return GLUS_FALSE;
	}

	// Compute shader will use these textures just for input.
	glusRaytraceLookAtf(g_positionBuffer, g_directionBuffer, g_directionBuffer, PADDING, WIDTH, HEIGHT, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f);

	//
	// Buffers with the initial ray position and direction.
	//

	glGenBuffers(1, &g_directionSSBO);

	glBindBuffer(GL_SHADER_STORAGE_BUFFER, g_directionSSBO);
	glBufferData(GL_SHADER_STORAGE_BUFFER, WIDTH * HEIGHT * (3 + PADDING) * sizeof(GLfloat), g_directionBuffer, GL_STATIC_READ);
	// see binding = 1 in the shader
	glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, g_directionSSBO);

	//

	glGenBuffers(1, &g_positionSSBO);

	glBindBuffer(GL_SHADER_STORAGE_BUFFER, g_positionSSBO);
	glBufferData(GL_SHADER_STORAGE_BUFFER, WIDTH * HEIGHT * 4 * sizeof(GLfloat), g_positionBuffer, GL_STATIC_READ);
	// see binding = 2 in the shader
	glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, g_positionSSBO);

	return GLUS_TRUE;
}
        void CommandBuffer::flushDrawStates()
        {
            glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer);

            glUseProgram(m_program);

            if (m_depthEnable)
            {
                glEnable(GL_DEPTH_TEST);
            }
            else
            {
                glDisable(GL_DEPTH_TEST);
            }

            int textureSlot = 0;
            for (unsigned index = 0; index < m_shaderResourceViewCountPS; ++index)
            {
                if (m_shaderResourceViewsPS[index])
                {
                    glUniform1i(index, textureSlot++);
                    glActiveTexture(GL_TEXTURE0);
                    glBindTexture(GL_TEXTURE_2D, m_shaderResourceViewsPS[0]->getTexture()->getNative());
                    glBindSampler(0, m_samplersPS[0]->getNative());
                }
            }

            static const GLsizei cTempVertexSize = 32;
            static const uintptr_t cTempNormalOffset = 12;
            static const uintptr_t cTempTexOffset = 24;
            glBindVertexArray(m_vao);
            const GLint positionIndex = glGetAttribLocation(m_program, "g_position");
            if (positionIndex != -1)
            {
                glVertexAttribPointer(positionIndex, 3, GL_FLOAT, GL_FALSE, cTempVertexSize, 0);
                glEnableVertexAttribArray(positionIndex);
            }
            const GLint normalIndex = glGetAttribLocation(m_program, "g_normal");
            if (normalIndex != -1)
            {
                glVertexAttribPointer(normalIndex, 3, GL_FLOAT, GL_FALSE, cTempVertexSize, reinterpret_cast<void*>(cTempNormalOffset));
                glEnableVertexAttribArray(normalIndex);
            }
            const GLint texIndex = glGetAttribLocation(m_program, "g_tex");
            if (texIndex != -1)
            {
                glVertexAttribPointer(texIndex, 2, GL_FLOAT, GL_FALSE, cTempVertexSize, reinterpret_cast<void*>(cTempTexOffset));
                glEnableVertexAttribArray(texIndex);
            }

            if (m_vertexBuffers[0])
            {
                glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffers[0]->getNative());
            }
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer ? m_indexBuffer->getNative() : 0);

            GLuint bindingIndex = 0;
            for (unsigned blockIndex = 0; blockIndex < m_constantBufferCountVS; ++blockIndex)
            {
                if (m_constantBuffersVS[blockIndex])
                {
                    glUniformBlockBinding(m_program, blockIndex, bindingIndex);
                    const auto nativeConstantBuffer = m_constantBuffersVS[blockIndex]->getNative();
                    glBindBufferBase(GL_UNIFORM_BUFFER, bindingIndex++, nativeConstantBuffer);
                }
            }
            for (unsigned blockIndex = 0; blockIndex < m_constantBufferCountPS; ++blockIndex)
            {
                if (m_constantBuffersPS[blockIndex])
                {
                    glUniformBlockBinding(m_program, blockIndex, bindingIndex);
                    const auto nativeConstantBuffer = m_constantBuffersPS[blockIndex]->getNative();
                    glBindBufferBase(GL_UNIFORM_BUFFER, bindingIndex++, nativeConstantBuffer);
                }
            }
        }
Beispiel #14
0
void GP_Buffer::bind(GLuint bindingPoint)
{
	glBindBufferBase(GL_SHADER_STORAGE_BUFFER, bindingPoint, id);
}
Beispiel #15
0
Particles::Particles(shared_ptr<ShaderGroup> m_updateShader, shared_ptr<ShaderGroup> m_renderShader) {
    this->m_updateShader = m_updateShader;
    this->m_renderShader = m_renderShader;
    m_currVB = 0;
    m_currTFB = 1;
    m_isFirst = true;

    float g_radiusRange = 150;
    float g_heightRange = 35;

    vector<particle_t> particles;

    for (int i = 0; i < NUM_RAIN; i++)
    {
        particle_t pt;
        particles.push_back(pt);
        float SeedX;
        float SeedY = random()*g_heightRange;
        float SeedZ;

        bool pointIsInside = false;
        while (!pointIsInside)
        {
            SeedX = random() - 0.5f;
            SeedZ = random() - 0.5f;
            if (sqrt(SeedX*SeedX + SeedZ*SeedZ) <= 0.5f)
                pointIsInside = true;
        }
        //save these random locations for reinitializing rain particles that have fallen out of bounds
        SeedX *= g_radiusRange;
        SeedZ *= g_radiusRange;

        particles[i].seed = glm::vec3(SeedX, SeedY, SeedZ);

        float SpeedX = 40.0f*(random() / 10.0f);
        float SpeedZ = 40.0f*(random() / -10.0f);
        float SpeedY = -40.0f*(random() / 10.0f);

        particles[i].speed = glm::vec3(SpeedX, SpeedY, SpeedZ);
        particles[i].pos = glm::vec3(SeedX, SeedY, SeedZ);
        particles[i].type = floor(random() * 6 + 1);
        particles[i].random = 0.5f + random()*0.5f;
    }

    glGenVertexArrays(2, m_vao);
    glGenTransformFeedbacks(2, m_transformFeedback);
    glGenBuffers(2, m_particleBuffer);
    GL_CHECK_ERRORS();

    for (unsigned int i = 0; i < 2; i++) {
        //init buffers
        glBindVertexArray(m_vao[i]);
        glBindBuffer(GL_ARRAY_BUFFER, m_particleBuffer[i]);
        glBufferData(GL_ARRAY_BUFFER, sizeof(particle_t) * particles.size(), particles.data(), GL_DYNAMIC_DRAW);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(particle_t), 0);                                     // vec3 pos
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(particle_t), (const GLvoid*)(3 * sizeof GLfloat));   // vec3 seed
        glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(particle_t), (const GLvoid*)(6 * sizeof GLfloat));   // vec3 speed
        glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, sizeof(particle_t), (const GLvoid*)(9 * sizeof GLfloat));   // float random
        glVertexAttribPointer(4, 1, GL_FLOAT, GL_FALSE, sizeof(particle_t), (const GLvoid*)(10 * sizeof GLfloat));  // int type
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glEnableVertexAttribArray(0);
        glEnableVertexAttribArray(1);
        glEnableVertexAttribArray(2);
        glEnableVertexAttribArray(3);
        glEnableVertexAttribArray(4);
        glBindVertexArray(0);

        //bind feedback buffers
        glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, m_transformFeedback[i]);
        glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, m_particleBuffer[i]);
        glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0);
    }
    GL_CHECK_ERRORS();
}
Beispiel #16
0
int FLightBuffer::UploadLights(FDynLightData &data)
{
	int size0 = data.arrays[0].Size()/4;
	int size1 = data.arrays[1].Size()/4;
	int size2 = data.arrays[2].Size()/4;
	int totalsize = size0 + size1 + size2 + 1;

	// pointless type casting because some compilers can't print enough warnings.
	if (mBlockAlign > 0 && (unsigned int)totalsize + (mIndex % mBlockAlign) > mBlockSize)
	{
		mIndex = ((mIndex + mBlockAlign) / mBlockAlign) * mBlockAlign;

		// can't be rendered all at once.
		if ((unsigned int)totalsize > mBlockSize)
		{
			int diff = totalsize - (int)mBlockSize;

			size2 -= diff;
			if (size2 < 0)
			{
				size1 += size2;
				size2 = 0;
			}
			if (size1 < 0)
			{
				size0 += size1;
				size1 = 0;
			}
			totalsize = size0 + size1 + size2 + 1;
		}
	}

	if (totalsize <= 1) return -1;

	if (mIndex + totalsize > mBufferSize/4)
	{
		// reallocate the buffer with twice the size
		unsigned int newbuffer;

		// first unmap the old buffer
		glBindBuffer(mBufferType, mBufferId);
		glUnmapBuffer(mBufferType);

		// create and bind the new buffer, bind the old one to a copy target (too bad that DSA is not yet supported well enough to omit this crap.)
		glGenBuffers(1, &newbuffer);
		glBindBufferBase(mBufferType, LIGHTBUF_BINDINGPOINT, newbuffer);
		glBindBuffer(mBufferType, newbuffer);	// Note: Some older AMD drivers don't do that in glBindBufferBase, as they should.
		glBindBuffer(GL_COPY_READ_BUFFER, mBufferId);

		// create the new buffer's storage (twice as large as the old one)
		mBufferSize *= 2;
		mByteSize *= 2;
		if (gl.lightmethod == LM_DIRECT)
		{
			glBufferStorage(mBufferType, mByteSize, NULL, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT);
			mBufferPointer = (float*)glMapBufferRange(mBufferType, 0, mByteSize, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT);
		}
		else
		{
			glBufferData(mBufferType, mByteSize, NULL, GL_DYNAMIC_DRAW);
			mBufferPointer = (float*)glMapBufferRange(mBufferType, 0, mByteSize, GL_MAP_WRITE_BIT|GL_MAP_INVALIDATE_BUFFER_BIT);
		}

		// copy contents and delete the old buffer.
		glCopyBufferSubData(GL_COPY_READ_BUFFER, mBufferType, 0, 0, mByteSize/2);
		glBindBuffer(GL_COPY_READ_BUFFER, 0);
		glDeleteBuffers(1, &mBufferId);
		mBufferId = newbuffer;
	}

	float *copyptr;
	
	assert(mBufferPointer != NULL);
	if (mBufferPointer == NULL) return -1;
	copyptr = mBufferPointer + mIndex * 4;

	float parmcnt[] = { 0, float(size0), float(size0 + size1), float(size0 + size1 + size2) };

	memcpy(&copyptr[0], parmcnt, 4 * sizeof(float));
	memcpy(&copyptr[4], &data.arrays[0][0], 4 * size0*sizeof(float));
	memcpy(&copyptr[4 + 4*size0], &data.arrays[1][0], 4 * size1*sizeof(float));
	memcpy(&copyptr[4 + 4*(size0 + size1)], &data.arrays[2][0], 4 * size2*sizeof(float));

	unsigned int bufferindex = mIndex;
	mIndex += totalsize;
	draw_dlight += (totalsize-1) / 2;
	return bufferindex;
}
Beispiel #17
0
void ShaderEffect::SetUniformBlock(std::string& name, uint_t bufIndex, uint_t ubo)
{
    glBindBufferBase(GL_UNIFORM_BUFFER, bufIndex, ubo);
	SetUniformBlock(name, bufIndex);
}
Beispiel #18
0
void Mercury::draw(void)
{   
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    if (mReset) {
        mReset = false;
        mParticles->reset();
        mTweakBar->syncValues();
    }

    //
    // Compute matrices without the legacy matrix stack support
    //
    nv::matrix4f projectionMatrix;
    nv::perspective( projectionMatrix, 45.0f * 2.0f*3.14159f / 360.0f, (float)m_width/(float)m_height, 0.1f, 10.0f);

    nv::matrix4f viewMatrix = m_transformer->getModelViewMat();

    //
    // update struct representing UBO
    //
    mShaderParams.numParticles = mParticles->getSize();
    mShaderParams.ModelView = viewMatrix;
	mShaderParams.InvViewMatrix = inverse(viewMatrix);
    mShaderParams.ModelViewProjection = projectionMatrix * viewMatrix;
    mShaderParams.ProjectionMatrix = projectionMatrix;

    // bind the buffer for the UBO, and update it with the latest values from the CPU-side struct
    glBindBufferBase(GL_UNIFORM_BUFFER, 1, mUBO);
    glBindBuffer( GL_UNIFORM_BUFFER, mUBO);
    glBufferSubData( GL_UNIFORM_BUFFER, 0, sizeof(ShaderParams), &mShaderParams);

    if (mAnimate) {
		float timeDelta = getFrameDeltaTime();
        mParticles->update(timeDelta);
    } 
	else {
//		float timeDelta = getFrameDeltaTime();
		mParticles->update(0);
	}

	// Display Binary Space Partitions
	if (mPolygonize) {
		mSurfaceRenderProg->enable();
		glBindFramebuffer(GL_FRAMEBUFFER, fbo);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		uint32_t cellsDim = mParticles->getMCPolygonizer()->getCellsDim();
		mShaderParams.cellsize = mParticles->getMCPolygonizer()->getCellSize();


		glEnable(GL_CULL_FACE);
		glEnable(GL_DEPTH_TEST);

		// Bind packed vertex-isovalue buffer.
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, mParticles->getMCPolygonizer()->getPackedPosValBuffer());
		// Bind triangle list hash table for marching cubes algorithm to be referenced from Geometry Shader
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, mParticles->getMCPolygonizer()->getTriTableBuffer());

		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mParticles->getMCPolygonizer()->getIndexBuffer());

		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_CUBE_MAP, mSkyBoxTexID);
		GLuint loc = glGetUniformLocation(mSurfaceRenderProg->getProgram(), "skyBoxTex");
		glProgramUniform1i(mSurfaceRenderProg->getProgram(), loc, 1);	

		glDrawElements(GL_TRIANGLES, cellsDim * cellsDim * cellsDim * 3, GL_UNSIGNED_INT, 0);

		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0);
		glDisable(GL_DEPTH_TEST);
		glDisable(GL_CULL_FACE);

		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		mSurfaceRenderProg->disable();
		
		glClearColor(0.0, 0.0, 0.0, 1.0);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		
		// Draw final scene
		mQuadProg->enable();
		glActiveTexture(GL_TEXTURE3);
		glBindTexture(GL_TEXTURE_2D, gbuffer_tex[0]);
		loc = glGetUniformLocation(mQuadProg->getProgram(), "gbuf0");
		glProgramUniform1i(mQuadProg->getProgram(), loc, 3);
		glActiveTexture(GL_TEXTURE4);
		glBindTexture(GL_TEXTURE_2D, gbuffer_tex[1]);
		loc = glGetUniformLocation(mQuadProg->getProgram(), "gbuf1");
		glProgramUniform1i(mQuadProg->getProgram(), loc, 4);
		glActiveTexture(GL_TEXTURE5);
		glBindTexture(GL_TEXTURE_2D, gbuffer_tex[2]);
		loc = glGetUniformLocation(mQuadProg->getProgram(), "gbuf2");
		glProgramUniform1i(mQuadProg->getProgram(), loc, 5);
		drawScreenAlignedQuad(mQuadProg->getProgram());		
		mQuadProg->disable();
		
		
	} 
	else {
		mParticlesRenderProg->enable();
		// draw particles  

		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE);  // additive blend

		glDisable(GL_DEPTH_TEST);
		glDisable(GL_CULL_FACE);

		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, mParticles->getPosBuffer()->getBuffer());
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mParticles->getIndexBuffer()->getBuffer());
		glDrawElements(GL_TRIANGLES, mParticles->getSize() * 6, GL_UNSIGNED_INT, 0);

		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0);

		glDisable(GL_BLEND);
		mParticlesRenderProg->disable();
	}
}
void
OsdGLSLComputeContext::UnbindEditShaderStorageBuffers() {

    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 9, 0);
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 10, 0);
}
Beispiel #20
0
static int
create_texture(void)
{
	GLuint tex;
	float *ptr;

	/* Generate mipmap level 0 */
	tex = piglit_rgbw_texture(GL_RGBA, TEX_WIDTH, TEX_WIDTH, GL_FALSE,
				  GL_TRUE, GL_FLOAT);
	glBindTexture(GL_TEXTURE_2D, tex);

	if (!piglit_check_gl_error(GL_NO_ERROR))
		piglit_report_result(PIGLIT_FAIL);

	/* Go into appropriate transform feedback or discard state */
	if (discard)
		glEnable(GL_RASTERIZER_DISCARD);
	if (buffer || prims_written) {
		float buffer[4096];
		buffer[0] = 12345.0;
		glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, xfb_buf);
		glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, sizeof(buffer),
			     buffer, GL_STREAM_READ);
		glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, xfb_buf);
		glUseProgram(xfb_prog);
		glBeginTransformFeedback(GL_POINTS);
	}
	if (prims_written) {
		glBeginQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN,
			     prims_written_query);
	}
	if (prims_generated) {
		glBeginQuery(GL_PRIMITIVES_GENERATED, prims_generated_query);
	}

	/* Ask the implementation to generate the remaining mipmap levels. */
	glGenerateMipmapEXT(GL_TEXTURE_2D);
	if (!piglit_check_gl_error(0))
		piglit_report_result(PIGLIT_FAIL);

	/* Check state */
	if (discard) {
		if (!glIsEnabled(GL_RASTERIZER_DISCARD)) {
			printf("GL_RASTERIZER_DISCARD state not restored "
			       "after glGenerateMipmapEXT\n");
			piglit_report_result(PIGLIT_FAIL);
		}
		glDisable(GL_RASTERIZER_DISCARD);
	}
	if (buffer || prims_written) {
		glEndTransformFeedback();
		glUseProgram(0);
	}
	if (buffer) {
		ptr = glMapBuffer(GL_TRANSFORM_FEEDBACK_BUFFER_EXT,
				  GL_READ_ONLY);
		if (ptr[0] != 12345.0) {
			printf("Transform feedback buffer was overwritten "
			       "during glGenerateMipmapEXT\n");
			piglit_report_result(PIGLIT_FAIL);
		}
	}
	if (prims_written) {
		GLuint result;
		glEndQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN);
		glGetQueryObjectuiv(prims_written_query,
				    GL_QUERY_RESULT, &result);
		if (result != 0) {
			printf("PRIMITIVES_WRITTEN counter was incremented "
			       "during glGenerateMipmapEXT\n");
			piglit_report_result(PIGLIT_FAIL);
		}
	}
	if (prims_generated) {
		GLuint result;
		glEndQuery(GL_PRIMITIVES_GENERATED);
		glGetQueryObjectuiv(prims_generated_query,
				    GL_QUERY_RESULT, &result);
		if (result != 0) {
			printf("PRIMITIVES_GENERATED counter was incremented "
			       "during glGenerateMipmapEXT\n");
			piglit_report_result(PIGLIT_FAIL);
		}
	}

	return tex;
}
Beispiel #21
0
/**
 * @brief draw particles
 */
void ParticleSystem::drawPoints() {
//    glEnable(GL_PROGRAM_POINT_SZE);
      glEnable(GL_BLEND);
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
      updateParticles();

      // --------------------------------------------------
      //  transform feedback
      // --------------------------------------------------
      glUseProgram(program_transform);
      glEnable(GL_RASTERIZER_DISCARD);
            setUniforms();

              glBindBuffer(GL_ARRAY_BUFFER, vbo_position);
              glEnableVertexAttribArray(0);
              glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0,0);
              glBindBuffer(GL_ARRAY_BUFFER, vbo_speed);
              glEnableVertexAttribArray(1);
              glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0,0);
              glBindBuffer(GL_ARRAY_BUFFER, vbo_ID);
              glEnableVertexAttribArray(2);
              glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, 0,0);

              glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER,0, vbo_draw);
              glBeginTransformFeedback(GL_POINTS);
                  glDrawArrays(GL_POINTS, 0, num_points);
              glEndTransformFeedback();

            glBindBuffer(GL_ARRAY_BUFFER, 0);


      glDisable(GL_RASTERIZER_DISCARD);
      glUseProgram(0);

      // --------------------------------------------------
      //  use the results from transformation to draw the particles
      // --------------------------------------------------
      srand (time(NULL));
      glm::vec3 r = glm::vec3(static_cast <float> (rand()) / static_cast <float> (RAND_MAX),
                                 static_cast <float> (rand()) / static_cast <float> (RAND_MAX),
                                 static_cast <float> (rand()) / static_cast <float> (RAND_MAX));
      shaderCtrlPoints.Bind();
      glUniform1f(shaderCtrlPoints.GetUniformLocation("pointSize"), (float)pointSize);
      glUniform3f(shaderCtrlPoints.GetUniformLocation("rand"), r.x, r.y, r.z);
      glUniformMatrix4fv(shaderCtrlPoints.GetUniformLocation("projMX"), 1, GL_FALSE,
                         glm::value_ptr(projMX));
      glUniformMatrix4fv(shaderCtrlPoints.GetUniformLocation("viewMX"), 1, GL_FALSE,
                         glm::value_ptr(viewMX));
      glUniform3f(shaderCtrlPoints.GetUniformLocation("translate"), 0.5f, 0.5f, 0.5f);
      currentTime+=deltaT;
      if(currentTime > 1000000.0f)
          currentTime = 0.0f;
      glUniform1f(shaderCtrlPoints.GetUniformLocation("time"), currentTime);

      glActiveTexture(GL_TEXTURE0);
      glBindTexture(GL_TEXTURE_2D, randomTex);
      glUniform1i(shaderCtrlPoints.GetUniformLocation("randomtex"), 0);

          glBindBuffer(GL_ARRAY_BUFFER, vbo_draw);
          glEnableVertexAttribArray(0);
          glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0,0);

          glBindBuffer(GL_ARRAY_BUFFER, vbo_speed);
          glEnableVertexAttribArray(1);
          glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0,0);

          glDrawArraysInstanced(GL_POINTS, 0, num_points, num_instances);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
  shaderCtrlPoints.Release();

  // --------------------------------------------------
  //  swap buffers for particles position (ping-pong update model)
  // --------------------------------------------------
  std::swap(vbo_position, vbo_draw);
}
Beispiel #22
0
void gfxBindUniformBuffer(uint32 ubo, void* data, size_t size, uint32 bindingPoint)
{
    glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, ubo);
    glBufferSubData(GL_UNIFORM_BUFFER, 0, size, data);
}
Beispiel #23
0
	void DeferredPainter::Render(AnimationManagerGFX* animationManager, unsigned int& renderIndex,
		FBOTexture* depthBuffer, FBOTexture* normalDepth, FBOTexture* diffuse, FBOTexture* specular,
		FBOTexture* glowMatID, glm::mat4 viewMatrix, glm::mat4 projMatrix, const float& gamma, RenderInfo& out_RenderInfo)
	{
		BasePainter::Render();
		unsigned int numDrawCalls = 0;
		unsigned int numTris = 0;

		BindGBuffer(depthBuffer, normalDepth, diffuse, specular, glowMatID);
		glEnable(GL_DEPTH_TEST);
		glDisable(GL_BLEND);

		glClearStencil(0);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

		// Clear depth RT
		float c[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
		glClearBufferfv(GL_COLOR, 1, &glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)[0]);
		m_shaderManager->UseProgram("StaticBlend");

		BasicCamera bc;
		bc.viewMatrix = viewMatrix;
		bc.projMatrix = projMatrix;

		m_uniformBufferManager->SetBasicCameraUBO(bc);

		std::vector<RenderJobManager::RenderJob> renderJobs = m_renderJobManager->GetJobs();

		unsigned int currentShader = std::numeric_limits<decltype(currentShader)>::max();
		unsigned int currentMaterial = std::numeric_limits<decltype(currentMaterial)>::max();
		unsigned int currentMesh = std::numeric_limits<decltype(currentMesh)>::max();
		unsigned int currentLayer = std::numeric_limits<decltype(currentMesh)>::max();


		unsigned int objType = std::numeric_limits<decltype(objType)>::max();
		unsigned int viewport = std::numeric_limits<decltype(viewport)>::max();
		unsigned int layer = std::numeric_limits<decltype(layer)>::max();
		unsigned int translucency = std::numeric_limits<decltype(translucency)>::max();
		unsigned int meshID = std::numeric_limits<decltype(meshID)>::max();
		unsigned int material = std::numeric_limits<decltype(material)>::max();
		unsigned int depth = std::numeric_limits<decltype(depth)>::max();

		int instanceBufferSize = 0;

		{
			Material mat;
			Mesh mesh;
			GFXBitmask bitmask;
			int instanceCount = 0;
			unsigned int instanceOffset = 0;
			unsigned int i;
			
			bool endMe = false;
			for (i = renderIndex; i < renderJobs.size(); i++)
			{
				bitmask = renderJobs[i].bitmask;

				objType = GetBitmaskValue(bitmask, BITMASK::TYPE);

				// Break if no opaque object
				if (objType != GFX::OBJECT_TYPES::OPAQUE_GEOMETRY)
				{
					endMe = true;
				}

				if (!endMe)
				{
					viewport = GetBitmaskValue(bitmask, BITMASK::VIEWPORT_ID);
					layer = GetBitmaskValue(bitmask, BITMASK::LAYER);
					translucency = GetBitmaskValue(bitmask, BITMASK::TRANSLUCENCY_TYPE);
					meshID = GetBitmaskValue(bitmask, BITMASK::MESH_ID);
					material = GetBitmaskValue(bitmask, BITMASK::MATERIAL_ID);
					depth = GetBitmaskValue(bitmask, BITMASK::DEPTH);
				}

				if (material == currentMaterial && meshID == currentMesh && !endMe && instanceCount < MAX_INSTANCES && layer == currentLayer)
				{
					InstanceData smid = *(InstanceData*)renderJobs.at(i).value;
					m_staticInstances[instanceOffset + instanceCount] = smid;
					instanceCount++;
					instanceBufferSize++;
				}
				else
				{
					if (i > 0)
					{
						instanceOffset += instanceCount;
						instanceCount = 0;
					}

					if (endMe)
						break;

					if (material != currentMaterial)
					{
						mat = m_materialManager->GetMaterial(material);

						currentMaterial = material;

						//compare shader
						if (mat.shaderProgramID != currentShader)
						{
							currentShader = mat.shaderProgramID;
						}
					}

					if (meshID != currentMesh)
					{
						mesh = m_meshManager->GetMesh(meshID);
						currentMesh = meshID;
					}

					if (layer != currentLayer)
					{
						currentLayer = layer;
					}
					InstanceData smid = *(InstanceData*)renderJobs.at(i).value;
					m_staticInstances[instanceOffset + instanceCount] = smid;
					instanceCount++;
					instanceBufferSize++;
				}
			}
		}
		
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_instanceBuffer);
		InstanceData* pData = (InstanceData*)glMapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, MAX_INSTANCES * sizeof(InstanceData),
			GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT | GL_MAP_UNSYNCHRONIZED_BIT);

		memcpy(pData, m_staticInstances, instanceBufferSize * sizeof(InstanceData));

		glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);

		
		currentShader = std::numeric_limits<decltype(currentShader)>::max();
		currentMaterial = std::numeric_limits<decltype(currentMaterial)>::max();
		currentMesh = std::numeric_limits<decltype(currentMesh)>::max();
		currentLayer = std::numeric_limits<decltype(currentMesh)>::max();
		objType = std::numeric_limits<decltype(objType)>::max();
		viewport = std::numeric_limits<decltype(viewport)>::max();
		layer = std::numeric_limits<decltype(layer)>::max();
		translucency = std::numeric_limits<decltype(translucency)>::max();
		meshID = std::numeric_limits<decltype(meshID)>::max();
		material = std::numeric_limits<decltype(material)>::max();
		depth = std::numeric_limits<decltype(depth)>::max();

		Material mat;
		Mesh mesh;
		GFXBitmask bitmask;
		int instanceCount = 0;
		unsigned int instanceOffset = 0;
		unsigned int i;
		bool endMe = false;
		for (i = renderIndex; i < renderJobs.size(); i++)
		{
			bitmask = renderJobs[i].bitmask;

			objType = GetBitmaskValue(bitmask, BITMASK::TYPE);

			// Break if no opaque object
			if (objType != GFX::OBJECT_TYPES::OPAQUE_GEOMETRY)
			{
				endMe = true;
			}

			if (!endMe)
			{
				viewport = GetBitmaskValue(bitmask, BITMASK::VIEWPORT_ID);
				layer = GetBitmaskValue(bitmask, BITMASK::LAYER);
				translucency = GetBitmaskValue(bitmask, BITMASK::TRANSLUCENCY_TYPE);
				meshID = GetBitmaskValue(bitmask, BITMASK::MESH_ID);
				material = GetBitmaskValue(bitmask, BITMASK::MATERIAL_ID);
				depth = GetBitmaskValue(bitmask, BITMASK::DEPTH);
			}

			if (material == currentMaterial && meshID == currentMesh && !endMe && instanceCount < MAX_INSTANCES && layer == currentLayer)
			{
				//InstanceData smid = *(InstanceData*)renderJobs.at(i).value;
				//m_staticInstances[instanceOffset+instanceCount] = smid;
				instanceCount++;
			}
			else
			{
				if (i > 0)
				{
						
					unsigned int asd[4] = {instanceOffset, 0U, 0U, 0U};
					glBindBufferBase(GL_UNIFORM_BUFFER, UniformBufferManager::INSTANCE_ID_OFFSET_INDEX, m_instanceOffsetBuffer);
					glBufferSubData(GL_UNIFORM_BUFFER, 0, 4*sizeof(unsigned int), asd);

					glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.IBO);

					if (currentLayer == LAYER_TYPES::OUTLINE_LAYER)
					{
						glEnable(GL_STENCIL_TEST);
						glStencilFunc(GL_ALWAYS, 1, -1);
						glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
						glEnable(GL_DEPTH_TEST);
					}

					glDrawElementsInstanced(GL_TRIANGLES, mesh.indexCount, GL_UNSIGNED_INT, (GLvoid*)0, instanceCount);
					numDrawCalls++;
					numTris += (mesh.indexCount / 3) * instanceCount;

					if (currentLayer == LAYER_TYPES::OUTLINE_LAYER)
					{
						glDisable(GL_DEPTH_TEST);
						glStencilFunc(GL_NOTEQUAL, 1, -1);
						glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
						glLineWidth(m_staticInstances[instanceOffset + instanceCount - 1].outlineColor[3]);
						glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

						if (currentShader == m_staticBlend || currentShader == m_staticNormal)
							m_shaderManager->UseProgram("StaticOutline");
						else if (currentShader == m_animatedBlend || currentShader == m_animatedNormal)
							m_shaderManager->UseProgram("AnimatedOutline");

						glDrawElementsInstanced(GL_TRIANGLES, mesh.indexCount, GL_UNSIGNED_INT, (GLvoid*)0, instanceCount);
						numDrawCalls++;
						numTris += (mesh.indexCount / 3) * instanceCount;

						glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);


						glUseProgram(currentShader);
						glEnable(GL_DEPTH_TEST);
						glDisable(GL_STENCIL_TEST);
					}
					
					instanceOffset += instanceCount;
					instanceCount = 0;
				}

				if (endMe)
					break;

				if (material != currentMaterial)
				{
					mat = m_materialManager->GetMaterial(material);

					//It's possible that a material is removed before an entity. Should this be ok, do we need to be
					// more rigorous from the outside?
					if (mat.textures.size() != 4)
					{
						LOG_ERROR << "Trying to render object with invalid material" << std::endl;
						continue;
					}
					//alt
					//assert(mat.textures.size() == 4); 

					currentMaterial = material;

					//compare shader
					if (mat.shaderProgramID != currentShader)
					{
						glUseProgram(mat.shaderProgramID);
						currentShader = mat.shaderProgramID;

						m_uniformTexture0 = m_shaderManager->GetUniformLocation(currentShader, "gDiffuse");
						m_uniformTexture1 = m_shaderManager->GetUniformLocation(currentShader, "gNormal");
						m_uniformTexture2 = m_shaderManager->GetUniformLocation(currentShader, "gSpecular");
						m_uniformTexture3 = m_shaderManager->GetUniformLocation(currentShader, "gGlow");

						m_gammaUniform = m_shaderManager->GetUniformLocation(currentShader, "gGamma");
					}

					//set textures
					m_textureManager->BindTexture(m_textureManager->GetTexture(mat.textures[0]).textureHandle, m_uniformTexture0, 0, GL_TEXTURE_2D);
					m_textureManager->BindTexture(m_textureManager->GetTexture(mat.textures[1]).textureHandle, m_uniformTexture1, 1, GL_TEXTURE_2D);
					m_textureManager->BindTexture(m_textureManager->GetTexture(mat.textures[2]).textureHandle, m_uniformTexture2, 2, GL_TEXTURE_2D);
					m_textureManager->BindTexture(m_textureManager->GetTexture(mat.textures[3]).textureHandle, m_uniformTexture3, 3, GL_TEXTURE_2D);

					//Set gamma
					m_shaderManager->SetUniform(gamma, m_gammaUniform);
				}

				if (meshID != currentMesh)
				{
					mesh = m_meshManager->GetMesh(meshID);
					currentMesh = meshID;

					glBindVertexArray(mesh.VAO);
				}

				if (layer != currentLayer)
				{
					currentLayer = layer;
				}
				instanceCount++;
			}


		}

		m_shaderManager->ResetProgram();

		glClearStencil(0);
		glClear(GL_STENCIL_BUFFER_BIT);
		glDisable(GL_STENCIL_TEST);

		ClearFBO();
		renderIndex = i;
		out_RenderInfo.numDrawCalls = numDrawCalls;
		out_RenderInfo.numTris = numTris;
	}
Beispiel #24
0
void
piglit_init(int argc, char **argv)
{
	bool pass = true;
	GLuint buffer[2];
	unsigned int i;
	float ssbo_values[SSBO_SIZE] = {0};
	float *map;
	int index;

	piglit_require_extension("GL_ARB_shader_storage_buffer_object");
	piglit_require_extension("GL_ARB_program_interface_query");

	prog = piglit_build_simple_program(vs_pass_thru_text, fs_source);

	glUseProgram(prog);

	glClearColor(0, 0, 0, 0);

	glGenBuffers(2, buffer);
	glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, buffer[0]);
	glBufferData(GL_SHADER_STORAGE_BUFFER, SSBO_SIZE*sizeof(GLfloat),
				&ssbo_values[0], GL_DYNAMIC_DRAW);
	/* Change binding point */
	index = glGetProgramResourceIndex(prog,
					  GL_SHADER_STORAGE_BLOCK, "ssbo[0]");
	glShaderStorageBlockBinding(prog, index, 4);

	glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, buffer[1]);
	glBufferData(GL_SHADER_STORAGE_BUFFER, SSBO_SIZE*sizeof(GLfloat),
				&ssbo_values[0], GL_DYNAMIC_DRAW);

	glViewport(0, 0, piglit_width, piglit_height);

	piglit_draw_rect(-1, -1, 2, 2);

	glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffer[0]);
	map = (float *) glMapBuffer(GL_SHADER_STORAGE_BUFFER,  GL_READ_ONLY);

	/* Former bound buffer should not be modified */
	for (i = 0; i < SSBO_SIZE; i++) {
		if (map[i] != 0) {
			printf("Wrong %d value in buffer[0]: %.2f\n",
			       i, map[i]);
			pass = false;
		}
	}
	glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);

	glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffer[1]);
	map = (float *) glMapBuffer(GL_SHADER_STORAGE_BUFFER,  GL_READ_ONLY);

	for (i = 0; i < SSBO_SIZE; i++) {
                /* Values should be below ten but different than zero */
		if (map[i] == 0 || map[i] > 10) {
			printf("Wrong %d value in buffer[1]: %.2f\n",
			       i, map[i]);
			pass = false;
		}
	}

	glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);

	if (!piglit_check_gl_error(GL_NO_ERROR))
	   pass = false;

	piglit_report_result(pass ? PIGLIT_PASS : PIGLIT_FAIL);
}
Beispiel #25
0
void IrrDriver::renderScene(scene::ICameraSceneNode * const camnode, unsigned pointlightcount, std::vector<GlowData>& glows, float dt, bool hasShadow, bool forceRTT)
{
    glBindBufferBase(GL_UNIFORM_BUFFER, 0, SharedObject::ViewProjectionMatrixesUBO);
    m_scene_manager->setActiveCamera(camnode);

    PROFILER_PUSH_CPU_MARKER("- Draw Call Generation", 0xFF, 0xFF, 0xFF);
    PrepareDrawCalls(camnode);
    PROFILER_POP_CPU_MARKER();
    // Shadows
    {
        // To avoid wrong culling, use the largest view possible
        m_scene_manager->setActiveCamera(m_suncam);
        if (!m_mipviz && !m_wireframe && UserConfigParams::m_dynamic_lights &&
            UserConfigParams::m_shadows && !irr_driver->needUBOWorkaround() && hasShadow)
        {
            PROFILER_PUSH_CPU_MARKER("- Shadow", 0x30, 0x6F, 0x90);
            renderShadows();
            PROFILER_POP_CPU_MARKER();
            if (UserConfigParams::m_gi)
            {
                PROFILER_PUSH_CPU_MARKER("- RSM", 0xFF, 0x0, 0xFF);
                renderRSM();
                PROFILER_POP_CPU_MARKER();
            }
        }
        m_scene_manager->setActiveCamera(camnode);

    }

    PROFILER_PUSH_CPU_MARKER("- Solid Pass 1", 0xFF, 0x00, 0x00);
    glDepthMask(GL_TRUE);
    glDepthFunc(GL_LEQUAL);
    glEnable(GL_DEPTH_TEST);
    glDisable(GL_BLEND);
    glEnable(GL_CULL_FACE);
    if (UserConfigParams::m_dynamic_lights || forceRTT)
    {
        m_rtts->getFBO(FBO_NORMAL_AND_DEPTHS).Bind();
        glClearColor(0., 0., 0., 0.);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
        renderSolidFirstPass();
    }
    PROFILER_POP_CPU_MARKER();



    // Lights
    {
        PROFILER_PUSH_CPU_MARKER("- Light", 0x00, 0xFF, 0x00);
        if (UserConfigParams::m_dynamic_lights)
            renderLights(pointlightcount, hasShadow);
        PROFILER_POP_CPU_MARKER();
    }

    // Handle SSAO
    {
        PROFILER_PUSH_CPU_MARKER("- SSAO", 0xFF, 0xFF, 0x00);
        ScopedGPUTimer Timer(getGPUTimer(Q_SSAO));
        if (UserConfigParams::m_ssao)
            renderSSAO();
        PROFILER_POP_CPU_MARKER();
    }

    PROFILER_PUSH_CPU_MARKER("- Solid Pass 2", 0x00, 0x00, 0xFF);
    if (UserConfigParams::m_dynamic_lights || forceRTT)
    {
        m_rtts->getFBO(FBO_COLORS).Bind();
        SColor clearColor(0, 150, 150, 150);
        if (World::getWorld() != NULL)
            clearColor = World::getWorld()->getClearColor();

        glClearColor(clearColor.getRed() / 255.f, clearColor.getGreen() / 255.f,
            clearColor.getBlue() / 255.f, clearColor.getAlpha() / 255.f);
        glClear(GL_COLOR_BUFFER_BIT);
        glDepthMask(GL_FALSE);
    }
    renderSolidSecondPass();
    PROFILER_POP_CPU_MARKER();

    if (getNormals())
    {
        m_rtts->getFBO(FBO_NORMAL_AND_DEPTHS).Bind();
        renderNormalsVisualisation();
        m_rtts->getFBO(FBO_COLORS).Bind();
    }

    if (UserConfigParams::m_dynamic_lights && World::getWorld() != NULL &&
        World::getWorld()->isFogEnabled())
    {
        PROFILER_PUSH_CPU_MARKER("- Fog", 0xFF, 0x00, 0x00);
        m_post_processing->renderFog();
        PROFILER_POP_CPU_MARKER();
    }

    PROFILER_PUSH_CPU_MARKER("- Skybox", 0xFF, 0x00, 0xFF);
    renderSkybox(camnode);
    PROFILER_POP_CPU_MARKER();

    if (getRH())
    {
        m_rtts->getFBO(FBO_COLORS).Bind();
        m_post_processing->renderRHDebug(m_rtts->getRH().getRTT()[0], m_rtts->getRH().getRTT()[1], m_rtts->getRH().getRTT()[2], rh_matrix, rh_extend);
    }

    if (getGI())
    {
        m_rtts->getFBO(FBO_COLORS).Bind();
        m_post_processing->renderGI(rh_matrix, rh_extend, m_rtts->getRH().getRTT()[0], m_rtts->getRH().getRTT()[1], m_rtts->getRH().getRTT()[2]);
    }

    PROFILER_PUSH_CPU_MARKER("- Glow", 0xFF, 0xFF, 0x00);
    // Render anything glowing.
    if (!m_mipviz && !m_wireframe && UserConfigParams::m_glow)
    {
        irr_driver->setPhase(GLOW_PASS);
        renderGlow(glows);
    } // end glow
    PROFILER_POP_CPU_MARKER();

    PROFILER_PUSH_CPU_MARKER("- Lensflare/godray", 0x00, 0xFF, 0xFF);
    computeSunVisibility();
    PROFILER_POP_CPU_MARKER();

    // Render transparent
    {
        PROFILER_PUSH_CPU_MARKER("- Transparent Pass", 0xFF, 0x00, 0x00);
        ScopedGPUTimer Timer(getGPUTimer(Q_TRANSPARENT));
        renderTransparent();
        PROFILER_POP_CPU_MARKER();
    }

    m_sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);

    // Render particles
    {
        PROFILER_PUSH_CPU_MARKER("- Particles", 0xFF, 0xFF, 0x00);
        ScopedGPUTimer Timer(getGPUTimer(Q_PARTICLES));
        renderParticles();
        PROFILER_POP_CPU_MARKER();
    }
    if (!UserConfigParams::m_dynamic_lights && !forceRTT)
    {
        glDisable(GL_FRAMEBUFFER_SRGB);
        glDisable(GL_DEPTH_TEST);
        glDepthMask(GL_FALSE);
        return;
    }

    // Ensure that no object will be drawn after that by using invalid pass
    irr_driver->setPhase(PASS_COUNT);
}
void ofBufferObject::unbindRange(GLenum target,GLuint index) const{
	glBindBufferBase(target,index,0);
}
void DrawableManager::initRenderTypes() {

	/*
	 *	precalls
	 */
	auto doubleBufferPreCall = [](gl::Program & prog, const DrawableType & drawType, const core::Camera & cam){
		prog.use();
#ifdef LEGACY_MODE
		const auto modelIndex = glGetUniformBlockIndex(static_cast<GLuint>(prog), "ModelMatrixBuffer");
		glUniformBlockBinding(static_cast<GLuint>(prog), modelIndex, k_modelBufferBinding);
		glBindBufferBase(GL_UNIFORM_BUFFER, k_modelBufferBinding, drawType.modelBuffer);
		const auto colorIndex = glGetUniformBlockIndex(static_cast<GLuint>(prog), "ColorBuffer");
		glUniformBlockBinding(static_cast<GLuint>(prog), colorIndex, k_colorBufferBinding);
		glBindBufferBase(GL_UNIFORM_BUFFER, k_colorBufferBinding, drawType.colorBuffer);
#else
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, k_modelBufferBinding, drawType.modelBuffer);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, k_colorBufferBinding, drawType.colorBuffer);
#endif

		prog["ViewProj"] = cam.getProjMatrix() * cam.getViewMatrix();
		prog["View"] = cam.getViewMatrix();
		prog["lightDir"] = glm::vec3(1.f, 2.f, -3.f);

		drawType.vao.bind();
	};
	auto tripleBufferPreCall = [](gl::Program & prog, const DrawableType & drawType, const core::Camera & cam){
		prog.use();
#ifdef LEGACY_MODE
		const auto modelIndex = glGetUniformBlockIndex(static_cast<GLuint>(prog), "ModelMatrixBuffer");
		glUniformBlockBinding(static_cast<GLuint>(prog), modelIndex, k_modelBufferBinding);
		glBindBufferBase(GL_UNIFORM_BUFFER, k_modelBufferBinding, drawType.modelBuffer);
		const auto colorIndex = glGetUniformBlockIndex(static_cast<GLuint>(prog), "ColorBuffer");
		glUniformBlockBinding(static_cast<GLuint>(prog), colorIndex, k_colorBufferBinding);
		glBindBufferBase(GL_UNIFORM_BUFFER, k_colorBufferBinding, drawType.colorBuffer);
		const auto miscIndex = glGetUniformBlockIndex(static_cast<GLuint>(prog), "MiscBuffer");
		glUniformBlockBinding(static_cast<GLuint>(prog), miscIndex, k_miscBufferBinding);
		glBindBufferBase(GL_UNIFORM_BUFFER, k_miscBufferBinding, drawType.miscBuffer);
#else
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, k_modelBufferBinding, drawType.modelBuffer);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, k_colorBufferBinding, drawType.colorBuffer);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, k_miscBufferBinding, drawType.miscBuffer);
#endif

		prog["ViewProj"] = cam.getProjMatrix() * cam.getViewMatrix();
		prog["View"] = cam.getViewMatrix();
		prog["lightDir"] = glm::vec3(1.f, 2.f, -3.f);

		drawType.vao.bind();
	};
	auto singleBufferPreCall = [](gl::Program & prog, const DrawableType & drawType, const core::Camera & cam){
		prog.use();
#ifdef LEGACY_MODE
		const auto modelIndex = glGetUniformBlockIndex(static_cast<GLuint>(prog), "ModelMatrixBuffer");
		glUniformBlockBinding(static_cast<GLuint>(prog), modelIndex, k_modelBufferBinding);
		glBindBufferBase(GL_UNIFORM_BUFFER, k_modelBufferBinding, drawType.modelBuffer);
#else
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, k_modelBufferBinding, drawType.modelBuffer);
#endif
		prog["col"] = drawType.col;
		prog["ViewProj"] = cam.getProjMatrix() * cam.getViewMatrix();
		prog["View"] = cam.getViewMatrix();
		prog["lightDir"] = glm::vec3(1.f, 2.f, -3.f);

		drawType.vao.bind();
	};

	/*
	 *	UNICOLORED QUAD
	 */
	const std::vector<GLubyte> quadIdx = {
		3, 2, 0,
		0, 1, 3
	};
	auto renderType = RenderTypeName::QUAD;
#ifdef LEGACY_MODE
	gl::Shader quadVert(GL_VERTEX_SHADER);
	quadVert.addSourceFromString("#version 330 core\n");
	quadVert.addSourceFromString("const int NUM_MATRICES = " + std::to_string(m_maxNumObjects) + ";\n");
	quadVert.addSourceFromFile("shader/geometries/quad_legacy.vert");
	if (!quadVert.compileSource()) {
		LOG_ERROR("could not compile vertex shader!");
	}
	gl::Shader frag("shader/lighting/direct_lighting_legacy.frag");
	m_renderTypes[renderType].prog.attachShader(quadVert);
	m_renderTypes[renderType].prog.attachShader(frag);

	m_renderTypes[renderType].ibo.bind(GL_ARRAY_BUFFER);
	m_renderTypes[renderType].ibo.createMutableStorage(static_cast<unsigned int>(quadIdx.size() * sizeof(GLubyte)),
			GL_STATIC_DRAW, quadIdx.data());
	m_renderTypes[renderType].ibo.unbind();
#else
	gl::Shader quadVert("shader/geometries/quad.vert", "quad_instance_vert");
	gl::Shader frag("shader/lighting/direct_lighting.frag");
	m_renderTypes[renderType].prog.attachShader(quadVert);
	m_renderTypes[renderType].prog.attachShader(frag);

	m_renderTypes[renderType].ibo.createImmutableStorage(static_cast<unsigned int>(quadIdx.size() * sizeof(GLubyte)),
			0, quadIdx.data());
#endif
	// drawCall
	m_renderTypes[renderType].drawCall = [](const GLsizei size){
		glDrawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0, size);
	};
	// preCall
	m_renderTypes[renderType].preCall = singleBufferPreCall;

	/*
	 *	MULTICOLORED QUAD
	 */
	renderType = RenderTypeName::MULTICOLOR_QUAD;
#ifdef LEGACY_MODE
	gl::Shader multicolorQuadVert(GL_VERTEX_SHADER);
	multicolorQuadVert.addSourceFromString("#version 330 core\n");
	multicolorQuadVert.addSourceFromString("const int NUM_MATRICES = " + std::to_string(m_maxNumObjects) + ";\n");
	multicolorQuadVert.addSourceFromFile("shader/geometries/multicolor_quad_legacy.vert");
	if (!multicolorQuadVert.compileSource()) {
		LOG_ERROR("could not compile vertex shader!");
	}
	m_renderTypes[renderType].prog.attachShader(multicolorQuadVert);
	m_renderTypes[renderType].prog.attachShader(frag);

	m_renderTypes[renderType].ibo.bind(GL_ARRAY_BUFFER);
	m_renderTypes[renderType].ibo.createMutableStorage(
			static_cast<unsigned int>(quadIdx.size() * sizeof(GLubyte)),
			GL_STATIC_DRAW,	quadIdx.data());
	m_renderTypes[renderType].ibo.unbind();
#else
	gl::Shader multicolorQuadVert("shader/geometries/multicolor_quad.vert", "multicolor_quad_vert");
	m_renderTypes[renderType].prog.attachShader(multicolorQuadVert);
	m_renderTypes[renderType].prog.attachShader(frag);

	m_renderTypes[renderType].ibo.createImmutableStorage(static_cast<unsigned int>(quadIdx.size() * sizeof(GLubyte)),
			0, quadIdx.data());
#endif
	// drawCall
	m_renderTypes[renderType].drawCall = [](const GLsizei size){
		glDrawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0, size);
	};
	// preCall
	m_renderTypes[renderType].preCall = doubleBufferPreCall;

	/*
	 *	UNICOLORED CUBE
	 */
	const std::vector<GLushort> cubeIdx = {
		19, 18, 16,
		16, 17, 19,

		7, 3, 1,
		1, 5, 7,

		22, 23, 21,
		21, 20, 22,

		2, 6, 4,
		4, 0, 2,

		9, 8, 12,
		12, 13, 9,

		14, 15, 11,
		11, 10, 14
	};
	renderType = RenderTypeName::CUBE;
#ifdef LEGACY_MODE
	gl::Shader cubeVert(GL_VERTEX_SHADER);
	cubeVert.addSourceFromString("#version 330 core\n");
	cubeVert.addSourceFromString("const int NUM_MATRICES = " + std::to_string(m_maxNumObjects) + ";\n");
	cubeVert.addSourceFromFile("shader/geometries/cube_legacy.vert");
	if (!cubeVert.compileSource()) {
		LOG_ERROR("could not compile vertex shader!");
	}
	m_renderTypes[renderType].prog.attachShader(cubeVert);
	m_renderTypes[renderType].prog.attachShader(frag);

	m_renderTypes[renderType].ibo.bind(GL_ARRAY_BUFFER);
	m_renderTypes[renderType].ibo.createMutableStorage(
			static_cast<unsigned int>(cubeIdx.size() * sizeof(GLushort)),
			GL_STATIC_DRAW,	cubeIdx.data());
	m_renderTypes[renderType].ibo.unbind();
#else
	gl::Shader cubeVert("shader/geometries/cube.vert", "cube_vert");
	m_renderTypes[renderType].prog.attachShader(cubeVert);
	m_renderTypes[renderType].prog.attachShader(frag);

	m_renderTypes[renderType].ibo.createImmutableStorage(static_cast<unsigned int>(cubeIdx.size() * sizeof(GLushort)),
			0, cubeIdx.data());
#endif
	// drawCall
	m_renderTypes[renderType].drawCall = [](const GLsizei size){
		glDrawElementsInstanced(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, 0, size);
	};
	// preCall
	m_renderTypes[renderType].preCall = singleBufferPreCall;

	/*
	 *	MULTICOLORED CUBE
	 */
	renderType = RenderTypeName::MULTICOLOR_CUBE;
#ifdef LEGACY_MODE
	gl::Shader multicolorCubeVert(GL_VERTEX_SHADER);
	multicolorCubeVert.addSourceFromString("#version 330 core\n");
	multicolorCubeVert.addSourceFromString("const int NUM_MATRICES = " + std::to_string(m_maxNumObjects) + ";\n");
	multicolorCubeVert.addSourceFromFile("shader/geometries/multicolor_cube_legacy.vert");
	if (!multicolorCubeVert.compileSource()) {
		LOG_ERROR("could not compile vertex shader!");
	}
	m_renderTypes[renderType].prog.attachShader(multicolorCubeVert);
	m_renderTypes[renderType].prog.attachShader(frag);

	m_renderTypes[renderType].ibo.bind(GL_ARRAY_BUFFER);
	m_renderTypes[renderType].ibo.createMutableStorage(
			static_cast<unsigned int>(cubeIdx.size() * sizeof(GLushort)),
			GL_STATIC_DRAW,	cubeIdx.data());
	m_renderTypes[renderType].ibo.unbind();
#else
	gl::Shader multicolorCubeVert("shader/geometries/multicolor_cube.vert", "multicolor_cube_vert");
	m_renderTypes[renderType].prog.attachShader(multicolorCubeVert);
	m_renderTypes[renderType].prog.attachShader(frag);

	m_renderTypes[renderType].ibo.createImmutableStorage(static_cast<unsigned int>(cubeIdx.size() * sizeof(GLushort)),
			0, cubeIdx.data());
#endif
	// drawCall
	m_renderTypes[renderType].drawCall = [](const GLsizei size){
		glDrawElementsInstanced(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, 0, size);
	};
	// preCall
	m_renderTypes[renderType].preCall = doubleBufferPreCall;

	/*
	 *	FAN
	 */
	std::vector<GLushort> fanIdx;
	constexpr auto segments = 100u;
	fanIdx.reserve(segments + 2);
	for (auto i = 0u; i < segments + 2; ++i) {
		fanIdx.emplace_back(i);
	}
	renderType = RenderTypeName::FAN;
#ifdef LEGACY_MODE
	gl::Shader fanVert(GL_VERTEX_SHADER);
	fanVert.addSourceFromString("#version 330 core\n");
	fanVert.addSourceFromString("const int NUM_MATRICES = " + std::to_string(m_maxNumObjects) + ";\n");
	fanVert.addSourceFromFile("shader/geometries/fan_legacy.vert");
	if (!fanVert.compileSource()) {
		LOG_ERROR("could not compile vertex shader!");
	}
	m_renderTypes[renderType].prog.attachShader(fanVert);
	m_renderTypes[renderType].prog.attachShader(frag);

	m_renderTypes[renderType].ibo.bind(GL_ARRAY_BUFFER);
	m_renderTypes[renderType].ibo.createMutableStorage(
			static_cast<unsigned int>(fanIdx.size() * sizeof(GLushort)),
			GL_STATIC_DRAW,	fanIdx.data());
	m_renderTypes[renderType].ibo.unbind();
#else
	gl::Shader fanVert("shader/geometries/fan.vert", "fan_vert");
	m_renderTypes[renderType].prog.attachShader(fanVert);
	m_renderTypes[renderType].prog.attachShader(frag);

	m_renderTypes[renderType].ibo.createImmutableStorage(static_cast<unsigned int>(fanIdx.size() * sizeof(GLushort)),
			0, fanIdx.data());
#endif
	// drawCall
	m_renderTypes[renderType].drawCall = [](const GLsizei size){
		glDrawElementsInstanced(GL_TRIANGLE_FAN, segments + 2, GL_UNSIGNED_SHORT, 0, size);
	};
	// preCall
	m_renderTypes[renderType].preCall = tripleBufferPreCall;

	/*
	 *	ANNULUS
	 */
	std::vector<GLushort> annulusIdx;
	annulusIdx.reserve(2 * segments + 2);
	for (auto i = 0u; i < 2 * segments + 2; ++i) {
		annulusIdx.emplace_back(i);
	}
	renderType = RenderTypeName::ANNULUS;
#ifdef LEGACY_MODE
	gl::Shader annulusVert(GL_VERTEX_SHADER);
	annulusVert.addSourceFromString("#version 330 core\n");
	annulusVert.addSourceFromString("const int NUM_MATRICES = " + std::to_string(m_maxNumObjects) + ";\n");
	annulusVert.addSourceFromFile("shader/geometries/circlesegment_legacy.vert");
	if (!annulusVert.compileSource()) {
		LOG_ERROR("could not compile vertex shader!");
	}
	m_renderTypes[renderType].prog.attachShader(annulusVert);
	m_renderTypes[renderType].prog.attachShader(frag);

	m_renderTypes[renderType].ibo.bind(GL_ARRAY_BUFFER);
	m_renderTypes[renderType].ibo.createMutableStorage(
			static_cast<unsigned int>(annulusIdx.size() * sizeof(GLushort)),
			GL_STATIC_DRAW,	annulusIdx.data());
	m_renderTypes[renderType].ibo.unbind();
#else
	gl::Shader annulusVert("shader/geometries/circlesegment.vert", "circlesegment_vert");
	m_renderTypes[renderType].prog.attachShader(annulusVert);
	m_renderTypes[renderType].prog.attachShader(frag);

	m_renderTypes[renderType].ibo.createImmutableStorage(static_cast<unsigned int>(annulusIdx.size() * sizeof(GLushort)),
			0, annulusIdx.data());
#endif
	// drawCall
	m_renderTypes[renderType].drawCall = [](const GLsizei size){
		glDrawElementsInstanced(GL_TRIANGLE_STRIP, 2 * segments + 2, GL_UNSIGNED_SHORT, 0, size);
	};
	// preCall
	m_renderTypes[renderType].preCall = tripleBufferPreCall;

	/*
	 *	TRAPEZOID
	 */
	renderType = RenderTypeName::TRAPEZOID;
#ifdef LEGACY_MODE
	gl::Shader trapezoidVert(GL_VERTEX_SHADER);
	trapezoidVert.addSourceFromString("#version 330 core\n");
	trapezoidVert.addSourceFromString("const int NUM_MATRICES = " + std::to_string(m_maxNumObjects) + ";\n");
	trapezoidVert.addSourceFromFile("shader/geometries/trapezoid_legacy.vert");
	if (!trapezoidVert.compileSource()) {
		LOG_ERROR("could not compile vertex shader!");
	}
	m_renderTypes[renderType].prog.attachShader(trapezoidVert);
	m_renderTypes[renderType].prog.attachShader(frag);

	m_renderTypes[renderType].ibo.bind(GL_ARRAY_BUFFER);
	m_renderTypes[renderType].ibo.createMutableStorage(
			static_cast<unsigned int>(quadIdx.size() * sizeof(GLubyte)),
			GL_STATIC_DRAW,	quadIdx.data());
	m_renderTypes[renderType].ibo.unbind();
#else
	gl::Shader trapezoidVert("shader/geometries/trapezoid.vert", "trapezoid_vert");
	m_renderTypes[renderType].prog.attachShader(trapezoidVert);
	m_renderTypes[renderType].prog.attachShader(frag);

	m_renderTypes[renderType].ibo.createImmutableStorage(static_cast<unsigned int>(quadIdx.size() * sizeof(GLubyte)),
			0, quadIdx.data());
#endif
	// drawCall
	m_renderTypes[renderType].drawCall = [](const GLsizei size){
		glDrawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0, size);
	};
	// preCall
	m_renderTypes[renderType].preCall = tripleBufferPreCall;
}
void ofBufferObject::unbindBase(GLenum target,GLuint index) const{
	glBindBufferBase(target,index,0);
	if(data){
		data->isBound = false;
	}
}
Beispiel #29
0
void GLSLShader::renderTF()
{
    float positionData[] = {
        -0.8f,  -0.8f,  0.0f,
        0.8f,   -0.8f,  0.0f,
        0.0f,   0.8f,   0.0f };

//    GLuint buffer;
//    glGenBuffers(1, &buffer);
//    glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, buffer);

//    GLuint id;
//    int bufferSize = 9 * sizeof(float);
//    glGenTransformFeedbacks(1, &id);
//    glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, bufferSize, NULL, GL_DYNAMIC_COPY);
//    glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, 0, buffer, 0, bufferSize);

//    const char* vars[] = { "in_Vertex_Position" };
//    glTransformFeedbackVaryings(programHandle, 1, vars, GL_INTERLEAVED_ATTRIBS );

//    std::vector<Eigen::Vector4f> vdata;
//    vdata.push_back(Eigen::Vector4f(-1, -1, 0, 1));
//    vdata.push_back(Eigen::Vector4f(1, -1, 0, 1));
//    vdata.push_back(Eigen::Vector4f(0, 1, 0, 1));
//    createVertexAttribute(0, "in_Vertex_Position", vdata);

//    link();
//    glBeginTransformFeedback( GL_TRIANGLES );

//    glBindVertexArray(vaoHandle);
//    glDrawArrays(GL_TRIANGLES, 0, 3);

//    std::vector<Eigen::Vector4f> feedbackData;

//    glEndTransformFeedback();
//    glFlush();
//  //  glGetBufferSubData( GL_TRANSFORM_FEEDBACK_BUFFER, 0, bufferSize, buffer  );

//    glInvalidateBufferData( buffer );
//    glDeleteTransformFeedbacks( 1, &id );
    //std::cout << "Feedback data:" << std::endl << std::endl << feedbackData << std::endl;


    //UPDATE
//    glEnable(GL_RASTERIZER_DISCARD);
//    glBindBuffer(GL_ARRAY_BUFFER, m_particleBuffer[m_currVB]);
//    glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, m_transformFeedback[m_currTFB]);

//    glEnableVertexAttribArray(0);
//    glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE, size ,(const GLvoid*)4); // position

//    glBeginTransformFeedback(GL_POINTS);

//    if (m_isFirst) {
//          glDrawArrays(GL_POINTS, 0, 1);
//          m_isFirst = false;
//      }
//      else {
//          glDrawTransformFeedback(GL_POINTS, m_transformFeedback[m_currVB]);
//      }
//    glEndTransformFeedback();
//    glDisableVertexAttribArray(0);

//    //RENDER

//    glDisable(GL_RASTERIZER_DISCARD);
//    glBindBuffer(GL_ARRAY_BUFFER, m_particleBuffer[m_currTFB]);
//    glEnableVertexAttribArray(0);
//    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, size, (const GLvoid*)4); // position

//    glDrawTransformFeedback(GL_POINTS, m_transformFeedback[m_currTFB]);
//    glDisableVertexAttribArray(0);

//    m_currVB = m_currTFB;
//    m_currTFB = (m_currTFB + 1) & 0x1;

//    glBindBuffer(GL_ARRAY_BUFFER, m_transformFeedback[0]);
////    glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, 0);
//    glEnableVertexAttribArray(1);
//    glDisableVertexAttribArray(0);

    static float c = 0.0;

    glDisableVertexAttribArray(1);
//    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glEnable(GL_RASTERIZER_DISCARD);
    glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, m_transformFeedback[0]);

    GLuint location = glGetUniformLocation(programHandle, "UseTF");
    glUniform1f(location,c);
    glBindVertexArray(vaoHandle);


    glBeginTransformFeedback(GL_POINTS);
    glDrawArrays(GL_POINTS, 0, 3);
    glEndTransformFeedback();


    glDisable(GL_RASTERIZER_DISCARD);

    glEnableVertexAttribArray(1);
    glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);

    location = glGetUniformLocation(programHandle, "UseTF");
    glUniform1f(location, 0.0);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    c += 0.01;

    if (c > 1.0) c = 0.0;

}
Beispiel #30
0
//*****************************************************************************
// Update
//*****************************************************************************
void ParticleSystem::Update()
{
    float fDeltaTime = 0.0f;
    int hProg = GetShaderProgram(PARTICLE_UPDATE_PROGRAM);

    m_timer.Stop();
    fDeltaTime = m_timer.Time();

    glUseProgram(hProg);
    
    // Toggle the update buffer index
    m_nUpdateBuffer = !m_nUpdateBuffer;
    
    // Bind the correct buffers
    glBindBuffer(GL_ARRAY_BUFFER, m_arVBOs[m_nUpdateBuffer]);
    glBindBuffer ( GL_TRANSFORM_FEEDBACK_BUFFER, m_arVBOs[!m_nUpdateBuffer]);
    glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, m_arVBOs[!m_nUpdateBuffer]);

    // Assign vertex attributes
    glVertexAttribPointer(0,
                          3,
                          GL_FLOAT,
                          GL_FALSE,
                          PARTICLE_DATA_SIZE,
                          0);
    glVertexAttribPointer(1,
                          3,
                          GL_FLOAT,
                          GL_FALSE,
                          PARTICLE_DATA_SIZE,
                          (void*) 12);
    glVertexAttribPointer(2,
                          4,
                          GL_FLOAT,
                          GL_FALSE,
                          PARTICLE_DATA_SIZE,
                          (void*) 24);
    glVertexAttribPointer(3,
                          1,
                          GL_FLOAT,
                          GL_FALSE,
                          PARTICLE_DATA_SIZE,
                          (void*) 40);
    glVertexAttribPointer(4,
                          1,
                          GL_FLOAT,
                          GL_FALSE,
                          PARTICLE_DATA_SIZE,
                          (void*) 44);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);
    glEnableVertexAttribArray(3);
    glEnableVertexAttribArray(4);

    // Set Uniforms
    glUniform1f(s_hMinLifetime, m_fMinLifetime);
    glUniform1f(s_hMaxLifetime, m_fMaxLifetime);
    glUniform4fv(s_hMinColor, 1, m_arMinColor);
    glUniform4fv(s_hMaxColor, 1, m_arMaxColor);
    glUniform3fv(s_hMinVelocity, 1, m_arMinVelocity);
    glUniform3fv(s_hMaxVelocity, 1, m_arMaxVelocity);
    glUniform1f(s_hMinSize, m_fMinSize);
    glUniform1f(s_hMaxSize, m_fMaxSize);
    glUniform3fv(s_hGravity, 1, m_arGravity);
    glUniform1i(s_hSeed, rand());
    glUniform1f(s_hDeltaTime, fDeltaTime);
    glUniform1i(s_hGenerate, m_nGenerate);
    glUniform3fv(s_hOrigin, 1, m_arOrigin);
    glUniform3fv(s_hSpawnVariance, 1, m_arSpawnVariance);
    
    // Since this shader is only being used for transform feedback,
    // we don't want anything to be drawn to the framebuffer.
    // To disable drawing, enable GL_RASTERIZE_DISCARD
    glEnable(GL_RASTERIZER_DISCARD);

    // Update particles with transform feedback
    glBeginTransformFeedback(GL_POINTS);
    glDrawArrays(GL_POINTS, 0, m_nParticleCount);
    glEndTransformFeedback();

    // Since the rendering relies on the particle update being finished,
    // and the gpu does its processing asynchronously, we must wait until
    // the gpu processing is done by using a sync object. glFinish should
    // work too, but might not be as effectient.
    m_pSync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);

    glDisable(GL_RASTERIZER_DISCARD);
    glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, 0);
    glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    m_timer.Start();
}