繪制并渲染幾何體主要有一下3步:
1.創(chuàng)建各種向量數(shù)據(jù),例如頂點、紋理坐標(biāo)、顏色、法線<逆時針添加坐標(biāo)數(shù)據(jù)>.
2.實例化一個幾何體對象(osg::geometry),設(shè)置頂點坐標(biāo)數(shù)組、紋理坐標(biāo)數(shù)組、顏色坐標(biāo)數(shù)組、法線數(shù)組、綁定方式及數(shù)據(jù)解析格式.
3.加入葉節(jié)點繪制渲染.
基本繪制:
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
//創(chuàng)建一個四邊形節(jié)點
13
osg::ref_ptr <osg::Node >cteateQuad()
{
14
//創(chuàng)建一個葉節(jié)點對象
15
osg::ref_ptr <osg::Geode > geode = new osg::Geode ();
16
//創(chuàng)建一個幾何體對象
17
osg::ref_ptr <osg::Geometry >geom=new osg::Geometry ();
18
//添加頂點數(shù)據(jù) 注意頂點的添加順序是逆時針
19
osg::ref_ptr <osg::Vec3Array >v=new osg::Vec3Array ();
20
//添加數(shù)據(jù)
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
//設(shè)置頂點數(shù)據(jù)
27
geom->setVertexArray (v.get ());
28
29
//創(chuàng)建紋理訂點數(shù)據(jù)
30
osg::ref_ptr <osg::Vec2Array >vt=new osg::Vec2Array ();
31
//添加紋理坐標(biāo)
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
//設(shè)置紋理坐標(biāo)
38
geom->setTexCoordArray(0,vt.get ());
39
40
//創(chuàng)建顏色數(shù)組
41
osg::ref_ptr <osg::Vec4Array >vc=new osg::Vec4Array ();
42
//添加數(shù)據(jù)
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
//設(shè)置顏色數(shù)組
49
geom->setColorArray (vc.get ());
50
//設(shè)置顏色的綁定方式為單個頂點
51
geom->setColorBinding (osg::Geometry ::BIND_PER_VERTEX );
52
53
//創(chuàng)建法線數(shù)組
54
osg::ref_ptr <osg::Vec3Array >nc=new osg::Vec3Array ();
55
//添加法線
56
nc->push_back (osg::Vec3 (0,-1,0));
57
//設(shè)置法線
58
geom->setNormalArray (nc.get ());
59
//設(shè)置法綁定為全部頂點
60
geom->setNormalBinding (osg::Geometry ::BIND_OVERALL );
61
//添加圖元
62
geom->addPrimitiveSet (new osg::DrawArrays (osg::PrimitiveSet ::QUADS ,0,4));
63
64
//添加到葉子節(jié)點
65
geode->addDrawable (geom.get ());
66
67
return geode.get ();
68
69
}
70
71
int 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
}