Ejemplo n.º 1
0
GameInstanceServer::ChunkCoordinates GameInstanceServer::positionToChunk(const osg::Vec3f& pos)
{
    return ChunkCoordinates(
               std::floor(pos.x() / chunksize),
               std::floor(pos.y() / chunksize),
               std::floor(pos.z() / chunksize));
}
Ejemplo n.º 2
0
unsigned int PhysicsEngine::addCollisionSphere(osg::Vec3f pos, float radius, float mass)
{
    assert(OpenThreads::Thread::CurrentThread() == m_physicsThread);

    btSphereShape* newShape = new btSphereShape(radius);
    m_collisionShapes.push_back(newShape);

    btTransform initialTransform;
    initialTransform.setIdentity();
    initialTransform.setOrigin(btVector3(pos.x(), pos.y(), pos.z()));

    //btMotionState* motionState = new btDefaultMotionState(initialTransform);
    //btVector3 inertia;
    //newShape->calculateLocalInertia(0.0, inertia);

    // TODO: upgrade to the rigid body status?
    btCollisionObject* newBody = new btCollisionObject;
    newBody->setCollisionShape(newShape);
    newBody->setWorldTransform(initialTransform);
    m_collisionObjects.insert(std::make_pair(m_nextUsedId, newBody));
    ++m_nextUsedId;

    m_physicsWorld->addCollisionObject(newBody, COLLISION_ASTEROIDGROUP, COLLISION_SHIPGROUP);
    return m_nextUsedId - 1;
}
Ejemplo n.º 3
0
std::string toString(const osg::Vec3f &value)
{
    std::stringstream str;

    str << value.x() << " " << value.y() << " " << value.z();
    return str.str();
}
Ejemplo n.º 4
0
 void Storage::fixNormal (osg::Vec3f& normal, int cellX, int cellY, int col, int row)
 {
     while (col >= ESM::Land::LAND_SIZE-1)
     {
         ++cellY;
         col -= ESM::Land::LAND_SIZE-1;
     }
     while (row >= ESM::Land::LAND_SIZE-1)
     {
         ++cellX;
         row -= ESM::Land::LAND_SIZE-1;
     }
     while (col < 0)
     {
         --cellY;
         col += ESM::Land::LAND_SIZE-1;
     }
     while (row < 0)
     {
         --cellX;
         row += ESM::Land::LAND_SIZE-1;
     }
     ESM::Land* land = getLand(cellX, cellY);
     if (land && land->mDataTypes&ESM::Land::DATA_VNML)
     {
         normal.x() = land->mLandData->mNormals[col*ESM::Land::LAND_SIZE*3+row*3];
         normal.y() = land->mLandData->mNormals[col*ESM::Land::LAND_SIZE*3+row*3+1];
         normal.z() = land->mLandData->mNormals[col*ESM::Land::LAND_SIZE*3+row*3+2];
         normal.normalize();
     }
     else
         normal = osg::Vec3f(0,0,1);
 }
Ejemplo n.º 5
0
 osg::Vec3f CoordinateConverter::toLocalVec3(const osg::Vec3f& point)
 {
     return osg::Vec3f(
         point.x() - static_cast<float>(mCellX),
         point.y() - static_cast<float>(mCellY),
         point.z()
     );
 }
Ejemplo n.º 6
0
GeometryTransitPtr CSGGeometry::toOsgGeometry(CGAL::Polyhedron *p) {
	GeoPnt3fPropertyRecPtr positions = GeoPnt3fProperty::create();
	GeoVec3fPropertyRecPtr normals = GeoVec3fProperty::create();
	GeoUInt32PropertyRecPtr indices = GeoUInt32Property::create();

	/*
	 * Iterate over all faces, add their vertices to 'positions' && write indices at
	 * the same time. Results in no shared vertices && therefore no normal interpolation between
	 * faces, but makes cubes look good. Well, well...
	 */

	Matrix localToWorld = getWorldMatrix();
	OSG::Vec3f translation;
	OSG::Quaternion rotation;
	OSG::Vec3f scaleFactor;
	OSG::Quaternion scaleOrientation;
	localToWorld.getTransform(translation, rotation, scaleFactor, scaleOrientation);
	Matrix worldToLocal;
	worldToLocal.invertFrom(localToWorld);

	// Convert indices && positions
	int curIndex = 0;
	for (CGAL::Polyhedron::Facet_const_iterator it = p->facets_begin(); it != p->facets_end(); it++) {
		CGAL::Polyhedron::Halfedge_around_facet_const_circulator circ = it->facet_begin();
		do {
			CGAL::Point cgalPos = circ->vertex()->point();
			// We need to transform each point from global coordinates into our local coordinate system
			// (CGAL uses global, OpenSG has geometry in node-local coords)
			OSG::Vec3f vecPos = OSG::Vec3f(CGAL::to_double(cgalPos.x()),
											  CGAL::to_double(cgalPos.y()),
											  CGAL::to_double(cgalPos.z()));
			OSG::Vec3f localVec = worldToLocal * (vecPos - translation);
			OSG::Pnt3f osgPos(localVec.x(), localVec.y(), localVec.z());

			positions->addValue(osgPos);
			normals->addValue(Vec3f(0,1,0));
			indices->addValue(curIndex);
			curIndex++;
		} while (++circ != it->facet_begin());
	}

	GeoUInt8PropertyRecPtr types = GeoUInt8Property::create();
	types->addValue(GL_TRIANGLES);
	GeoUInt32PropertyRecPtr lengths = GeoUInt32Property::create();
	lengths->addValue(indices->size());

	GeometryRecPtr mesh = Geometry::create();
	mesh->setPositions(positions);
	mesh->setNormals(normals);
	mesh->setIndices(indices);
	mesh->setTypes(types);
	mesh->setLengths(lengths);
	mesh->setMaterial(VRMaterial::getDefault()->getMaterial());
    createSharedIndex(mesh);
	calcVertexNormals(mesh, 0.523598775598 /*30 deg in rad*/);

	return GeometryTransitPtr(mesh);
}
Ejemplo n.º 7
0
void RippleSimulation::emitRipple(const osg::Vec3f &pos)
{
    if (std::abs(pos.z() - mParticleNode->getPosition().z()) < 20)
    {
        osgParticle::Particle* p = mParticleSystem->createParticle(NULL);
        p->setPosition(osg::Vec3f(pos.x(), pos.y(), 0.f));
        p->setAngle(osg::Vec3f(0,0, Misc::Rng::rollProbability() * osg::PI * 2 - osg::PI));
    }
}
Ejemplo n.º 8
0
//***********************************************************
//FUNCTION:
void CPickNode::__drawCoordinateLine(const osg::Vec3f& vOrigin, float vLength, osg::ref_ptr<osg::Geode>& vLineNode)
{
	osg::ref_ptr<osg::Geometry> CoordGeometry = new osg::Geometry();
	osg::ref_ptr<osg::Vec3Array> CoordVertex = new osg::Vec3Array();

	CoordVertex->push_back(vOrigin);
	CoordVertex->push_back(osg::Vec3(vOrigin.x()+vLength, vOrigin.y(), vOrigin.z()));
	CoordVertex->push_back(vOrigin);
	CoordVertex->push_back(osg::Vec3(vOrigin.x(), vOrigin.y()+vLength, vOrigin.z()));
	CoordVertex->push_back(vOrigin);
	CoordVertex->push_back(osg::Vec3(vOrigin.x(), vOrigin.y(), vOrigin.z()+vLength));
	CoordGeometry->setVertexArray(CoordVertex.get());
	CoordGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, 6));

	osg::ref_ptr<osg::Vec4Array> VertColor = new osg::Vec4Array();
	VertColor->push_back(osg::Vec4(1.0, 0.0, 0.0, 1.0));
	VertColor->push_back(osg::Vec4(1.0, 0.0, 0.0, 1.0));
	VertColor->push_back(osg::Vec4(0.0, 1.0, 0.0, 1.0));
	VertColor->push_back(osg::Vec4(0.0, 1.0, 0.0, 1.0));
	VertColor->push_back(osg::Vec4(0.0, 0.0, 1.0, 1.0));
	VertColor->push_back(osg::Vec4(0.0, 0.0, 1.0, 1.0));
	CoordGeometry->setColorArray(VertColor.get());
	CoordGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);

	osg::ref_ptr<osg::LineWidth> LineSize = new osg::LineWidth();
	LineSize->setWidth(5);
	vLineNode->getOrCreateStateSet()->setAttributeAndModes(LineSize.get(), osg::StateAttribute::ON);
	vLineNode->addDrawable(CoordGeometry.get());
}
OSG_BASE_DLLMAPPING bool MatrixLookAt(OSG::Matrix &result,
                                      OSG::Pnt3f   from, 
                                      OSG::Pnt3f   at, 
                                      OSG::Vec3f   up    )
{
    Vec3f view;
    Vec3f right;
    Vec3f newup;
    Vec3f tmp;

    view = from - at;
    view.normalize();

    right = up.cross(view);

    if(right.dot(right) < TypeTraits<Real>::getDefaultEps())
    {
        return true;
    }

    right.normalize();

    newup = view.cross(right);

    result.setIdentity ();
    result.setTranslate(from[0], from[1], from[2]);

    Matrix tmpm;

    tmpm.setValue(right, newup, view);

    result.mult(tmpm);

    return false;
}
Ejemplo n.º 10
0
// Convenience function to calculate the translation base on a time and
// direction parameter.
OSG::Vec3f calcTranslation(OSG::Real32 t, OSG::Vec3f dir)
{
   // The 'dir' vector encodes direction and velocity
   OSG::Real32 v = dir.length();
   OSG::Real32 s = v * t;
   return(dir * s);
}
osg::Vec3f ShapeVisitor_RestrictedPositionGetter::toCube( const osg::Vec3f& center, const osg::Vec3f& surfaceX, const osg::Vec3f& surfaceY, const osg::Vec3f& surfaceZ, const osg::Vec3f& point )
{
	float distanceX = std::fabs( ( center - surfaceX ).x() );
	float distanceY = std::fabs( ( center - surfaceY ).y() );
	float distanceZ = std::fabs( ( center - surfaceZ ).z() );

	//  nearest_point_on_box(x, y, z, box_min_x, box_min_y, box_min_z, box_max_x, box_max_y, box_max_z)
	float x = /*point.x() -*/ median( point.x(), center.x() - distanceX, center.x() + distanceX );
	float y = /*point.y() -*/ median( point.y(), center.y() - distanceY, center.y() + distanceY );
	float z = /*point.z() -*/ median( point.z(), center.z() - distanceZ, center.z() + distanceZ );

	return osg::Vec3f( x,y,z );
}
Ejemplo n.º 12
0
bool
TritonContext::intersect(const osg::Vec3d& start, const osg::Vec3d& dir, float& out_height, osg::Vec3f& out_normal) const
{
    ::Triton::Vector3 p(start.ptr());
    ::Triton::Vector3 d(dir.ptr());
    ::Triton::Vector3 normal;
    bool ok = _ocean->GetHeight(p, d, out_height, normal);
    out_normal.set(normal.x, normal.y, normal.z);
    return ok;
}
Ejemplo n.º 13
0
 void Storage::averageNormal(osg::Vec3f &normal, int cellX, int cellY, int col, int row)
 {
     osg::Vec3f n1,n2,n3,n4;
     fixNormal(n1, cellX, cellY, col+1, row);
     fixNormal(n2, cellX, cellY, col-1, row);
     fixNormal(n3, cellX, cellY, col, row+1);
     fixNormal(n4, cellX, cellY, col, row-1);
     normal = (n1+n2+n3+n4);
     normal.normalize();
 }
