Пример #1
0
AppState::AppState(osgViewer::Viewer* viewer_)
    : displayScene(true), invertRange(true), currentConfig(0),
      viewer(viewer_), zNear(0.03125)
{
    sw = new Switch;
    string fontName("fonts/arial.ttf");
    // Text description of current config
    configText = new osgText::Text;
    configText->setDataVariance(Object::DYNAMIC);
    configText->setFont(fontName);
    configText->setPosition(Vec3(50.0f, 50.0f, 0.0f));
    configText->setColor(Vec4(1.0, 1.0, 1.0, 1.0));
    Geode* textGeode = new Geode;
    textGeode->addDrawable(configText.get());
    // Text for the near plane distance
    zNearText = new osgText::Text;
    zNearText->setDataVariance(Object::DYNAMIC);
    zNearText->setFont(fontName);
    zNearText->setPosition(Vec3(1230.0f, 50.0f, 0.0f));
    zNearText->setColor(Vec4(1.0, 1.0, 1.0, 1.0));
    zNearText->setAlignment(osgText::Text::RIGHT_BASE_LINE);
    textGeode->addDrawable(zNearText.get());
    // Projection that lets the text be placed in pixels.
    textProjection = new Projection;
    textProjection->setMatrix(Matrix::ortho2D(0,1280,0,1024));
    textProjection->addChild(textGeode);
    // "texture not available" text displayed when the user trys to
    // display the depth texture while multisampling.
    osgText::Text* noCanDo = new osgText::Text;
    noCanDo->setFont(fontName);
    noCanDo->setPosition(Vec3(512.0f, 384.0f, 0.0f));
    noCanDo->setColor(Vec4(1.0, 0.0, 0.0, 1.0));
    noCanDo->setText("not available");
    textNotAvailable = new Geode;
    textNotAvailable->addDrawable(noCanDo);
    textProjection->addChild(textNotAvailable.get());
    // Is the depth test inverted?
    osgText::Text* inverted = new osgText::Text;
    inverted->setFont(fontName);
    inverted->setPosition(Vec3(512.0f, 50.0f, 0.0f));
    inverted->setColor(Vec4(1.0, 1.0, 1.0, 1.0));
    inverted->setText("inverted depth test");
    textInverted = new Geode;
    textInverted->addDrawable(inverted);
    textInverted->setNodeMask(~0u);
    textProjection->addChild(textInverted.get());
    textProjection->getOrCreateStateSet()->setRenderBinDetails(11, "RenderBin");
}
/***************************************************************
* Function: createText()
***************************************************************/
Geode *CAVEGroupReferenceAxis::createText3D(osgText::Text3D **text)
{
    Geode *textGeode = new Geode;
    *text = new osgText::Text3D;
    textGeode->addDrawable(*text);

    (*text)->setFont(CAVEGeode::getDataDir() + "Fonts/TN.ttf");
    (*text)->setCharacterSize(gCharSize, 0.7);
    (*text)->setCharacterDepth(gCharDepth);
    (*text)->setPosition(Vec3(0, 0, 0));
    (*text)->setAlignment(osgText::Text3D::CENTER_BOTTOM);
    (*text)->setDrawMode(osgText::Text3D::TEXT);
    (*text)->setAxisAlignment(osgText::Text3D::XZ_PLANE);
    (*text)->setRenderMode(osgText::Text3D::PER_GLYPH);
    (*text)->setText("");

    Material *material = new Material;
    material->setDiffuse(Material::FRONT_AND_BACK, Vec4(0, 1, 0, 1));
    material->setAmbient(Material::FRONT_AND_BACK, Vec4(0, 1, 0, 1));
    material->setAlpha(Material::FRONT_AND_BACK, 1.0f);

    StateSet *stateset = textGeode->getOrCreateStateSet();
    stateset->setAttributeAndModes(material, StateAttribute::OVERRIDE | StateAttribute::ON);
    stateset->setMode(GL_BLEND, StateAttribute::OVERRIDE | StateAttribute::ON );
    stateset->setRenderingHint(StateSet::TRANSPARENT_BIN);

    return textGeode;
}
Пример #3
0
Geode* createTextureQuad(Texture2D *texture)
{
    Vec3Array *vertices = new Vec3Array;
    vertices->push_back(Vec3(-1.0, -1.0, 0.0));
    vertices->push_back(Vec3(1.0, -1.0, 0.0));
    vertices->push_back(Vec3(1.0, 1.0, 0.0));
    vertices->push_back(Vec3(-1.0, 1.0, 0.0));

    Vec2Array *texcoord = new Vec2Array;
    texcoord->push_back(Vec2(0.0, 0.0));
    texcoord->push_back(Vec2(1.0, 0.0));
    texcoord->push_back(Vec2(1.0, 1.0));
    texcoord->push_back(Vec2(0.0, 1.0));

    Geometry *geom = new Geometry;
    geom->setVertexArray(vertices);
    geom->setTexCoordArray(0, texcoord);
    geom->addPrimitiveSet(new DrawArrays(GL_QUADS, 0, 4));

    Geode *geode = new Geode;
    geode->addDrawable(geom);
    geode->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture, StateAttribute::ON);

    return geode;
}
Пример #4
0
void _dwobj::buildDrawable(Group *grp, const osgDB::ReaderWriter::Options *options)
{  // current DWobject complete; make a drawable, and add it to a osg::Group
    if (nfaces>0) {
        if (themat->isType(dwmaterial::PointLight) || themat->isType(dwmaterial::SpotLight)) {
            Vec4 pos;
            pos.set(0.0f,0.0f,0.0f,0.0f);
            for (int i=0; i<nverts; i++) {
                pos[0]+=verts[i].x();
                pos[1]+=verts[i].y();
                pos[2]+=verts[i].z();
            }
            pos/=nverts;
            pos[3]=1.0f;
            LightSource *ls=themat->makeLight(pos);
            grp->addChild(ls);
        } else {
            Geode *geode = new Geode;
            int nfnvf=0; // number of vertices for faces plus holes
            int i; // a general counter
            for (i=0; i<nfaces; i++) { // for each face
                faces[i].setnorm(verts); // set its normal and any hole normals
                nfnvf+=faces[i].getallverts(); // get total vertices in object, defines dimensions of NEW arrays
            }


            GLUtesselator* ts=gluNewTess();
            gluTessCallback(ts, GLU_TESS_BEGIN, (GLU_TESS_CALLBACK) myFaceBegin);
            gluTessCallback(ts, GLU_TESS_VERTEX, (GLU_TESS_CALLBACK) myVertex);
            gluTessCallback(ts, GLU_TESS_END, (GLU_TESS_CALLBACK) myFaceEnd);
            gluTessCallback(ts, GLU_TESS_ERROR, (GLU_TESS_CALLBACK) error);
            gluTessCallback(ts, GLU_TESS_COMBINE_DATA, (GLU_TESS_CALLBACK) combineCallback);
            //  for (int nvf=0; nvf<6; nvf++) { // for each length of face
            // for Geometry we dont need to collect prim types individually
            //     prd.setmode(nvf , nfnvf); // filter out only this type of tessellated face
            prd=new prims;
            prd->settmat(tmat.get());
            osg::Geometry *gset = new osg::Geometry;
            prd->setGeometry(gset);
            StateSet *dstate=themat->make(options);
            gset->setStateSet( dstate );
            grp->addChild( geode ); // add to the world outside
            geode->addDrawable(gset);

            // each face adds a primitive to the geometry, after it is tessellated
            for (i=0; i<nfaces; i++) { // for each face, collect up
                prd->tessellate(faces[i],verts, themat, ts, this);
            }
            for (i=0; i<nopens; i++) { // for each hole, join up front & back with Quads
                if (fc1 && fc2) {
                    faces[fc1[i]].link(openings[i*2], &faces[fc2[i]],openings[i*2+1],verts, themat);
                }
            } // for each opening
            prd->buildGeometry();
        gluDeleteTess(ts);
        delete prd;
        }
    } // nfaces>0
    verts.clear();
}
Пример #5
0
Geode* ChessUtils::createRectangleWithTexture(Vec3 centerPosition, Image* image, int width, int height, Vec4 color) {
	int halfWidth = width / 2;
	int halfHeight = height / 2;

	Vec3Array* vertices = new Vec3Array();	
	vertices->push_back(Vec3(centerPosition.x() - halfWidth, centerPosition.y() - halfHeight, centerPosition.z()));
	vertices->push_back(Vec3(centerPosition.x() + halfWidth, centerPosition.y() - halfHeight, centerPosition.z()));
	vertices->push_back(Vec3(centerPosition.x() + halfWidth, centerPosition.y() + halfHeight, centerPosition.z()));
	vertices->push_back(Vec3(centerPosition.x() - halfWidth, centerPosition.y() + halfHeight, centerPosition.z()));

	Vec3Array* normals = new Vec3Array();
	normals->push_back(Vec3(0.0f, 0.0f, 1.0f));

	Vec2Array* texcoords = new Vec2Array();
	texcoords->push_back(Vec2(0.0f, 0.0f));
	texcoords->push_back(Vec2(1.0f, 0.0f));
	texcoords->push_back(Vec2(1.0f, 1.0f));
	texcoords->push_back(Vec2(0.0f, 1.0f));

	Vec4Array* colors = new Vec4Array();
	colors->push_back(color);

	Geometry* quad = new Geometry();
	quad->setVertexArray(vertices);
	quad->setNormalArray(normals);
	quad->setNormalBinding(osg::Geometry::BIND_OVERALL);	
	quad->setColorArray(colors);
	quad->setColorBinding(osg::Geometry::BIND_OVERALL);
	quad->setTexCoordArray(0, texcoords);
	quad->addPrimitiveSet(new osg::DrawArrays(GL_QUADS, 0, 4));

	Texture2D* texture = new Texture2D();
	if (image != NULL) {
		texture->setImage(image);
	}			

	Geode* geode = new Geode();
	geode->addDrawable(quad);

	osg::BlendFunc* blendFunc = new osg::BlendFunc();
	blendFunc->setFunction(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	osg::TexEnv* blendTexEnv = new osg::TexEnv();
	blendTexEnv->setMode(osg::TexEnv::BLEND);

	osg::StateSet* geodeStateset = geode->getOrCreateStateSet();
	geodeStateset->setAttributeAndModes(blendFunc);
	geodeStateset->setTextureAttribute(0, blendTexEnv);
	geodeStateset->setTextureAttributeAndModes(0, texture);
	geodeStateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
	
	return geode;
}
Пример #6
0
Geode *Marker::createBox(Vec4 &color)
{
    Geode *geode = new Geode();

    TessellationHints *hints = new TessellationHints();
    hints->setDetailRatio(0.3f);

    Vec3 boxCenter(0.0f, 0.0f, 0.0f);
    _boxShape = new Box(boxCenter, 1.0f);
    _shapeDrawable = new ShapeDrawable(_boxShape);
    _shapeDrawable->setTessellationHints(hints);
    _shapeDrawable->setColor(color);
    geode->addDrawable(_shapeDrawable);
    _shapeDrawable->setUseDisplayList(false); // allow changes to color and shape
    return geode;
}
Пример #7
0
OpenRAVE::GraphHandlePtr OSGViewer::plot3(const float* ppoints, int numPoints, int stride, float pointsize, const float* colors, int drawstyle, bool bhasalpha) {

  osg::Geometry* geom = new osg::Geometry;


  int floats_per_pt = stride / sizeof(float);

  Vec3Array* osgPts = new Vec3Array;
  osgPts->reserve(numPoints);
  for (int i=0; i < numPoints; ++i) {
    const float* p = ppoints + i*floats_per_pt;
    if (isfinite(p[0]))  osgPts->push_back(osg::Vec3(p[0], p[1], p[2]));
  }
  osg::StateSet* ss = geom->getOrCreateStateSet();
  osg::Point *point = new osg::Point();
  point->setSize(pointsize);
  ss->setAttribute(point);

  ss->setMode(GL_LIGHTING, osg::StateAttribute::OFF);

  osg::BlendFunc* blendFunc = new osg::BlendFunc;
  blendFunc->setFunction(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  ss->setAttributeAndModes(blendFunc);
  ss->setMode(GL_BLEND, osg::StateAttribute::ON);

  geom->setVertexArray(osgPts);
  geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::POINTS,0,osgPts->size()));
//
//  if (colors != NULL) {
//    Vec4Array* osgCols = new Vec4Array;
//    for (int i=0; i < numPoints; ++i) {
//      float* p = colors + i;
//      osgCols->push_back(osg::Vec4(p[0], p[1], p[2],1));
//    }
//    geom->setColorArray(osgCols);
//    geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
//  }

  Geode* geode = new osg::Geode();
  geode->addDrawable(geom);

  return GraphHandlePtr(new OsgGraphHandle(geode, m_root.get()));
}
Пример #8
0
Geode *Marker::createSphere(Vec4 &color)
{
    Geode *geode = new Geode();

    // setDetailRatio is a factor to multiply the default values for
    // numSegments (40) and numRows (10).
    // They won't go below the minimum values of MIN_NUM_SEGMENTS = 5, MIN_NUM_ROWS = 3
    TessellationHints *hints = new TessellationHints();
    hints->setDetailRatio(0.3f);

    Vec3 sphereCenter(0.0f, 0.0f, 0.0f);
    _sphereShape = new Sphere(sphereCenter, 1.0f);
    _shapeDrawable = new ShapeDrawable(_sphereShape);
    _shapeDrawable->setTessellationHints(hints);
    _shapeDrawable->setColor(color);
    geode->addDrawable(_shapeDrawable);
    _shapeDrawable->setUseDisplayList(false); // allow changes to color and shape
    return geode;
}
Пример #9
0
void World::addDrawable(Drawable::Drawable *drawable,
			 			Transform *transform, std::string name)
{
	// adding all to top-level group for now
	Geode *geo = new Geode;
	geo->addDrawable(drawable);
	if(transform) {
		transform->addChild(geo);
		_root->addChild(transform);
	} else {
		_root->addChild(geo);
	}

	if(!name.empty()) {
		_names[name] = drawable;
	}

	//notifyViews();
}
Пример #10
0
PositionAttitudeTransform *VideoGeode::createVideoSphere(float size, bool texRepeat)
{
	Geode *sphere = new Geode();
	sphere->addDrawable(new ShapeDrawable(new Sphere(Vec3(0, 0, 4), size)));
	
	// assign the material to the sphere
	StateSet *sphereStateSet = sphere->getOrCreateStateSet();
	sphereStateSet->ref();
	sphereStateSet->setAttribute(_material);
	
   try {
      sphereStateSet->setTextureAttributeAndModes(0, createVideoTexture(texRepeat), StateAttribute::ON);
   } catch (char *e) {
      throw e;
   }
	
	PositionAttitudeTransform *sphereTransform = new PositionAttitudeTransform();
	sphereTransform->addChild(sphere);
	return sphereTransform;
}
Пример #11
0
Geode *Marker::createCone(Vec4 &color)
{
    Geode *geode = new Geode();

    // setDetailRatio is a factor to multiply the default values for
    // numSegments (40) and numRows (10).
    // They won't go below the minimum values of MIN_NUM_SEGMENTS = 5, MIN_NUM_ROWS = 3
    TessellationHints *hints = new TessellationHints();
    hints->setDetailRatio(0.3f);

    // Create cone geometry:
    _coneShape = new Cone(Vec3(0, 0, 0), 0.1f, 0.5f); // center, radius, height
    _shapeDrawable = new ShapeDrawable(_coneShape);
    _shapeDrawable->setTessellationHints(hints);
    _shapeDrawable->setColor(color);
    _shapeDrawable->setUseDisplayList(false); // allow changes to color and shape

    geode->addDrawable(_shapeDrawable);
    return geode;
}
Пример #12
0
Group* CreateBomb()
{
	MatrixTransform *matrix_trans = new MatrixTransform();
	Matrix *matrix = new Matrix();
	Geode *node = new Geode();
	float radius = 10;

	//创建精细度对象,精细度越高,细分就越多
	osg::TessellationHints* hints = new osg::TessellationHints;
	//设置精细度为0.5f
	hints->setDetailRatio(0.5f);

	//添加一个球体,第一个参数是预定义几何体对象,第二个是精细度,默认为0
	node->addDrawable(new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0, 100, 300), radius),hints));

	matrix_trans->addChild(node);
	matrix_trans->setUpdateCallback(new BombCallback(Vec3(0,100,300)));
	//matrix_trans->setDataVariance(osg::Object::DYNAMIC);
	return matrix_trans;
}
Пример #13
0
TFColorWidget::TFColorWidget(Interaction *interaction, Measure *b, int size)
    : Widget()
    , Events()
{
    _interaction = interaction;

    Geode *geode = new Geode();

    _geom = new Geometry();
    _geom->setUseDisplayList(false);

    _vertices = new Vec3Array();
    _vertices->push_back(Vec3(0, 0, 0));
    _vertices->push_back(Vec3(0, 0, .2));
    _vector = (*_vertices)[1] - (*_vertices)[0];
    _vector.normalize();
    _geom->setVertexArray(_vertices);

    DrawElementsUInt *line = new DrawElementsUInt(osg::PrimitiveSet::LINES, 0);
    line->push_back(0);
    line->push_back(1);
    _geom->addPrimitiveSet(line);

    _colors = new Vec4Array(1);
    (*_colors)[0].set(0.0, 0.0, 0.0, 1.0);
    _geom->setColorArray(_colors);
    _geom->setColorBinding(osg::Geometry::BIND_OVERALL);

    geode->addDrawable(_geom);

    _node->addChild(geode);

    LineWidth *width = new LineWidth();
    width->setWidth(size);
    StateSet *state = _geom->getOrCreateStateSet();
    state->setAttribute(width, osg::StateAttribute::ON);
    state->setMode(GL_LIGHTING, StateAttribute::OFF);

    _interaction->addListener(this, this);
}
Пример #14
0
OpenRAVE::GraphHandlePtr  OSGViewer::drawlinelist(const float *ppoints,  int numPoints, int stride, float fwidth, const RaveVectorf &color) {

  osg::Geometry* geom = new osg::Geometry;

  int floats_per_pt = stride / sizeof(float);

  Vec3Array* osgPts = new Vec3Array;
  osgPts->reserve(numPoints);
  for (int i=0; i < numPoints; ++i) {
    const float* p = ppoints + i*floats_per_pt;
    if (isfinite(p[0]))  osgPts->push_back(osg::Vec3(p[0], p[1], p[2]));
  }
  osg::StateSet* ss = geom->getOrCreateStateSet();
  osg::LineWidth *lw= new osg::LineWidth;
  lw->setWidth(fwidth);
  ss->setAttribute(lw);

  ss->setMode(GL_LIGHTING, osg::StateAttribute::OFF);

  osg::BlendFunc* blendFunc = new osg::BlendFunc;
  blendFunc->setFunction(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  ss->setAttributeAndModes(blendFunc);
  ss->setMode(GL_BLEND, osg::StateAttribute::ON);

  osg::Vec4Array* osgColor = new osg::Vec4Array();
  osgColor->push_back( osg::Vec4( color[0], color[1], color[2], color[3] ) );
  geom->setColorArray(osgColor);
  geom->setColorBinding(osg::Geometry::BIND_OVERALL);

  geom->setVertexArray(osgPts);
  geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES,0,osgPts->size()));


  Geode* geode = new osg::Geode();
  geode->addDrawable(geom);

  return GraphHandlePtr(new OsgGraphHandle(geode, m_root.get()));
}
Пример #15
0
Geode *ClipPlanePlugin::loadPlane()
{

    // *5---*6---*7
    // |    |    |
    // *3--------*4
    // |    |    |
    // *0---*1---*2

    float w = cover->getSceneSize() * 0.1; // width of plane

    Vec3Array *lineCoords = new Vec3Array(12);
    (*lineCoords)[0].set(-w, -0.01, -w);
    (*lineCoords)[1].set(w, -0.01, -w);
    (*lineCoords)[2].set(-w, -0.01, 0.0f);
    (*lineCoords)[3].set(w, -0.01, 0.0f);
    (*lineCoords)[4].set(-w, -0.01, w);
    (*lineCoords)[5].set(w, -0.01, w);
    (*lineCoords)[6].set(-w, -0.01, -w);
    (*lineCoords)[7].set(-w, -0.01, w);
    (*lineCoords)[8].set(0.0f, -0.01, -w);
    (*lineCoords)[9].set(0.0f, -0.01, w);
    (*lineCoords)[10].set(w, -0.01, -w);
    (*lineCoords)[11].set(w, -0.01, w);

    DrawArrayLengths *primitives = new DrawArrayLengths(PrimitiveSet::LINE_STRIP);
    for (int i = 0; i < 6; i++)
    {
        primitives->push_back(2);
    }

    Vec3Array *lineColors = new Vec3Array(12);
    for (int i = 0; i < 12; i++)
    {
        (*lineColors)[i].set(Vec3(1.0f, 1.0f, 1.0f));
    }

    Geometry *geoset = new Geometry();
    geoset->setVertexArray(lineCoords);
    geoset->addPrimitiveSet(primitives);
    geoset->setColorArray(lineColors);

    Material *mtl = new Material;
    mtl->setColorMode(Material::AMBIENT_AND_DIFFUSE);
    mtl->setAmbient(Material::FRONT_AND_BACK, Vec4(0.2f, 0.2f, 0.2f, 1.0f));
    mtl->setDiffuse(Material::FRONT_AND_BACK, Vec4(0.9f, 0.9f, 0.9f, 1.0f));
    mtl->setSpecular(Material::FRONT_AND_BACK, Vec4(0.9f, 0.9f, 0.9f, 1.0f));
    mtl->setEmission(Material::FRONT_AND_BACK, Vec4(0.0f, 0.0f, 0.0f, 1.0f));
    mtl->setShininess(Material::FRONT_AND_BACK, 16.0f);

    Geode *geode = new Geode;
    geode->setName("ClipPlane");
    geode->addDrawable(geoset);

    StateSet *geostate = geode->getOrCreateStateSet();
    geostate->setAttributeAndModes(mtl, StateAttribute::ON);
    geostate->setMode(GL_LIGHTING, StateAttribute::OFF);
    LineWidth *lineWidth = new LineWidth(3.0);
    geostate->setAttributeAndModes(lineWidth, StateAttribute::ON);
    geode->setStateSet(geostate);

    return geode;
}
/***************************************************************
* Function: createFloorplanGeometry()
***************************************************************/
void VirtualScenicHandler::createFloorplanGeometry(const int numPages, 
    CAVEAnimationModeler::ANIMPageEntry **pageEntryArray)
{
    if (numPages <= 0)
    {
        return;
    }

    for (int i = 0; i < numPages; i++)
    {
        // create floorplan geometry
        float length = pageEntryArray[i]->mLength;
        float width = pageEntryArray[i]->mWidth;
        float altitude = pageEntryArray[i]->mAlti;

        Geode *floorplanGeode = new Geode;
        Geometry *floorplanGeometry = new Geometry;

        Vec3Array* vertices = new Vec3Array;
        Vec3Array* normals = new Vec3Array;
        Vec2Array* texcoords = new Vec2Array(4);

        vertices->push_back(Vec3(-length / 2,  width / 2, altitude));	(*texcoords)[0].set(0, 1);
        vertices->push_back(Vec3(-length / 2, -width / 2, altitude));	(*texcoords)[1].set(0, 0);
        vertices->push_back(Vec3( length / 2, -width / 2, altitude));	(*texcoords)[2].set(1, 0);
        vertices->push_back(Vec3( length / 2,  width / 2, altitude));	(*texcoords)[3].set(1, 1);

        for (int k = 0; k < 4; k++) 
        { 
            normals->push_back(Vec3(0, 0, 1));
        }

        DrawElementsUInt* rectangle = new DrawElementsUInt(PrimitiveSet::POLYGON, 0);
        rectangle->push_back(0);	rectangle->push_back(1);
        rectangle->push_back(2);	rectangle->push_back(3);

        floorplanGeometry->addPrimitiveSet(rectangle);
        floorplanGeometry->setVertexArray(vertices);
        floorplanGeometry->setNormalArray(normals);
        floorplanGeometry->setTexCoordArray(0, texcoords);
        floorplanGeometry->setNormalBinding(Geometry::BIND_PER_VERTEX);

        floorplanGeode->addDrawable(floorplanGeometry);
        mFloorplanSwitch->addChild(floorplanGeode);

        /* load floorplan images */
        Material *transmaterial = new Material;
        transmaterial->setDiffuse(Material::FRONT_AND_BACK, Vec4(1, 1, 1, 1));
        transmaterial->setAlpha(Material::FRONT_AND_BACK, 1.0f);

        Image* imgFloorplan = osgDB::readImageFile(pageEntryArray[i]->mTexFilename);

        Texture2D* texFloorplan = new Texture2D(imgFloorplan); 

        StateSet *floorplanStateSet = floorplanGeode->getOrCreateStateSet();
        floorplanStateSet->setTextureAttributeAndModes(0, texFloorplan, StateAttribute::ON);
        floorplanStateSet->setMode(GL_BLEND, StateAttribute::OVERRIDE | StateAttribute::ON );
        floorplanStateSet->setRenderingHint(StateSet::TRANSPARENT_BIN);
        floorplanStateSet->setAttributeAndModes(transmaterial, StateAttribute::OVERRIDE | StateAttribute::ON);
    }
}
Пример #17
0
Node *makeSky( void )
{
    int i, j;
    float lev[] = { -5, -1.0, 1.0, 15.0, 30.0, 60.0, 90.0  };
    float cc[][4] =
    {
        { 0.0, 0.0, 0.15 },
        { 0.0, 0.0, 0.15 },
        { 0.4, 0.4, 0.7 },
        { 0.2, 0.2, 0.6 },
        { 0.1, 0.1, 0.6 },
        { 0.1, 0.1, 0.6 },
        { 0.1, 0.1, 0.6 },
    };
    float x, y, z;
    float alpha, theta;
    float radius = 20.0f;
    int nlev = sizeof( lev )/sizeof(float);

    Geometry *geom = new Geometry;

    Vec3Array& coords = *(new Vec3Array(19*nlev));
    Vec4Array& colors = *(new Vec4Array(19*nlev));
    Vec2Array& tcoords = *(new Vec2Array(19*nlev));
    
    
    int ci = 0;

    for( i = 0; i < nlev; i++ )
    {
        for( j = 0; j <= 18; j++ )
        {
            alpha = osg::DegreesToRadians(lev[i]);
            theta = osg::DegreesToRadians((float)(j*20));

            x = radius * cosf( alpha ) * cosf( theta );
            y = radius * cosf( alpha ) * -sinf( theta );
            z = radius * sinf( alpha );

            coords[ci][0] = x;
            coords[ci][1] = y;
            coords[ci][2] = z;

            colors[ci][0] = cc[i][0];
            colors[ci][1] = cc[i][1];
            colors[ci][2] = cc[i][2];
            colors[ci][3] = 1.0;

            tcoords[ci][0] = (float)j/18.0;
            tcoords[ci][1] = (float)i/(float)(nlev-1);

            ci++;
        }


    }

    for( i = 0; i < nlev-1; i++ )
    {
        DrawElementsUShort* drawElements = new DrawElementsUShort(PrimitiveSet::TRIANGLE_STRIP);
        drawElements->reserve(38);

        for( j = 0; j <= 18; j++ )
        {
            drawElements->push_back((i+1)*19+j);
            drawElements->push_back((i+0)*19+j);
        }

        geom->addPrimitiveSet(drawElements);
    }
    
    geom->setVertexArray( &coords );
    geom->setTexCoordArray( 0, &tcoords );

    geom->setColorArray( &colors );
    geom->setColorBinding( Geometry::BIND_PER_VERTEX );


    Texture2D *tex = new Texture2D;
    tex->setImage(osgDB::readImageFile("Images/white.rgb"));

    StateSet *dstate = new StateSet;

    dstate->setTextureAttributeAndModes(0, tex, StateAttribute::OFF );
    dstate->setTextureAttribute(0, new TexEnv );
    dstate->setMode( GL_LIGHTING, StateAttribute::OFF );
    dstate->setMode( GL_CULL_FACE, StateAttribute::ON );
    

    // clear the depth to the far plane.
    osg::Depth* depth = new osg::Depth;
    depth->setFunction(osg::Depth::ALWAYS);
    depth->setRange(1.0,1.0);   
    dstate->setAttributeAndModes(depth,StateAttribute::ON );

    dstate->setRenderBinDetails(-2,"RenderBin");

    geom->setStateSet( dstate );

    Geode *geode = new Geode;
    geode->addDrawable( geom );

    geode->setName( "Sky" );

    return geode;
}
Пример #18
0
/***************************************************************
* Function: ANIMCreateVirtualSphere()
*
***************************************************************/
void ANIMCreateVirtualSphere(osg::PositionAttitudeTransform** xformScaleFwd, 
			     osg::PositionAttitudeTransform** xformScaleBwd)
{
    // create sphere geometry
    *xformScaleFwd = new PositionAttitudeTransform;
    *xformScaleBwd = new PositionAttitudeTransform;
    Geode* sphereGeode = new Geode();
    Sphere* virtualSphere = new Sphere();
    Drawable* sphereDrawable = new ShapeDrawable(virtualSphere);

    virtualSphere->setRadius(ANIM_VIRTUAL_SPHERE_RADIUS);
    sphereGeode->addDrawable(sphereDrawable);
    (*xformScaleFwd)->addChild(sphereGeode);
    (*xformScaleBwd)->addChild(sphereGeode);

    osg::StateSet* stateset;   

    // highlights
/*    Sphere* highlightSphere = new Sphere();
    ShapeDrawable* highlightDrawable = new ShapeDrawable(highlightSphere);
    Geode* highlightGeode = new Geode();
    highlightSphere->setRadius(ANIM_VIRTUAL_SPHERE_RADIUS * 1.3);
    highlightDrawable->setColor(osg::Vec4(0,0,1,0.3));
    highlightGeode->addDrawable(highlightDrawable);
    (*xformScaleFwd)->addChild(highlightGeode);
    (*xformScaleBwd)->addChild(highlightGeode);

    stateset = highlightDrawable->getOrCreateStateSet();
    stateset->setMode(GL_BLEND, StateAttribute::ON);
    stateset->setMode(GL_CULL_FACE, StateAttribute::ON);
    stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
    stateset->setRenderingHint(StateSet::TRANSPARENT_BIN);
*/

    // set up the forward / backward scale animation path
    AnimationPath* animationPathScaleFwd = new AnimationPath;
    AnimationPath* animationPathScaleBwd = new AnimationPath;
    animationPathScaleFwd->setLoopMode(AnimationPath::NO_LOOPING);
    animationPathScaleBwd->setLoopMode(AnimationPath::NO_LOOPING);

    osg::Vec3 pos(-1.5, 0, 0);

    Vec3 scaleFwd, scaleBwd;
    float step = 1.f / ANIM_VIRTUAL_SPHERE_NUM_SAMPS;
    for (int i = 0; i < ANIM_VIRTUAL_SPHERE_NUM_SAMPS + 1; i++)
    {
        float val = i * step;
        scaleFwd = Vec3(val, val, val);
        scaleBwd = Vec3(1-val, 1-val, 1-val);
        animationPathScaleFwd->insert(val, AnimationPath::ControlPoint(pos, Quat(), scaleFwd));
        animationPathScaleBwd->insert(val, AnimationPath::ControlPoint(pos, Quat(), scaleBwd));
    }

    AnimationPathCallback *animCallbackFwd = new AnimationPathCallback(animationPathScaleFwd,
						0.0, 1.f / ANIM_VIRTUAL_SPHERE_LAPSE_TIME);
    AnimationPathCallback *animCallbackBwd = new AnimationPathCallback(animationPathScaleBwd,
						0.0, 1.f / ANIM_VIRTUAL_SPHERE_LAPSE_TIME);
    (*xformScaleFwd)->setUpdateCallback(animCallbackFwd);
    (*xformScaleBwd)->setUpdateCallback(animCallbackBwd);

    /* apply shaders to geode stateset */
    stateset = new StateSet();
    stateset->setMode(GL_BLEND, StateAttribute::OVERRIDE | StateAttribute::ON );
    stateset->setRenderingHint(StateSet::TRANSPARENT_BIN);
    //sphereGeode->setStateSet(stateset);
    sphereDrawable->setStateSet(stateset);

    Program* shaderProg = new Program;
    stateset->setAttribute(shaderProg);
    shaderProg->addShader(Shader::readShaderFile(Shader::VERTEX, ANIMDataDir() + "Shaders/VirtualSphere.vert"));
    shaderProg->addShader(Shader::readShaderFile(Shader::FRAGMENT, ANIMDataDir() + "Shaders/VirtualSphere.frag"));

    Image* envMap = osgDB::readImageFile(ANIMDataDir() + "Textures/EnvMap.JPG");
    Texture2D* envTex = new Texture2D(envMap);
    stateset->setTextureAttributeAndModes(0, envTex, StateAttribute::ON);

    Uniform* envMapSampler = new Uniform("EnvMap", 0);
    stateset->addUniform(envMapSampler);

    Uniform* baseColorUniform = new Uniform("BaseColor", Vec3(0.2, 1.0, 0.2));
    stateset->addUniform(baseColorUniform);

    Uniform* lightPosUniform = new Uniform("LightPos", Vec4(1.0, 0.0, 0.2, 0.0));
    stateset->addUniform(lightPosUniform);

}
Пример #19
0
/***************************************************************
* Function: ANIMCreateSingleShapeSwitchAnimation()
***************************************************************/
void ANIMCreateSingleShapeSwitchAnimation(ANIMShapeSwitchEntry **shapeEntry, const CAVEGeodeShape::Type &typ)
{
    PositionAttitudeTransform *flipUpFwdTrans = new PositionAttitudeTransform;
    PositionAttitudeTransform *flipDownFwdTrans = new PositionAttitudeTransform;
    PositionAttitudeTransform *flipUpBwdTrans = new PositionAttitudeTransform;
    PositionAttitudeTransform *flipDownBwdTrans = new PositionAttitudeTransform;

    (*shapeEntry)->mSwitch->addChild(flipUpFwdTrans);		// child #0
    (*shapeEntry)->mSwitch->addChild(flipDownFwdTrans);		// child #1
    (*shapeEntry)->mSwitch->addChild(flipUpBwdTrans);		// child #2
    (*shapeEntry)->mSwitch->addChild(flipDownBwdTrans);		// child #3
    (*shapeEntry)->mSwitch->setAllChildrenOff();

    osg::Vec3 pos(0, 0, 0);

    /* create shape geode based on 'ANIMShapeSwitchEntry::Type' */
    Geode *shapeGeode = new Geode;
    if (typ == CAVEGeodeShape::BOX)
    {
        Box *box = new Box(osg::Vec3(), ANIM_VIRTUAL_SPHERE_RADIUS / 0.9);
        shapeGeode->addDrawable(new ShapeDrawable(box));
    }
    else if (typ == CAVEGeodeShape::CYLINDER)
    {
        float r = ANIM_VIRTUAL_SPHERE_RADIUS / 1.5;
        Cylinder *cylinder = new Cylinder(osg::Vec3(), r, r * 2);
        shapeGeode->addDrawable(new ShapeDrawable(cylinder));
    }
    flipUpFwdTrans->addChild(shapeGeode);
    flipDownFwdTrans->addChild(shapeGeode);
    flipUpBwdTrans->addChild(shapeGeode);
    flipDownBwdTrans->addChild(shapeGeode);

    /* set up flip up / flip down animation paths for shape switch */
    AnimationPath* animationFlipUpFwd = new AnimationPath;
    AnimationPath* animationFlipDownFwd = new AnimationPath;
    AnimationPath* animationFlipUpBwd = new AnimationPath;
    AnimationPath* animationFlipDownBwd = new AnimationPath;
    animationFlipUpFwd->setLoopMode(AnimationPath::NO_LOOPING);
    animationFlipDownFwd->setLoopMode(AnimationPath::NO_LOOPING);
    animationFlipUpBwd->setLoopMode(AnimationPath::NO_LOOPING);
    animationFlipDownBwd->setLoopMode(AnimationPath::NO_LOOPING);
   
    Vec3 scaleUpVect, scaleDownVect;
    Quat flipUpFwdQuat, flipDownFwdQuat, flipUpBwdQuat, flipDownBwdQuat;
    float timestep = ANIM_GEOMETRY_CREATOR_SHAPE_FLIP_TIME / ANIM_GEOMETRY_CREATOR_SHAPE_FLIP_SAMPS;
    float scalestep = 1.f / ANIM_GEOMETRY_CREATOR_SHAPE_FLIP_SAMPS;
    float anglestep = M_PI * 0.5 / ANIM_GEOMETRY_CREATOR_SHAPE_FLIP_SAMPS;

    if (typ == CAVEGeodeShape::BOX)
        pos[2] -= 0.5;
    else if (typ == CAVEGeodeShape::CYLINDER)
        pos[2] -= 1.0;

    osg::Vec3 diff, startPos(0,0,0), fwd, bwd;

    for (int i = 0; i < ANIM_GEOMETRY_CREATOR_SHAPE_FLIP_SAMPS + 1; i++)
    {
        float t = i * timestep;
        float val = i * scalestep;
        scaleUpVect = Vec3(val, val, val);
        scaleDownVect = Vec3(1.f-val, 1.f-val, 1.f-val);

        flipUpFwdQuat = Quat(i * anglestep - M_PI / 2, Vec3(1, 0, 0));
        flipDownFwdQuat = Quat(i * anglestep, Vec3(1, 0, 0));
        flipUpBwdQuat = Quat(i * anglestep - M_PI / 2, Vec3(-1, 0, 0));
        flipDownBwdQuat = Quat(i * anglestep, Vec3(-1, 0, 0));

        diff = startPos - pos;
        
        for (int j = 0; j < 3; ++j)
            diff[j] *= val; 
        fwd = startPos - diff;
        bwd = pos + diff;

        animationFlipUpFwd->insert(t, AnimationPath::ControlPoint(fwd, flipUpFwdQuat, scaleUpVect));
        animationFlipDownFwd->insert(t, AnimationPath::ControlPoint(fwd, flipDownFwdQuat, scaleUpVect));
        animationFlipUpBwd->insert(t, AnimationPath::ControlPoint(bwd, flipUpBwdQuat, scaleDownVect));
        animationFlipDownBwd->insert(t, AnimationPath::ControlPoint(bwd, flipDownBwdQuat, scaleDownVect));
    }

    AnimationPathCallback *animCallbackFlipUpFwd = new AnimationPathCallback(animationFlipUpFwd, 
						0.0, 1.f / ANIM_GEOMETRY_CREATOR_SHAPE_FLIP_TIME);
    AnimationPathCallback *animCallbackFlipDownFwd = new AnimationPathCallback(animationFlipDownFwd, 
						0.0, 1.f / ANIM_GEOMETRY_CREATOR_SHAPE_FLIP_TIME);
    AnimationPathCallback *animCallbackFlipUpBwd = new AnimationPathCallback(animationFlipUpBwd, 
						0.0, 1.f / ANIM_GEOMETRY_CREATOR_SHAPE_FLIP_TIME);
    AnimationPathCallback *animCallbackFlipDownBwd = new AnimationPathCallback(animationFlipDownBwd, 
						0.0, 1.f / ANIM_GEOMETRY_CREATOR_SHAPE_FLIP_TIME);
    flipUpFwdTrans->setUpdateCallback(animCallbackFlipUpFwd);
    flipDownFwdTrans->setUpdateCallback(animCallbackFlipDownFwd);
    flipUpBwdTrans->setUpdateCallback(animCallbackFlipUpBwd);
    flipDownBwdTrans->setUpdateCallback(animCallbackFlipDownBwd);

    /* write into shape switch entry array record*/
    (*shapeEntry)->mFlipUpFwdAnim = animCallbackFlipUpFwd;
    (*shapeEntry)->mFlipDownFwdAnim = animCallbackFlipDownFwd;
    (*shapeEntry)->mFlipUpBwdAnim = animCallbackFlipUpBwd;
    (*shapeEntry)->mFlipDownBwdAnim = animCallbackFlipDownBwd;
}
Пример #20
0
/***************************************************************
* Function: ANIMCreateRefSkyDome()
*
***************************************************************/
MatrixTransform *ANIMCreateRefSkyDome(StateSet **stateset)
{
    /* sky dome geometry */
    Sphere *skyShape = new Sphere();
    ShapeDrawable* skyDrawable = new ShapeDrawable(skyShape);
    Geode* skyGeode = new Geode();
    MatrixTransform *skyDomeTrans = new MatrixTransform;
    
    //osg::Matrix m;
    //m.makeRotate(osg::Quat(M_PI/2, osg::Vec3(0, 1, 0)));
    //skyDomeTrans->setMatrix(m);

    skyShape->setRadius(ANIM_SKYDOME_RADIUS);
    skyGeode->addDrawable(skyDrawable);
    skyDomeTrans->addChild(skyGeode);

    // apply simple colored materials
    Material* material = new Material;
    material->setDiffuse(Material::FRONT_AND_BACK, Vec4(1.0f, 1.0f, 1.0f, 1.0f));
    material->setAlpha(Material::FRONT_AND_BACK, 1.0f);

    (*stateset) = new StateSet();
    (*stateset)->setAttributeAndModes(material, StateAttribute::OVERRIDE | StateAttribute::ON);
    (*stateset)->setMode(GL_BLEND, StateAttribute::OVERRIDE | StateAttribute::ON );
    (*stateset)->setRenderingHint(StateSet::TRANSPARENT_BIN);
    skyGeode->setStateSet(*stateset);

//    skyGeode->setNodeMask(0xFFFFFF & ~(0x2 | 0x3));

    // load sky dome shader
    Uniform* sunrUniform = new Uniform("hazeRadisuMin", 0.975f);
    (*stateset)->addUniform(sunrUniform);

    Uniform* sunRUniform = new Uniform("hazeRadisuMax", 0.995f);
    (*stateset)->addUniform(sunRUniform);

    Uniform* sunDirUniform = new Uniform("sundir", Vec4(0.0, 0.0, 1.0, 1.0));
    (*stateset)->addUniform(sunDirUniform);

    Uniform* suncolorUniform = new Uniform("suncolor", Vec4(1.0, 1.0, 1.0, 1.0));
    (*stateset)->addUniform(suncolorUniform);

    Uniform* skycolorUniform = new Uniform("skycolor", Vec4(0.5, 0.5, 1.0, 1.0));
    (*stateset)->addUniform(skycolorUniform);

    Uniform* skyfadingcolorUniform = new Uniform("skyfadingcolor", Vec4(0.8, 0.8, 0.8, 1.0));
    (*stateset)->addUniform(skyfadingcolorUniform);

    Uniform* skymaskingcolorUniform = new Uniform("skymaskingcolor", Vec4(1.0, 1.0, 1.0, 1.0));
    (*stateset)->addUniform(skymaskingcolorUniform);

    Uniform *matShaderToWorldUniform = new Uniform("shaderToWorldMat", Matrixd());
    (*stateset)->addUniform(matShaderToWorldUniform);

    Image* imageSky = osgDB::readImageFile(ANIMDataDir() + "Textures/NightSky.JPG");
    Texture2D* textureSky = new Texture2D(imageSky);    
    (*stateset)->setTextureAttributeAndModes(0, textureSky, StateAttribute::ON);

    Image* imagePara = osgDB::readImageFile(ANIMDataDir() + "Textures/Paramounts/Paramount00.JPG");
    Texture2D* texturePara = new Texture2D(imagePara);

    (*stateset)->setTextureAttributeAndModes(1, texturePara, StateAttribute::ON);

    Uniform* skyNightSampler = new Uniform("texNightSky", 0);
    (*stateset)->addUniform(skyNightSampler);

    Uniform* paraImageTextureSampler = new Uniform("texParamount", 1);
    (*stateset)->addUniform(paraImageTextureSampler);

    Program* programSky = new Program;
    (*stateset)->setAttribute(programSky);
    programSky->addShader(Shader::readShaderFile(Shader::VERTEX, ANIMDataDir() + "Shaders/EnvSky.vert"));
    programSky->addShader(Shader::readShaderFile(Shader::FRAGMENT, ANIMDataDir() + "Shaders/EnvSky.frag"));

    return skyDomeTrans;
}
Пример #21
0
void
Lwo2Layer::GenerateGeode( Geode& geode, short tags_count, DrawableToTagMapping& tag_mapping)
{
  OSG_DEBUG;

  // variable used to track using textures
  bool have_texture_coords;

  // create diffirent geomerty for each tag
  for (short current_tag = 0; current_tag < tags_count; current_tag++)
    {
      have_texture_coords = false;

      // new geometry
      ref_ptr<Geometry> geometry = new Geometry;

      // create coords array
      ref_ptr<Vec3Array> coords = new Vec3Array;

      // create texture array
      ref_ptr<Vec2Array> texcoords = new Vec2Array;

      // selecting polygons for current layer only
      int polygon_index = 0;
      PolygonsList polygons;
      IteratorPolygonsList polygon_iterator;
      for (polygon_iterator = _polygons.begin(); polygon_iterator != _polygons.end(); polygon_iterator++, polygon_index++)
        {
          // *polygon_iterator it's a PolygonsList

          // polygons of current tag only
          if (_polygons_tag[polygon_index] == current_tag)
            {

              // reset point_index member for later comparing poins data
              PointsList points_list = *polygon_iterator;
              for (unsigned int i = 0; i < points_list.size(); i++)
                {
                  points_list[i].point_index = 0;
                }

              polygons.push_back(*polygon_iterator);
            }
        }

      // find and compose triangle fans
      PolygonsList triangle_fans;
      _find_triangle_fans(polygons, triangle_fans);

      // find and compose triangle strips
      PolygonsList triangle_strips;
      _find_triangle_strips(polygons, triangle_strips);

      // polygons of current layer
      polygon_index = 0;
      for (polygon_iterator = polygons.begin(); polygon_iterator != polygons.end(); polygon_iterator++, polygon_index++)
        {
          if ((*polygon_iterator)[0].point_index != -1)
            {
              // all points of polygon
              for (IteratorPoint itr = (*polygon_iterator).begin(); itr != (*polygon_iterator).end(); itr++)
                {
                  // *itr - it's a PointData

                  // polygons data
                  (*coords).push_back((*itr).coord);
                  (*texcoords).push_back((*itr).texcoord);

                  if ((*itr).texcoord.x() != -1.0f || (*itr).texcoord.y() != -1.0f)
                    {
                      have_texture_coords = true;
                    }
                }

              unsigned int points_start = (*coords).size() - (*polygon_iterator).size();
              unsigned int points_count = (*polygon_iterator).size();
              if (points_count == 3)
                {
                  geometry->addPrimitiveSet(new DrawArrays(PrimitiveSet::TRIANGLES, points_start, points_count));
                }
              else if (points_count == 4)
                {
                  geometry->addPrimitiveSet(new DrawArrays(PrimitiveSet::QUADS, points_start, points_count));
                }
              else
                {
                  geometry->addPrimitiveSet(new DrawArrays(PrimitiveSet::POLYGON, points_start, points_count));
                }
            }
        }

      // triangle fans of current layer
      polygon_index = 0;
      for (polygon_iterator = triangle_fans.begin(); polygon_iterator != triangle_fans.end(); polygon_iterator++, polygon_index++)
        {

          // all points of polygon
          for (IteratorPoint itr = (*polygon_iterator).begin(); itr != (*polygon_iterator).end(); itr++)
            {
              // *itr - it's a PointData

              // polygons data
              (*coords).push_back((*itr).coord);
              (*texcoords).push_back((*itr).texcoord);

              if ((*itr).texcoord.x() != -1.0f || (*itr).texcoord.y() != -1.0f)
                {
                  have_texture_coords = true;
                }
            }

          unsigned int points_start = (*coords).size() - (*polygon_iterator).size();
          unsigned int points_count = (*polygon_iterator).size();
          geometry->addPrimitiveSet(new DrawArrays(PrimitiveSet::TRIANGLE_FAN, points_start, points_count));
        }

      // triangle strips of current layer
      polygon_index = 0;
      for (polygon_iterator = triangle_strips.begin(); polygon_iterator != triangle_strips.end(); polygon_iterator++, polygon_index++)
        {

          // all points of polygon
          for (IteratorPoint itr = (*polygon_iterator).begin(); itr != (*polygon_iterator).end(); itr++)
            {
              // *itr - it's a PointData

              // polygons data
              (*coords).push_back((*itr).coord);
              (*texcoords).push_back((*itr).texcoord);

              if ((*itr).texcoord.x() != -1.0f || (*itr).texcoord.y() != -1.0f)
                {
                  have_texture_coords = true;
                }
            }

          unsigned int points_start = (*coords).size() - (*polygon_iterator).size();
          unsigned int points_count = (*polygon_iterator).size();
          geometry->addPrimitiveSet(new DrawArrays(PrimitiveSet::TRIANGLE_STRIP, points_start, points_count));
        }

      // add geometry if it contains any points
      if (coords->size() != 0)
        {
          geometry->setVertexArray(coords.get());

          // assign texture array
          if (have_texture_coords)
            {
              geometry->setTexCoordArray(0, texcoords.get());
            }

          // generate normals
          osgUtil::SmoothingVisitor smoother;
          smoother.smooth(*(geometry.get()));

          geode.addDrawable(geometry.get());

          OSG_DEBUG << "  inserting tag " << geode.getNumDrawables() - 1 << ":" << current_tag << std::endl;
          tag_mapping.insert(PairDrawableToTag(geode.getNumDrawables() - 1, current_tag));
        }
    }
}
Пример #22
0
Файл: tank.cpp Проект: 3dcl/osg
Node *makeTank( void )
{

    Geode *geode = new Geode;

    getDatabaseCenterRadius( dbcenter, &dbradius );

    Matrix mat(
        0.05, 0, 0, 0,
        0, 0.05, 0, 0,
        0, 0, 0.05, 0,
        1.5999 - 0.3,
        3.1474,
        dbcenter[2] + 0.6542 - 0.09,
        1
        );

    // 42 required for sides, 22 for the top.
    Vec3Array& vc = *(new Vec3Array(42+22));
    Vec2Array& tc = *(new Vec2Array(42+22));

    Geometry *gset = new Geometry;
    gset->setVertexArray( &vc );
    gset->setTexCoordArray( 0, &tc );

    // create the sides of the tank.
    unsigned int i, c = 0;
    for( i = 0; i <= 360; i += 18 )
    {
        float x, y, z;
        float s, t;
        float theta = osg::DegreesToRadians((float)i);

        s = (float)i/90.0;
        t = 1.0;

        x = radius * cosf( theta );
        y = radius * sinf( theta );
        z = 1.0;

        vc[c][0] = x;
        vc[c][1] = y;
        vc[c][2] = z;

        tc[c][0] = s;
        tc[c][1] = t;

        c++;

        t = 0.0;
        z = 0.0;

        vc[c][0] = x;
        vc[c][1] = y;
        vc[c][2] = z;

        tc[c][0] = s;
        tc[c][1] = t;
        c++;
    }

    gset->addPrimitiveSet( new DrawArrays(PrimitiveSet::TRIANGLE_STRIP,0,c) );

    // create the top of the tank.

    int prev_c = c;

    vc[c][0] = 0.0f;
    vc[c][1] = 0.0f;
    vc[c][2] = 1.0f;

    tc[c][0] = 0.0f;
    tc[c][1] = 0.0f;
    c++;

    for( i = 0; i <= 360; i += 18 )
    {
        float x, y, z;
        float s, t;
        float theta = osg::DegreesToRadians((float)i);

        //    s = (float)i/360.0;
        //   t = 1.0;
        s = cosf( theta );
        t = sinf( theta );

        x = radius * cosf( theta );
        y = radius * sinf( theta );
        z = 1.0;

        vc[c][0] = x;
        vc[c][1] = y;
        vc[c][2] = z;

        tc[c][0] = s;
        tc[c][1] = t;

        c++;
    }

    for( i = 0; i < c; i++ )
        conv( vc[i], mat, vc[i] );
     
     gset->addPrimitiveSet(new DrawArrays(PrimitiveSet::TRIANGLE_FAN,prev_c,c-prev_c));




    Texture2D *tex = new Texture2D;

    tex->setWrap( Texture2D::WRAP_S, Texture2D::REPEAT );
    tex->setWrap( Texture2D::WRAP_T, Texture2D::REPEAT );
    tex->setImage(osgDB::readImageFile("Images/tank.rgb"));

    StateSet *dstate = new StateSet;
    dstate->setTextureAttributeAndModes(0, tex, StateAttribute::ON );
    dstate->setTextureAttribute(0, new TexEnv );

    gset->setStateSet( dstate );
    geode->addDrawable( gset );

    return geode;
}
Пример #23
0
osg::Node *JTOpenPlugin::createShape(JtkShape *partShape, const char *objName)
{
    //cout << "JtkSHAPE\n";

    Geode *geode = new Geode();
    ref_ptr<Geometry> geom = new Geometry();
    StateSet *geoState = geode->getOrCreateStateSet();
    Vec3Array *vert = new Vec3Array;
    Vec3Array *normalArray = new Vec3Array();
    Vec3Array *colorArray = new Vec3Array();
    Vec2Array *tcArray = new Vec2Array();

    DrawArrayLengths *primitives = NULL;
    if (partShape->typeID() == JtkEntity::JtkPOLYGONSET)
    {
        primitives = new DrawArrayLengths(PrimitiveSet::POLYGON);
    }
    else if (partShape->typeID() == JtkEntity::JtkLINESTRIPSET)
    {
        primitives = new DrawArrayLengths(PrimitiveSet::LINE_STRIP);
    }
    else if (partShape->typeID() == JtkEntity::JtkTRISTRIPSET)
    {
        primitives = new DrawArrayLengths(PrimitiveSet::TRIANGLE_STRIP);
    }
    else
    {
        cerr << "unknown partShape->typeID " << partShape->typeID() << endl;
    }
    geode->setName(objName);
    if (primitives)
    {
        for (int set = 0; set < partShape->numOfSets(); set++)
        {
            float *vertex = NULL,
                  *normal = NULL,
                  *color = NULL,
                  *texture = NULL;
            int vertexCount = -1,
                normCount = -1,
                colorCount = -1,
                textCount = -1;

            partShape->getInternal(vertex, vertexCount, normal, normCount,
                                   color, colorCount, texture, textCount, set);

            primitives->push_back(vertexCount);

            // backFaceCulling nur dann, wenn es im CoviseConfig enabled ist
            /*if(backFaceCulling && (mask & Viewer::MASK_SOLID))
         {
         CullFace *cullFace = new CullFace();        // da viele Modelle backface Culling nicht vertragen (nicht richtig modelliert sind)
         cullFace->setMode(CullFace::BACK);
         geoState->setAttributeAndModes(cullFace, StateAttribute::ON);
         }

         // already done in updateMaterial()
         #if 0
         if(Blended)
         {
         BlendFunc *blendFunc = new BlendFunc();
         blendFunc->setFunction(BlendFunc::SRC_ALPHA, BlendFunc::ONE_MINUS_SRC_ALPHA);
         geoState->setAttributeAndModes(blendFunc, StateAttribute::ON);
         #if 1
         AlphaFunc *alphaFunc = new AlphaFunc();
         alphaFunc->setFunction(AlphaFunc::ALWAYS,1.0);
         geoState->setAttributeAndModes(alphaFunc, StateAttribute::OFF);
         #endif
         }
         #endif
         #ifdef HAVE_OSGNV
         if((strncmp(d_currentObject->node->name(),"combineTextures",15)==0)||(strncmp(objName,"combineTextures",15)==0))
         {
         geoState->setAttributeAndModes(combineTextures.get(), StateAttribute::ON);
         }
         if((strncmp(d_currentObject->node->name(),"combineEnvTextures",15)==0)||(strncmp(objName,"combineEnvTextures",15)==0))
         {
         geoState->setAttributeAndModes(combineEnvTextures.get(), StateAttribute::ON);
         }
         #endif*/

            if (vertex && (vertexCount > 0))
            {
                for (int elems = 0; elems < vertexCount; elems++)
                {
                    vert->push_back(Vec3(vertex[elems * 3 + 0], vertex[elems * 3 + 1], vertex[elems * 3 + 2]));
                }
                JtkEntityFactory::deleteMemory(vertex);
            }

            if (normal && (normCount > 0))
            {
                for (int elems = 0; elems < normCount; elems++)
                {
                    normalArray->push_back(Vec3(normal[elems * 3 + 0], normal[elems * 3 + 1], normal[elems * 3 + 2]));
                }
                if (normCount == vertexCount)
                {
                }
                else
                {
                    //geom->setNormalBinding(Geometry::BIND_PER_PRIMITIVE);
                    std::cerr << "JTOpen: normals per primitive not supported" << std::endl;
                }
                JtkEntityFactory::deleteMemory(normal);
            }
            else // generate normals
            {
            }

            if (color && (colorCount > 0))
            {

                for (int elems = 0; elems < colorCount; elems++)
                {
                    colorArray->push_back(Vec3(color[elems * 3 + 0], color[elems * 3 + 1], color[elems * 3 + 2]));
                }

                if (colorCount == vertexCount)
                {
                }
                else
                {
                    //geom->setColorBinding(Geometry::BIND_PER_PRIMITIVE);
                    std::cerr << "JTOpen: colors per primitive not supported" << std::endl;
                }
                JtkEntityFactory::deleteMemory(color);
            }

            if (texture && (textCount > 0))
            {

                for (int elems = 0; elems < textCount; elems++)
                {
                    tcArray->push_back(Vec2(texture[elems * 2 + 0], texture[elems * 2 + 1]));
                }
                JtkEntityFactory::deleteMemory(texture);
            }

            /*   if(!(mask & Viewer::MASK_CONVEX))
         {
         osgUtil::Tesselator *tess = new osgUtil::Tesselator;
         tess->retesselatePolygons(*geom);
         //delete[] tess;
         }*/

            // if enabled, generate tri strips, but not for animated objects
            // if(genStrips && strncmp(objName, "Animated", 8))
            {
                //      d_stripper->stripify(*geom);
            }
        }
        geom->setVertexArray(vert);
        geom->addPrimitiveSet(primitives);
        if (normalArray->size() > 0)
        {
            geom->setNormalArray(normalArray);
            geom->setNormalBinding(Geometry::BIND_PER_VERTEX);
        }
        if (colorArray->size() > 0)
        {
            geom->setColorArray(colorArray);
            geom->setColorBinding(Geometry::BIND_PER_VERTEX);
        }
        if (tcArray->size() > 0)
            geom->setTexCoordArray(0, tcArray);
        if (normalArray->size() == 0)
        {
            osgUtil::SmoothingVisitor::smooth(*(geom.get()), 40.0 / 180.0 * M_PI);
        }
        geode->addDrawable(geom.get());
        geode->setStateSet(geoState);
        return geode;
    }
    return NULL;
}
Пример #24
0
void OsgChromosome::renderChromosome(char * file){
    Sphere * mysphere;
	ShapeDrawable * mydrawable;
	Geode* mygeode = new Geode();
    osg::ref_ptr<osg::Material> pMaterial;
	ifstream myReadFile;
    SceneObject * so = new SceneObject(file, true, true, true, true, false);
    PluginHelper::registerSceneObject(so);
    so->attachToScene();
    so->setNavigationOn(true);
    so->addMoveMenuItem();
    so->addNavigationMenuItem();
    
    // open file to read
    myReadFile.open(file);
 	string chr, start, end, comp, x, y, z, output;
    Vec3 prev, curr;
    Vec4 color;
    bool isFirst = true;
 	if (myReadFile.is_open()) {
        printf("is open\n");
            // get rid of top line  
	    getline(myReadFile, output);
            // read each table entry 
        while (!myReadFile.eof()) {
            myReadFile >> chr;
            myReadFile >> start;
            myReadFile >> end;
            myReadFile >> comp;
            myReadFile >> x;
            myReadFile >> y;
            myReadFile >> z;
            curr = Vec3(atof(x.c_str()), atof(y.c_str()), atof(z.c_str()));
            mysphere = new Sphere(curr, .02);

            mydrawable = new ShapeDrawable(mysphere);
            mygeode = new Geode();
            mygeode->addDrawable(mydrawable);
            so->addChild(mygeode);
        	//root->addChild(mygeode);

            // determine the color of the segment
            pMaterial = new osg::Material;
            if (comp.compare("A") == 0)
                color = Vec4(1,0,0,1);
            else if (comp.compare("B") == 0)
                color = Vec4(0,0,1,1);
            else
                color = Vec4(0,1,0,1);

            // set the color of the sphere
	        pMaterial->setDiffuse( osg::Material::FRONT, color);
            mygeode->getOrCreateStateSet()->setAttribute( pMaterial, osg::StateAttribute::OVERRIDE );

            // draw the cylinder bewtween spheres
            if (!isFirst) {
                //mygeode = new Geode();
                AddCylinderBetweenPoints(prev, curr, (float) .02, color, so/*(Group *) root*/);
                //root->addChild(mygeode);   
            }
            prev = curr;
            isFirst = false;
        }
        printf("get attached is %d, number of children is %d\n", so->getAttached(), so->getNumChildObjects());
    }
Пример #25
0
PositionAttitudeTransform *VideoGeode::createVideoPlane(float sizeX, float sizeY, bool texRepeat)
{
	// vertex array
	Vec3Array *vertexArray = new Vec3Array();
   
   sizeX /= 2.0;
   sizeY /= 2.0;
	
   vertexArray->push_back(Vec3(-sizeX, 0, -sizeY));
	vertexArray->push_back(Vec3(sizeX, 0, -sizeY));
	vertexArray->push_back(Vec3(sizeX, 0, sizeY));
	vertexArray->push_back(Vec3(-sizeX, 0, sizeY));

	
   /*vertexArray->push_back(Vec3(-sizeX, -sizeY, 0));
	vertexArray->push_back(Vec3(sizeX, -sizeY, 0));
	vertexArray->push_back(Vec3(sizeX, sizeY, 0));
	vertexArray->push_back(Vec3(-sizeX, sizeY, 0));*/
   
	// face array
	DrawElementsUInt *faceArray = new DrawElementsUInt(PrimitiveSet::TRIANGLES, 0);
	
	faceArray->push_back(0); // face 1
	faceArray->push_back(1);
	faceArray->push_back(2);
	faceArray->push_back(2); // face 2
	faceArray->push_back(3);
	faceArray->push_back(0);
	
	// normal array
	Vec3Array *normalArray = new Vec3Array();
	normalArray->push_back(Vec3(0, 0, 1));
	
	// normal index
	TemplateIndexArray<unsigned int, Array::UIntArrayType, 24, 4> *normalIndexArray;
	normalIndexArray = new TemplateIndexArray<unsigned int, Array::UIntArrayType, 24, 4>();
	
	normalIndexArray->push_back(0);
	normalIndexArray->push_back(0);
	normalIndexArray->push_back(0);
	normalIndexArray->push_back(0);
	
	// texture coordinates
	Vec2Array *texCoords = new Vec2Array();
	texCoords->push_back(Vec2(0.0f, 0.0f));
	texCoords->push_back(Vec2(1.0f, 0.0f));
	texCoords->push_back(Vec2(1.0f, 1.0f));
	texCoords->push_back(Vec2(0.0f, 1.0f));
	
	Geometry *geometry = new Geometry();
	geometry->setVertexArray(vertexArray);
	geometry->setNormalArray(normalArray);
	geometry->setNormalIndices(normalIndexArray);
	geometry->setNormalBinding(Geometry::BIND_PER_VERTEX);
	geometry->setTexCoordArray(0, texCoords);
	geometry->addPrimitiveSet(faceArray);
	
	Geode *plane = new Geode();
	plane->addDrawable(geometry);
	
	// assign the material to the sphere
	StateSet *planeStateSet = plane->getOrCreateStateSet();
	planeStateSet->ref();
	planeStateSet->setAttribute(_material);
	
   try {
		planeStateSet->setTextureAttributeAndModes(0, createVideoTexture(texRepeat), StateAttribute::ON);
   } catch (char *e) {
      throw e;
   }
	
	PositionAttitudeTransform *planeTransform = new PositionAttitudeTransform();
	planeTransform->addChild(plane);
	return planeTransform;
}
Пример #26
0
Node *makeTerrain( void )
{
    int m, n;
    int  i, j;
    float dbcenter[3];
    float dbradius;

    getDatabaseCenterRadius( dbcenter, &dbradius );

    m = (sizeof( vertex ) /(sizeof( float[3])))/39;
    n = 39;

    Vec3Array& v    = *(new Vec3Array(m*n));
    Vec2Array& t    = *(new Vec2Array(m*n));
    Vec4Array& col  = *(new Vec4Array(1));

    col[0][0] = col[0][1] = col[0][2] = col[0][3] = 1.0f;

    for( i = 0; i < m * n; i++ )
    {
        float* vc = vertex[i];
        v[i][0] = vc[0] - dbcenter[0];
        v[i][1] = vc[1] - dbcenter[1];
        v[i][2] = vc[2];

        float* tc = texcoord[i];
        t[i][0] = tc[0];
        t[i][1] = tc[1];
    }

    Geometry *geom = new Geometry;

    geom->setVertexArray( &v );
    geom->setTexCoordArray( 0, &t );

    geom->setColorArray( &col, Array::BIND_OVERALL );

    for( i = 0; i < m-2; i++ )
    {
        DrawElementsUShort* elements = new DrawElementsUShort(PrimitiveSet::TRIANGLE_STRIP);
        elements->reserve(39*2);
        for( j = 0; j < n; j++ )
        {
            elements->push_back((i+0)*n+j);
            elements->push_back((i+1)*n+j);
        }
        geom->addPrimitiveSet(elements);
    }


    Texture2D *tex = new Texture2D;

    tex->setImage(osgDB::readRefImageFile("Images/lz.rgb"));

    StateSet *dstate = new StateSet;
    dstate->setMode( GL_LIGHTING, StateAttribute::OFF );
    dstate->setTextureAttributeAndModes(0, tex, StateAttribute::ON );
    dstate->setTextureAttribute(0, new TexEnv );

    geom->setStateSet( dstate );

    Geode *geode = new Geode;
    geode->addDrawable( geom );

    return geode;
}