Skip to content

Instantly share code, notes, and snippets.

@gwaldron
Last active March 11, 2021 13:20
Show Gist options
  • Save gwaldron/8728f5278de2a6c213a86ba16ecd1f42 to your computer and use it in GitHub Desktop.
Save gwaldron/8728f5278de2a6c213a86ba16ecd1f42 to your computer and use it in GitHub Desktop.
GLSL model outline for OSG
#include <osgViewer/Viewer>
#include <osg/Depth>
#include <osg/Program>
#include <osg/Uniform>
#include <osgDB/ReadFile>
int
main(int argc, char** argv)
{
osg::ArgumentParser arguments(&argc,argv);
osg::Node* node = osgDB::readNodeFiles(arguments);
if ( !node )
return -1;
const char* VS =
"#version 330 compatibility \n"
"uniform float outlineWidth; \n"
"void main()"
"{ \n"
" vec4 clip = gl_ModelViewProjectionMatrix * gl_Vertex; \n"
" vec3 normal = normalize(gl_NormalMatrix * gl_Normal); \n"
" normal.x *= gl_ProjectionMatrix[0][0]; \n"
" normal.y *= gl_ProjectionMatrix[1][1]; \n"
" clip.xy += normal.xy * clip.w * outlineWidth;\n"
" gl_Position = clip; \n"
"} \n";
const char* FS =
"#version 330\n"
"void main() \n"
"{ \n"
" gl_FragColor = vec4(1,0,0,1); \n"
"} \n";
osg::Program* program = new osg::Program();
program->addShader(new osg::Shader(osg::Shader::VERTEX, VS));
program->addShader(new osg::Shader(osg::Shader::FRAGMENT, FS));
osg::Group* outline = new osg::Group();
osg::StateSet* outlineSS = outline->getOrCreateStateSet();
outlineSS->setRenderBinDetails(1, "RenderBin");
outlineSS->setAttributeAndModes(new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false));
outlineSS->setMode(GL_CULL_FACE, 0);
outlineSS->setAttribute(program);
outlineSS->addUniform(new osg::Uniform("outlineWidth", 0.002f));
outline->addChild(node);
osg::Group* model = new osg::Group();
model->getOrCreateStateSet()->setRenderBinDetails(2, "RenderBin");
model->addChild(node);
osg::Group* root = new osg::Group();
root->addChild(outline);
root->addChild(model);
osgViewer::Viewer viewer(arguments);
viewer.setSceneData(root);
return viewer.run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment