Ejemplo n.º 1
0
void BatchSpriteRenderer::render(F32 x, F32 y, F32 width, F32 height, F32 angleRads) {
	F32 top = height/2;
	F32 right = width/2;
	F32 bottom = -height/2;
	F32 left = -width/2;
	F32 verts[] = {
			left, top, 0, right, top, 0, right, bottom, 0, left, bottom, 0
	};
	F32 uvs[] = {
			0, 0, 1, 0, 1, 1, 0, 1
	};
	if (context->gConfig->useShaders) {
		ShaderProgram *shaderProgram = context->glResourceManager->getShaderProgram("quad");
		Matrix4f myMvMatrix = context->renderContext->mvMatrix;
		myMvMatrix.translate(x, y, 0);
		myMvMatrix.rotate(angleRads * (180 / PI), 0, 0, -1.0f);
		glVertexAttribPointer(shaderProgram->getVertexAttributeLoc("vPosition"), 3, GL_FLOAT, GL_FALSE, 0, verts);
		glVertexAttribPointer(shaderProgram->getVertexAttributeLoc("uvMap"), 2, GL_FLOAT, GL_FALSE, 0, uvs);
		glUniformMatrix4fv(shaderProgram->getUniformLoc("projection_matrix"), 1, GL_FALSE, (GLfloat*) context->renderContext->projMatrix.data);
		glUniformMatrix4fv(shaderProgram->getUniformLoc("modelview_matrix"), 1, GL_FALSE, (GLfloat*) myMvMatrix.data);
		glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
		glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
	} else {
		// GL1 rendering branch
		Vector4f colorFilter = context->renderContext->colorFilter;
		glColor4f(colorFilter.x,colorFilter.y,colorFilter.z,colorFilter.a);
		glPushMatrix();
		glTranslatef(x, y, 0);
		glRotatef(angleRads * (180 / PI), 0, 0, 1.0f);
		glVertexPointer(3, GL_FLOAT, 0, &verts);
		glTexCoordPointer(2, GL_FLOAT, 0, &uvs);
		glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
		glPopMatrix();
	}
}
	ShaderProgram & ShaderManager::loadShader(const char * vertexShaderFilename, const char * fragmentShaderFilename)
	{
		// Has that shader already been loaded?
		for(vector<ShaderCacheHandle>::iterator iter = shaderProgramCache.begin(); iter != shaderProgramCache.end(); iter++) {
			if (iter->vertexShaderFilename.compare(vertexShaderFilename) == 0 && iter->fragmentShaderFilename.compare(fragmentShaderFilename) == 0) {
				LOG(LOG_RESOURCE, LOG_DEBUG) << "Returning cached shaderprogram: " << iter->shaderProgram->getProgramHandle();
				return *iter->shaderProgram;
			}
		}

		bool success = true;

		// Compile and link the shader program
		ShaderProgram * shaderProgram = new ShaderProgram();
		success = success && shaderProgram->addShaderFromFileResource(ShaderProgram::TYPE_VERTEX_SHADER, FileResource(vertexShaderFilename));
		success = success && shaderProgram->addShaderFromFileResource(ShaderProgram::TYPE_FRAGMENT_SHADER, FileResource(fragmentShaderFilename));
		success = success && shaderProgram->link();

		if (!success) {
			shaderProgram->unload();
		}

		ShaderCacheHandle cacheHandle;
		cacheHandle.vertexShaderFilename = vertexShaderFilename;
		cacheHandle.fragmentShaderFilename = fragmentShaderFilename;
		cacheHandle.shaderProgram = shaderProgram;
		shaderProgramCache.push_back(cacheHandle);

		return * shaderProgram;
	}
