CPUTBufferOGL::~CPUTBufferOGL()
{
    GL_CHECK(glDeleteBuffers(1, &mBuffer));
}
Пример #2
0
Vao::~Vao() {
    if (m_glVertexArray) {
        GL_CHECK(glDeleteVertexArrays(1, &m_glVertexArray));
    }
}
Пример #3
0
 void Enable()
 {
     GL_CHECK(glBindVertexArray(mVertexArray));
 }
Пример #4
0
unsigned int
shader_create_program(program_type_e type)
{
    GLuint vs = 0;
    GLuint fs = 0;
    GLuint program = glCreateProgram();
    GLint link_status;
    GLint length = 0;

    switch(type) {
      case PROGRAM_BACKGROUND:
        vs = shader_create_shader(GL_VERTEX_SHADER, background_vshader_g);
        fs = shader_create_shader(GL_FRAGMENT_SHADER, simpletex_fshader_g);
        break;
      case PROGRAM_CHARACTER:
        vs = shader_create_shader(GL_VERTEX_SHADER, character_vshader_g);
        fs = shader_create_shader(GL_FRAGMENT_SHADER, simpletex_fshader_g);
        break;
      default:
        log_e("program type: %d is not implemented", type);
        goto error;
    }

    if (!vs || !fs) {
        goto error;
    }

    if (program) {
        glAttachShader(program, vs);
        glAttachShader(program, fs);
        glLinkProgram(program);
        link_status = GL_FALSE;
        glGetProgramiv(program, GL_LINK_STATUS, &link_status);
        if (link_status != GL_TRUE) {
            length = 0;
            glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length);
            if (length) {
                char* buf = (char*) malloc(length);
                if (buf) {
                    glGetProgramInfoLog(program, length, NULL, buf);
                    log_e("Could not link program: %s\n", buf);
                    free(buf);
                }
            }
            goto error;
        }
    } else {
        goto error;
    }

    GL_CHECK(glDeleteShader, vs);
    GL_CHECK(glDeleteShader, fs);

    log_i("Created program: %d", program);

    return program;

error:
    log_e("Could not create program: %d", type);

    glDeleteShader(vs);
    glDeleteShader(fs);
    glDeleteProgram(program);

    return 0;
}
Пример #5
0
void Vao::bind() const {
    GL_CHECK(glBindVertexArray(m_glVertexArray));
}
Пример #6
0
 Text::~Text(void)
 {
     clear();
     
     GL_CHECK(glDeleteTextures(1, &textureID));
 }
