//void Renderer::draw(const VertexArray& va, const ElementBuffer& eb, const ShaderProgram& shader) const
void Renderer::draw(const VertexArray& va, const ElementBuffer& eb, const ShaderProgram& shader)
{
    va.bind();
    eb.bind();  
    shader.bind();
    GLCall(glDrawElements(GL_TRIANGLES, eb.count(), GL_UNSIGNED_INT, nullptr));
    //
    // UNBIND [optional]... discuss
}
Esempio n. 2
0
/*!
Set a shader program to be used in the current rendering pipeline
@param	shader	Reference to the shader program to set as active
@return	Wether the specified shader was set as active or not.
*/
bool sgct::ShaderManager::bindShaderProgram( const ShaderProgram & shaderProgram ) const
{
	if( shaderProgram == NullShader )
	{
		sgct::MessageHandler::instance()->print(sgct::MessageHandler::NOTIFY_WARNING, "Could not set shader program [Invalid Pointer] as active: Not found in manager.\n");
		glUseProgram( GL_FALSE ); //unbind to prevent errors
		return false;
	}

	return shaderProgram.bind();
}
void BatchSpriteRenderer::startBatch() {
	checkGLError("BatchSpriteRenderer Start");
	glBindTexture(GL_TEXTURE_2D, textureId);
	glFrontFace(GL_CW);
	if (context->gConfig->useShaders) {
		ShaderProgram *shaderProgram = context->glResourceManager->getShaderProgram("quad");
		shaderProgram->bind();
		glUniform1i(shaderProgram->getUniformLoc("tex"), 0);
		Vector4f colorFilter = context->renderContext->colorFilter;
		glUniform4f(shaderProgram->getUniformLoc("colorFilter"), colorFilter.x,colorFilter.y,colorFilter.z,colorFilter.a);
	}
}
Esempio n. 4
0
/*!
Set a shader program to be used in the current rendering pipeline
@param	name	Name of the shader program to set as active
@return	Wether the specified shader was set as active or not.
*/
bool sgct::ShaderManager::bindShaderProgram( const std::string & name ) const
{
	ShaderProgram sp = getShaderProgram( name );

	if( sp == NullShader )
	{
		sgct::MessageHandler::instance()->print(sgct::MessageHandler::NOTIFY_WARNING, "Could not set shader program [%s] as active: Not found in manager.\n", name.c_str() );
		glUseProgram( GL_FALSE ); //unbind to prevent errors
		return false;
	}

	return sp.bind();
}
Esempio n. 5
0
	void MeshRenderer::draw_integer(unsigned int name)
	{
		if (!data_ || !data_->vertices || !data_->triangles)
			return;

		//set up vertex array object
		if (update_)
		{
			update();
			update_ = false;
		}

		ShaderProgram* shader = 0;

		glBindVertexArray(m_vao);
		GLMgroup* group = data_->groups;
		GLint pos = 0;

		//set up shader
		shader = msh_shader_factory_.shader(1,
			0, false, false, false);
		if (shader)
		{
			if (!shader->valid())
				shader->create();
			shader->bind();
		}
		//uniforms
		shader->setLocalParamMatrix(0, glm::value_ptr(m_proj_mat));
		shader->setLocalParamMatrix(1, glm::value_ptr(m_mv_mat));
		shader->setLocalParamUInt(0, name);

		while (group)
		{
			if (group->numtriangles == 0)
			{
				group = group->next;
				continue;
			}

			//draw
			glDrawArrays(GL_TRIANGLES, pos, (GLsizei)(group->numtriangles*3));
			pos += group->numtriangles*3;
			group = group->next;
		}
		glBindVertexArray(0);

		// Release shader.
		if (shader && shader->valid())
			shader->release();
	}
Esempio n. 6
0
        void initGL(){
             glClearColor(1,1,1,1);
             srand( time(NULL) );



			string Vert = AVertex + Varying + UMatrix  + NTransform + VLighting + VCalc + MVert;
			string Frag = USampler + Varying + MFrag;

	        program.source(Vert,Frag);
			program.bind();
	             Pipe::BindAttributes();
	        program.unbind();
 
       }
Esempio n. 7
0
        void initGL(){
             glClearColor(1,1,1,1);
             srand( time(NULL) );

			string Vert = AVertex + Varying + UMatrix  + NTransform + VLighting + VCalc + MVert;
			string Frag = MFrag;

	        program.source(Vert,Frag);
			program.bind();
	             pipe.bindAttributes();
	        program.unbind();  
	
			pipe.program = &program;
			
			initBufferObjects();
 
       }              
Esempio n. 8
0
        virtual void onDraw(){
	
			using namespace vsr;
			
			static Circle c = CXY(1).trs(0,0,-3);
			static Point p = PT(0,0,0);
			static Field<Pnt> f(30,30,1,.1);
			//static Field<Sca> f(30,30,1);
			static DualSphere dls = Ro::dls(p, .3);
			
			Par par = Gen::bst( Ro::par( dls, Vec::y) * .1);
        				

			static double time = 0.0; time += .01;
			
			Circle tc = c.sp( Gen::mot( DLN(1,0,0).trs(0,0,-3) * time ) );		
			Vector tv = Vec(1,0,0).sp( Gen::rot( Biv::xy * time ) );
			
			for (int i = 0; i < f.num(); ++i){
				double dist = 1.0 / ( Ro::sqd( f[i], PAO ) +.01 );
				f[i] =  Ro::loc( f[i] .sp( Gen::bst( par * dist) ) );//.sp(bst) );
			}
			
			//Dipole changes size and moves around screen
			dls = Ro::dls(p, .3 + sin(time) ).trs(1,0,0).sp( Gen::mot( DLN(0,0,1) * time ) );
			
		    program.bind();
		
		         program.uniform("projection",  scene.xf.proj);
		         program.uniform("lightPosition", 2.0, 2.0, 2.0);

		         program.uniform("normalMatrix", scene.xf.normal);
				 program.uniform("modelView", scene.xf.modelView );//app.scene().xf.modelView);        
				
				Render( f, scene.xf.modelViewMatrixf(), program );
				
				
				
				//Pipe::Line(circle);


		    program.unbind();

        }
