绘制并渲染几何体主要有一下3步:
1.创建各种向量数据,例如顶点、纹理坐标、颜色、法线<逆时针添加坐标数据>.
2.实例化一个几何体对象(osg::geometry),设置顶点坐标数组、纹理坐标数组、颜色坐标数组、法线数组、绑定方式及数据解析格式.
3.加入叶节点绘制渲染.
基本绘制:
1#include <osgViewer/Viewer>
2
3#include <osg/Node>
4#include <osg/Geode>
5#include <osg/Group>
6
7#include <osgDB/ReadFile>
8#include <osgDB/WriteFile>
9
10#include <osgUtil/Optimizer>
11
12//创建一个四边形节点
13osg::ref_ptr <osg::Node >cteateQuad(){
14 //创建一个叶节点对象
15 osg::ref_ptr <osg::Geode > geode = new osg::Geode ();
16 //创建一个几何体对象
17 osg::ref_ptr <osg::Geometry >geom=new osg::Geometry ();
18 //添加顶点数据 注意顶点的添加顺序是逆时针
19 osg::ref_ptr <osg::Vec3Array >v=new osg::Vec3Array ();
20 //添加数据
21 v->push_back (osg::Vec3 (0,0,0));
22 v->push_back (osg::Vec3 (1,0,0));
23 v->push_back (osg::Vec3 (1,0,1));
24 v->push_back (osg::Vec3 (0,0,1));
25
26 //设置顶点数据
27 geom->setVertexArray (v.get ());
28
29 //创建纹理订点数据
30 osg::ref_ptr <osg::Vec2Array >vt=new osg::Vec2Array ();
31 //添加纹理坐标
32 vt->push_back (osg::Vec2 (0,0));
33 vt->push_back (osg::Vec2 (1,0));
34 vt->push_back (osg::Vec2 (1,1));
35 vt->push_back (osg::Vec2 (0,1));
36
37 //设置纹理坐标
38 geom->setTexCoordArray(0,vt.get ());
39
40 //创建颜色数组
41 osg::ref_ptr <osg::Vec4Array >vc=new osg::Vec4Array ();
42 //添加数据
43 vc->push_back (osg::Vec4 (1,0,0,1));
44 vc->push_back (osg::Vec4 (0,1,0,1));
45 vc->push_back (osg::Vec4 (0,0,1,1));
46 vc->push_back (osg::Vec4 (1,1,0,1));
47
48 //设置颜色数组
49 geom->setColorArray (vc.get ());
50 //设置颜色的绑定方式为单个顶点
51 geom->setColorBinding (osg::Geometry ::BIND_PER_VERTEX );
52
53 //创建法线数组
54 osg::ref_ptr <osg::Vec3Array >nc=new osg::Vec3Array ();
55 //添加法线
56 nc->push_back (osg::Vec3 (0,-1,0));
57 //设置法线
58 geom->setNormalArray (nc.get ());
59 //设置法绑定为全部顶点
60 geom->setNormalBinding (osg::Geometry ::BIND_OVERALL );
61 //添加图元
62 geom->addPrimitiveSet (new osg::DrawArrays (osg::PrimitiveSet ::QUADS ,0,4));
63
64 //添加到叶子节点
65 geode->addDrawable (geom.get ());
66
67 return geode.get ();
68
69}
70
71int main(){
72 osg::ref_ptr<osgViewer::Viewer >viewer=new osgViewer::Viewer();
73
74 osg::ref_ptr<osg::Group>root=new osg::Group();
75
76 root->addChild (cteateQuad());
77
78 osgUtil::Optimizer optimizer;
79 optimizer.optimize (root.get ());
80
81 viewer->setSceneData (root.get());
82
83 viewer->realize ();
84
85 viewer->run();
86
87 return 0;
88
89}