OpenGL加载shader代码

c++加载shader的代码:

<pre name="code" class="cpp">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "glew.h"
#include "stdafx.h"
static char *shaderLoadSource(const char *filePath)
{
	const size_t blockSize=512;
	FILE *fp;
	char buf[blockSize];
	char *source=NULL;
	size_t tmp,sourceLength=0;

	fp=fopen(filePath,"r");
	if(!fp){
		fprintf(stderr,"shaderLoadSource():Unable to open %s for reading\n",filePath);
		return NULL;
	}

	while((tmp=fread(buf,1,blockSize,fp))>0)
	{
		char *newSource=(char *)malloc(sourceLength+tmp+1);
		if(!newSource){
			fprintf(stderr,"shaderLoadSource():malloc failed\n");
			if(source){
				free(source);
			}
			return NULL;
		}
		if(source){
			memcpy(newSource,source,sourceLength);
			free(source);
		}
		memcpy(newSource+sourceLength,buf,tmp);
		source=newSource;
		sourceLength+=tmp;
	}
	fclose(fp);
	if(source){
		source[sourceLength]='\0';
	}

	return source;
}

static GLuint shaderCompileFromFile(GLenum type,const char *filePath)
{
	char *source;
	GLuint shader;
	GLint length,result;

	source=shaderLoadSource(filePath);
	if(!source){
		return 0;
	}
	shader=glCreateShader(type);
	length=strlen(source);
	glShaderSource(shader,1,(const char**)&source,&length);
	glCompileShader(shader);
	free(source);

	glGetShaderiv(shader,GL_COMPILE_STATUS,&result);
	if(result==GL_FALSE){
		char *log;
		
		glGetShaderiv(shader,GL_INFO_LOG_LENGTH,&length);
		log=(char *)malloc(length);
		glGetShaderInfoLog(shader,length,&result,log);
		fprintf(stderr,"shaderCompileFromFile(): Unable to compile %s: %s\n",filePath,log);
		free(log);

		glDeleteShader(shader);
		return 0;
	}

	return shader;
}

void shaderAttachFromFile(GLuint program,GLenum type,const char *filePath)
{
	GLuint shader=shaderCompileFromFile(type,filePath);
	if(shader!=0){
		glAttachShader(program,shader);
		glDeleteShader(shader);
	}
}

 program 需要在场景中初始,参考我的博客相关介绍。 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值