Ejemplo n.º 14
0
    void Scene::playerMoved(const osg::Vec3f &pos)
    {
        if (!mCurrentCell || !mCurrentCell->isExterior())
            return;

        // figure out the center of the current cell grid (*not* necessarily mCurrentCell, which is the cell the player is in)
        int cellX, cellY;
        getGridCenter(cellX, cellY);
        float centerX, centerY;
        MWBase::Environment::get().getWorld()->indexToPosition(cellX, cellY, centerX, centerY, true);
        const float maxDistance = 8192/2 + 1024; // 1/2 cell size + threshold
        float distance = std::max(std::abs(centerX-pos.x()), std::abs(centerY-pos.y()));
        if (distance > maxDistance)
        {
            int newX, newY;
            MWBase::Environment::get().getWorld()->positionToIndex(pos.x(), pos.y(), newX, newY);
            changeCellGrid(newX, newY);
            //mRendering.updateTerrain();
        }
    }
Ejemplo n.º 15
0
//***********************************************************
//FUNCTION:
void CPickNode::__drawCoordinateMask(const osg::Vec3f& vOrigin, float vLength, osg::ref_ptr<osg::Geode>& vMaskNode)
{
	osg::ref_ptr<osg::Geometry> MakGeom = new osg::Geometry();
	osg::ref_ptr<osg::Vec3Array> MaskVert = new osg::Vec3Array();

	for (unsigned int i=1; i<=10; i++)
	{
		float Offfset = vLength / 10.0 * i;
		MaskVert->push_back(osg::Vec3(vOrigin.x()+Offfset, vOrigin.y(), vOrigin.z()));
		MaskVert->push_back(osg::Vec3(vOrigin.x(), vOrigin.y()+Offfset, vOrigin.z()));
		MaskVert->push_back(osg::Vec3(vOrigin.x(), vOrigin.y(), vOrigin.z()+Offfset));
	}
	osg::ref_ptr<osg::Vec4Array> ColorArray = new osg::Vec4Array;
	ColorArray->push_back(osg::Vec4(1.0, 1.0, 1.0, 1.0));

	MakGeom->setVertexArray(MaskVert.get());
	MakGeom->setColorArray(ColorArray);
	MakGeom->setColorBinding(osg::Geometry::BIND_OVERALL);

	MakGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::POINTS, 0, 30));
	vMaskNode->addDrawable(MakGeom.get());

	osg::ref_ptr<osg::Point> PointSize = new osg::Point(5.0);
	osg::ref_ptr<osg::StateSet> PointStateSet = vMaskNode->getOrCreateStateSet();
	PointStateSet->setAttribute(PointSize);
}
Ejemplo n.º 16
0
osg::Vec4f Raytracer::renderPixel(int x, int y, const osg::Vec3f& eye, const osg::Vec3f& dir)
{
    osg::Vec3f lightPos(-338.572, 0, 400);
    RTCRay ray;
    ray.primID = RTC_INVALID_GEOMETRY_ID;
    ray.geomID = RTC_INVALID_GEOMETRY_ID;
    ray.instID = RTC_INVALID_GEOMETRY_ID;
    ray.tnear = 0.0f;
    ray.tfar = 100000.0f;
    ray.org[0] = eye.x();
    ray.org[1] = eye.y();
    ray.org[2] = eye.z();
    ray.dir[0]=  dir.x();
    ray.dir[1] = dir.y();
    ray.dir[2] = dir.z();
    rtcIntersect(_scene, ray);
    if(ray.primID != -1)
    {
        osg::Vec3f pos = eye + dir*ray.tfar;
        osg::Vec4f diffuse = getSurfaceColor(ray.geomID, ray.primID,ray.u,ray.v);
        osg::Vec3 normal = getNormal(ray.geomID,ray.primID,ray.u,ray.v);
        osg::Vec3f lightDir = lightPos - pos;
        lightDir.normalize();

        float NdotL = std::max(normal * lightDir,0.0f);
        return diffuse * NdotL;

    }
    return _backgroundColor;
}
Ejemplo n.º 17
0
void ActorTracer::findGround(const Actor* actor, const osg::Vec3f& start, const osg::Vec3f& end, const btCollisionWorld* world)
{
    const btVector3 btstart(start.x(), start.y(), start.z());
    const btVector3 btend(end.x(), end.y(), end.z());

    const btTransform &trans = actor->getCollisionObject()->getWorldTransform();
    btTransform from(trans.getBasis(), btstart);
    btTransform to(trans.getBasis(), btend);

    ClosestNotMeConvexResultCallback newTraceCallback(actor->getCollisionObject(), btstart-btend, btScalar(0.0));
    // Inherit the actor's collision group and mask
    newTraceCallback.m_collisionFilterGroup = actor->getCollisionObject()->getBroadphaseHandle()->m_collisionFilterGroup;
    newTraceCallback.m_collisionFilterMask = actor->getCollisionObject()->getBroadphaseHandle()->m_collisionFilterMask;
    newTraceCallback.m_collisionFilterMask &= ~CollisionType_Actor;

    world->convexSweepTest(actor->getConvexShape(), from, to, newTraceCallback);
    if(newTraceCallback.hasHit())
    {
        const btVector3& tracehitnormal = newTraceCallback.m_hitNormalWorld;
        mFraction = newTraceCallback.m_closestHitFraction;
        mPlaneNormal = osg::Vec3f(tracehitnormal.x(), tracehitnormal.y(), tracehitnormal.z());
        mEndPos = (end-start)*mFraction + start;
    }
    else
    {
        mEndPos = end;
        mPlaneNormal = osg::Vec3f(0.0f, 0.0f, 1.0f);
        mFraction = 1.0f;
    }
}
Ejemplo n.º 18
0
unsigned int PhysicsEngine::addUserVehicle(const osg::Vec3f& pos, const osg::Vec3f& sizes, const osg::Quat& orient, float mass)
{
    assert(OpenThreads::Thread::CurrentThread() == m_physicsThread);

    if (! m_vehicleShape)
        m_vehicleShape = new btBoxShape(btVector3(sizes.x() / 2, sizes.y() / 2, sizes.z() / 2));
    //m_collisionShapes.push_back(m_vehicleShape);

    btTransform startTransform;
    startTransform.setIdentity();
    startTransform.setRotation(btQuaternion(orient.x(), orient.y(), orient.z(), orient.w()));
    startTransform.setOrigin(btVector3(pos.x(), pos.y(), pos.z()));

    VehicleMotionState* motionState = new VehicleMotionState(this, m_nextUsedId, startTransform);
    btVector3 inertia;
    m_vehicleShape->calculateLocalInertia(mass, inertia);

    btRigidBody* body = new btRigidBody(mass, motionState, m_vehicleShape, inertia);
    m_vehicles[m_nextUsedId] = body;
    ++m_nextUsedId;

    body->setDamping(0.5f, 0.7f);
    m_physicsWorld->addRigidBody(body, COLLISION_SHIPGROUP, COLLISION_SHIPGROUP | COLLISION_ASTEROIDGROUP);

    return m_nextUsedId - 1;
}
Ejemplo n.º 19
0
/*
 Linearly interpolate the position where an isosurface cuts
 an edge between two vertices, each with their own scalar value
 */