Пример #7
0
bool Texture::LoadZIM(const char *filename) {
	uint8_t *image_data[ZIM_MAX_MIP_LEVELS];
	int width[ZIM_MAX_MIP_LEVELS];
	int height[ZIM_MAX_MIP_LEVELS];

	int flags;
	int num_levels = ::LoadZIM(filename, &width[0], &height[0], &flags, &image_data[0]);
	if (!num_levels)
		return false;
	width_ = width[0];
	height_ = height[0];
	int data_type = GL_UNSIGNED_BYTE;
	int colors = GL_RGBA;
	int storage = GL_RGBA;
	bool compressed = false;
	switch (flags & ZIM_FORMAT_MASK) {
	case ZIM_RGBA8888:
		data_type = GL_UNSIGNED_BYTE;
		break;
	case ZIM_RGBA4444:
		data_type = DXGI_FORMAT_B4G4R4A4_UNORM;
		break;
	case ZIM_RGB565:
		data_type = DXGI_FORMAT_B5G6R5_UNORM;
		colors = GL_RGB;
		storage = GL_RGB;
		break;
	case ZIM_ETC1:
		compressed = true;
		break;
	}

	GL_CHECK();
	//glGenTextures(1, &id_);
	//glBindTexture(GL_TEXTURE_2D, id_);
	SetTextureParameters(flags);

	if (compressed) {
		for (int l = 0; l < num_levels; l++) {
			int data_w = width[l];
			int data_h = height[l];
			if (data_w < 4) data_w = 4;
			if (data_h < 4) data_h = 4;
#if defined(USING_GLES2)
			int compressed_image_bytes = data_w * data_h / 2;
			glCompressedTexImage2D(GL_TEXTURE_2D, l, GL_ETC1_RGB8_OES, width[l], height[l], 0, compressed_image_bytes, image_data[l]);
			GL_CHECK();
#else
			//image_data[l] = ETC1ToRGBA(image_data[l], data_w, data_h);
			//glTexImage2D(GL_TEXTURE_2D, l, GL_RGBA, width[l], height[l], 0,
			//						GL_RGBA, GL_UNSIGNED_BYTE, image_data[l]);
#endif
		}
		GL_CHECK();
#if !defined(USING_GLES2)
		//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, num_levels - 2);
#endif
	} else {
		for (int l = 0; l < num_levels; l++) {
			//glTexImage2D(GL_TEXTURE_2D, l, storage, width[l], height[l], 0,
			//						 colors, data_type, image_data[l]);
		}
		if (num_levels == 1 && (flags & ZIM_GEN_MIPS)) {
			//glGenerateMipmap(GL_TEXTURE_2D);
		}
	}
	SetTextureParameters(flags);

	GL_CHECK();
	// Only free the top level, since the allocation is used for all of them.
	delete [] image_data[0];
	return true;
}
Пример #8
0
// Create a window context
//-----------------------------------------------------------------------------
CPUTResult CPUT_OGL::CPUTCreateWindowAndContext(const cString WindowTitle, CPUTWindowCreationParams windowParams)
{
    CPUTResult result = CPUT_SUCCESS;

    HEAPCHECK;

    // We shouldn't destroy old window if it already exist, 
    // Framework user should do this by himself to be aware
    // of what he is doing.
    if( mpWindow )
    {
        return CPUT_ERROR_WINDOW_ALREADY_EXISTS;
    }

    result = MakeWindow(WindowTitle, windowParams);
    if(CPUTFAILED(result))
    {
        return result;
    }


    HEAPCHECK;

    // create the GL context
    result = CreateOGLContext(windowParams.deviceParams);
    if(CPUTFAILED(result))
    {
        return result;
    }


    HEAPCHECK;

    result = CreateContext();

    CPUTRenderStateBlock *pBlock = new CPUTRenderStateBlockOGL();
    CPUTRenderStateBlock::SetDefaultRenderStateBlock( pBlock );

    cString name = _L("$cbPerFrameValues");
    mpPerFrameConstantBuffer = new CPUTBufferOGL(name);
    GLuint id = mpPerFrameConstantBuffer->GetBufferID();
#ifndef CPUT_FOR_OGLES2
    GL_CHECK(glBindBuffer(GL_UNIFORM_BUFFER, mpPerFrameConstantBuffer->GetBufferID()));
    GL_CHECK(glBufferData(GL_UNIFORM_BUFFER, sizeof(CPUTFrameConstantBuffer), NULL, GL_DYNAMIC_DRAW)); // NULL to just init buffer size
    DEBUG_PRINT(_L("bind per frame buffer buffer %d\n"), id);
//FIXME: constant buffer binding
    GL_CHECK(ES3_COMPAT(glBindBufferBase(GL_UNIFORM_BUFFER, id, id)));
    DEBUG_PRINT(_L("completed - bind buffer %d\n"), id);
    GL_CHECK(glBindBuffer(GL_UNIFORM_BUFFER, 0));
#else
#warning "Need to do something with uniform buffers here"
#endif
    CPUTAssetLibrary::GetAssetLibrary()->AddConstantBuffer(_L(""), name, _L(""), mpPerFrameConstantBuffer);
    
    name = _L("$cbPerModelValues");
    mpPerModelConstantBuffer = new CPUTBufferOGL(name, GL_UNIFORM_BUFFER, GL_DYNAMIC_DRAW, sizeof(CPUTModelConstantBuffer), NULL);
    
    id = mpPerModelConstantBuffer->GetBufferID();
#ifndef CPUT_FOR_OGLES2
    DEBUG_PRINT(_L("Bind per model values %d"), id);
    GL_CHECK(ES3_COMPAT(glBindBufferBase(GL_UNIFORM_BUFFER, id, id)));
    DEBUG_PRINT(_L("Completed bind per model values"));
    GL_CHECK(glBindBuffer(GL_UNIFORM_BUFFER, 0));
#else
#warning "Need to do something with uniform buffers here"
#endif
    CPUTAssetLibrary::GetAssetLibrary()->AddConstantBuffer(_L(""), name, _L(""), mpPerModelConstantBuffer);

    name = _L("$cbGUIConstants");
    CPUTBuffer* pBuffer = new CPUTBufferOGL(name, GL_UNIFORM_BUFFER, GL_DYNAMIC_DRAW, sizeof(GUIConstants), NULL);
    
    CPUTAssetLibrary::GetAssetLibrary()->AddConstantBuffer(_L(""), name, _L(""), pBuffer);
    SAFE_RELEASE(pBuffer);
	// Add our programatic (and global) material parameters
    CPUTMaterial::mGlobalProperties.AddValue( _L("cbPerFrameValues"), _L("$cbPerFrameValues") );
    CPUTMaterial::mGlobalProperties.AddValue( _L("cbPerModelValues"), _L("$cbPerModelValues") );
    CPUTMaterial::mGlobalProperties.AddValue( _L("cbGUIValues"), _L("$cbGUIValues") );
    HEAPCHECK;

    // Trigger a post-create user callback event
    Create();
    HEAPCHECK;

    //
    // Start the timer after everything is initialized and assets have been loaded
    //
    mpTimer->StartTimer();

    int x,y,width,height;
    mpWindow->GetClientDimensions(&x, &y, &width, &height);

    ResizeWindow(width,height);

    return result;
}
Пример #9
0
///////////////////////////////////////////////////////////////////////
//load, compile and set the shaders
void setShaders()
{
	char *vs,*fs,*gs;

	v = glCreateShader(GL_VERTEX_SHADER);
	f = glCreateShader(GL_FRAGMENT_SHADER);
	g = glCreateShader(GL_GEOMETRY_SHADER);

  vs = textFileRead(const_cast<char *>("./shader03.vert"));
  fs = textFileRead(const_cast<char *>("./shader03.frag"));
  gs = textFileRead(const_cast<char *>("./shader03.geom"));

	const char * ff = fs;
	const char * vv = vs;
	const char * gg = gs;

	glShaderSource(v, 1, &vv,NULL);
	glShaderSource(f, 1, &ff,NULL);
	glShaderSource(g, 1, &gg,NULL);

	free(vs);free(fs);free(gs);

	glCompileShader(v);
	glCompileShader(f);
	glCompileShader(g);

	GLint blen = 0; 
	GLsizei slen = 0;

	glGetShaderiv(v, GL_INFO_LOG_LENGTH , &blen);       
	if (blen > 1)
	{
		GLchar* compiler_log = (GLchar*)malloc(blen);
		glGetShaderInfoLog(v, blen, &slen, compiler_log);
		std::cout << "compiler_log vertex shader:\n" << compiler_log << std::endl;
		free (compiler_log);
	}
	blen = 0; 
	slen = 0;
	glGetShaderiv(f, GL_INFO_LOG_LENGTH , &blen);       
	if (blen > 1)
	{
		GLchar* compiler_log = (GLchar*)malloc(blen);
		glGetShaderInfoLog(f, blen, &slen, compiler_log);
		std::cout << "compiler_log fragment shader:\n" << compiler_log << std::endl;
		free (compiler_log);
	}
	blen = 0; 
	slen = 0;
	glGetShaderiv(g, GL_INFO_LOG_LENGTH , &blen);       
	if (blen > 1)
	{
		GLchar* compiler_log = (GLchar*)malloc(blen);
		glGetShaderInfoLog(g, blen, &slen, compiler_log);
		std::cout << "compiler_log geometry shader:\n" << compiler_log << std::endl;
		free (compiler_log);
	}

	p = glCreateProgram();

	glAttachShader(p,f);
	glAttachShader(p,v);
	glAttachShader(p,g);

	glLinkProgram(p);
	// comment out this line to not use the shader

	glUseProgram(p);

	GLint loc = glGetUniformLocation(p, "ambientColor");
	if (loc != -1)
	{
		GL_CHECK(glUniform4f(loc, 1.0,0.0,0.0,1.0));
	}

	loc = glGetUniformLocation(p, "diffuseColor");
	if (loc != -1)
	{
		GL_CHECK(glUniform4f(loc, 1.0,1.0,1.0,1.0));
	}

	loc = glGetUniformLocation(p, "specularColor");
	if (loc != -1)
	{
		GL_CHECK(glUniform4f(loc, 1.0,1.0,1.0,1.0));
	}

	loc = glGetUniformLocation(p, "specularExponent");
	if (loc != -1)
	{
		GL_CHECK(glUniform1f(loc, 25.0));
	}
}
Пример #10
0
void PipelineImpl::doRenderPass(Pipeline::RenderPass pass)
{
  auto end = tasks[pass].end();
  for(auto i = tasks[pass].begin(); i != end; ++i) {
    DrawTaskObject dto = i->first;
    DrawTaskData dtd = i->second;

    // break out if the data isn't fully loaded
    if(!dto.mat->shaders || !dto.mesh->buffer || !dto.mesh->buffer->vao)
      continue;

    // bind the shader and vertex array
    GL_CHECK(glUseProgram(dto.mat->shaders->gl_id));
    GL_CHECK(glBindVertexArray(dto.mesh->buffer->vao));

    // loop over the uniforms. Set aside the modelview matrix if found.
    GLint mv_id = -1;
    GLuint current_tex = 0;
    auto uend = dto.mat->uniforms.end();
    for(auto j = dto.mat->uniforms.begin(); j != uend; j++) {
      GLuint uid = boost::any_cast<int>(j->pipe_id);
      switch(j->type) {
      case UniformDef::Texture:
        {
          Image *img = boost::any_cast<Image*>(j->value);
          GL_CHECK(glActiveTexture(GL_TEXTURE0+current_tex));
          if(img->tex) {
            GL_CHECK(glBindTexture(GL_TEXTURE_2D, img->tex->id));
          } else {
            GL_CHECK(glBindTexture(GL_TEXTURE_2D, 0));
          }
          GL_CHECK(glUniform1i(uid, current_tex));
          current_tex++;
          break;
        }
      case UniformDef::ModelView:
        {
          mv_id = uid;
          break;
        }
      case UniformDef::BoneMatrices:
        {
          size_t mat_count = dtd.transforms.size();
          if(mat_count > SENSE_MAX_VTX_BONES)
            mat_count = SENSE_MAX_VTX_BONES;
          glUniformMatrix4fv(uid, mat_count, GL_FALSE, (GLfloat*)(&(dtd.transforms[0])));
          break;
        }
      case UniformDef::GBufColor:
        {
          GL_CHECK(glActiveTexture(GL_TEXTURE0+current_tex));
          GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, current_framebuffer->color_id));
          GL_CHECK(glUniform1i(uid, current_tex));
          current_tex++;
          break;
        }
      case UniformDef::GBufNormal:
        {
          GL_CHECK(glActiveTexture(GL_TEXTURE0+current_tex));
          GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, current_framebuffer->normal_id));
          GL_CHECK(glUniform1i(uid, current_tex));
          current_tex++;
          break;
        }
      case UniformDef::GBufMatProp:
        {
          GL_CHECK(glActiveTexture(GL_TEXTURE0+current_tex));
          GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, current_framebuffer->matprop_id));
          GL_CHECK(glUniform1i(uid, current_tex));
          current_tex++;
          break;
        }
      case UniformDef::DepthInfo:
      case UniformDef::LightColor:
      case UniformDef::LightPosition:
      case UniformDef::LightRadius:
      case UniformDef::Projection:
      case UniformDef::Webview:
      default:
        throw std::runtime_error("Tried to use unimplemenented uniform type");
      }
    }
    GL_CHECK(glValidateProgram(dto.mat->shaders->gl_id));
    GLint status;
    GL_CHECK(glGetProgramiv(dto.mat->shaders->gl_id, GL_VALIDATE_STATUS, &status));
    if(status == GL_FALSE) {
      int info_log_length;
      GL_CHECK(glGetShaderiv(dto.mat->shaders->gl_id, GL_INFO_LOG_LENGTH, &info_log_length));
      char *log = new char[info_log_length];
      GL_CHECK(glGetShaderInfoLog(dto.mat->shaders->gl_id, info_log_length, &info_log_length, log));
      std::string infolog = log;
      delete[] log;
      throw std::runtime_error("Error validating shader: " + infolog);
    }
    if(mv_id != -1) {
      // we have a model-view matrix array handle. We need to draw one or more instance passes now.
      size_t cur_transform = 0;
      size_t remaining_mvs = dtd.transforms.size();
      do {
        size_t batch_size = remaining_mvs <= SENSE_MAX_INSTANCES ? remaining_mvs : SENSE_MAX_INSTANCES;
        GLfloat* data_ptr = (GLfloat*)&dtd.transforms[cur_transform];
        GL_CHECK(glUniformMatrix4fv(mv_id, batch_size, GL_FALSE, data_ptr));
        if(dto.mesh->index_data) {
          GL_CHECK(glDrawElementsInstanced(GL_TRIANGLES, dto.mesh->index_count, dto.mesh->buffer->idx_type, 0, batch_size));
        } else {
          GL_CHECK(glDrawArraysInstanced(GL_TRIANGLES, 0, dto.mesh->data_size / dto.mesh->data_stride, batch_size));
        }
        cur_transform += batch_size;
        remaining_mvs -= batch_size;
      } while (remaining_mvs);
    } else {
      if(dto.mesh->index_data) {
        GL_CHECK(glDrawElements(GL_TRIANGLES, dto.mesh->index_count, dto.mesh->buffer->idx_type, 0));
      } else {
        GL_CHECK(glDrawArrays(GL_TRIANGLES, 0, dto.mesh->data_size / dto.mesh->data_stride));
      }
    }
  }
}
Пример #11
0
bool Texture::LoadZIM(const char *filename) {
	uint8_t *image_data[ZIM_MAX_MIP_LEVELS];
	int width[ZIM_MAX_MIP_LEVELS];
	int height[ZIM_MAX_MIP_LEVELS];

	int flags;
	int num_levels = ::LoadZIM(filename, &width[0], &height[0], &flags, &image_data[0]);
	if (!num_levels)
		return false;
	if (num_levels >= ZIM_MAX_MIP_LEVELS)
		return false;
	width_ = width[0];
	height_ = height[0];
	int data_type = GL_UNSIGNED_BYTE;
	int colors = GL_RGBA;
	int storage = GL_RGBA;
	bool compressed = false;
	switch (flags & ZIM_FORMAT_MASK) {
	case ZIM_RGBA8888:
		data_type = GL_UNSIGNED_BYTE;
		break;
	case ZIM_RGBA4444:
		data_type = GL_UNSIGNED_SHORT_4_4_4_4;
		break;
	case ZIM_RGB565:
		data_type = GL_UNSIGNED_SHORT_5_6_5;
		colors = GL_RGB;
		storage = GL_RGB;
		break;
	case ZIM_ETC1:
		compressed = true;
		break;
	}

	GL_CHECK();

	glGenTextures(1, &id_);
	glBindTexture(GL_TEXTURE_2D, id_);
	SetTextureParameters(flags);

	if (compressed) {
		for (int l = 0; l < num_levels; l++) {
			int data_w = width[l];
			int data_h = height[l];
			if (data_w < 4) data_w = 4;
			if (data_h < 4) data_h = 4;
#if defined(USING_GLES2) && !defined(IOS)
			int compressed_image_bytes = data_w * data_h / 2;
			glCompressedTexImage2D(GL_TEXTURE_2D, l, GL_ETC1_RGB8_OES, width[l], height[l], 0, compressed_image_bytes, image_data[l]);
			GL_CHECK();
#else
			// TODO: OpenGL 4.3+ accepts ETC1 so we should not have to do this anymore on those cards.
			// Also, iOS does not have support for ETC1 compressed textures so we just decompress.
			// TODO: Use PVR texture compression on iOS.
			image_data[l] = ETC1ToRGBA(image_data[l], data_w, data_h);
			glTexImage2D(GL_TEXTURE_2D, l, GL_RGBA, width[l], height[l], 0,
				GL_RGBA, GL_UNSIGNED_BYTE, image_data[l]);
#endif
		}
		GL_CHECK();
#if !defined(USING_GLES2)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, num_levels - 2);
#endif
	} else {
		for (int l = 0; l < num_levels; l++) {
			glTexImage2D(GL_TEXTURE_2D, l, storage, width[l], height[l], 0,
				colors, data_type, image_data[l]);
		}
		if (num_levels == 1 && (flags & ZIM_GEN_MIPS)) {
			if(gl_extensions.FBO_ARB) {
				glGenerateMipmap(GL_TEXTURE_2D);
			}else{
#ifndef USING_GLES2
				glGenerateMipmapEXT(GL_TEXTURE_2D);
#endif
			}
		}
	}
	SetTextureParameters(flags);

	GL_CHECK();
	// Only free the top level, since the allocation is used for all of them.
	free(image_data[0]);
	return true;
}
Пример #12
0
RenderTarget* Pipeline::createRenderTarget(uint32_t width, uint32_t height, bool mipmap)
{
  GLuint texids[5];
  GLuint fboids[2];
  glGenFramebuffers(2, fboids);
  glGenTextures(5, texids);
  RenderTarget rt;
  rt.depth_id = texids[0];
  rt.color_id = texids[1];
  rt.normal_id = texids[2];
  rt.matprop_id = texids[3];
  rt.lighting_id = texids[4];
  rt.lbuffer_id = fboids[0];
  rt.gbuffer_id = fboids[1];

  rt.build_mips = mipmap;
  rt.dirty = true;

  rt.width = width;
  rt.height = height;

  GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, rt.lbuffer_id));
  GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.lighting_id));
  GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_RGBA16F, width, height, GL_FALSE));
  GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.depth_id));
  GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_DEPTH24_STENCIL8, width, height, GL_FALSE));
  GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, rt.lighting_id, 0));
  GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, rt.depth_id, 0));
  GL_CHECK(glViewport(0, 0, width, height));
  FBO_CHECK;
  
  GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, rt.gbuffer_id));
  GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.color_id));
  GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_RGBA8, width, height, GL_FALSE));
  GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.normal_id));
  GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_RGBA8, width, height, GL_FALSE));
  GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.matprop_id));
  GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_RG16F, width, height, GL_FALSE));
  GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, rt.color_id, 0));
  GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D_MULTISAMPLE, rt.normal_id, 0));
  GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D_MULTISAMPLE, rt.matprop_id, 0));
  GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, rt.depth_id, 0));
  GL_CHECK(glViewport(0, 0, width, height));
  GL_CHECK(glDrawBuffers(3, buffers));
  FBO_CHECK;

  RenderTarget* result = new RenderTarget;
  *result = rt;
  return result;
}
Пример #13
0
void Lightmap::render(const Falltergeist::Point &pos)
{
    if (_indexes<=0) return;

    GL_CHECK(glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR));
    auto shader = ResourceManager::getInstance()->shader("lightmap");

    GL_CHECK(shader->use());

    GL_CHECK(shader->setUniform(_uniformMVP, Game::getInstance()->renderer()->getMVP()));

    // set camera offset
    GL_CHECK(shader->setUniform(_uniformOffset, glm::vec2((float)pos.x(), (float)pos.y()) ));

    GL_CHECK(shader->setUniform(_uniformFade,Game::getInstance()->renderer()->fadeColor()));


    GL_CHECK(glBindVertexArray(_vao));


    GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, _coords));
    GL_CHECK(glVertexAttribPointer(_attribPos, 2, GL_FLOAT, GL_FALSE, 0, (void*)0 ));


    GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, _lights));

    GL_CHECK(glVertexAttribPointer(_attribLights, 1, GL_FLOAT, GL_FALSE, 0, (void*)0 ));

    GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo));


    GL_CHECK(glEnableVertexAttribArray(_attribPos));

    GL_CHECK(glEnableVertexAttribArray(_attribLights));

    GL_CHECK(glDrawElements(GL_TRIANGLES, _indexes, GL_UNSIGNED_INT, 0 ));

    GL_CHECK(glDisableVertexAttribArray(_attribPos));

    GL_CHECK(glDisableVertexAttribArray(_attribLights));

    GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
    GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0));
    GL_CHECK(glBindVertexArray(0));

    GL_CHECK(shader->unuse());
    GL_CHECK(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
}
Пример #14
0
Lightmap::Lightmap(std::vector<glm::vec2> coords,std::vector<GLuint> indexes)
{
    GL_CHECK(glGenVertexArrays(1, &_vao));
    GL_CHECK(glBindVertexArray(_vao));

    // generate VBOs for verts and tex
    GL_CHECK(glGenBuffers(1, &_coords));
    GL_CHECK(glGenBuffers(1, &_lights));
    GL_CHECK(glGenBuffers(1, &_ebo));

    if (coords.size()<=0) return;

    GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, _coords));
    //update coords
    GL_CHECK(glBufferData(GL_ARRAY_BUFFER, coords.size() * sizeof(glm::vec2), &coords[0], GL_STATIC_DRAW));


    GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, _lights));
    //update texcoords
