shader简史
在Direct8之前,GPU使用固定方式变换像素和顶点,即所谓的“固定管道”。这使得开发者不可能改变像素和顶点转换和处理的进程,使大多数游戏的图像表现看起来非常相似。
Direct8提出顶点和像素着色器,这让开发者可以在管道中决定如何处理顶点和像素,使它们获得了很强的灵活性。
一开始shader编程使用汇编语言程序使用的着色器,这对shader开发者来说相当困难,Shader Model 1.0是唯一支持的版本。但DirectX9发布后这一切改变了,开发者能够使用高级着色语言(HLSL)取代了汇编语言,HLSL语法类似C语言,这使shader更容易编写,阅读和学习。
DirectX 10.0提出了一个新的shader——Geometry Shader作为Shader Model 4.0的组成部分。但这需要一个最先进的显卡和Windows Vista才能支持。
XNA支持Shader Model 1.0至3.0,可以在XP,Vista和XBox360!上运行。
shader分为vertex顶点部分和Fragment像素部分两个部分,总体而言就是显卡上所提供的可编程部分。相当于可以交托给显卡运行的脚本的感觉,shader的一个好处就是可以跑出很多比较酷的效果而不用加载额外的资源。至于vertex和fagment的分法,其实是因为显卡在绘制的时候是先画点再涂颜色的。
cocos2d-x如何使用shader
以cocos2d-x3.0 win32为例
第一步 下载shader文件解压,把gray.fsh,gray.vsh添加到资源文件resource下
http://www.cocoachina.com/bbs/job.php?action=download&aid=67864
第二步 修改HelloWorld 文件(注意有两个USING_NG_CC,笔者第一次在.h里没有放,结果一堆错误哦)
//.cpp文件
#include "HelloWorldScene.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
if (!Layer::init())
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
auto sprite = Sprite::create("HelloWorld.png");
sprite->setAnchorPoint(Point(0.5, 0.5));
sprite->setPosition(Point(visibleSize.width / 3, visibleSize.height / 3));
this->addChild(sprite);
graySprite(sprite);
return true;
}
void HelloWorld::graySprite(Sprite * sprite)
{
if (sprite)
{
GLProgram * p = new GLProgram();
p->initWithFilenames("gray.vsh", "gray.fsh");
p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION);
p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR);
p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORDS);
p->link();
p->updateUniforms();
sprite->setShaderProgram(p);
}
}
//.h文件
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
USING_NS_CC;
class HelloWorld : public cocos2d::Layer
{
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
void graySprite(Sprite * sprite);
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__
好了,运行程序,是不是变灰了,哈哈,恭喜你
----------