osg::Vec3f VertexInterp(double isolevel, osg::Vec3f p1, osg::Vec3f p2, double valp1, double valp2)
{
	double mu;
	osg::Vec3f p;
	
	if (ABS(isolevel-valp1) < 0.00001)
		return p1;
	if (ABS(isolevel-valp2) < 0.00001)
		return p2;
	if (ABS(valp1-valp2) < 0.00001)
		return p1;
	
	mu = (isolevel - valp1) / (valp2 - valp1);
	
	p.set(p1.x() + mu * (p2.x() - p1.x()),
		  p1.y() + mu * (p2.y() - p1.y()),
		  p1.z() + mu * (p2.z() - p1.z()));
	
	return p;
}
Ejemplo n.º 20
0
const osg::Vec3f Stars::sRgbColor(const osg::Vec3f xyzTristimulus)
{
    // (The Colors of the Stars - Olson - 1998) - sRGB matrix - feel free to use other matrices here...

    const float r =  3.24  * xyzTristimulus.x() -1.537 * xyzTristimulus.y() -0.499 * xyzTristimulus.z();
    const float g = -0.969 * xyzTristimulus.x() +1.876 * xyzTristimulus.y() +0.042 * xyzTristimulus.z();
    const float b =  0.056 * xyzTristimulus.x() -0.204 * xyzTristimulus.y() +1.057 * xyzTristimulus.z();

    return osg::Vec3f(r, g, b);
}
Ejemplo n.º 21
0
//------------------------------------------------------------------------------
osg::ref_ptr<osg::Node> setupScene( osg::ref_ptr<osg::Geometry> geom, osg::Vec3f bbmin, osg::Vec3f bbmax )
{
    osg::ref_ptr<osg::Group> scene = new osg::Group;

    //////////////////////////////
    // CREATE PARTICLE GEOMETRY //
    //////////////////////////////
    osg::ref_ptr<osg::Geode> geode = new osg::Geode;
    geode->addDrawable( geom.get() );

    osg::ref_ptr<osg::Program> computation = new osg::Program;

    const std::string vtxShader=
        "uniform vec2 pixelsize;                                                                \n"
        "                                                                                       \n"
        "void main(void)                                                                        \n"
        "{                                                                                      \n"
        "   vec4 worldPos = vec4(gl_Vertex.x,gl_Vertex.y,gl_Vertex.z,1.0);                      \n"
        "   vec4 projPos = gl_ModelViewProjectionMatrix * worldPos;                             \n"
        "                                                                                       \n"
        "   float dist = projPos.z / projPos.w;                                                 \n"
        "   float distAlpha = (dist+1.0)/2.0;                                                   \n"
        "   gl_PointSize = pixelsize.y - distAlpha * (pixelsize.y - pixelsize.x);               \n"
        "                                                                                       \n"
        "   gl_Position = projPos;                                                              \n"
        "}                                                                                      \n";
    computation->addShader( new osg::Shader(osg::Shader::VERTEX, vtxShader ) );

    const std::string frgShader=
        "void main (void)                                                                       \n"
        "{                                                                                      \n"
        "   vec4 result;                                                                        \n"
        "                                                                                       \n"
        "   vec2 tex_coord = gl_TexCoord[0].xy;                                                 \n"
        "   tex_coord.y = 1.0-tex_coord.y;                                                      \n"
        "   float d = 2.0*distance(tex_coord.xy, vec2(0.5, 0.5));                               \n"
        "   result.a = step(d, 1.0);                                                            \n"
        "                                                                                       \n"
        "   vec3 eye_vector = normalize(vec3(0.0, 0.0, 1.0));                                   \n"
        "   vec3 light_vector = normalize(vec3(2.0, 2.0, 1.0));                                 \n"
        "   vec3 surface_normal = normalize(vec3(2.0*                                           \n"
        "           (tex_coord.xy-vec2(0.5, 0.5)), sqrt(1.0-d)));                               \n"
        "   vec3 half_vector = normalize(eye_vector+light_vector);                              \n"
        "                                                                                       \n"
        "   float specular = dot(surface_normal, half_vector);                                  \n"
        "   float diffuse  = dot(surface_normal, light_vector);                                 \n"
        "                                                                                       \n"
        "   vec4 lighting = vec4(0.75, max(diffuse, 0.0), pow(max(specular, 0.0), 40.0), 0.0);  \n"
        "                                                                                       \n"
        "   result.rgb = lighting.x*vec3(0.2, 0.8, 0.2)+lighting.y*vec3(0.6, 0.6, 0.6)+         \n"
        "   lighting.z*vec3(0.25, 0.25, 0.25);                                                  \n"
        "                                                                                       \n"
        "   gl_FragColor = result;                                                              \n"
        "}                                                                                      \n";

    computation->addShader( new osg::Shader( osg::Shader::FRAGMENT, frgShader ) );
    geode->getOrCreateStateSet()->setAttribute(computation);
    geode->getOrCreateStateSet()->setMode(GL_VERTEX_PROGRAM_POINT_SIZE, osg::StateAttribute::ON);
    geode->getOrCreateStateSet()->setTextureAttributeAndModes(0, new osg::PointSprite, osg::StateAttribute::ON);
    geode->getOrCreateStateSet()->setAttribute( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.1f) );
    geode->getOrCreateStateSet()->setMode( GL_ALPHA_TEST, GL_TRUE );
    geode->getOrCreateStateSet()->addUniform( new osg::Uniform( "pixelsize", osg::Vec2(1.0f,50.0f) ) ); 
    geode->setCullingActive( false );
    scene->addChild( geode );

    /////////////////////////
    // CREATE BOUNDING BOX //
    /////////////////////////
    osg::Geode* bbox = new osg::Geode;
    bbox->addDrawable(new osg::ShapeDrawable(new osg::Box((bbmin + bbmax) * 0.5f,bbmax.x() - bbmin.x(),bbmax.y() - bbmin.y(),bbmax.z() - bbmin.z()),new osg::TessellationHints()));
    bbox->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
    bbox->getOrCreateStateSet()->setAttribute( new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK,osg::PolygonMode::LINE));
    scene->addChild( bbox );

    return scene;
}
Ejemplo n.º 22
0
void vecfFunc(osg::Vec3f vec) {
    std::cout << "Got the float vector " << vec.x() << "," << vec.y() << "," << vec.z() << std::endl;
}
Ejemplo n.º 23
0
    float Storage::getHeightAt(const osg::Vec3f &worldPos)
    {
        int cellX = static_cast<int>(std::floor(worldPos.x() / 8192.f));
        int cellY = static_cast<int>(std::floor(worldPos.y() / 8192.f));

        ESM::Land* land = getLand(cellX, cellY);
        if (!land || !(land->mDataTypes&ESM::Land::DATA_VHGT))
            return -2048;

        // Mostly lifted from Ogre::Terrain::getHeightAtTerrainPosition

        // Normalized position in the cell
        float nX = (worldPos.x() - (cellX * 8192))/8192.f;
        float nY = (worldPos.y() - (cellY * 8192))/8192.f;

        // get left / bottom points (rounded down)
        float factor = ESM::Land::LAND_SIZE - 1.0f;
        float invFactor = 1.0f / factor;

        int startX = static_cast<int>(nX * factor);
        int startY = static_cast<int>(nY * factor);
        int endX = startX + 1;
        int endY = startY + 1;

        endX = std::min(endX, ESM::Land::LAND_SIZE-1);
        endY = std::min(endY, ESM::Land::LAND_SIZE-1);

        // now get points in terrain space (effectively rounding them to boundaries)
        float startXTS = startX * invFactor;
        float startYTS = startY * invFactor;
        float endXTS = endX * invFactor;
        float endYTS = endY * invFactor;

        // get parametric from start coord to next point
        float xParam = (nX - startXTS) * factor;
        float yParam = (nY - startYTS) * factor;

        /* For even / odd tri strip rows, triangles are this shape:
        even     odd
        3---2   3---2
        | / |   | \ |
        0---1   0---1
        */

        // Build all 4 positions in normalized cell space, using point-sampled height
        osg::Vec3f v0 (startXTS, startYTS, getVertexHeight(land, startX, startY) / 8192.f);
        osg::Vec3f v1 (endXTS, startYTS, getVertexHeight(land, endX, startY) / 8192.f);
        osg::Vec3f v2 (endXTS, endYTS, getVertexHeight(land, endX, endY) / 8192.f);
        osg::Vec3f v3 (startXTS, endYTS, getVertexHeight(land, startX, endY) / 8192.f);
        // define this plane in terrain space
        osg::Plane plane;
        // FIXME: deal with differing triangle alignment
        if (true)
        {
            // odd row
            bool secondTri = ((1.0 - yParam) > xParam);
            if (secondTri)
                plane = osg::Plane(v0, v1, v3);
            else
                plane = osg::Plane(v1, v2, v3);
        }
        /*
        else
        {
            // even row
            bool secondTri = (yParam > xParam);
            if (secondTri)
                plane.redefine(v0, v2, v3);
            else
                plane.redefine(v0, v1, v2);
        }
        */

        // Solve plane equation for z
        return (-plane.getNormal().x() * nX
                -plane.getNormal().y() * nY
                - plane[3]) / plane.getNormal().z() * 8192;

    }