//    GL_CHECK(glBufferData(GL_ARRAY_BUFFER, textureCoords.size() * sizeof(glm::vec2), &textureCoords[0], GL_STATIC_DRAW));

    GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo));
    // update indexes
    GL_CHECK(glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexes.size() * sizeof(GLuint), &indexes[0], GL_DYNAMIC_DRAW));
    _indexes = indexes.size();

    GL_CHECK(glBindVertexArray(0));

    auto shader = ResourceManager::getInstance()->shader("lightmap");

    _uniformFade = shader->getUniform("fade");
    _uniformMVP = shader->getUniform("MVP");
    _uniformOffset = shader->getUniform("offset");

    _attribPos = shader->getAttrib("Position");
    _attribLights = shader->getAttrib("lights");
}
Пример #15
0
void Renderer::clear() const
{
    GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
}
int
main(int argc, char *argv[])
{
    int fsaa, accel;
    int value;
    int i, done;
    SDL_DisplayMode mode;
    SDL_Event event;
    Uint32 then, now, frames;
    int status;
    shader_data *datas, *data;

    /* Initialize parameters */
    fsaa = 0;
    accel = 0;

    /* Initialize test framework */
    state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
    if (!state) {
        return 1;
    }
    for (i = 1; i < argc;) {
        int consumed;

        consumed = SDLTest_CommonArg(state, i);
        if (consumed == 0) {
            if (SDL_strcasecmp(argv[i], "--fsaa") == 0) {
                ++fsaa;
                consumed = 1;
            } else if (SDL_strcasecmp(argv[i], "--accel") == 0) {
                ++accel;
                consumed = 1;
            } else if (SDL_strcasecmp(argv[i], "--zdepth") == 0) {
                i++;
                if (!argv[i]) {
                    consumed = -1;
                } else {
                    depth = SDL_atoi(argv[i]);
                    consumed = 1;
                }
            } else {
                consumed = -1;
            }
        }
        if (consumed < 0) {
            SDL_Log ("Usage: %s %s [--fsaa] [--accel] [--zdepth %%d]\n", argv[0],
                    SDLTest_CommonUsage(state));
            quit(1);
        }
        i += consumed;
    }

    /* Set OpenGL parameters */
    state->window_flags |= SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_BORDERLESS;
    state->gl_red_size = 5;
    state->gl_green_size = 5;
    state->gl_blue_size = 5;
    state->gl_depth_size = depth;
    state->gl_major_version = 2;
    state->gl_minor_version = 0;
    state->gl_profile_mask = SDL_GL_CONTEXT_PROFILE_ES;

    if (fsaa) {
        state->gl_multisamplebuffers=1;
        state->gl_multisamplesamples=fsaa;
    }
    if (accel) {
        state->gl_accelerated=1;
    }
    if (!SDLTest_CommonInit(state)) {
        quit(2);
        return 0;
    }

    context = SDL_calloc(state->num_windows, sizeof(context));
    if (context == NULL) {
        SDL_Log("Out of memory!\n");
        quit(2);
    }
    
    /* Create OpenGL ES contexts */
    for (i = 0; i < state->num_windows; i++) {
        context[i] = SDL_GL_CreateContext(state->windows[i]);
        if (!context[i]) {
            SDL_Log("SDL_GL_CreateContext(): %s\n", SDL_GetError());
            quit(2);
        }
    }

    /* Important: call this *after* creating the context */
    if (LoadContext(&ctx) < 0) {
        SDL_Log("Could not load GLES2 functions\n");
        quit(2);
        return 0;
    }



    if (state->render_flags & SDL_RENDERER_PRESENTVSYNC) {
        SDL_GL_SetSwapInterval(1);
    } else {
        SDL_GL_SetSwapInterval(0);
    }

    SDL_GetCurrentDisplayMode(0, &mode);
    SDL_Log("Screen bpp: %d\n", SDL_BITSPERPIXEL(mode.format));
    SDL_Log("\n");
    SDL_Log("Vendor     : %s\n", ctx.glGetString(GL_VENDOR));
    SDL_Log("Renderer   : %s\n", ctx.glGetString(GL_RENDERER));
    SDL_Log("Version    : %s\n", ctx.glGetString(GL_VERSION));
    SDL_Log("Extensions : %s\n", ctx.glGetString(GL_EXTENSIONS));
    SDL_Log("\n");

    status = SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &value);
    if (!status) {
        SDL_Log("SDL_GL_RED_SIZE: requested %d, got %d\n", 5, value);
    } else {
        SDL_Log( "Failed to get SDL_GL_RED_SIZE: %s\n",
                SDL_GetError());
    }
    status = SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &value);
    if (!status) {
        SDL_Log("SDL_GL_GREEN_SIZE: requested %d, got %d\n", 5, value);
    } else {
        SDL_Log( "Failed to get SDL_GL_GREEN_SIZE: %s\n",
                SDL_GetError());
    }
    status = SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &value);
    if (!status) {
        SDL_Log("SDL_GL_BLUE_SIZE: requested %d, got %d\n", 5, value);
    } else {
        SDL_Log( "Failed to get SDL_GL_BLUE_SIZE: %s\n",
                SDL_GetError());
    }
    status = SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &value);
    if (!status) {
        SDL_Log("SDL_GL_DEPTH_SIZE: requested %d, got %d\n", depth, value);
    } else {
        SDL_Log( "Failed to get SDL_GL_DEPTH_SIZE: %s\n",
                SDL_GetError());
    }
    if (fsaa) {
        status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &value);
        if (!status) {
            SDL_Log("SDL_GL_MULTISAMPLEBUFFERS: requested 1, got %d\n", value);
        } else {
            SDL_Log( "Failed to get SDL_GL_MULTISAMPLEBUFFERS: %s\n",
                    SDL_GetError());
        }
        status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &value);
        if (!status) {
            SDL_Log("SDL_GL_MULTISAMPLESAMPLES: requested %d, got %d\n", fsaa,
                   value);
        } else {
            SDL_Log( "Failed to get SDL_GL_MULTISAMPLESAMPLES: %s\n",
                    SDL_GetError());
        }
    }
    if (accel) {
        status = SDL_GL_GetAttribute(SDL_GL_ACCELERATED_VISUAL, &value);
        if (!status) {
            SDL_Log("SDL_GL_ACCELERATED_VISUAL: requested 1, got %d\n", value);
        } else {
            SDL_Log( "Failed to get SDL_GL_ACCELERATED_VISUAL: %s\n",
                    SDL_GetError());
        }
    }

    datas = SDL_calloc(state->num_windows, sizeof(shader_data));

    /* Set rendering settings for each context */
    for (i = 0; i < state->num_windows; ++i) {

        status = SDL_GL_MakeCurrent(state->windows[i], context[i]);
        if (status) {
            SDL_Log("SDL_GL_MakeCurrent(): %s\n", SDL_GetError());

            /* Continue for next window */
            continue;
        }
        ctx.glViewport(0, 0, state->window_w, state->window_h);

        data = &datas[i];
        data->angle_x = 0; data->angle_y = 0; data->angle_z = 0;

        /* Shader Initialization */
        process_shader(&data->shader_vert, _shader_vert_src, GL_VERTEX_SHADER);
        process_shader(&data->shader_frag, _shader_frag_src, GL_FRAGMENT_SHADER);

        /* Create shader_program (ready to attach shaders) */
        data->shader_program = GL_CHECK(ctx.glCreateProgram());

        /* Attach shaders and link shader_program */
        GL_CHECK(ctx.glAttachShader(data->shader_program, data->shader_vert));
        GL_CHECK(ctx.glAttachShader(data->shader_program, data->shader_frag));
        GL_CHECK(ctx.glLinkProgram(data->shader_program));

        /* Get attribute locations of non-fixed attributes like color and texture coordinates. */
        data->attr_position = GL_CHECK(ctx.glGetAttribLocation(data->shader_program, "av4position"));
        data->attr_color = GL_CHECK(ctx.glGetAttribLocation(data->shader_program, "av3color"));

        /* Get uniform locations */
        data->attr_mvp = GL_CHECK(ctx.glGetUniformLocation(data->shader_program, "mvp"));

        GL_CHECK(ctx.glUseProgram(data->shader_program));

        /* Enable attributes for position, color and texture coordinates etc. */
        GL_CHECK(ctx.glEnableVertexAttribArray(data->attr_position));
        GL_CHECK(ctx.glEnableVertexAttribArray(data->attr_color));

        /* Populate attributes for position, color and texture coordinates etc. */
        GL_CHECK(ctx.glVertexAttribPointer(data->attr_position, 3, GL_FLOAT, GL_FALSE, 0, _vertices));
        GL_CHECK(ctx.glVertexAttribPointer(data->attr_color, 3, GL_FLOAT, GL_FALSE, 0, _colors));

        GL_CHECK(ctx.glEnable(GL_CULL_FACE));
        GL_CHECK(ctx.glEnable(GL_DEPTH_TEST));
    }

    /* Main render loop */
    frames = 0;
    then = SDL_GetTicks();
    done = 0;
    while (!done) {
        /* Check for events */
        ++frames;
        while (SDL_PollEvent(&event) && !done) {
            switch (event.type) {
            case SDL_WINDOWEVENT:
                switch (event.window.event) {
                    case SDL_WINDOWEVENT_RESIZED:
                        for (i = 0; i < state->num_windows; ++i) {
                            if (event.window.windowID == SDL_GetWindowID(state->windows[i])) {
                                status = SDL_GL_MakeCurrent(state->windows[i], context[i]);
                                if (status) {
                                    SDL_Log("SDL_GL_MakeCurrent(): %s\n", SDL_GetError());
                                    break;
                                }
                                /* Change view port to the new window dimensions */
                                ctx.glViewport(0, 0, event.window.data1, event.window.data2);
                                /* Update window content */
                                Render(event.window.data1, event.window.data2, &datas[i]);
                                SDL_GL_SwapWindow(state->windows[i]);
                                break;
                            }
                        }
                        break;
                }
            }
            SDLTest_CommonEvent(state, &event, &done);
        }
        if (!done) {
          for (i = 0; i < state->num_windows; ++i) {
              status = SDL_GL_MakeCurrent(state->windows[i], context[i]);
              if (status) {
                  SDL_Log("SDL_GL_MakeCurrent(): %s\n", SDL_GetError());

                  /* Continue for next window */
                  continue;
              }
              Render(state->window_w, state->window_h, &datas[i]);
              SDL_GL_SwapWindow(state->windows[i]);
          }
        }
    }

    /* Print out some timing information */
    now = SDL_GetTicks();
    if (now > then) {
        SDL_Log("%2.2f frames per second\n",
               ((double) frames * 1000) / (now - then));
    }