Ejemplo n.º 3
0
void VertexLayout::enable(ShaderProgram& _program, size_t _byteOffset, void* _ptr) {

    GLuint glProgram = _program.getGlProgram();

    // Enable all attributes for this layout
    for (auto& attrib : m_attribs) {

        GLint location = _program.getAttribLocation(attrib.name);

        if (location != -1) {
            auto& loc = s_enabledAttribs[location];
            // Track currently enabled attribs by the program to which they are bound
            if (loc != glProgram) {
                glEnableVertexAttribArray(location);
                loc = glProgram;
            }

            void* data = _ptr ? _ptr : ((unsigned char*) attrib.offset) + _byteOffset;
            glVertexAttribPointer(location, attrib.size, attrib.type, attrib.normalized, m_stride, data);
        }
    }

    // Disable previously bound and now-unneeded attributes
    for (auto& locationProgramPair : s_enabledAttribs) {

        const GLint& location = locationProgramPair.first;
        GLuint& boundProgram = locationProgramPair.second;

        if (boundProgram != glProgram && boundProgram != 0) {
            glDisableVertexAttribArray(location);
            boundProgram = 0;
        }
    }
}
Ejemplo n.º 4
0
jboolean Java_android_filterfw_core_ShaderProgram_setShaderAttributeVertexFrame(
    JNIEnv* env,
    jobject thiz,
    jstring attr_name,
    jobject vertex_frame,
    jint type,
    jint component_count,
    jint stride,
    jint offset,
    jboolean normalize) {
  ShaderProgram* program = ConvertFromJava<ShaderProgram>(env, thiz);
  if (program) {
    // Get the vertex frame
    VertexFrame* v_frame = ConvertFromJava<VertexFrame>(env, vertex_frame);

    // Get the program variable to set
    const std::string attr_string = ToCppString(env, attr_name);
    ProgramVar program_var = program->GetAttribute(attr_string);

    // Set the variable
    if (v_frame && ShaderProgram::IsVarValid(program_var)) {
      const bool success = program->SetAttributeValues(program_var,
                                                       v_frame,
                                                       type,
                                                       component_count,
                                                       stride,
                                                       offset,
                                                       ToCppBool(normalize));
      return ToJBool(success);
    }
  }
  return JNI_FALSE;
}
Ejemplo n.º 5
0
ParticleSystem::ParticleSystem() :
	textureCount(0), textureSheet(NULL),
	projectionMatrix(1.0f), viewMatrix(1.0f) {
	std::vector<Vertex::Element> elements;
	elements.push_back(Vertex::Element(Vertex::Attribute::Position   , Vertex::Element::Float, 3));
	elements.push_back(Vertex::Element(Vertex::Attribute::get("a_vel"), Vertex::Element::Float, 3));
	elements.push_back(Vertex::Element(Vertex::Attribute::Color      , Vertex::Element::Float, 4));
	elements.push_back(Vertex::Element(Vertex::Attribute::get("a_size"), Vertex::Element::Float, 1));
	elements.push_back(Vertex::Element(Vertex::Attribute::get("a_texIndex"), Vertex::Element::Int, 1));
	Vertex::Format format(elements);

	Mesh* mesh= new Mesh(format, 0, Mesh::STREAM);
	mesh->setPrimitiveType(Mesh::POINTS);
	model.mesh = mesh;
	Meshes.add("particlesMesh",mesh);
	if(!Programs.exists("__particleShader")) {
		ShaderProgram* p = new ShaderProgram();
		p->makeProgramFromString(vertexShader,geometryShader,fragmentShader);
		Programs.add("__particleShader",p);
	}
	model.program = Programs.get("__particleShader");
	setName("particleSystem");
	setUpdatePriority(-100);
	setDrawPriority(100);
}
Ejemplo n.º 6
0
void openGLThread(bool _draw, GLfloat _red) {
    //WindowGL * window = WindowGL::createWindow(640, 480);

    Context context;

    DriverGPU *driver = DriverGPU::get();

    Shader vShader(eShaderType::eVertexShader, "../../src/shaders/vTriangleShader.vertex");
    Shader fShader(eShaderType::eFragmentShader, "../../src/shaders/fTriangleShader.fragment");


    ShaderProgram sProgram;
    sProgram.attachShader(vShader);
    sProgram.attachShader(fShader);
    sProgram.bindAttribute(0, "vPosition");

    sProgram.link();

    while(running) {
        //window->peekMessage();
        //window->swapBuffers();
        //if (_draw)
        //	drawOnBuffer(640, 480, sProgram, _red);
    }

    delete driver;
}
Ejemplo n.º 7
0
ShaderProgram* SpriteCache::createDefaultShader () {
    if (!Gdx::graphics->isGL20Available()) return NULL;
    std::string vertexShader = "attribute vec4 " + ShaderProgram::POSITION_ATTRIBUTE + ";\n" //
     "attribute vec4 " + ShaderProgram::COLOR_ATTRIBUTE + ";\n" //
     "attribute vec2 " + ShaderProgram::TEXCOORD_ATTRIBUTE + "0;\n" //
     "uniform mat4 u_projectionViewMatrix;\n" //
     "varying vec4 v_color;\n" //
     "varying vec2 v_texCoords;\n" //
     "\n" //
     "void main()\n" //
     "{\n" //
     "   v_color = " + ShaderProgram::COLOR_ATTRIBUTE + ";\n" //
     "   v_texCoords = " + ShaderProgram::TEXCOORD_ATTRIBUTE + "0;\n" //
     "   gl_Position =  u_projectionViewMatrix * " + ShaderProgram::POSITION_ATTRIBUTE + ";\n" //
     "}\n";
    std::string fragmentShader = "#ifdef GL_ES\n" //
     "precision mediump float;\n" //
     "#endif\n" //
     "varying vec4 v_color;\n" //
     "varying vec2 v_texCoords;\n" //
     "uniform sampler2D u_texture;\n" //
     "void main()\n"//
     "{\n" //
     "  gl_FragColor = v_color * texture2D(u_texture, v_texCoords);\n" //
     "}";

    ShaderProgram* shader = new ShaderProgram(vertexShader, fragmentShader);
    if (shader->isCompiled() == false)
        throw std::runtime_error("Error compiling shader: " + shader->getLog());
    return shader;
}
Ejemplo n.º 8
0
void move_it(ShaderProgram program, Matrix& modelMatrix, Matrix& projectionMatrix, Matrix& viewMatrix,float x, float y){
	program.setModelMatrix(modelMatrix);
	program.setProjectionMatrix(projectionMatrix);
	program.setViewMatrix(viewMatrix);
	modelMatrix.identity();
	modelMatrix.Translate(x, y, 0.0);
}
Ejemplo n.º 9
0
    void cannotValidateUnlinkProgram()
    {
        ShaderProgram shaderProgram;

        QVERIFY(!shaderProgram.validate());
        QVERIFY(!shaderProgram.getLastValidationLog().empty());
    }