Ejemplo n.º 24
0
bool
ModelData::update()
{
    // -- Update bone parameters --
    bool anythingChanged = false;
    for ( BoneParamsVector::iterator
              b    = bones.begin(),
              bEnd = bones.end() - 1;
          b < bEnd; ++b )
    {
        const CalQuaternion& rotation = b->bone->getRotationBoneSpace();
        const CalVector&     translation = b->bone->getTranslationBoneSpace();
        const CalMatrix&     rm = b->bone->getTransformMatrix();

        const osg::Matrix3   r( rm.dxdx, rm.dydx, rm.dzdx,
                                rm.dxdy, rm.dydy, rm.dzdy,
                                rm.dxdz, rm.dydz, rm.dzdz );
        const osg::Vec3f     t( translation.x, translation.y, translation.z );

        // -- Check for deformed --
        b->deformed =
            // cal3d reports nonzero translations for non-animated models
            // and non zero quaternions (seems like some FP round-off error). 
            // So we must check for deformations using some epsilon value.
            // Problem:
            //   * It is cal3d that must return correct values, no epsilons
            // But nevertheless we use this to reduce CPU load.

            t.length() > /*boundingBox.radius() **/ 1e-5 // usually 1e-6 .. 1e-7
            ||
            osg::Vec3d( rotation.x,
                        rotation.y,
                        rotation.z ).length() > 1e-6 // usually 1e-7 .. 1e-8
            ;

        // -- Check for changes --
        float s = 0;
        for ( int j = 0; j < 9; j++ )
        {
            s += square( r[j] - b->rotation[j] );
        }
        s += ( t - b->translation ).length2();

        if ( s < 1e-7 ) // usually 1e-11..1e-12
        {
            b->changed = false;
        }
        else
        {
            b->changed = true;
            anythingChanged = true;
            b->rotation = r;
            b->translation = t;
        }
        
//         std::cout << "bone: " << b->bone->getCoreBone()->getName() << std::endl
//                   << "quaternion: "
//                   << rotation.x << ' '
//                   << rotation.y << ' '
//                   << rotation.z << ' '
//                   << rotation.w << std::endl
//                   << "translation: "
//                   << t.x() << ' ' << t.y() << ' ' << t.z()
//                   << "; len = " << t.length()
//                   << "; s = " << s // << std::endl
//                   << "; changed = " << b->changed // << std::endl
//                   << "; deformed = " << b->deformed // << std::endl
// //                  << "len / bbox.radius = " << translation.length() / boundingBox.radius()
//                   << std::endl;
    }

    return anythingChanged;
}
Ejemplo n.º 25
0
// on cull begin
void LightNodeHandler::onCullBegin( osgUtil::CullVisitor * pCV, const osg::BoundingSphere * pSpherePtr /* = NULL */ )
{
    if(!_init)
        return;

    if(!m_pFatherRef)
        m_pFatherRef = GetScene()->getLights();

    // current stateset to work with
    const bool bReflPass = (pCV->getCullMask() == REFLECTION_MASK/*0x00010000UL*/);
    LightsPackStateSet & curStatePack = (bReflPass) ? m_lightsRefl : m_lightsMain;
    const std::vector<LightExternalInfo> & aCullVisibleLights = (bReflPass) ? m_pFatherRef->m_aReflVisibleLights : m_pFatherRef->m_aMainVisibleLights;
    const std::vector<LightProcessedInfo> & aCullProcessedLights = (bReflPass) ? m_pFatherRef->m_aReflProcessedLights : m_pFatherRef->m_aMainProcessedLights;
    // was state pushed last time?
    bool & bWasActive = (bReflPass) ? m_bReflWasActive : m_bMainWasActive;

    // calculate lights for specific geometry
    unsigned uLightsAdded = 0;
    for (unsigned i = 0; i < aCullVisibleLights.size() && uLightsAdded < nMaxLights; ++i)
    {
        const LightExternalInfo & lightData = aCullVisibleLights[i];

        // too big priority - continue
        if (lightData.uPriority > m_uMaxPriority)
            continue;

        const LightProcessedInfo & uniformData = aCullProcessedLights[i];

        // calculate whether light touches sphere
        if (pSpherePtr)
        {
            // test for spheres non-intersection
            const osg::Vec3f vVSLightPos(uniformData.lightVSPosAmbRatio.x(), uniformData.lightVSPosAmbRatio.y(), uniformData.lightVSPosAmbRatio.z());
            const float fRadSqrSum = cg::sqr(lightData.rDistAtt.hi() + pSpherePtr->radius());
            const osg::Vec3f vVecToCenter = pSpherePtr->center() - vVSLightPos;
            if (vVecToCenter.length2() >= fRadSqrSum)
                continue;

            // if cone - test for cone intersection
            if (!lightData.rConeAtt.empty() && vVecToCenter.length2() > pSpherePtr->radius2())
            {
                // get direction angle
                osg::Vec3f vVecToCenterDir = vVecToCenter;
                const float fVecLength = vVecToCenterDir.normalize();
                const float
                    fCenterAngle = acosf(vVecToCenterDir * osg::Vec3f(uniformData.lightVSDirSpecRatio.x(), uniformData.lightVSDirSpecRatio.y(), uniformData.lightVSDirSpecRatio.z())),
                    fSphereAngle = atan2f(pSpherePtr->radius(), fVecLength),
                    fMinDirAngle = std::max(fCenterAngle - fSphereAngle, 0.f);
                if (fMinDirAngle >= lightData.rConeAtt.hi())
                    continue;
            }
        }

#if LIGHTS_TURN_ON
        // okey, so we can add
        curStatePack.LightVSPosAmbRatio->setElement(uLightsAdded, uniformData.lightVSPosAmbRatio);
        curStatePack.LightVSDirSpecRatio->setElement(uLightsAdded, uniformData.lightVSDirSpecRatio);
        curStatePack.LightAttenuation->setElement(uLightsAdded, uniformData.lightAttenuation);
        curStatePack.LightDiffuse->setElement(uLightsAdded, uniformData.lightDiffuse);
#endif
        uLightsAdded++;
    }

    // so push stateset if needed
    m_bStatePushed = false;
    if (uLightsAdded > 0 || bWasActive)
    {
        curStatePack.LightsActiveNum->set(int(uLightsAdded));
        pCV->pushStateSet(curStatePack.pStateSet.get());
        bWasActive = (uLightsAdded > 0);
        m_bStatePushed = true;
    }

    // exit
    return;
}
Ejemplo n.º 26
0
int init(int argc, char **argv)
{
    OSG::osgInit(argc,argv);
    
    // GLUT init

    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
    int winid = glutCreateWindow("OpenSG");
    glutKeyboardFunc(key);
    glutVisibilityFunc(vis);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);       
    glutMouseFunc(mouse);   
    glutMotionFunc(motion); 
    
    glutIdleFunc(display);  

    // OSG
    OSG::SceneFileHandler::the()->print();

    // create the graph

    // beacon for camera and light  
    OSG::NodeUnrecPtr b1n = OSG::Node::create();
    OSG::GroupUnrecPtr b1 = OSG::Group::create();

    b1n->setCore(b1);

    // transformation
    OSG::NodeUnrecPtr      t1n = OSG::Node::create();
    OSG::TransformUnrecPtr t1  = OSG::Transform::create();

    t1n->setCore (t1 );
    t1n->addChild(b1n);

    cam_trans = t1;

    // light
    OSG::NodeUnrecPtr             dlight = OSG::Node::create();
    OSG::DirectionalLightUnrecPtr dl     = OSG::DirectionalLight::create();

    dlight->setCore(dl);
    
    dl->setAmbient  (0.0, 0.0, 0.0, 1.0);
    dl->setDiffuse  (0.8, 0.8, 0.8, 1.0);
    dl->setDirection(0.0, 0.0, 1.0     );
    dl->setBeacon   (b1n               );

    // root
    OSG::NodeUnrecPtr  root = OSG::Node::create();
    OSG::GroupUnrecPtr gr1  = OSG::Group::create();

    root->setCore (gr1   );
    root->addChild(t1n   );
    root->addChild(dlight);

    // Load the file
    OSG::NodeUnrecPtr file = NULL;
    
    if(argc > 1)
    {
        file = OSG::SceneFileHandler::the()->read(argv[1], NULL);
    }

    if(file == NULL)
    {
        std::cerr << "Couldn't load file, ignoring" << std::endl;

        //file = OSG::makeSphere(4, 2.0);

        file = OSG::Node::create();
        OSG::AlgorithmStageUnrecPtr pStage = OSG::AlgorithmStage::create();

        file->setCore(pStage);

        pAlgo = OSG::GPUVolRTV2::create();

        pStage->setAlgorithm(pAlgo);

        // fix/freeze the node volume
        file->editVolume().setStatic(true);
        file->editVolume().setBounds( 0.f,   0.f,   0.f,
                                      1.f,   1.f,   1.f);
        
   }
   
    OSG::commitChanges();

    file->updateVolume();


    OSG::Vec3f min,max;
    file->getVolume().getBounds( min, max );
    

    std::cout << "Volume: from " << min << " to " << max << std::endl;



    OSG::MultiCoreUnrecPtr pMCore = OSG::MultiCore::create();

                         pCOver      = OSG::ChunkOverrideGroup::create();
    OSG::TransformRecPtr scene_trans = OSG::Transform::create();

    pMCore->addCore(scene_trans);
    pMCore->addCore(pCOver     );

    pPoly = OSG::PolygonChunk::create();

    OSG::NodeUnrecPtr sceneTrN = OSG::Node::create();

    sceneTrN->setCore (pMCore);
    sceneTrN->addChild(file  );

    dlight->addChild(sceneTrN);


    // Camera
    
    OSG::PerspectiveCameraRecPtr cam = OSG::PerspectiveCamera::create();

    cam->setBeacon(b1n                   );
    cam->setFov   (OSG::osgDegree2Rad(60));
    cam->setNear  (0.1                   );
    cam->setFar   (400                   );

    // Background
    OSG::SolidBackgroundUnrecPtr bkgnd = OSG::SolidBackground::create();

    bkgnd->setColor(OSG::Color3f(0,0,0));
    
    // Viewport
    OSG::ViewportRecPtr vp = OSG::Viewport::create();

    vp->setCamera    (cam       );
    vp->setBackground(bkgnd     );
    vp->setRoot      (root      );
    vp->setSize      (0, 0, 1, 1);


    // Window
    std::cout << "GLUT winid: " << winid << std::endl;

    GLint glvp[4];

    glGetIntegerv(GL_VIEWPORT, glvp);

    OSG::GLUTWindowUnrecPtr gwin = OSG::GLUTWindow::create();

    gwin->setGlutId(winid);
    gwin->setSize( glvp[2], glvp[3] );

    win = gwin;

    win->addPort(vp);

    win->init();


    // Action
    rentravact = OSG::RenderAction::create();