#if !defined(__ANDROID__)    
    quit(0);
#endif    
    return 0;
}
Пример #17
0
    void Text::draw(void)
    {
        GL_CHECK(glBindVertexArray(0));
        GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0));

        if(numberOfCharacters == 0) 
        {
            return;
        }

        GL_CHECK(glUseProgram(programID));

        if(m_iLocPosition != -1)
        {
            GL_CHECK(glEnableVertexAttribArray(m_iLocPosition));
            GL_CHECK(glVertexAttribPointer(m_iLocPosition, 3, GL_FLOAT, GL_FALSE, 0, textVertex));
        }

        if(m_iLocTextColor != -1)
        {
            GL_CHECK(glEnableVertexAttribArray(m_iLocTextColor));
            GL_CHECK(glVertexAttribPointer(m_iLocTextColor, 4, GL_FLOAT, GL_FALSE, 0, color));
        }

        if(m_iLocTexCoord != -1)
        {
            GL_CHECK(glEnableVertexAttribArray(m_iLocTexCoord));
            GL_CHECK(glVertexAttribPointer(m_iLocTexCoord, 2, GL_FLOAT, GL_FALSE, 0, textTextureCoordinates));
        }

        if(m_iLocProjection != -1)
        {
            GL_CHECK(glUniformMatrix4fv(m_iLocProjection, 1, GL_FALSE, projectionMatrix.getAsArray()));
        }

        GL_CHECK(glActiveTexture(GL_TEXTURE0));
        GL_CHECK(glBindTexture(GL_TEXTURE_2D, textureID));

        GL_CHECK(glDrawElements(GL_TRIANGLE_STRIP, numberOfCharacters * 6 - 2, GL_UNSIGNED_SHORT, textIndex));

        if(m_iLocTextColor != -1)
        {
            GL_CHECK(glDisableVertexAttribArray(m_iLocTextColor));
        }

        if(m_iLocTexCoord != -1)
        {
            GL_CHECK(glDisableVertexAttribArray(m_iLocTexCoord));
        }

        if(m_iLocPosition != -1)
        {
            GL_CHECK(glDisableVertexAttribArray(m_iLocPosition));
        }
    }