void
PhysicsRendererer::initShader()
{
    //--------------------------------------------------------------------------
    // setup the shader
    //--------------------------------------------------------------------------
    const GLchar * vertexShaderSrc =
    "attribute vec3 positionAttr;"
    ""
    "uniform mat4 projectionTransform;"
    "uniform mat4 viewTransform;"
    "uniform mat4 modelTransform;"
    ""    
    "void main() {"
    "   gl_Position = projectionTransform * viewTransform * modelTransform * vec4(positionAttr.xyz, 1.0);"
    "}";
    
    const GLchar * fragShaderSrc =
    ""
    "uniform " HIGHP " vec3 color;"
    ""
    "void main() {"
    "   gl_FragColor = vec4(color,1.0);"
    "}";
    
    _shader.setVertexShaderSrc(vertexShaderSrc);
    _shader.setFragmentShaderSrc(fragShaderSrc);
    _shader.declareAttrib("positionAttr", _positionAttrib);
    _shader.initGL();
    
    //--------------------------------------------------------------------------
    // setup the shader matrices
    //--------------------------------------------------------------------------
    _proj.makeOrtho(0, 1,   0, 1,   1, 10);
    _view.makeLookAt(0, 0, 4,    0, 0, 0,    0, 1, 0);
    _model.makeIdentity();
    
    _shader.bind();
    _shader.setUniformMat4fv("projectionTransform", _proj.get());
    _shader.setUniformMat4fv("viewTransform",       _view.get());
    _shader.setUniformMat4fv("modelTransform",      _model.get());
    _shader.unbind();
    
}
Esempio n. 10
0
void SkyBox::onRender()
{
	glPushMatrix();
	
	GLfloat modelviewMatrix[16];
	glGetFloatv(GL_MODELVIEW_MATRIX, modelviewMatrix);
	// Remove translation from modelview matrix.
	for (int i = 12; i <= 14; i++)
		modelviewMatrix[i] = 0.0f;

	glLoadMatrixf(modelviewMatrix);	
	glScalef(500.0f, 500.0f, 500.0f);
	glTranslatef(0.0f, 0.2f, 0.0f);

	glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
	glEnableVertexAttribArray(0);

	glBindBuffer(GL_ARRAY_BUFFER, m_texCoordBuffer);
	glVertexAttribPointer(2, 2, GL_SHORT, GL_FALSE, 0, BUFFER_OFFSET(0));
	glEnableVertexAttribArray(2);
	
	ShaderProgram *program = m_engine->m_skyboxProgram;
	program->bind();

	program->sendMatrices();
	program->sendUniform("texture0", 0);	
	program->sendMaterialProps(m_materialProps);
	
	for (int i = 0; i < 5; i++)
	{
		glBindTexture(GL_TEXTURE_2D, m_textures[i]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	
		glDrawArrays(GL_QUADS, (i) * 4, 4);
	}

	glDisableVertexAttribArray(2);
	glDisableVertexAttribArray(0);

	glPopMatrix();
}
Esempio n. 11
0
static void run(int argc, char *argv[])
{
	Logger::init(&cerr);

	GLFWwindow *window;
	srand(time(nullptr));

	if (!glfwInit())
		throw runtime_error("Couldn't initialize GLFW.");

	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "KUIPER RACE", nullptr, nullptr);

	if (!window) {
		glfwTerminate();
		throw runtime_error("Couldn't create GLFWwindow.");
	}

	InputHandler &input = InputHandler::getInstance();

	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
	glfwSetKeyCallback(window, InputHandler::keyCallback);
	glfwSetCursorPosCallback(window, InputHandler::mousePositionCallback);
	glfwSetMouseButtonCallback(window, InputHandler::mouseButtonCallback);

	glfwMakeContextCurrent(window);

	glewExperimental = GL_TRUE;
	if (glewInit() != GLEW_OK) {
		glfwDestroyWindow(window);
		glfwTerminate();
		throw runtime_error("Couldn't initialize GLEW.");
	}

	glfwSwapInterval(1);

	glClearColor(0, 0, 0, 1);
	glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);

	int width, height;

	glfwGetFramebufferSize(window, &width, &height);

	TransformPipeline tp;
	tp.perspectiveProjection(70, width, WINDOW_HEIGHT, 0.1f, 100000);

	TransformPipeline tpHud;
	tpHud.orthographicProjection(-width / 2, width / 2, -height / 2, height / 2, -10, 10);

	initialize();

	Texture gbufferDiffuse(width, height, Texture::RGBA8, Texture::RGB, Texture::UnsignedByte);
	Texture gbufferDepth(width, height, Texture::DepthComponent32f, Texture::Depth, Texture::Float);

	Framebuffer framebuffer;
	framebuffer.bind(Framebuffer::DrawFramebuffer);
	framebuffer.attachTexture(gbufferDiffuse, Framebuffer::Color0);
	framebuffer.attachTexture(gbufferDepth, Framebuffer::Depth);
	framebuffer.drawBuffers({Framebuffer::Color0});
	framebuffer.unbind(Framebuffer::DrawFramebuffer);

	ShaderProgram postprocessShader("shaders/postprocess.vert", "shaders/postprocess.frag");
	postprocessShader.bindAttribLocation("in_Position", 0);
	postprocessShader.bindFragDataLocation("out_Color", 0);
	postprocessShader.link();
	postprocessShader.bind();
	postprocessShader["u_Texture"].set1i(1);
	postprocessShader["u_Depth"].set1i(2);
	postprocessShader["u_Width"].set1f(width);
	postprocessShader["u_Height"].set1f(height);
	postprocessShader.unbind();

	Sampler samplerScreenquad(Sampler::MinLinear, Sampler::MagLinear, Sampler::ClampToEdge);

	ShaderProgram *screenShader = Registry::shaders["screen"];

	bool running = true;
	bool titleScreen = true;
	float currentTime = glfwGetTime();

	level.init();

	while (running) {
		float dt = glfwGetTime() - currentTime;
		currentTime = glfwGetTime();

		input.poll();

		if (glfwWindowShouldClose(window) || input.keyWasPressed(InputHandler::Quit))
			running = false;

		update(dt);

		float speed = level.getShipSpeed();
		tp.perspectiveProjection(58 + speed * 0.9, width, height, 0.1f, 100000);

		if (speed > 0.1) {
			titleScreen = false;
		}

		framebuffer.bind(Framebuffer::DrawFramebuffer);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		draw(tp);
		framebuffer.unbind(Framebuffer::DrawFramebuffer);

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glDisable(GL_CULL_FACE);

		postprocessShader.bind();
		postprocessShader["u_ViewMatrix"].setMatrix4(tp.getViewMatrix());
		postprocessShader["u_ProjectionMatrix"].setMatrix4(tp.getProjectionMatrix());
		samplerScreenquad.bind(1);
		gbufferDiffuse.bind(1);
		samplerScreenquad.bind(2);
		gbufferDepth.bind(2);
		Registry::screenQuad->bind();
		Registry::screenQuad->drawElements();
		Registry::screenQuad->unbind();
		postprocessShader.unbind();

		glClear(GL_DEPTH_BUFFER_BIT);
		level.drawHUD(width, height);
		glEnable(GL_CULL_FACE);

		glDisable(GL_DEPTH_TEST);
		glEnable(GL_BLEND);
		glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
		screenShader->bind();
		samplerScreenquad.bind(1);
		Registry::screenQuad->bind();

		if (titleScreen) {
			Registry::textures["screen-title"]->bind(1);
			Registry::screenQuad->drawElements();

			Registry::textures["screen-level"]->bind(1);
			Registry::screenQuad->drawElements();

			Registry::textures["screen-controls"]->bind(1);
			Registry::screenQuad->drawElements();
		} else if (level.isDead()) {
			if (level.hasCrashed()) {
				Registry::textures["screen-crashed"]->bind(1);
				Registry::screenQuad->drawElements();
			} else {
				Registry::textures["screen-timeout"]->bind(1);
				Registry::screenQuad->drawElements();
			}

			Registry::textures["screen-level"]->bind(1);
			Registry::screenQuad->drawElements();
		} else if (level.isWin()) {
			Registry::textures["screen-won"]->bind(1);
			Registry::screenQuad->drawElements();

			Registry::textures["screen-level"]->bind(1);
			Registry::screenQuad->drawElements();
		}

		Registry::screenQuad->unbind();
		screenShader->unbind();
		glDisable(GL_BLEND);
		glEnable(GL_DEPTH_TEST);

		glfwSwapBuffers(window);
	}

	Audio::cleanup();
	glfwDestroyWindow(window);
	glfwTerminate();
}
Esempio n. 12
0
	void MeshRenderer::draw_wireframe()
	{
		if (!data_ || !data_->vertices || !data_->triangles)
			return;

		//set up vertex array object
		if (update_)
		{
			update();
			update_ = false;
		}

		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

		ShaderProgram* shader = 0;

		glBindVertexArray(m_vao);
		GLMgroup* group = data_->groups;
		GLint pos = 0;
		int peel = 0;
		bool tex = false;
		bool light = false;
		
		//set up shader
		shader = msh_shader_factory_.shader(0,
			peel, tex, fog_, light);
		if (shader)
		{
			if (!shader->valid())
				shader->create();
			shader->bind();
		}
		//uniforms
		shader->setLocalParamMatrix(0, glm::value_ptr(m_proj_mat));
		shader->setLocalParamMatrix(1, glm::value_ptr(m_mv_mat));
		GLMmaterial* material = &data_->materials[0];
		if (material)
			shader->setLocalParam(0, material->diffuse[0], material->diffuse[1], material->diffuse[2], material->diffuse[3]);
		else
			shader->setLocalParam(0, 1.0, 0.0, 0.0, 1.0);
		shader->setLocalParam(3, 0.0, 1.0, 0.0, 0.0);//alpha
		if (fog_)
			shader->setLocalParam(8, m_fog_intensity, m_fog_start, m_fog_end, 0.0);


		while (group)
		{
			if (group->numtriangles == 0)
			{
				group = group->next;
				continue;
			}

			//draw
			glDrawArrays(GL_TRIANGLES, pos, (GLsizei)(group->numtriangles*3));
			pos += group->numtriangles*3;
			group = group->next;
		}
		glBindVertexArray(0);

		// Release shader.
		if (shader && shader->valid())
			shader->release();
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	}
Esempio n. 13
0
	void MeshRenderer::draw()
	{
		if (!data_ || !data_->vertices || !data_->triangles)
			return;

		//set up vertex array object
		if (update_)
		{
			update();
			update_ = false;
		}

		GLint vp[4];
		glGetIntegerv(GL_VIEWPORT, vp);

		ShaderProgram* shader = 0;

		glBindVertexArray(m_vao);
		GLMgroup* group = data_->groups;
		GLint pos = 0;
		bool tex = data_->hastexture==GL_TRUE;
		while (group)
		{
			if (group->numtriangles == 0)
			{
				group = group->next;
				continue;
			}

			//set up shader
			shader = msh_shader_factory_.shader(0,
				depth_peel_, tex, fog_, light_);
			if (shader)
			{
				if (!shader->valid())
					shader->create();
				shader->bind();
			}
			//uniforms
			shader->setLocalParamMatrix(0, glm::value_ptr(m_proj_mat));
			shader->setLocalParamMatrix(1, glm::value_ptr(m_mv_mat));
			if (light_)
			{
				glm::mat4 normal_mat = glm::mat4(glm::inverseTranspose(glm::mat3(m_mv_mat)));
				shader->setLocalParamMatrix(2, glm::value_ptr(normal_mat));
				GLMmaterial* material = &data_->materials[group->material];
				if (material)
				{
					shader->setLocalParam(0, material->ambient[0], material->ambient[1], material->ambient[2], material->ambient[3]);
					shader->setLocalParam(1, material->diffuse[0], material->diffuse[1], material->diffuse[2], material->diffuse[3]);
					shader->setLocalParam(2, material->specular[0], material->specular[1], material->specular[2], material->specular[3]);
					shader->setLocalParam(3, material->shininess, alpha_, 0.0, 0.0);
				}
			}
			else
			{//color
				GLMmaterial* material = &data_->materials[group->material];
				if (material)
					shader->setLocalParam(0, material->diffuse[0], material->diffuse[1], material->diffuse[2], material->diffuse[3]);
				else
					shader->setLocalParam(0, 1.0, 0.0, 0.0, 1.0);//color
				shader->setLocalParam(3, 0.0, alpha_, 0.0, 0.0);//alpha
			}
			if (tex)
			{
				GLMmaterial* material = &data_->materials[group->material];
				if (material)
				{
					glActiveTexture(GL_TEXTURE0);
					glBindTexture(GL_TEXTURE_2D,
						material->textureID);
				}
			}
			if (fog_)
				shader->setLocalParam(8, m_fog_intensity, m_fog_start, m_fog_end, 0.0);

			if (depth_peel_)
				shader->setLocalParam(7, 1.0/double(vp[2]), 1.0/double(vp[3]), 0.0, 0.0);

			//draw
			glDrawArrays(GL_TRIANGLES, pos, (GLsizei)(group->numtriangles*3));
			pos += group->numtriangles*3;
			group = group->next;
		}
		glBindVertexArray(0);

		// Release shader.
		if (shader && shader->valid())
			shader->release();
		//release texture
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, 0);
	}