//    renact->setFrustumCulling(false);


    // tball

    OSG::Vec3f pos;
    pos.setValues(min[0] + ((max[0] - min[0]) * 0.5), 
                  min[1] + ((max[1] - min[1]) * 0.5), 
                  max[2] + ( max[2] - min[2] ) * 1.5 );
    
    float scale = (max[2] - min[2] + max[1] - min[1] + max[0] - min[0]) / 6;

    OSG::Pnt3f tCenter(min[0] + (max[0] - min[0]) / 2,
                       min[1] + (max[1] - min[1]) / 2,
                       min[2] + (max[2] - min[2]) / 2);

    fprintf(stderr, "Startpos : %f %f %f\n", pos[0], pos[1], pos[2]);

    tball.setMode            (OSG::Trackball::OSGObject);
    tball.setStartPosition   (pos, true                );
    tball.setSum             (true                     );
    tball.setTranslationMode (OSG::Trackball::OSGFree  );
    tball.setTranslationScale(scale                    );
    tball.setRotationCenter  (tCenter                  );

    // run...


    return 0;
}
Ejemplo n.º 27
0
 inline void update(void)
 {
    _pat.setPosition(osg::Vec3f(_eye.x(), _eye.y(), _pat.getPosition().z()));
 }
Ejemplo n.º 28
0
bool SDCloudLayer::reposition( const osg::Vec3f& p, double dt )
{
    if (getCoverage() != SDCloudLayer::SD_CLOUD_CLEAR)
    {
        osg::Vec3 asl_offset( p );
        asl_offset.normalize();
        if ( p.y() <= layer_asl )
        {
            asl_offset *= layer_asl;
        } else
        {
            asl_offset *= layer_asl + layer_thickness;
        }

        asl_offset += p;

        osg::Matrix T, LON, LAT;
        T.makeTranslate( asl_offset );
        //LON.makeRotate(lon, osg::Vec3(0, 0, 1));
        //LAT.makeRotate(90.0 * SD_DEGREES_TO_RADIANS - lat, osg::Vec3(0, 1, 0));

        layer_transform->setMatrix( T );

        group_bottom->getStateSet()->setRenderBinDetails(-(int)layer_asl, "RenderBin");
        group_top->getStateSet()->setRenderBinDetails((int)layer_asl, "RenderBin");
        if ( alt <= layer_asl )
        {
            layer_root->setSingleChildOn(0);
        } else if ( alt >= layer_asl + layer_thickness )
        {
            layer_root->setSingleChildOn(1);
        } else
        {
            layer_root->setAllChildrenOff();
        }

        double sp_dist = speed * dt;
        
        if ( p.x() != last_x || p.y() != last_y || sp_dist != 0 )
        {
            double ax = 0.0, ay = 0.0, bx = 0.0, by = 0.0;

            if (sp_dist > 0)
            {
                bx = cos((180.0-direction) * SD_DEGREES_TO_RADIANS) * sp_dist;
                by = sin((180.0-direction) * SD_DEGREES_TO_RADIANS) * sp_dist;
            }

            double xoff = (ax + bx) / (2 * scale);
            double yoff = (ay + by) / (2 * scale);

            const float layer_scale = layer_span / scale;

            base[0] += xoff;

            if ( base[0] > -10.0 && base[0] < 10.0 )
            {
                base[0] -= (int)base[0];
            } else
            {
                base[0] = 0.0;
            }

            base[1] += yoff;

            if ( base[1] > -10.0 && base[1] < 10.0 )
            {
                base[1] -= (int)base[1];
            } else
            {
                base[1] = 0.0;
            }

            setTextureOffset(base);
            last_pos = p;
            scale = layer_scale;
        }
    }

    //layer3D->reposition( p, up, lon, lat, dt, layer_asl, speed, direction);

    return true;
}
int init(int argc, char **argv)
{
    OSG::osgInit(argc,argv);
    
    // GLUT init

    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
    int winid = glutCreateWindow("OpenSG");
    glutKeyboardFunc(key);
    glutVisibilityFunc(vis);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);       
    glutMouseFunc(mouse);   
    glutMotionFunc(motion); 
    
    glutIdleFunc(display);  

    // glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
    
