poljak181

OSG. Fixed size texture problem

Aug 4th, 2015
439
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.37 KB | None | 0 0
  1. #include <osg/MatrixTransform>
  2. #include <osg/Texture2D>
  3. #include <osg/Geode>
  4. #include <osg/AutoTransform>
  5.  
  6. #include <osgDB/ReadFile>
  7.  
  8. #include <osgViewer/Viewer>
  9.  
  10. osg::ref_ptr<osg::Node> createFixedSizeTexture(double x, double y, osg::Image *image)
  11. {
  12.     float imageWidth = image->s();
  13.     float imageHeight = image->t();
  14.  
  15.     osg::Vec3Array* verts = new osg::Vec3Array(4);
  16.     (*verts)[0] = osg::Vec3(x - imageWidth/2.0f, y - imageHeight/2.0, 0.0f);
  17.     (*verts)[1] = osg::Vec3(x + imageWidth/2.0f, y - imageHeight/2.0, 0.0f);
  18.     (*verts)[2] = osg::Vec3(x + imageWidth/2.0f, y + imageHeight/2.0, 0.0f);
  19.     (*verts)[3] = osg::Vec3(x - imageWidth/2.0f, y + imageHeight/2.0, 0.0f);
  20.  
  21.     osg::Vec2Array* texcoords = new osg::Vec2Array(4);
  22.     (*texcoords)[0].set(0.0f , 0.0f);
  23.     (*texcoords)[1].set(1.0f , 0.0f);
  24.     (*texcoords)[2].set(1.0f , 1.0f);
  25.     (*texcoords)[3].set(0.0f , 1.0f);
  26.  
  27.     osg::Vec4Array* colors = new osg::Vec4Array(1);
  28.     (*colors)[0].set(1, 1, 1, 1);
  29.  
  30.     osg::Geometry* geometry = new osg::Geometry;
  31.     geometry->setVertexArray( verts );
  32.     geometry->setTexCoordArray(0, texcoords);
  33.     geometry->setColorArray( colors );
  34.     geometry->setColorBinding( osg::Geometry::BIND_OVERALL );
  35.     geometry->addPrimitiveSet( new osg::DrawArrays(GL_QUADS, 0, 4));
  36.  
  37.     osg::Texture2D* texture = new osg::Texture2D( image );
  38.     texture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
  39.     texture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
  40.  
  41.     osg::StateSet* stateSet = geometry->getOrCreateStateSet();
  42.     stateSet->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);
  43.     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
  44.     stateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
  45.  
  46.     osg::Geode* geode = new osg::Geode;
  47.     geode->addDrawable( geometry );
  48.  
  49.     return geode;
  50. }
  51.  
  52. int main(int argc, char **argv)
  53. {
  54.     osg::setNotifyLevel(osg::WARN);
  55.  
  56.     osg::AutoTransform *at = new osg::AutoTransform;
  57.     at->setAutoScaleToScreen(true);
  58.     at->setAutoRotateMode( osg::AutoTransform::ROTATE_TO_SCREEN );
  59.  
  60.     osg::ref_ptr<osg::Image> image = osgDB::readImageFile("track_8x8.png");
  61.     at->addChild(createFixedSizeTexture(0, 0, image.get()));
  62.  
  63.     osgViewer::Viewer viewer;
  64.     viewer.setUpViewInWindow(0, 0, 640, 480);
  65.     viewer.setSceneData(at);
  66.  
  67.     return viewer.run();
  68. }
Advertisement
Add Comment
Please, Sign In to add comment