Esempio n. 14
0
void RenderDevice::render( const RenderState& state, const LightQueue& lights )
{
    BufferManager* buffers = activeContext->bufferManager;
    ProgramManager* programs = activeContext->programManager;
    
    RenderBatch* renderable = state.renderable;
    bindBuffers(renderable);

    const GeometryBuffer* gb = renderable->getGeometryBuffer().get();
    if( gb->data.Empty() ) return;

    BufferEntry* bufs = buffers->getBuffer(gb);

    // Setup the vertex buffer format.
    VertexBuffer* vb = bufs->vb.get();
    renderBackend->setupVertexBuffer(vb);
    
    Material* material = state.material;
    ShaderMaterial* shader = material->getShader().Resolve();

    ShaderProgram* shaderProgram = programs->getProgram(shader);
    if( !shaderProgram ) return;

    if( !shaderProgram->isLinked() && !shaderProgram->link() )
        return;

    shaderProgram->bind();

    renderBackend->setupRenderState(state, true);
    bindTextureUnits(state, true);

    if( !renderable->onPreRender.empty() )
    {
        // Call the user pre render hook.
        renderable->onPreRender(activeView, state);
    }

    RenderLayer stage = renderable->getRenderLayer();

    if( stage != RenderLayer::Overlays )
    {
        if( !setupRenderStateMatrix(state) )
            return;

        //if( !setupRenderStateLight(state, lights) )
        //  return;
    }
    else if( stage == RenderLayer::Overlays )
    {
        if( !setupRenderStateOverlay(state) )
            return;
    }

    UniformBuffer* ub = renderable->getUniformBuffer().get();
    shaderProgram->setUniforms(ub);

    renderBackend->renderBatch(renderable);
    
    if( !renderable->onPostRender.empty() )
    {
        // Call the user post render hook.
        renderable->onPostRender(activeView, state);
    }
    
    renderBackend->unsetupRenderState(state);
    unbindTextureUnits(state.material);
    
    shaderProgram->unbind();

    renderBackend->unbindVertexBuffer(vb);
    unbindBuffers(renderable);
}
Esempio n. 15
0
DRReturn PlanetSektor::render(float fTime, Camera* cam)
{
#if SDL_VERSION_ATLEAST(1,3,0)
	Uint8 *keystate = SDL_GetKeyboardState(NULL);
#else
	Uint8 *keystate = SDL_GetKeyState(NULL);
#endif
    
    //if(isObjectInSektor(cam->getSektorPosition())) return DR_OK;
	//Unit distance1 = Vector3Unit(mSektorPosition - cam->getSektorPosition()).length();
    //Unit distance1 = Vector3Unit(mSektorPosition - mLastRelativeCameraPosition).length();    
    Unit distance1 = (-mLastRelativeCameraPosition).length();    
	//DRVector3 diff = Vector3Unit(mSektorPosition - cam->getSektorPosition()).convertTo(KM).getVector3();

    distance1 = distance1.convertTo(mRadius.getType());
    double distance2 = 200.0f;
    Unit radius1 = mRadius;
    double radius2 = ((radius1 * distance2) / distance1);

    
	//DRVector3 pos = (mSektorPosition - cam->getSektorPosition()).getVector3().normalize();
    //DRVector3 pos = (mSektorPosition - mLastRelativeCameraPosition).getVector3().normalize();
    DRVector3 pos = (-mLastRelativeCameraPosition).getVector3().normalize();
//    DRVector3 relCameraPos = -pos*distance1/mRadius;
     pos *= static_cast<DRReal>(distance2);
/*   printf("\r %f %f %f, %.8f, %s  x:%s y:%s z:%s (%f %f %f)", pos.x, pos.y, pos.z, radius2, distance1.print().data(),
									   absCameraPosition.x.print().data(), absCameraPosition.y.print().data(),
									   absCameraPosition.z.print().data(), diff.x, diff.y, diff.z);
										   //*/
    //glTranslatef(pos.x, pos.y, pos.z);
    //glScaled(radius2, radius2, radius2);
	
    mMatrix = DRMatrix::scaling(DRVector3(static_cast<DRReal>(radius2))) * DRMatrix::translation(pos) * cam->getKameraMatrixRotation();
	
	//glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	//if(mRenderer && !isObjectInSektor(cam->getSektorPosition()))
    //DRReturn ret = mRenderer->render(fTime, cam);
    if(!isObjectInSektor(mLastRelativeCameraPosition))
    {
        mNotRenderSeconds = 0.0f;
        if(!mRenderer)
            mRenderer = new RenderPlanet(mID, getSektorPathName(), &mPlanetNoiseParameters);
        if(!mRenderer) LOG_ERROR("no renderer", DR_ERROR);
        
        if(radius2 > 160.0f) mRenderer->setCurrentDetail(10);
        else if(radius2 > 140.0f) mRenderer->setCurrentDetail(9);
        else if(radius2 > 120.0f) mRenderer->setCurrentDetail(8);
        else if(radius2 > 90.0f) mRenderer->setCurrentDetail(7);
        else if(radius2 > 70.0f) mRenderer->setCurrentDetail(6);
        else if(radius2 > 30.0f) mRenderer->setCurrentDetail(5);
        else if(radius2 > 25.0f) mRenderer->setCurrentDetail(4);
        else if(radius2 > 15.0f) mRenderer->setCurrentDetail(3);
        else if(radius2 > 5.0f) mRenderer->setCurrentDetail(2);
        else if(radius2 > 1.0f) mRenderer->setCurrentDetail(1);
        else mRenderer->setCurrentDetail(0);
    
      //GlobalRenderer::getSingleton().getPlanetShaderPtr()->bind();
        ShaderProgram* shader = mRenderer->getShaderProgram();
        if(!shader) LOG_ERROR("RenderPlanet hasn't valid shader", DR_ERROR);
        shader->bind();

        shader->setUniformMatrix("modelview", mMatrix);
        shader->setUniformMatrix("projection", GlobalRenderer::Instance().getProjectionMatrix().transpose());
        DRGrafikError("PlanetSektor::render");
        
        DRReturn ret = mRenderer->render(fTime, cam);
        shader->unbind();
//		GlobalRenderer::getSingleton().getPlanetShaderPtr()->unbind();
        if(ret) LOG_ERROR("Fehler bei call planet renderer", DR_ERROR);
        //child didn't need to render
        return DR_NOT_ERROR;
        //return DR_OK;
    } 
    else
    {
        mNotRenderSeconds += fTime;
    }
    
    return DR_OK;
}
Esempio n. 16
0
static void initialize()
{
	srand(time(nullptr));

	Audio::initialize();
	Audio::load("sounds/checkpoint.wav", "checkpoint");
	Audio::load("sounds/ship.wav", "ship");
	Audio::load("sounds/asteroid.wav", "asteroid");
	Audio::load("sounds/explosion.wav", "explosion");
	Audio::load("sounds/timeout.wav", "timeout");
	Audio::load("sounds/ding.wav", "ding");

	level.generate();

	ShaderProgram *asteroidShader = new ShaderProgram("shaders/asteroid.vert", "shaders/default.frag");
	asteroidShader->bindAttribLocation("in_Position", 0);
	asteroidShader->bindAttribLocation("in_Normal", 1);
	asteroidShader->bindAttribLocation("in_TextureCoords", 2);
	asteroidShader->bindAttribLocation("in_Tangent", 3);
	asteroidShader->bindAttribLocation("in_InstancePosition", 4);
	asteroidShader->bindAttribLocation("in_InstanceScale", 5);
	asteroidShader->bindAttribLocation("in_InstanceRotation", 6);
	asteroidShader->bindFragDataLocation("out_Color", 0);
	asteroidShader->link();
	Registry::shaders["asteroid"] = asteroidShader;

	asteroidShader->bind();
	(*asteroidShader)["u_DiffuseTexture"].set1i(1);
	(*asteroidShader)["u_NormalTexture"].set1i(2);
	(*asteroidShader)["u_EmitTexture"].set1i(3);
	(*asteroidShader)["u_SpecularTexture"].set1i(4);
	asteroidShader->unbind();

	Registry::textures["asteroid-diffuse"] = loadPngTexture("textures/asteroid-diffuse.png", true);
	Registry::textures["asteroid-emit"] = loadPngTexture("textures/asteroid-emit.png", true);
	Registry::textures["asteroid-normal"] = loadPngTexture("textures/asteroid-normal.png", true);
	Registry::textures["asteroid-specular"] = loadPngTexture("textures/asteroid-specular.png", true);
	Registry::models["asteroid"] = loadCobjModel("models/asteroid.cobj");

	// ----- Cubemap -----

	Cubemap *cubemap = loadPngCubemap({
		"textures/stars.png",
		"textures/stars.png",
		"textures/stars.png",
		"textures/stars.png",
		"textures/sun.png",
		"textures/stars.png"
	}, true);
	Registry::cubemap = cubemap;

	Registry::models["environment_cube"] = loadCobjModel("models/environment_cube.cobj");

	ShaderProgram *shaderCubemap = new ShaderProgram("shaders/cubemap.vert", "shaders/cubemap.frag");
	shaderCubemap->bindAttribLocation("in_Position", 0);
	shaderCubemap->bindFragDataLocation("out_Color", 0);
	shaderCubemap->link();

	shaderCubemap->bind();
	(*shaderCubemap)["u_Cubemap"].set1i(1);
	shaderCubemap->unbind();

	Registry::shaders["cubemap"] = shaderCubemap;

	// ----- Planet -----

	Registry::textures["planet"] = loadPngTexture("textures/planet.png", true);
	Registry::models["planet"] = loadCobjModel("models/planet.cobj");

	ShaderProgram *planetShader = new ShaderProgram("shaders/planet.vert", "shaders/planet.frag");
	planetShader->bindAttribLocation("in_Position", 0);
	planetShader->bindAttribLocation("in_Normal", 1);
	planetShader->bindAttribLocation("in_TextureCoords", 2);
	planetShader->bindFragDataLocation("out_Color", 0);
	planetShader->link();
	planetShader->bind();
	(*planetShader)["u_Texture"].set1i(1);
	planetShader->unbind();

	Registry::shaders["planet"] = planetShader;

	planetShader = new ShaderProgram("shaders/planet.vert", "shaders/atmosphere.frag");
	planetShader->bindAttribLocation("in_Position", 0);
	planetShader->bindAttribLocation("in_Normal", 1);
	planetShader->bindAttribLocation("in_TextureCoords", 2);
	planetShader->bindFragDataLocation("out_Color", 0);
	planetShader->link();
	planetShader->bind();
	(*planetShader)["u_Texture"].set1i(1);
	planetShader->unbind();

	Registry::shaders["planet-atmosphere"] = planetShader;

	// ----- Screen quad -----

	float quadCoords[] = {0, 0, 1, 0, 1, 1, 0, 1};
	unsigned int quadIndices[] = {0, 1, 3, 3, 1, 2};

	VertexArray *quadVao = new VertexArray(VertexArray::Triangles, 6);

	Buffer *quadCoordsBuffer = new Buffer(Buffer::Array, Buffer::StaticDraw);
	quadCoordsBuffer->data(8 * sizeof(float), reinterpret_cast<const void*>(quadCoords));

	Buffer *quadIndicesBuffer = new Buffer(Buffer::ElementArray, Buffer::StaticDraw);
	quadIndicesBuffer->data(6 * sizeof(unsigned int), reinterpret_cast<const void*>(quadIndices));

	quadVao->addAttrib(0, VertexAttrib(quadCoordsBuffer, 2, VertexAttrib::Float));
	quadVao->setElementIndexArray(ElementIndexArray(quadIndicesBuffer));

	Registry::screenQuad = quadVao;

	// ----- Spaceship -----

	Registry::textures["ship-diffuse"] = loadPngTexture("textures/ship-diffuse.png", true);
	Registry::textures["ship-emit"] = loadPngTexture("textures/ship-emit.png", true);
	Registry::textures["ship-normal"] = loadPngTexture("textures/ship-normal.png", true);
	Registry::textures["ship-specular"] = loadPngTexture("textures/ship-specular.png", true);
	Registry::models["ship"] = loadCobjModel("models/ship.cobj");

	ShaderProgram *shipShader = new ShaderProgram("shaders/ship.vert", "shaders/default.frag");
	shipShader->bindAttribLocation("in_Position", 0);
	shipShader->bindAttribLocation("in_Normal", 1);
	shipShader->bindAttribLocation("in_TextureCoords", 2);
	shipShader->bindAttribLocation("in_Tangent", 3);
	shipShader->bindFragDataLocation("out_Color", 0);
	shipShader->link();
	Registry::shaders["ship"] = shipShader;

	shipShader->bind();
	(*shipShader)["u_DiffuseTexture"].set1i(1);
	(*shipShader)["u_NormalTexture"].set1i(2);
	(*shipShader)["u_EmitTexture"].set1i(3);
	(*shipShader)["u_SpecularTexture"].set1i(4);
	shipShader->unbind();

	// ----- Overlay -----

	ShaderProgram *overlayShader = new ShaderProgram("shaders/overlay.vert", "shaders/overlay.frag");
	overlayShader->bindAttribLocation("in_Position", 0);
	overlayShader->bindFragDataLocation("out_Color", 0);
	overlayShader->link();
	Registry::shaders["overlay"] = overlayShader;

	// ----- Checkpoint -----

	float pointCoords[] = {0, 0, 0};
	VertexArray *pointVao = new VertexArray(VertexArray::Points, 1);
	Buffer *pointCoordsBuffer = new Buffer(Buffer::Array, Buffer::StaticDraw);
	pointCoordsBuffer->data(3 * sizeof(float), reinterpret_cast<const void*>(pointCoords));
	pointVao->addAttrib(0, VertexAttrib(pointCoordsBuffer, 3, VertexAttrib::Float));
	Registry::point = pointVao;

	ShaderProgram *checkpointShader = new ShaderProgram("shaders/checkpoint.vert", "shaders/checkpoint.frag");
	checkpointShader->bindAttribLocation("in_Position", 0);
	checkpointShader->bindFragDataLocation("out_Color", 0);
	checkpointShader->link();
	Registry::shaders["checkpoint"] = checkpointShader;

	Registry::models["checkpoint"] = loadCobjModel("models/checkpoint.cobj");

	// ----- Arrow -----

	Registry::models["arrow"] = loadCobjModel("models/arrow.cobj");

	ShaderProgram *arrowShader = new ShaderProgram("shaders/arrow.vert", "shaders/arrow.frag");
	arrowShader->bindAttribLocation("in_Position", 0);
	arrowShader->bindAttribLocation("in_TextureCoords", 2);
	arrowShader->bindFragDataLocation("out_Color", 0);
	arrowShader->link();

	arrowShader->bind();
	(*arrowShader)["u_DiffuseTexture"].set1i(1);
	arrowShader->unbind();

	Registry::shaders["arrow"] = arrowShader;
	Registry::textures["arrow-diffuse"] = loadPngTexture("textures/arrow-diffuse.png", true);

	// ----- Screens -----

	Registry::textures["screen-title"] = loadPngTexture("textures/screens/title.png", false);
	Registry::textures["screen-won"] = loadPngTexture("textures/screens/won.png", false);
	Registry::textures["screen-crashed"] = loadPngTexture("textures/screens/crashed.png", false);
	Registry::textures["screen-timeout"] = loadPngTexture("textures/screens/time-out.png", false);
	Registry::textures["screen-controls"] = loadPngTexture("textures/screens/controls.png", false);
	Registry::textures["screen-level"] = loadPngTexture("textures/screens/level.png", false);

	ShaderProgram *screenShader = new ShaderProgram("shaders/postprocess.vert", "shaders/screen.frag");
	screenShader->bindAttribLocation("in_Position", 0);
	screenShader->bindFragDataLocation("out_Color", 0);
	screenShader->link();
	screenShader->bind();
	(*screenShader)["u_Texture"].set1i(1);
	screenShader->unbind();

	Registry::shaders["screen"] = screenShader;
}
Esempio n. 17
0
	void Shadow2D::render()
	{
		static ShaderProgram fp("first_pass.vs.glsl", "first_pass.fs.glsl");
		static ShaderProgram sp("second_pass.vs.glsl", "second_pass.fs.glsl");

		static bool init = false;
		static GLuint fbo;
		static GLuint colour_tex;
		static GLuint depth_tex;

		static GLuint colour_texture_loc;
		static GLuint depth_texture_loc;

		static GLuint light_pos_loc = glGetUniformLocation(sp, "light_pos");
		static GLuint screen_dim_loc = glGetUniformLocation(sp, "screen_dimensions");

		glProgramUniform2f(sp, screen_dim_loc, (float)getWidth(), (float)getHeight());

		if (glfwGetMouseButton(_window, 0))
		{
			double x, y;

			glfwGetCursorPos(_window, &x, &y);

			x /= (double)getWidth();
			y /= (double)getHeight();

			x *= 2.0f;
			y *= 2.0f;

			x = 1.0f - x;
			y -= 1.0f;

			glProgramUniform2f(sp, light_pos_loc, x, y);
		}
		
		if (!init)
		{
			init = true;

			int width, height;
			glfwGetWindowSize(_window, &width, &height);

			colour_texture_loc = glGetUniformLocation(sp, "colour");
			depth_texture_loc = glGetUniformLocation(sp, "depth");

			glGenTextures(1, &colour_tex);
			glBindTexture(GL_TEXTURE_2D, colour_tex);
			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_CLAMP_TO_EDGE);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_FLOAT, 0);

			glGenTextures(1, &depth_tex);
			glBindTexture(GL_TEXTURE_2D, depth_tex);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
			glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);

			glGenFramebuffers(1, &fbo);
			glBindFramebuffer(GL_FRAMEBUFFER, fbo);
			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colour_tex, 0);
			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth_tex, 0);

			checkGlError();
		}

		glBindFramebuffer(GL_FRAMEBUFFER, 0);

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

		glEnable(GL_DEPTH_TEST);

		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
		glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);

		glClearColor(0, 0, 0, 0);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		fp.bind();

		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		glLoadIdentity();

		//glRotatef(glfwGetTime() * 15.0f, 0, 0, 1.0f);

		//glBegin(GL_TRIANGLES);
		//glVertex2f(-1.0f, -1.0f);
		//glVertex2f(0.0f, -1.0f);
		//glVertex2f(0.0f, 0.0f);
		//glEnd();

		for (int i = 0; i < CIRCLE_COUNT; ++i)
		{
			glPushMatrix();
			glLoadIdentity();

			glTranslatef(circle_positions[i].x, circle_positions[i].y, 0.0f);

			glScalef(circle_sizes[i], circle_sizes[i], 1.0f);

			glEnableClientState(GL_VERTEX_ARRAY);
			glVertexPointer(2, GL_FLOAT, 0, _circleVertexArray);
			glDrawArrays(GL_TRIANGLE_FAN, 0, CIRCLE_DIVISIONS);
			glDisableClientState(GL_VERTEX_ARRAY);

			glPopMatrix();
		}

		glPopMatrix();

		glDisable(GL_DEPTH_TEST);

		glBindFramebuffer(GL_FRAMEBUFFER, 0);

		glClearColor(0, 0, 0, 0);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		//glBlitFramebuffer(0, 0, getWidth(), getHeight(), 0, 0, getWidth(), getHeight(), GL_COLOR_BUFFER_BIT, GL_LINEAR);

		sp.bind();

		glEnable(GL_TEXTURE_2D);

		//glActiveTexture(GL_TEXTURE0);
		//glBindTexture(GL_TEXTURE_2D, colour_tex);
		//glProgramUniform1i(sp, colour_texture_loc, 0);

		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, depth_tex);
		glProgramUniform1i(sp, depth_texture_loc, 1);

		glBegin(GL_QUADS);
		glColor3f(1.0f, 1.0f, 1.0f);

		glTexCoord2f(0.0f, 0.0f);
		glVertex2f(-1.0f, -1.0f);

		glTexCoord2f(1.0f, 0.0f);
		glVertex2f(1.0f, -1.0f);

		glTexCoord2f(1.0f, 1.0f);
		glVertex2f(1.0f, 1.0f);

		glTexCoord2f(0.0f, 1.0f);
		glVertex2f(-1.0f, 1.0f);
		glEnd();
	}
