#include <osgViewer/Viewer>
#include <osg/MatrixTransform>
#include <osgDB/ReadFile>
#include <osg/Callback>
#include <osgAnimation/Animation>
class RotateCallback : public osg
::NodeCallback
{
public:
RotateCallback(osgAnimation
::Animation
*dls
)
{
_startTick
= osg
::Timer
::instance()->tick();
_animation
= dls
;
}
virtual void operator()(osg
::Node
* node
, osg
::NodeVisitor
* nv
)
{
osg
::MatrixTransform
*mt
= dynamic_cast<osg
::MatrixTransform
*>(node
);
if (mt
)
{
double currentTick
= osg
::Timer
::instance()->tick();
double elaspedTime
= osg
::Timer
::instance()->delta_s(_startTick
, currentTick
);
_animation
->resetTargets();
_animation
->setPlayMode(osgAnimation
::Animation
::LOOP
);
_animation
->update(elaspedTime
);
_animation
->setWeight(1.0);
osgAnimation
::ChannelList cls
= _animation
->getChannels();
double currentRot
= dynamic_cast<osgAnimation
::DoubleTarget
*>(cls
.at(0)->getTarget())->getValue();
osg
::Quat
rotQuat(currentRot
, osg
::Z_AXIS
);
osg
::Matrix
rotMatrix(rotQuat
);
mt
->setMatrix(rotMatrix
);
}
traverse(node
, nv
);
}
protected:
osgAnimation
::Animation
* _animation
;
double _startTick
;
};
int main()
{
osg
::ref_ptr
<osgViewer
::Viewer
> viewer
= new osgViewer
::Viewer
;
osg
::ref_ptr
<osg
::Node
> cowNode
= osgDB
::readNodeFile("cow.osg");
osg
::ref_ptr
<osg
::MatrixTransform
> root
= new osg
::MatrixTransform
;
root
->addChild(cowNode
);
osgAnimation
::DoubleKeyframe
keyframe1(0.0, 0.0);
osgAnimation
::DoubleKeyframe
keyframe2(10.0, osg
::PI
* 2);
osg
::ref_ptr
<osgAnimation
::DoubleKeyframeContainer
> keyframeContainer
= new osgAnimation
::DoubleKeyframeContainer();
keyframeContainer
->push_back(keyframe1
);
keyframeContainer
->push_back(keyframe2
);
osg
::ref_ptr
<osgAnimation
::DoubleLinearSampler
> sampler
= new osgAnimation
::DoubleLinearSampler();
sampler
->setKeyframeContainer(keyframeContainer
.get());
osg
::ref_ptr
<osgAnimation
::DoubleLinearChannel
> channel
= new osgAnimation
::DoubleLinearChannel();
channel
->setSampler(sampler
.get());
osg
::ref_ptr
<osgAnimation
::Animation
> animation
= new osgAnimation
::Animation();
animation
->addChannel(channel
.get());
root
->addUpdateCallback(new RotateCallback(animation
.get()));
viewer
->setUpViewInWindow(200, 200, 800, 600);
viewer
->setSceneData(root
);
return viewer
->run();
}
转载请注明原文地址:https://blackberry.8miu.com/read-36652.html