void TerrainDeformationProgram::Initialize(){
	m_FrameBuffer = new FrameBuffer();
	m_FrameBuffer->Init();

	glGenTextures(1, &m_BrushTexture);
	glBindTexture(GL_TEXTURE_2D, m_BrushTexture);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_BRUSH_RES, m_BRUSH_RES, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glBindTexture(GL_TEXTURE_2D, 0);
	//fill in brush
	m_BrushGenProgram = g_ShaderBank.LoadShaderProgram("../../../shader/BrushTexGenProgram.glsl");
	ShaderProgram* prog = g_ShaderBank.GetProgramFromHandle(m_BrushGenProgram);
	prog->Apply();
	prog->SetUniformFloat("hardness", 1.0f);
	glBindImageTexture(0, m_BrushTexture, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA8);
	const int WORK_GROUP_SIZE = 32;
	GLuint WorkGroupSize = GLuint((m_BRUSH_RES + WORK_GROUP_SIZE - 1) / float(WORK_GROUP_SIZE));
	glDispatchCompute(WorkGroupSize, WorkGroupSize, 1);
	
	m_DrawProgram = g_ShaderBank.LoadShaderProgram("../../../shader/SpriteShader.glsl");
	m_BrushTex = new Texture();
	m_BrushTex->Init("../../../binasset/texture/brush.png", TEXTURE_COLOR);

	m_FilterProgram = g_ShaderBank.LoadShaderProgram("../../../shader/TerrainDeformFilter.glsl");
}
Ejemplo n.º 11
0
		void render(float delta){
			float ClearColor[4] = { 0.5f, 0.5f, 0.5f, 1.0f }; // red,green,blue,alpha
			float ClearColor2[4] = { 0.1f, 0.2f, 0.3f, 1.0f }; // red,green,blue,alpha
			clearTargetColor(m_pRenderTargetView,ClearColor);
			clearTargetColor(*backTarget->getTarget(),ClearColor2);
			clearTargetDepth(m_depthStencilView,1);
			static float t=0;
			t+=delta;
			m_World = XMMatrixRotationY(t);
			ConstantBuffer cb;
			cb.mWorld = XMMatrixTranspose( m_World );
			cb.mView = XMMatrixTranspose( m_View );
			cb.mProjection = XMMatrixTranspose( m_Projection);
			people->updateConstantbuffer(m_pImmediateContext,0,&cb);
			
			m_pImmediateContext->OMSetRenderTargets(1,backTarget->getTarget(),m_depthStencilView);
			people->draw(m_pImmediateContext);
			clearTargetDepth(m_depthStencilView,1);
			m_pImmediateContext->OMSetRenderTargets(1,&m_pRenderTargetView,m_depthStencilView);
			people->draw(m_pImmediateContext);
			
			view_shader->use(m_pImmediateContext);
			m_pImmediateContext->PSSetShaderResources(0,1,backTarget->getShaderResource());
			view_shader->setConstantBuffer(m_pImmediateContext,0,&quard->s_Matrix);
			//quard->draw(m_pImmediateContext);

			controller->visite(m_pImmediateContext);
           
			//MyLuaManager::getInstance()->doFile("lua/lua_script/render.lua");
			presentDraw();
		}