//    glEnable( GL_DEPTH_TEST );
//    glEnable( GL_LIGHTING );
//    glEnable( GL_LIGHT0 );
//    glFrontFace(GL_CW);
    glEnable(GL_CULL_FACE);

    // OSG

    OSG::SceneFileHandler::the()->print();

    // create the graph

    // beacon for camera and light  
    OSG::NodeUnrecPtr b1n = OSG::Node::create();
    OSG::GroupUnrecPtr b1 = OSG::Group::create();

    b1n->setCore( b1 );

    // transformation
    OSG::NodeUnrecPtr t1n = OSG::Node::create();
    OSG::TransformUnrecPtr t1 = OSG::Transform::create();

    t1n->setCore( t1 );
    t1n->addChild( b1n );

    cam_trans = t1;

    // light
    
    OSG::NodeUnrecPtr dlight = OSG::Node::create();
    OSG::DirectionalLightUnrecPtr dl = OSG::DirectionalLight::create();

    dlight->setCore( dl );
//    dlight->setCore( Group::create() );
    
    dl->setAmbient( .0, .0, .0, 1 );
    dl->setDiffuse( .8f, .8f, .8f, 1.f );
    dl->setDirection(0,0,1);
    dl->setBeacon( b1n);

    // root
    root = OSG::Node::create();
    OSG::GroupUnrecPtr gr1 = OSG::Group::create();

    root->setCore( gr1 );
    root->addChild( t1n );
    root->addChild( dlight );

    // Load the file

    OSG::NodeUnrecPtr file = NULL;
    
    if(argc > 1)
        file = OSG::SceneFileHandler::the()->read(argv[1], NULL);
    
    if ( file == NULL )
    {
        std::cerr << "Couldn't load file, ignoring" << std::endl;

        file = OSG::makeSphere(4, 2.0);

    }

#if 0
    OSG::GeometryPtr pGeo = cast_dynamic<OSG::GeometryPtr>(file->getCore());
    
    if(pGeo == NULL && file->getNChildren() != 0)
    {
        pGeo = cast_dynamic<OSG::GeometryPtr>(file->getChild(0)->getCore());
    }

    if(pGeo == NULL)
    {
        fprintf(stderr, "no geo\n");
    }
#endif

//    OSG::GraphOpRefPtr op = OSG::GraphOpFactory::the()->create("Stripe");

//    op->traverse(file);
//    createOptimizedPrimitives(pGeo);
//    createSharedIndex(pGeo);
    
    OSG::Thread::getCurrentChangeList()->commitChanges();

//    file->dump();
    file->updateVolume();

#if 0
    const char *outFileName = "/tmp/foo1.osg";

    OSG::IndentFileOutStream outFileStream(outFileName);

    if( !outFileStream )
    {
        std::cerr << "Can not open output stream to file: "
                  << outFileName << std::endl;
        return -1;
    }

    std::cerr << "STARTING PRINTOUT:" << std::endl;
    OSGWriter writer( outFileStream, 4 );

    writer.write( file );

    outFileStream.close();

    OSG::SceneFileHandler::the()->write(file, "/tmp/foo.osb");