Пример #18
0
void Movie::render(int x, int y)
{
    std::vector<glm::vec2> vertices;
    std::vector<glm::vec2> UV;

    int width = 640;
    int height = 320;

    glm::vec2 vertex_up_left    = glm::vec2( (float)x, (float)y);
    glm::vec2 vertex_up_right   = glm::vec2( (float)(x+width), (float)y);
    glm::vec2 vertex_down_right = glm::vec2( (float)(x+width), (float)(y+height));
    glm::vec2 vertex_down_left  = glm::vec2( (float)x, (float)(y+height));

    vertices.push_back(vertex_up_left   );
    vertices.push_back(vertex_down_left );
    vertices.push_back(vertex_up_right  );
    vertices.push_back(vertex_down_right);

    glm::vec2 uv_up_left    = glm::vec2( 0.0, 0.0 );
    glm::vec2 uv_up_right   = glm::vec2( (float)_texture->width()/(float)_texture->textureWidth(), 0.0 );
    glm::vec2 uv_down_right = glm::vec2( (float)_texture->width()/(float)_texture->textureWidth(), (float)_texture->height()/(float)_texture->textureHeight() );
    glm::vec2 uv_down_left  = glm::vec2( 0.0, (float)_texture->height()/(float)_texture->textureHeight() );

    UV.push_back(uv_up_left   );
    UV.push_back(uv_down_left );
    UV.push_back(uv_up_right  );
    UV.push_back(uv_down_right);

    // TODO: different shader

    GL_CHECK(ResourceManager::getInstance()->shader("sprite")->use());

    GL_CHECK(_texture->bind(0));

    GL_CHECK(ResourceManager::getInstance()->shader("sprite")->setUniform("tex",0));

    GL_CHECK(ResourceManager::getInstance()->shader("sprite")->setUniform("fade",Game::getInstance()->renderer()->fadeColor()));

    GL_CHECK(ResourceManager::getInstance()->shader("sprite")->setUniform("MVP", Game::getInstance()->renderer()->getMVP()));

    if (Game::getInstance()->renderer()->renderPath() == Renderer::RenderPath::OGL32)
    {
        GLint curvao;
        glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &curvao);
        GLint vao = Game::getInstance()->renderer()->getVAO();
        if (curvao != vao)
        {
            GL_CHECK(glBindVertexArray(vao));
        }
    }


    GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, Game::getInstance()->renderer()->getVVBO()));

    GL_CHECK(glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec2), &vertices[0], GL_DYNAMIC_DRAW));

    GL_CHECK(glVertexAttribPointer(ResourceManager::getInstance()->shader("sprite")->getAttrib("Position"), 2, GL_FLOAT, GL_FALSE, 0, (void*)0 ));


    GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, Game::getInstance()->renderer()->getTVBO()));

    GL_CHECK(glBufferData(GL_ARRAY_BUFFER, UV.size() * sizeof(glm::vec2), &UV[0], GL_DYNAMIC_DRAW));

    GL_CHECK(glVertexAttribPointer(ResourceManager::getInstance()->shader("sprite")->getAttrib("TexCoord"), 2, GL_FLOAT, GL_FALSE, 0, (void*)0 ));

    GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Game::getInstance()->renderer()->getEBO()));

    GL_CHECK(glEnableVertexAttribArray(ResourceManager::getInstance()->shader("sprite")->getAttrib("Position")));

    GL_CHECK(glEnableVertexAttribArray(ResourceManager::getInstance()->shader("sprite")->getAttrib("TexCoord")));

    GL_CHECK(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0 ));

    GL_CHECK(glDisableVertexAttribArray(ResourceManager::getInstance()->shader("sprite")->getAttrib("Position")));

    GL_CHECK(glDisableVertexAttribArray(ResourceManager::getInstance()->shader("sprite")->getAttrib("TexCoord")));

