所谓的法线是指 物品在光的照射下肉眼能看到的物体的面 而物体里面是看不到的。也就说,计算光照是运算需要法线。未设置法线那么一般情况是看不到物体的,处于一片漆黑状态。
#include<osgDB/ReadFile>
#include<osgViewer/Viewer>
#include<osg/Node>
#include<osg/Geode>
#include<osg/Geometry>
#include <osgUtil/SmoothingVisitor>
osg::ref_ptr<osg::Node> createQuad();
void main()
{
osgViewer::Viewer viewer;
osg::Group *root=new osg::Group();
root->addChild(createQuad().get());
viewer.setSceneData(root);
viewer.realize();
viewer.run();
}
osg::ref_ptr<osg::Node> createQuad()
{
osg::ref_ptr<osg::Geometry> geom=new osg::Geometry;
//首先定义四个点
osg::ref_ptr<osg::Vec3Array> v=new osg::Vec3Array;
geom->setVertexArray(v.get());
v->push_back(osg::Vec3(-1.f,0.f,-1.f));
v->push_back(osg::Vec3(1.f,0.f,-1.f));
v->push_back(osg::Vec3(1.f,0.f,1.f));
v->push_back(osg::Vec3(-1.f,0.f,1.f));
//定义颜色数组
osg::ref_ptr<osg::Vec4Array> c=new osg::Vec4Array;
geom->setColorArray(c.get());
geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
c->push_back(osg::Vec4(1.f,0.f,0.f,1.f));
c->push_back(osg::Vec4(0.f,1.f,0.f,1.f));
c->push_back(osg::Vec4(0.f,0.f,1.f,1.f));
c->push_back(osg::Vec4(1.f,1.f,1.f,1.f));
//设置定点关联方式
geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
//方法一
//手动定义法线
osg::ref_ptr<osg::Vec3Array> n=new osg::Vec3Array;
geom->setNormalArray(n.get());
geom->setNormalBinding(osg::Geometry::BIND_OVERALL);
n->push_back(osg::Vec3(-2.f,-1.f,10.f));
//方法二
//自动生成法线
//osgUtil::SmoothingVisitor::smooth(*(geom.get()));//自动生成法线
osg::ref_ptr<osg::Geode> geode=new osg::Geode;
geode->addDrawable(geom.get());
return geode.get();
}