#endif    


//    return 0;


    OSG::Vec3f min,max;
    file->getVolume().getBounds( min, max );
    

    std::cout << "Volume: from " << min << " to " << max << std::endl;


    OSG::MultiCoreUnrecPtr pMCore = OSG::MultiCore::create();

    pCOver      = OSG::ChunkOverrideGroup::create();
    scene_trans = OSG::Transform::create();

    pMCore->addCore(scene_trans);
    pMCore->addCore(pCOver     );

    OSG::NodeUnrecPtr sceneTrN = OSG::Node::create();

    sceneTrN->setCore(pMCore);
    sceneTrN->addChild(file);


    dlight->addChild(sceneTrN);

    std::cerr << "Tree: " << std::endl;
//  root->dump();

    // Camera
    
    cam = OSG::PerspectiveCamera::create();

    cam->setBeacon( b1n );
    cam->setFov( OSG::osgDegree2Rad( 90 ) );
    cam->setNear( 0.1f );
    cam->setFar( 100000 );

    // Background
    OSG::SolidBackgroundUnrecPtr bkgnd = OSG::SolidBackground::create();

    bkgnd->setColor(OSG::Color3f(1,0,0));
    
    // Viewport

    vp = OSG::Viewport::create();

    vp->setCamera( cam );
    vp->setBackground( bkgnd );
    vp->setRoot( root );
    vp->setSize( 0,0, 1,1 );

#if 0
    OSG::UInt8 imgdata[] =
    {  
        64,64,64, 128,128,128, 192,192,192, 255,255,255 
    };
#endif

    pImg = OSG::Image::create();

    pImg->set(OSG::Image::OSG_RGB_PF, 128, 128); //, 1, 1, 1, 0.0, imgdata);

    tx1o = OSG::TextureObjChunk::create();
    tx1e = OSG::TextureEnvChunk::create();

    tx1o->setImage    (pImg      ); 
    tx1o->setMinFilter(GL_LINEAR );
    tx1o->setMagFilter(GL_LINEAR );
    tx1o->setWrapS    (GL_CLAMP );
    tx1o->setWrapT    (GL_CLAMP );
    tx1e->setEnvMode  (GL_REPLACE);

    OSG::SimpleMaterialUnrecPtr mat = OSG::SimpleMaterial::create();
    
    mat->setDiffuse(OSG::Color3f(1,1,1));
    mat->setLit    (false              );
    mat->addChunk  (tx1o               );
    mat->addChunk  (tx1e               );

    OSG::PolygonForegroundUnrecPtr pFG =  OSG::PolygonForeground::create();

    pFG->setMaterial(mat);

    OSG::MFPnt2f *pPos = pFG->editMFPositions();
    OSG::MFVec3f *pTex = pFG->editMFTexCoords();

    pPos->push_back(OSG::Pnt2f(0.0f, 0.0f));
    pPos->push_back(OSG::Pnt2f(0.3f, 0.0f));
    pPos->push_back(OSG::Pnt2f(0.3f, 0.3f));
    pPos->push_back(OSG::Pnt2f(0.0f, 0.3f));

    pTex->push_back(OSG::Vec3f(0.0f, 1.0f, 0.0f));
    pTex->push_back(OSG::Vec3f(1.0f, 1.0f, 0.0f));
    pTex->push_back(OSG::Vec3f(1.0f, 0.0f, 0.0f));
    pTex->push_back(OSG::Vec3f(0.0f, 0.0f, 0.0f));

    vp->addForeground(pFG);



    OSG::SimpleMaterialUnrecPtr matFgCheck = OSG::SimpleMaterial::create();
    
    matFgCheck->setDiffuse(OSG::Color3f(0,1,0));
    matFgCheck->setLit    (false              );

    OSG::PolygonForegroundUnrecPtr pFGCheck =  OSG::PolygonForeground::create();

    pFGCheck->setMaterial(matFgCheck);

    pPos = pFGCheck->editMFPositions();

    pPos->push_back(OSG::Pnt2f(0.6f, 0.0f));
    pPos->push_back(OSG::Pnt2f(0.9f, 0.0f));
    pPos->push_back(OSG::Pnt2f(0.9f, 0.3f));
    pPos->push_back(OSG::Pnt2f(0.6f, 0.3f));


    vp->addForeground(pFG);
    vp->addForeground(pFGCheck);
//    vp->dump();


    // Background
    OSG::SolidBackgroundUnrecPtr bkgndFBO = OSG::SolidBackground::create();

    bkgndFBO->setColor(OSG::Color3f(1.0,0.5,0.5));
    
    // Viewport

    vpFBO = OSG::FBOViewport::create();

    vpFBO->setCamera    (cam       );
    vpFBO->setBackground(bkgndFBO  );
    vpFBO->setRoot      (root      );
    vpFBO->setSize      (0, 0, 1, 1);

    vpFBO->addForeground(pFGCheck);

    OSG::FrameBufferObjectUnrecPtr pFBO = OSG::FrameBufferObject::create();

                               pTexBuffer   = OSG::TextureBuffer::create();
    OSG::RenderBufferUnrecPtr  pDepthBuffer = OSG::RenderBuffer ::create();

    pDepthBuffer->setInternalFormat(GL_DEPTH_COMPONENT24   );

    pTexBuffer->setTexture(tx1o);

    pFBO->setSize(128, 128);
    
    pFBO->setColorAttachment(pTexBuffer, 0);
    pFBO->setDepthAttachment(pDepthBuffer );

    pFBO->editMFDrawBuffers()->clear();
    pFBO->editMFDrawBuffers()->push_back(GL_COLOR_ATTACHMENT0_EXT);


    vpFBO->setFrameBufferObject(pFBO);



    // Window
    std::cout << "GLUT winid: " << winid << std::endl;


    GLint glvp[4];

    glGetIntegerv( GL_VIEWPORT, glvp );

    gwin = OSG::GLUTWindow::create();
    gwin->setGlutId(winid);
    gwin->setSize( glvp[2], glvp[3] );

    win = gwin;

    win->addPort(vpFBO   );
    win->addPort(vp      );

    win->init();

    // Action
    
    rentravact = OSG::RenderAction::create();