Ejemplo n.º 12
0
/*-------------------------------------
 * Set the vertex layout locations for an unlinked shader program
-------------------------------------*/
bool ShaderProgramAssembly::assign_shader_layouts(
    const ShaderProgram& prog,
    const ShaderObject& shdr
) const noexcept {

    if (prog.get_attached_shader_id(shdr.get_shader_type()) != shdr.gpu_id()) {
        return false;
    }

    // fragment shaders in OpenGLES 3.0 can't have their location manually
    // specified as glBindFragDataLocation is unavailable. Geometry shaders on
    // desktop GL versions should not have attribs as it increases the amount
    // of required maintenance for a feature with limited support.
    if (shdr.get_shader_type() != shader_stage_t::SHADER_STAGE_VERTEX) {
        return true;
    }

    // Manually assign layout locations so OpenGL doesn't optimize out
    // perfectly valid locations of variables.
    const ShaderAttribArray& attribs = shdr.get_attribs();
    
    for (unsigned i = 0; i < attribs.get_num_attribs(); ++i) {
        const ShaderAttrib& attrib = attribs.get_attrib(i);
        glBindAttribLocation(prog.gpu_id(), attrib.get_location(), attrib.get_name().get());
        LS_LOG_GL_ERR();
    }

    return true;
}
Ejemplo n.º 13
0
void Font::Flush(float deltaTime)
{
	//flush all of the vertices to the GPU for drawing
	if (!preRenderStage)
	{
		timer += deltaTime;
		if (timer > 1.f / 60.f) //60fps text updating
		{
			timer = 0;
			preRenderStage = true;

			//clear out the memory to start rendering new ones
			vertices = new vector<Vertex>();
			indices = new vector<int>();
		}
	}
	else
	{
		m->SetVertices(vertices, GL_STREAM_DRAW, true);
		m->SetIndices(indices, GL_STREAM_DRAW, true);
		m->FlushBuffers();
		preRenderStage = false;
	}

	glEnable(GL_BLEND);
	renderer->Ready();
	ShaderProgram *prog = renderer->GetProgram();
	prog->SetUniform("MVP", (void*)value_ptr(guiCam->Get()));
	renderer->Render();
	glDisable(GL_BLEND);
}
Ejemplo n.º 14
0
void VertexLayout::enable(RenderState& rs, ShaderProgram& _program, size_t _byteOffset, void* _ptr) {

    GLuint glProgram = _program.getGlProgram();

    // Enable all attributes for this layout
    for (auto& attrib : m_attribs) {

        GLint location = _program.getAttribLocation(attrib.name);

        if (location != -1) {
            auto& loc = rs.attributeBindings[location];
            // Track currently enabled attribs by the program to which they are bound
            if (loc != glProgram) {
                GL::enableVertexAttribArray(location);
                loc = glProgram;
            }

            void* data = (unsigned char*)_ptr + attrib.offset + _byteOffset;
            GL::vertexAttribPointer(location, attrib.size, attrib.type, attrib.normalized, m_stride, data);
        }
    }

    // Disable previously bound and now-unneeded attributes
    for (size_t i = 0; i < RenderState::MAX_ATTRIBUTES; ++i) {

        GLuint& boundProgram = rs.attributeBindings[i];

        if (boundProgram != glProgram && boundProgram != 0) {
            GL::disableVertexAttribArray(i);
            boundProgram = 0;
        }
    }
}
Ejemplo n.º 15
0
void Entity::update(float& lastFrameTicks, float& elapsed, Matrix& projectionMatrix, Matrix& viewMatrix, ShaderProgram& program, bool stat) {
    //    Update modelMatrix
    Matrix modelMatrix;
    static bool wall = false;
    if (stat) {
        modelMatrix.identity();
        modelMatrix.Scale(0.5, 2, 0);
        program.setModelMatrix(modelMatrix);
    }
    else {
        if (y >= -0.65) {
            if (x > -1.85 && !wall) {
                x -= elapsed/2;
            }
            if (x <= -1.85) {
                wall = true;
                y -= elapsed*2;
            }
            if (x < 1.85 && wall) {
                x += elapsed/2;
            }
            if (x >= 1.85) {
                wall = false;
                y -= elapsed*4;
            }
        }
        modelMatrix.identity();
        modelMatrix.Scale(0.5, 2, 0);
        modelMatrix.Translate(x, y+0.4, 0);
        program.setModelMatrix(modelMatrix);
    }
}
Ejemplo n.º 16
0
    void cannotLinkProgramWithoutShader()
    {
        ShaderProgram shaderProgram;

        QVERIFY(!shaderProgram.link());
        QCOMPARE(shaderProgram.getLastLinkLog().c_str(), "Cannot link program because no shader is attached!");
    }