Esempio n. 18
0
        virtual void onDraw(){
	         
			static float time = 0.0; time += .05;  
			

			//Slow method
			
			// for (int i = 0; i < f.num(); ++i){   
			// 	Pnt tp = f[i]; Pnt np;  
			//                   for (int j = 0; j < numDipoles; ++j ){  
			// 		double dist = 1.0 / ( Ro::sqd( f[i], dls[j] ) +.01 );
			// 		np +=  Ro::loc( tp.sp( Gen::bst( par[j] * dist) ) );//.sp(bst) );
			// 	   }
			// 	f[i] = np; 
			// }  
			        
			
			//OR (faster) . . .  [this is not an accurate EM field, but looks like one . . .]
			Vec tally;
			
			for (int i = 0; i < f.num(); ++i){   
				  Par tpar;
                  for (int j = 0; j < numDipoles; ++j ){ 
					float sqd =  ( Ro::sqd( f[i], dls[j] ) +1. );
					float dist = 1.0 / sqd;  
					tpar += par[j] * dist;
				   }
				f[i] = Ro::loc( f[i].sp(  Gen::bst( tpar  * s[i] )  )  );  
				tally += f[i];  
    		}
		   
		 	// Average particle position  is used as Camera Target
			tally /= f.num(); 

			Vec tp( scene.camera.pos()[0], scene.camera.pos()[1], scene.camera.pos()[2] );  
			Vec goal = ( tally - tp ).unit();    
			Rot rot  = Gen::ratio( -Vec::z, goal ); 

			scene.camera.quat() = Rot2Quat(rot); 		
			scene.camera.orient(); 
			
			
			// Oscillation of the Dipoles Position  		   
			for (int j = 0; j < numDipoles; ++j ){     
				float t = 1.0 * j/numDipoles;
				dp[j] = tally + ( Vec::x * width * sin(time) * (j&1? -1 : 1) );
				dls[j] = Ro::dls( dp[j], .2 + .3 * t).trs (0, t * cos(time) * height, 0);
				par[j] = Ro::par( dls[j], Vec::x * (j&1?-1:1) ) * .1; 
		   }
			   
			Mat4f mvm = scene.xf.modelViewMatrixf();
			
		    program.bind();
						
		         program.uniform("projection",  scene.xf.proj);
		         program.uniform("lightPosition", 2.0, 2.0, 2.0);
		         program.uniform("normalMatrix", scene.xf.normal);  
				 program.uniform("modelView", scene.xf.modelView );//app.scene().xf.modelView);        
				
					Render( f, mvm, pipe ); 
				
					for (int j = 0; j < numDipoles; ++j){  
						Render( dls[j], mvm, pipe );
					}   
				
	       program.unbind();       

        }