//    renact->setFrustumCulling(false);


    // tball

    OSG::Vec3f pos;
    pos.setValues(min[0] + ((max[0] - min[0]) * 0.5), 
                  min[1] + ((max[1] - min[1]) * 0.5), 
                  max[2] + ( max[2] - min[2] ) * 1.5 );
    
    float scale = (max[2] - min[2] + max[1] - min[1] + max[0] - min[0]) / 6;

    OSG::Pnt3f tCenter(min[0] + (max[0] - min[0]) / 2,
                       min[1] + (max[1] - min[1]) / 2,
                       min[2] + (max[2] - min[2]) / 2);

    fprintf(stderr, "Startpos : %f %f %f\n", pos[0], pos[1], pos[2]);

    tball.setMode( OSG::Trackball::OSGObject );
    tball.setStartPosition( pos, true );
    tball.setSum( true );
    tball.setTranslationMode( OSG::Trackball::OSGFree );
    tball.setTranslationScale(scale);
    tball.setRotationCenter(tCenter);

    // run...
    
    pPoly = OSG::PolygonChunk::create();

    pCOver->subChunk(pPoly);

    return 0;
}
int doMain (int argc, char **argv)
{
    OSG::osgInit(argc,argv);
    
    // GLUT init

    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
    glutInitWindowSize(800, 800);
    

    int winid = glutCreateWindow("OpenSG");
    glutKeyboardFunc(key);
    glutVisibilityFunc(vis);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);       
    glutMouseFunc(mouse);   
    glutMotionFunc(motion); 
    
    glutIdleFunc(display);  

    // OSG

    OSG::SceneFileHandler::the()->print();

    // create the graph

    // beacon for camera and light  
    OSG::NodeUnrecPtr  b1n = OSG::Node::create();
    OSG::GroupUnrecPtr b1  = OSG::Group::create();

    fprintf(stderr, "Create b1n %p %d %d \n",
            b1n.get(),
            b1n->getRefCount(),
            b1n->getWeakRefCount());

    b1n->setCore( b1 );

    // transformation
    OSG::NodeUnrecPtr      t1n = OSG::Node::create();
    OSG::TransformUnrecPtr t1  = OSG::Transform::create();

    t1n->setCore (t1 );
    t1n->addChild(b1n);

    fprintf(stderr, "Create t1n %p %d %d \n",
            t1n.get(),
            t1n->getRefCount(),
            t1n->getWeakRefCount());

    cam_trans = t1;

    // light
    
    OSG::NodeUnrecPtr             dlight = OSG::Node::create();
    OSG::DirectionalLightUnrecPtr dl     = OSG::DirectionalLight::create();

    {
        dlight->setCore(dl);
        
        dl->setAmbient( .3f, .3f, .3f, 1 );
        dl->setDiffuse( .8f, .8f, .8f, .8f );
        dl->setDirection(0,0,1);
        dl->setBeacon( b1n);
    }

    fprintf(stderr, "Create dlight %p %d %d \n",
            dlight.get(),
            dlight->getRefCount(),
            dlight->getWeakRefCount());

    hdrroot = OSG::Node::create();
    
    hdrroot->editVolume().setInfinite();
    hdrroot->editVolume().setStatic  ();

    hdrroot->setCore(OSG::Group::create());

    // root
    root         = OSG::Node:: create();

    OSG::GroupUnrecPtr gr1 = OSG::Group::create();

    root->setCore(gr1);

    
    hdrroot->addChild(root);

    root->addChild(t1n   );
    root->addChild(dlight);

    fprintf(stderr, "Create root %p %d %d \n",
            root.get(),
            root->getRefCount(),
            root->getWeakRefCount());

    // Load the file

    OSG::NodeUnrecPtr file = NULL;
    
    if(argc > 1)
    {
        file = OSG::SceneFileHandler::the()->read(argv[1], NULL);
    }

    if(file == NULL)
    {
        std::cerr << "Couldn't load file, ignoring" << std::endl;

//        file = makeBox(2.f, 2.f, 2.f, 2, 2, 2);
        file = OSG::makeSphere(4, 2.0);
    }

    OSG::NodeUnrecPtr pCubeRoot            = OSG::Node::create();
    OSG::CubeMapGeneratorUnrecPtr pCubeGen = OSG::CubeMapGenerator::create();

    pCubeRoot->addChild(file);
    pCubeRoot->setCore(pCubeGen);
//    pCubeRoot->setCore(Group::create());

    OSG::NodeUnrecPtr         pCubeSceneRoot = OSG::Node::create();
    OSG::VisitSubTreeUnrecPtr pCubeVisit     = OSG::VisitSubTree::create();

    pCubeSceneRoot->setCore(pCubeVisit);
    pCubeVisit->setSubTreeRoot(root);

    pCubeGen->setRoot         (pCubeSceneRoot);
    pCubeGen->setTextureFormat(GL_RGB32F_ARB );
    pCubeGen->setSize         (512, 
                               512           );
    pCubeGen->setTexUnit      (3);

    // Cubemap Background
    OSG::SolidBackgroundUnrecPtr cubeBkgnd = OSG::SolidBackground::create();
    {
        cubeBkgnd->setColor(OSG::Color3f(0.5f, 0.3f, 0.3f));
    }

    pCubeGen->setBackground(cubeBkgnd);


    OSG::NodeUnrecPtr pAnimRoot = setupAnim();

            scene_trans = OSG::Transform::create();
    OSG::NodeUnrecPtr sceneTrN    = OSG::Node::create();

    scene_trans->editMatrix()[3][2] = -50.f;

    sceneTrN->setCore (scene_trans);
    sceneTrN->addChild(pCubeRoot  );
    sceneTrN->addChild(pAnimRoot  );

    OSG::Thread::getCurrentChangeList()->commitChanges();

    OSG::Vec3f min,max;
    sceneTrN->updateVolume();
    sceneTrN->getVolume().getBounds(min, max);
    
    std::cout << "Volume: from " << min << " to " << max << std::endl;


    dlight->addChild(sceneTrN);

    // Camera
    
    cam = OSG::PerspectiveCamera::create();
    {
        cam->setBeacon( b1n );
        cam->setFov( OSG::osgDegree2Rad( 90 ) );
        cam->setNear( 0.1f );
        cam->setFar( 100000 );
    }

    // Background
    OSG::SolidBackgroundUnrecPtr bkgnd = OSG::SolidBackground::create();
    {
        bkgnd->setColor(OSG::Color3f(0.3f, 0.3f, 0.3f));
    }

    // Viewport
    vp = OSG::Viewport::create();
    {
        vp->setCamera( cam );
        vp->setBackground( bkgnd );
        vp->setRoot( hdrroot );
//        vp->setRoot( root );
        vp->setSize( 0,0, 1,1 );
    }


    // Window
    OSG::GLUTWindowUnrecPtr gwin;

    GLint glvp[4];

    glGetIntegerv(GL_VIEWPORT, glvp);

    gwin = OSG::GLUTWindow::create();
    {
        gwin->setGlutId(winid);
        gwin->setSize( glvp[2], glvp[3] );
        
        win = gwin;

        win->addPort( vp );

        win->init();
    }

    // Action
    rentravact = OSG::RenderAction::create();

    rentravact->setVolumeDrawing(true);
//    rentravact->setFrustumCulling(false);

    // tball
    OSG::Vec3f pos;

    pos.setValues(min[0] + ((max[0] - min[0]) * 0.5), 
                  min[1] + ((max[1] - min[1]) * 0.5), 
                  max[2] + ( max[2] - min[2] ) * 1.5 );
    
    float scale = (max[2] - min[2] + max[1] - min[1] + max[0] - min[0]) / 6;

    OSG::Pnt3f tCenter(min[0] + (max[0] - min[0]) / 2,
                       min[1] + (max[1] - min[1]) / 2,
                       min[2] + (max[2] - min[2]) / 2);

    fprintf(stderr, "Startpos : %f %f %f\n", pos[0], pos[1], pos[2]);

    tball.setMode            (OSG::Trackball::OSGObject);
    tball.setStartPosition   (pos, true                );
    tball.setSum             (true                     );
    tball.setTranslationMode (OSG::Trackball::OSGFree  );
    tball.setTranslationScale(scale                    );
    tball.setRotationCenter  (tCenter                  );

    fprintf(stderr, "Create b1n %p %d %d \n",
            b1n.get(),
            b1n->getRefCount(),
            b1n->getWeakRefCount());

    fprintf(stderr, "Create t1n %p %d %d \n",
            t1n.get(),
            t1n->getRefCount(),
            t1n->getWeakRefCount());

    fprintf(stderr, "Create dlight %p %d %d \n",
            dlight.get(),
            dlight->getRefCount(),
            dlight->getWeakRefCount());

    fprintf(stderr, "Create hdrroot %p %d %d \n",
            hdrroot.get(),
            hdrroot->getRefCount(),
            hdrroot->getWeakRefCount());

    fprintf(stderr, "Create root %p %d %d \n",
            root.get(),
            root->getRefCount(),
            root->getWeakRefCount());

    return 0;
}