Ejemplo n.º 17
0
	void nativeRender(int camtex, float *mat) {
		if (!running) return;
		ShaderEngine::Engine->reset();
		ShaderBuffer *oldfbo = ShaderEngine::Engine->setFramebuffer(rdrTgt);
		ShaderEngine::Engine->setViewport(0, 0, tex->width, tex->height);
		Matrix4 projection = ShaderEngine::Engine->setOrthoFrustum(0,
				tex->baseWidth, 0, tex->baseHeight, -1, 1);
		ShaderEngine::Engine->setProjection(projection);
		Matrix4 model;
		ShaderEngine::Engine->setModel(model);

		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_EXTERNAL_OES, camtex);

		shader->setConstant(shader->getConstantByName("tMatrix"),
				ShaderProgram::CMATRIX, 1, mat);
		shader->setData(ShaderProgram::DataVertex, ShaderProgram::DFLOAT, 2,
				&vertices[0], vertices.size(), vertices.modified,
				&vertices.bufferCache);
		shader->setData(ShaderProgram::DataTexture, ShaderProgram::DFLOAT, 2,
				&texcoords[0], texcoords.size(), texcoords.modified,
				&texcoords.bufferCache);
		shader->drawElements(ShaderProgram::TriangleStrip, indices.size(),
				ShaderProgram::DUSHORT, &indices[0], indices.modified,
				&indices.bufferCache);
		vertices.modified = false;
		texcoords.modified = false;
		indices.modified = false;

		ShaderEngine::Engine->setFramebuffer(oldfbo);
	}
