效果图:
代码示例:
#include <osgViewer/Viewer>
#include <osg/Node>
#include <osg/Geode>
#include <osg/Group>
#include <osg/Camera>
#include <osg/ShapeDrawable>
#include <osg/ComputeBoundsVisitor>
#include <osg/BoundingBox>
#include <osg/BoundingSphere>
#include <osg/AnimationPath>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgShadow/ShadowedScene>
#include <osgShadow/ShadowVolume>
#include <osgShadow/ShadowTexture>
#include <osgShadow/ShadowMap>
#include <osgShadow/SoftShadowMap>
#include <osgShadow/ParallelSplitShadowMap>
#include <osgUtil/Optimizer>
#include <iostream>
//标识阴影接收对象
const int ReceivesShadowTraversalMask = 0x1;
//标识阴影投影对象
const int CastsShadowTraversalMask = 0x2;
//创建场景数据
osg::ref_ptr<osg::Node> createModel()
{
osg::Vec3 center(0.0f, 0.0f, 0.0f);
float radius = 100.0f;
osg::Vec3 lightPosition(center + osg::Vec3(0.0f, 0.0f, radius));
osg::ref_ptr<osg::Node> shadower = osgDB::readNodeFile("D:\OSGmodel\WKZ005_JZ_24.OSGB");
shadower->setNodeMask(CastsShadowTraversalMask);
osg::ref_ptr<osg::Node> shadowed = osgDB::readNodeFile("D:\OSGmodel\floor.OSGB");
shadowed->setNodeMask(ReceivesShadowTraversalMask);
osg::ref_ptr<osg::Group> group = new osg::Group;
group->addChild(shadowed.get());
group->addChild(shadower.get());
return group.get();
}
//创建一个光照
osg::ref_ptr<osg::Node> createLight(osg::ref_ptr<osg::Node> model)
{
osg::ComputeBoundsVisitor cbbv;
model->accept(cbbv);
osg::BoundingBox bb = cbbv.getBoundingBox();
osg::Vec4 lightpos;
lightpos.set(bb.center().x(), bb.center().y(), bb.zMax() + bb.radius()*2.0f, 1.0f);
osg::ref_ptr<osg::LightSource> ls = new osg::LightSource();
ls->getLight()->setPosition(lightpos);
ls->getLight()->setAmbient(osg::Vec4(0.2, 0.2, 0.2, 1.0));
ls->getLight()->setDiffuse(osg::Vec4(0.8, 0.8, 0.8, 1.0));
return ls.get();
}
int main()
{
osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer();
osg::ref_ptr<osg::Group> root = new osg::Group();
//创建一个阴影节点,并标识接收对象和投影对象
osg::ref_ptr<osgShadow::ShadowedScene> shadowedScene = new osgShadow::ShadowedScene();
shadowedScene->setReceivesShadowTraversalMask(ReceivesShadowTraversalMask);
shadowedScene->setCastsShadowTraversalMask(CastsShadowTraversalMask);
//创建阴影纹理
osg::ref_ptr<osgShadow::ShadowTexture> st = new osgShadow::ShadowTexture();
//关联阴影纹理
shadowedScene->setShadowTechnique(st);
osg::ref_ptr<osg::Node> node = new osg::Node();
node = createModel();
//添加场景数据并添加光源
shadowedScene->addChild(createLight(node.get()));
shadowedScene->addChild(node.get());
root->addChild(shadowedScene.get());
//优化场景数据
osgUtil::Optimizer optimizer;
optimizer.optimize(root.get());
viewer->setSceneData(root.get());
viewer->realize();
viewer->run();
return 0;
}
注:模型的路径需要修改。
附加:图中两个模型下载。