class MVPCallback : public osg::Uniform::Callback
{
public:
MVPCallback(osg::Camera* camera) : mCamera(camera)
{
}
virtual void operator()(osg::Uniform* uniform, osg::NodeVisitor* nv)
{
osg::Matrix modelView = mCamera->getViewMatrix();
osg::Matrix projectM = mCamera->getProjectionMatrix();
uniform->set(modelView * projectM);
}
private:
osg::Camera* mCamera;
};
osg::Geometry* createLine2(const std::vector<osg::Vec3d>& allPTs, const std::vector<osg::Vec3d>& colors, osg::Camera* camera)
{
cout << "osg::getGLVersionNumber" << osg::getGLVersionNumber() << endl;
osg::ref_ptr<osg::Vec3Array> a_color = new osg::Vec3Array;
int nCount = allPTs.size();
osg::ref_ptr<osg::Geometry> pGeometry = new osg::Geometry();
osg::ref_ptr<osg::Vec3Array> a_pos = new osg::Vec3Array;
for (int i = 0; i < allPTs.size(); i++)
{
a_pos->push_back(allPTs[i]);
}
const int kLastIndex = allPTs.size() - 1;
osg::ref_ptr<osg::ElementBufferObject> ebo = new osg::ElementBufferObject;
osg::ref_ptr<osg::DrawElementsUInt> indices = new osg::DrawElementsUInt(osg::PrimitiveSet::LINE_STRIP);
std::default_random_engine eng(time(NULL));
std::uniform_real_distribution<float> rand(.3, 1.);
int count = 0;
for (unsigned int i = 0; i < allPTs.size(); i++)
{
if (allPTs[i].x() == -1 && allPTs[i].y() == -1)
{
indices->push_back(kLastIndex);
}
else
{
indices->push_back(i);
}
count++;
a_color->push_back(colors[i]);
}
indices->setElementBufferObject(ebo);
pGeometry->addPrimitiveSet(indices.get());
pGeometry->setUseVertexBufferObjects(true);
osg::StateSet* ss = pGeometry->getOrCreateStateSet();
ss->setAttributeAndModes(new osg::LineWidth(2), osg::StateAttribute::ON);
ss->setMode(GL_LIGHTING, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
ss->setMode(GL_PRIMITIVE_RESTART, osg::StateAttribute::ON);
ss->setAttributeAndModes(new osg::PrimitiveRestartIndex(kLastIndex), osg::StateAttribute::ON);
osg::Program* program = new osg::Program;
program->setName("LINESTRIPE");
program->addShader(osgDB::readShaderFile(osg::Shader::VERTEX, shader_dir() + "/line_stripe2.vert"));
program->addShader(osgDB::readShaderFile(osg::Shader::FRAGMENT, shader_dir() + "/line_stripe2.frag"));
ss->setAttributeAndModes(program, osg::StateAttribute::ON);
pGeometry->setVertexArray(a_pos);
pGeometry->setVertexAttribArray(0, a_pos, osg::Array::BIND_PER_VERTEX);
pGeometry->setVertexAttribBinding(0, osg::Geometry::BIND_PER_VERTEX);
program->addBindAttribLocation("a_pos", 0);
pGeometry->setVertexAttribArray(1, a_color, osg::Array::BIND_PER_VERTEX);
pGeometry->setVertexAttribBinding(1, osg::Geometry::BIND_PER_VERTEX);
program->addBindAttribLocation("a_color", 1);
osg::Uniform* u_MVP(new osg::Uniform(osg::Uniform::FLOAT_MAT4, "u_MVP"));
u_MVP->setUpdateCallback(new MVPCallback(camera));
ss->addUniform(u_MVP);
return pGeometry.release();
}