Ejemplo n.º 18
0
int main(void){
	WindowGL window("render2texture", 640, 480);
	
	DriverGPU * driver = DriverGPU::get();

	Texture tulipsTex("./Tulips.jpg");

	Shader vShader(eShaderType::eVertexShader, "../../src/shaders/flat.vertex");
	Shader sobelShader(eShaderType::eFragmentShader, "../../src/shaders/sobel.fragment");

	ShaderProgram program;

	program.attachShader(vShader);
	
	program.attachShader(sobelShader);
	program.link();

	#if defined(_WIN32)
	window.peekMessage();
	double t0 = STime::get()->getTime();
	drawImage(tulipsTex, program);
	double t1 = STime::get()->getTime();
	#endif

	std::cout << "Edge detection spent " << t1 - t0 << std::endl;

	window.swapBuffers();

	//	delete window; 	Class has no destructor, undefined behaviour
	delete driver;
	system("PAUSE");
	return 0;
}
Ejemplo n.º 19
0
void ShadowMap::Render( RenderQueue* rq ) {
	ShaderProgram* prog = g_ShaderBank.GetProgramFromHandle( m_Shader );

	prog->Apply();
	glBindFramebuffer( GL_FRAMEBUFFER, m_FrameBuffer );

	glEnable( GL_DEPTH_TEST );
	glEnable(  GL_CULL_FACE );
	glCullFace( GL_BACK);
	const GLfloat one = 1.0f;
	glClearBufferfv( GL_DEPTH, 0, &one );
	glViewport( 0, 0, m_Size, m_Size );
	glEnable(GL_POLYGON_OFFSET_FILL);
	glPolygonOffset( 1.0f, 4.0f );

	//glm::mat4 viewProj = m_Proj * m_View;
	//prog->SetUniformMat4( "g_ViewProj", viewProj );
	//unsigned int bufferOffset  = 0;
	//unsigned int instanceCount = 0;
	//g_ModelBank.ApplyBuffers();
	//// for each model to be rendered
	//for ( auto& mo : rq->GetModelQueue() ) {
	//	const Model& model = g_ModelBank.FetchModel( mo.Model );
	//	instanceCount = mo.InstanceCount;
	//	prog->SetUniformUInt( "g_BufferOffset", bufferOffset );
	//	// for each mesh
	//	for ( auto& mesh : model.Meshes ) {
	//		glDrawElementsInstanced( GL_TRIANGLES, mesh.Indices, GL_UNSIGNED_INT,
	//			( GLvoid* )( 0 + ( ( model.IndexHandle + mesh.IndexBufferOffset ) * sizeof( unsigned int ) ) ), instanceCount );
	//	}
	//	bufferOffset += instanceCount;
	//}
	//glDisable(GL_POLYGON_OFFSET_FILL);
}
	void onDraw(Graphics& g){
		g.pointSize(renderMode+0.5);
		g.color(RGB(1));
		mesh.colors().reset();
		switch (renderMode) {
			case 0:
				// do it on the CPU:
				for (int k=0; k<N; k++) {
				for (int j=0; j<N; j++) {
				for (int i=0; i<N; i++) {
					Color color;
					data.read_interp(color.components, i,j,k);
					mesh.color(color);
				}}}
				g.draw(mesh);
				break;
			case 1:
				// use 3D texcoords:
				tex.bind();
				g.draw(mesh);
				tex.unbind();
				break;
			case 2:
				// use shader:
				shader.begin();
				tex.bind();
				g.draw(mesh);
				tex.unbind();
				shader.end();
				break;
			default:;
		}
	}