//    GL_CHECK(glBindVertexArray(0));
}
Пример #19
0
    Text::Text(const char* vertexShaderFileName,
               const char* fragmentShaderFileName,
               const char* textureFileName,
               int         windowWidth,
               int         windowHeight)
    {
        vertexShaderID   = 0;
        fragmentShaderID = 0;
        programID        = 0;

        numberOfCharacters     = 0;
        textVertex             = NULL;
        textTextureCoordinates = NULL;
        color                  = NULL;
        textIndex              = NULL;

        /* Create an orthographic projection. */
        projectionMatrix = Matrix::matrixOrthographic(0, (float)windowWidth, 0, (float)windowHeight, 0, 1);

        /* Shaders. */
        Shader::processShader(&vertexShaderID,   vertexShaderFileName,   GL_VERTEX_SHADER);
        Shader::processShader(&fragmentShaderID, fragmentShaderFileName, GL_FRAGMENT_SHADER);

        /* Set up shaders. */
        programID = GL_CHECK(glCreateProgram());

        GL_CHECK(glAttachShader(programID, vertexShaderID));
        GL_CHECK(glAttachShader(programID, fragmentShaderID));
        GL_CHECK(glLinkProgram(programID));
        GL_CHECK(glUseProgram(programID));

        /* Vertex positions. */
        m_iLocPosition = GL_CHECK(glGetAttribLocation(programID, "a_v4Position"));
        /* Text colors. */
        m_iLocTextColor = GL_CHECK(glGetAttribLocation(programID, "a_v4FontColor"));
        /* TexCoords. */
        m_iLocTexCoord = GL_CHECK(glGetAttribLocation(programID, "a_v2TexCoord"));
        /* Projection matrix. */
        m_iLocProjection = GL_CHECK(glGetUniformLocation(programID, "u_m4Projection"));
        /* Set the sampler to point at the 0th texture unit. */
        m_iLocTexture = GL_CHECK(glGetUniformLocation(programID, "u_s2dTexture"));

        ASSERT(m_iLocPosition != -1,  "Attribute not found: a_v4Position");
        ASSERT(m_iLocTextColor != -1, "Attribute not found: a_v4FontColor");
        ASSERT(m_iLocTexCoord != -1, "Attribute not found: a_v2TexCoord");
        ASSERT(m_iLocProjection != -1, "Uniform not found: u_m4Projection");
        ASSERT(m_iLocTexture != -1, "Uniform not found: u_s2dTexture");

        GL_CHECK(glUniformMatrix4fv(m_iLocProjection, 1, GL_FALSE, projectionMatrix.getAsArray()));
        GL_CHECK(glUniform1i       (m_iLocTexture, 1));

        /* Load texture. */
        GL_CHECK(glActiveTexture(GL_TEXTURE1));
        GL_CHECK(glGenTextures  (1, &textureID));
        GL_CHECK(glBindTexture  (GL_TEXTURE_2D, textureID));

        /* Set filtering. */
        GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
        GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
        GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
        GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));

        unsigned char *textureData = NULL;

        Texture::loadData(textureFileName, &textureData);

        GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 256, 48, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData));

        free(textureData);
        textureData = NULL;
    }