Ejemplo n.º 21
0
jboolean Java_android_filterfw_core_ShaderProgram_setShaderAttributeValues(
    JNIEnv* env,
    jobject thiz,
    jstring attr_name,
    jfloatArray values,
    jint component_count) {
  ShaderProgram* program = ConvertFromJava<ShaderProgram>(env, thiz);
  if (program) {
    // Get the floats to set
    jfloat* float_ptr = env->GetFloatArrayElements(values, NULL);
    const int length = env->GetArrayLength(values);

    // Get the program variable to set
    const std::string attr_string = ToCppString(env, attr_name);
    ProgramVar program_var = program->GetAttribute(attr_string);

    // Set the variable
    if (float_ptr && ShaderProgram::IsVarValid(program_var)) {
      const bool success = program->SetAttributeValues(program_var,
                                                       reinterpret_cast<float*>(float_ptr),
                                                       length,
                                                       component_count);
      env->ReleaseFloatArrayElements(values, float_ptr, JNI_ABORT);
      return ToJBool(success);
    }
  }
  return JNI_FALSE;
}
void VertexBufferObjectSubData::bind (ShaderProgram& shader) {
    GL20& gl = *gl20;

    gl.glBindBuffer(gdx::GL::ARRAY_BUFFER, bufferHandle);
    if (isDirty) {
        byteBuffer.limit(buffer.limit() * 4);
        gl.glBufferSubData(gdx::GL::ARRAY_BUFFER, 0, byteBuffer.limit(), byteBuffer);
// gl.glBufferData(gdx::GL::ARRAY_BUFFER, byteBuffer.limit(),
// byteBuffer, usage);
        isDirty = false;
    }

    int numAttributes = attributes.size();
    for (int i = 0; i < numAttributes; i++) {
        VertexAttribute& attribute = attributes.get(i);
        shader.enableVertexAttribute(attribute.alias);
        int colorType = gdx::GL::FLOAT;
        bool normalize = false;
        if (attribute.usage == VertexAttributes::Usage::ColorPacked) {
            colorType = gdx::GL::UNSIGNED_BYTE;
            normalize = true;
        }
        shader.setVertexAttribute(attribute.alias, attribute.numComponents, colorType, normalize, attributes.vertexSize,
                                  attribute.offset);
    }
    isBound = true;
}
Ejemplo n.º 23
0
jobject Java_android_filterfw_core_ShaderProgram_getUniformValue(JNIEnv* env,
                                                                 jobject thiz,
                                                                 jstring key) {
  ShaderProgram* program = ConvertFromJava<ShaderProgram>(env, thiz);
  const std::string c_key = ToCppString(env, key);
  return program ? ToJObject(env, program->GetUniformValue(c_key)) : JNI_NULL;
}
Ejemplo n.º 24
0
gfx::ShaderProgramHandle gfx::ShaderBank::LoadShaderProgramWithDefines ( const std::string& filename, ShaderDefineContainer& defines ) {
	ShaderProgram* program = new ShaderProgram ();
#ifdef SHADER_BINARY_PROGRAM

	ShaderProgramBinary header;
	if(program->LoadProgramBinaryHeader(filename, header)) {
		if(strcmp(header.Version, (char*)glGetString(GL_VERSION)) == 0) {
			program->LoadProgramBinary(filename);
			ShaderProgramHandle handle = m_Counter++;
			m_Programs.push_back(program);
			m_HandleToPrograms.emplace( handle, program );
			return handle;
		}
	}
	if(program->LoadCompleteShaderProgramFromFile(filename, true, defines)) {
		program->SaveProgramBinary();
	}
#else
	//program->LoadCompleteShaderProgramFromFile(filename, true, defines);
#endif
	ShaderProgramHandle handle = m_Counter++;
	m_Programs.push_back(program);
	m_HandleToPrograms.emplace( handle, program );
	return handle;
}
Ejemplo n.º 25
0
int main(void){
	WindowGL window("Texture loader", 640, 480);
	
	DriverGPU * driver = DriverGPU::get();

	Shader vShader(eShaderType::eVertexShader, "../../src/shaders/flat.vertex");
	Shader fShader(eShaderType::eFragmentShader, "../../src/shaders/flat.fragment");

	ShaderProgram program;

	program.attachShader(vShader);
	program.attachShader(fShader);
	program.link();

	bool condition = true;
	do{	
		#if defined(_WIN32)
		window.peekMessage();
		drawImage(program);
		#endif
		window.swapBuffers();
		
	} while (condition);


	window.hide();

	#ifdef _WIN32
	system("PAUSE");
	#endif
	//	delete window; 	Class has no destructor, undefined behaviour
	delete driver;

	return 0;
}
Ejemplo n.º 26
0
void VideoLayerAndroid::showPreparingAnimation(const SkRect& rect,
                                               const SkRect innerRect)
{
    ShaderProgram* shader = TilesManager::instance()->shader();
    VideoLayerManager* manager = TilesManager::instance()->videoLayerManager();
    // Paint the video content's background.
    PureColorQuadData backGroundQuadData(Color(128, 128, 128, 255), LayerQuad,
                                         &m_drawTransform, &rect);
    shader->drawQuad(&backGroundQuadData);

    TransformationMatrix addReverseRotation;
    TransformationMatrix addRotation = m_drawTransform;
    addRotation.translate(innerRect.fLeft, innerRect.fTop);
    double halfButtonSize = manager->getButtonSize() / 2;
    addRotation.translate(halfButtonSize, halfButtonSize);
    addReverseRotation = addRotation;
    addRotation.rotate(m_rotateDegree);
    addRotation.translate(-halfButtonSize, -halfButtonSize);

    SkRect size = SkRect::MakeWH(innerRect.width(), innerRect.height());

    TextureQuadData spinnerQuadData(manager->getSpinnerOuterTextureId(),
                                    GL_TEXTURE_2D, GL_LINEAR,
                                    LayerQuad, &addRotation, &size);
    shader->drawQuad(&spinnerQuadData);

    addReverseRotation.rotate(-m_rotateDegree);
    addReverseRotation.translate(-halfButtonSize, -halfButtonSize);

    spinnerQuadData.updateTextureId(manager->getSpinnerInnerTextureId());
    spinnerQuadData.updateDrawMatrix(&addReverseRotation);
    shader->drawQuad(&spinnerQuadData);

    m_rotateDegree += ROTATESTEP;
}
Ejemplo n.º 27
0
//----------------------------------------------------------------------------
void SSDOTriMesh::OnGetShaderConstants()
{
	TriangleMesh::OnGetShaderConstants();

	ShaderProgram* program = mMaterial->GetProgram(0, 0);
    program->GetUniformLocation(&mMaterialColorLoc, "materialColor");
}
static ShaderProgram* createProgram( ShaderProgramIndex index )
{
	ShaderProgram* program = nullptr;
	Ptr<Data> vertex_data;
	Ptr<Data> pixel_data;

	switch( index )
	{
	case kShaderProgram_Color:
		{
			program = new ShaderProgram();
			vertex_data = Assets::loadFile( "standard/shaders/test_vertex.glsl" );
			pixel_data = Assets::loadFile( "standard/shaders/test_fragment.glsl" );
		}
		break;
	default:
		break;
	}

	if( vertex_data == nullptr || fragment_data == nullptr )
		return nullptr;

	program->setVertexSource( vertex_data->ptr() );
	program->setFragmentSource( fragment_data->ptr() );
	
	if( !program->build() )
		return nullptr;

	if( !program-> )


	return program;
}
Ejemplo n.º 29
0
double GLWebViewState::setupDrawing(const IntRect& invScreenRect,
                                    const SkRect& visibleContentRect,
                                    const IntRect& screenRect, int titleBarHeight,
                                    const IntRect& screenClip, float scale)
{
    TilesManager* tilesManager = TilesManager::instance();

    // Make sure GL resources are created on the UI thread.
    // They are created either for the first time, or after EGL context
    // recreation caused by onTrimMemory in the framework.
    ShaderProgram* shader = tilesManager->shader();
    if (shader->needsInit()) {
        ALOGD("Reinit shader");
        shader->initGLResources();
    }
    TransferQueue* transferQueue = tilesManager->transferQueue();
    if (transferQueue->needsInit()) {
        ALOGD("Reinit transferQueue");
        transferQueue->initGLResources(TilesManager::tileWidth(),
                                       TilesManager::tileHeight());
    }
    shader->setupDrawing(invScreenRect, visibleContentRect, screenRect,
                         titleBarHeight, screenClip, scale);

    double currentTime = WTF::currentTime();

    setVisibleContentRect(visibleContentRect, scale);

    return currentTime;
}
Ejemplo n.º 30
0
void SimpleRender::Render(ICamera* camera, const Vector4f& lightPosition) {

    ShaderProgram* shader = isAo ? m_aoShader : m_simpleShader;

    // bind shader of the batch.
    shader->Bind();

    m_vertexBuffer->EnableVertexAttribInterleavedWithBind();

    shader->SetUniform("textureArray", 0);
    Texture::SetActiveTextureUnit(0);
    m_arrayTexture->Bind();

    shader->SetUniform("aoOnly", 1.0f);

    Matrix4f modelMatrix = Matrix4f::CreateIdentity(); //geoObj->GetModelMatrix();

    shader->SetPhongUniforms(
	modelMatrix
	, camera, lightPosition);

    for(size_t i = 0; i < m_chunks.size(); ++i) {

	Chunk* chunk = m_chunks[i];

	chunk->m_indexBuffer->Bind();
	chunk->m_indexBuffer->DrawIndices(GL_TRIANGLES, (chunk->m_numTriangles)*3);
	chunk->m_indexBuffer->Unbind();
    }

    m_vertexBuffer->DisableVertexAttribInterleavedWithBind();

    m_arrayTexture->Unbind();

}