Пример #20
0
void MeshRenderer::RenderInstanced(int count) {
    GL_CHECK( glBindVertexArray(VAO) );
    GL_CHECK( glDrawElementsInstanced(GL_TRIANGLES, elementsCount, GL_UNSIGNED_INT, nullptr, count) );
    GL_CHECK( glBindVertexArray(0) );
}
Пример #21
0
void
shader_delete_shader(unsigned int shader)
{
    GL_CHECK(glDeleteShader, shader);
}
Пример #22
0
void MeshRenderer::Init(Mesh* mesh) {
    this->owner = mesh;
    
    // Copy data to graphics card
    GL_CHECK( glGenBuffers(1, &VBO) );
    GL_CHECK( glBindBuffer(GL_ARRAY_BUFFER, VBO) );
    GL_CHECK( glBufferData(GL_ARRAY_BUFFER, mesh->vertices.size() * sizeof(VboEntry), nullptr, GL_STATIC_DRAW) );

    for (size_t i = 0; i < mesh->vertices.size(); ++i) {
        GL_CHECK( glBufferSubData(GL_ARRAY_BUFFER, i * sizeof(VboEntry) + offsetof(VboEntry, pos)     , sizeof(glm::vec3), &mesh->vertices [i]) );
        GL_CHECK( glBufferSubData(GL_ARRAY_BUFFER, i * sizeof(VboEntry) + offsetof(VboEntry, normal)  , sizeof(glm::vec3), &mesh->normals  [i]) );
        GL_CHECK( glBufferSubData(GL_ARRAY_BUFFER, i * sizeof(VboEntry) + offsetof(VboEntry, texcoord), sizeof(glm::vec2), &mesh->texCoords[i]) );
    }
    
    // setup vbo for index buffer
    GL_CHECK( glGenBuffers(1, &EBO) );
    GL_CHECK( glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) );
    GL_CHECK( glBufferData(GL_ELEMENT_ARRAY_BUFFER, mesh->faces.size()*sizeof(glm::ivec3), &mesh->faces[0].x, GL_STATIC_DRAW) );


    // setup VAO
    // Narozdil od VBO neukladaji data o vrcholech (pozice, normala, ...), ale ukladaji reference na VBO a nastaveni atributu.
    // VAO usnadnuji a urychluji vykreslovani. Pro vykresleni staci aktivovat VAO a ten si pamatuje veskere nastaveni.
    // subsequent calls that change the vertex array state (glBindBuffer, glVertexAttribPointer, glEnableVertexAttribArray, and glDisableVertexAttribArray) will affect the new VAO.
    GL_CHECK( glGenVertexArrays(1, &VAO) );  // TODO UBO pro kazdy mesh?
    GL_CHECK( glBindVertexArray(VAO) );

    GL_CHECK( glBindBuffer(GL_ARRAY_BUFFER, VBO) );
    GL_CHECK( glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) );

    // setup vertex shader attribute bindings (connecting current <position and tc> buffer to associated 'in' variable in vertex shader)
    GL_CHECK( glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VboEntry), (const GLvoid*)offsetof(VboEntry, pos     )) );
    GL_CHECK( glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(VboEntry), (const GLvoid*)offsetof(VboEntry, normal  )) );
    GL_CHECK( glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(VboEntry), (const GLvoid*)offsetof(VboEntry, texcoord)) );

    // enable vertex buffers
    GL_CHECK( glEnableVertexAttribArray(0) );
    GL_CHECK( glEnableVertexAttribArray(1) );
    GL_CHECK( glEnableVertexAttribArray(2) );

    // unbind VAO
    GL_CHECK( glBindVertexArray(0) );

    elementsCount = mesh->faces.size() * 3;
}
Пример #23
0
void
shader_delete_program(unsigned int program)
{
    GL_CHECK(glDeleteProgram, program);
}
Пример #24
0
void MeshRenderer::Render() {
    GL_CHECK( glBindVertexArray(VAO) );
    GL_CHECK( glDrawElements(GL_TRIANGLES, elementsCount, GL_UNSIGNED_INT, nullptr) );
    GL_CHECK( glBindVertexArray(0) );
}
Пример #25
0
void Vao::unbind() const {
	GL_CHECK(glBindVertexArray(0));
}
Пример #26
0
Shader::~Shader()
{
    GL_CHECK(glDeleteShader(_gl_shader));
}
Пример #27
0
 // Not supported in ES
 void AddVertexIPointer(GLint index, GLint count, GLenum type, GLint stride, void * offset)
 {
     GL_CHECK(glEnableVertexAttribArray(index));
     GL_CHECK(glVertexAttribIPointer(index, count, type, stride, offset));
 }
	//! Load into video memory
	void OpenGLTexture::GraphicLoad()
	{
		if(m_GLTextureID)
		{
			SHOOT_WARNING(false, "Texture '%s' video data already loaded", m_strPath.c_str());
			return;
		}

		if(!m_pData)
		{
			SHOOT_ASSERT(false, "Texture '%s' disk data not available", m_strPath.c_str());
			return;
		}
		
		GL_CHECK(glEnable(GL_TEXTURE_2D));
		GL_CHECK(glGenTextures(1, &m_GLTextureID));
		GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_GLTextureID)); // 2d texture (x and y size)
		GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
		if(m_bMipMaps)
		{
			GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST)); 
			GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE));
		}
		else
		{
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		}

		Size size((s32)m_vSize.X, (s32)m_vSize.Y);
		Size hwSize((s32)m_vHardwareSize.X, (s32)m_vHardwareSize.Y);
		if((size != hwSize))
		{
			u8* pOldData = static_cast<u8*>(m_pData);
			u8* pNewData = snew u8[hwSize.Width * hwSize.Height * m_bpp];
			memset(pNewData, 0, hwSize.Width * hwSize.Height * m_bpp);
			for(s32 row=0; row<size.Height; ++row)
			{
				memcpy(pNewData+row*hwSize.Width*m_bpp, pOldData+row*size.Width*m_bpp, size.Width*m_bpp);
			}
			sdelete_array(pOldData);
			m_pData = pNewData;
		}

		// Load texture into video memory
		switch(m_eFormat)
		{
		case TF_RGB:
			GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, hwSize.Width, hwSize.Height, 0, GL_RGB, (m_bpp == 2) ? GL_UNSIGNED_SHORT_5_6_5 : GL_UNSIGNED_BYTE, m_pData));
			break;

		case TF_RGBA:
			GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, hwSize.Width, hwSize.Height, 0, GL_RGBA, (m_bpp == 2) ? GL_UNSIGNED_SHORT_4_4_4_4 : GL_UNSIGNED_BYTE, m_pData));
			break;
		}

		m_MemorySize = hwSize.Width*hwSize.Height*m_bpp;
		
		u8* pData = static_cast<u8*>(m_pData);
		sdelete_array(pData);
		m_pData = NULL;
	}
Пример #29
0
 void Disable()
 {
     GL_CHECK(glBindVertexArray(0));
     GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
     GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0));
 }
CPUTBufferOGL::CPUTBufferOGL(cString name) :
    CPUTBuffer(name)
{
    GL_CHECK(glGenBuffers(1, &mBuffer));
}