Ejemplo n.º 1
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.º 2
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.º 3
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.º 4
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());
}
Ejemplo n.º 5
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.º 6
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);
}
bool ShapeVisitor_RestrictedPositionGetter::insideCube( const osg::Vec3f& center, const osg::Vec3f& surfaceX, const osg::Vec3f& surfaceY, const osg::Vec3f& surfaceZ, osg::Vec3f& point )
{
	float distanceX = fabsf( ( center - surfaceX ).x() );
	float distanceY = fabsf( ( center - surfaceY ).y() );
	float distanceZ = fabsf( ( center - surfaceZ ).z() );

	return ( point.x() > center.x() - distanceX && point.x() < center.x() + distanceX &&
			 point.y() > center.y() - distanceY && point.y() < center.y() + distanceY &&
			 point.z() > center.z() - distanceZ && point.z() < center.z() + distanceZ );
}
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.º 9
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.º 10
0
std::string toString(const osg::Vec3f &value)
{
    std::stringstream str;

    str << value.x() << " " << value.y() << " " << value.z();
    return str.str();
}
Ejemplo n.º 11
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.º 12
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.º 13
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.º 14
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.º 15
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.º 16
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.º 17
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.º 18
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;
}
Ejemplo n.º 19
0
////////////////////////////////////////////////////////////
/// Set the sound position (take a 3D vector).
/// The default position is (0, 0, 0)
////////////////////////////////////////////////////////////
void Sound::SetPosition(const osg::Vec3f& Position)
{
    SetPosition(Position.x(), Position.y(), Position.z());
}
Ejemplo n.º 20
0
 inline void update(void)
 {
    _pat.setPosition(osg::Vec3f(_eye.x(), _eye.y(), _pat.getPosition().z()));
 }
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
bool FFTOceanSurface::updateMipmaps( const osg::Vec3f& eye, unsigned int frame )
{
    static unsigned int count = 0;

    bool updated = false;

    _newNumVertices = 0;

    int tileSize = _tileResolution+1;

    int x_offset = 0;
    int y_offset = 0;

    if(_isEndless)
    {
        float xMin = _startPos.x();
        float yMin = _startPos.y() - (float)((_tileResolution+1)*_numTiles);

        x_offset = (int) ( (eye.x()-xMin) / (float)_tileResolution );
        y_offset = (int) ( (eye.y()-yMin) / (float)_tileResolution );

        x_offset -= _numTiles/2;
        y_offset -= _numTiles/2;

        _startPos.x() += (float)(x_offset * tileSize); 
        _startPos.y() += (float)(y_offset * tileSize); 
    }

    for( unsigned int y = 0; y < _numTiles; ++y)
    {
        for( unsigned int x = 0; x < _numTiles; ++x)
        {
            osg::Vec3f newbound = getTile(x,y)->getBound().center();
            newbound.x() += (float)(x_offset * tileSize);
            newbound.y() += (float)(y_offset * tileSize);

            osg::Vec3f distanceToTile = newbound - eye;
            
            unsigned int mipmapLevel = 0;

            for( unsigned int m = 0; m < _minDist.size(); ++m )
            {
                if( distanceToTile.length2() > _minDist.at(m) )
                    mipmapLevel = m;
            }

            if( getTile(x,y)->getLevel() != mipmapLevel )
                updated = true;

            getTile(x,y)->setLevel( mipmapLevel );
            getTile(x,y)->setIdx( _newNumVertices );
            
            unsigned int verts = 0;
            unsigned int size = getTile(x,y)->getResolution();

            verts = size * size;

            if(x == _numTiles-1 )
                verts += size;
            if(y == _numTiles-1 )
                verts += size;
            if(x == _numTiles-1 && y == _numTiles-1)
                verts += 1;

            _newNumVertices += verts;
        }
    }

    return updated;    
}
Ejemplo n.º 23
0
 void CoordinateConverter::toLocal(osg::Vec3f& point)
 {
     point.x() -= static_cast<float>(mCellX);
     point.y() -= static_cast<float>(mCellY);
 }
Ejemplo n.º 24
0
Vector3::Vector3(osg::Vec3f const &vec)
: m_x(vec.x()), m_y(vec.y()), m_z(vec.z())
{}
void OsgDrawableCullCallback::SetParams (bool wms_active, int cx, int cy, 
											osg::Vec3f &_eye, osg::Vec3f &_center, osg::Vec3f &_up, 
											osg::Vec3f &_punto_mira, bool _resetWMS,
											double msec, const unsigned char &_blending)
{
	// guardamos los parámetros
	eye = _eye;	// posición de la cámara
	punto_mira = _punto_mira; // punto de corte con la escena
	width2 = cx; // mitad del ancho de la imagen, en pixels
	height2 = cy; // mitad del alto de la imagen, en pixels

	// calculamos los 3 ejes del sistema de referencia de la cámara
	vx = _up.x();
	vy = _up.y();
	vz = _up.z();
	wx = _center.x() - _eye.x();
	wy = _center.y() - _eye.y();
	wz = _center.z() - _eye.z();
	ux = wy*vz - wz*vy;
	uy = wz*vx - wx*vz;
	uz = wx*vy - wy*vx;

	// calculamos la distancia focal (mirar perspectiva.tex)
	// tendría que usar la función UTMToSceneCoords, pero no sé como hacerlo desde aquí
	//cpw::Point3d<float> P1 = cpw::ApplicationScene::GetInstance()->GetScene()->UTMToSceneCoords(cpw::Point3d<float>(punto_mira.x(), punto_mira.y(), punto_mira.z()));

	cpw::Point3d<double> out = ((OsgScene *)cpw::ApplicationScene::GetInstance()->GetScene())->UTMToSceneCoords(
			cpw::Point3d<double>(punto_mira.x() - traslation.x(), 
								punto_mira.y() - traslation.y(), 
								punto_mira.z() - traslation.z()));
	double x1=out.x, y1=out.y, z1=out.z;

	/* ahora convertimos a utm con la llamada de David
	double x1 = punto_mira.x() - traslation.x();
	double y1 = punto_mira.y() - traslation.y() - 3e6;
	double z1 = punto_mira.z() - traslation.z();
	*/

	double num = x1*wx + y1*wy + z1*wz - eye.x()*wx - eye.y()*wy - eye.z()*wz;
	double den = x1*vx + y1*vy + z1*vz - eye.x()*vx - eye.y()*vy - eye.z()*vz; 
	D = - height2 / 3.0 * num / den;
	
	// si alquien picó en el tree layer, _resetWMS está a true, y pasamos al estado 3
	if (_resetWMS) {
		switch (estadoWMS) {
			case 1: CancelPetitions();
					resetWMS = true;
					break;
			case 2: estadoWMS = 3;
					CancelPetitions();
					// según si quedan capas o no, pasamos al estado 3 o seguimos en el estado 2
					if (wms_active) {
						estadoWMS=1;
						//resetWMS = true;
					} else {
						estadoWMS=3;
					}
					break;
			case 3: CancelPetitions();
					break;
		}
	}

	// colocamos el estado WMS actual (ver grafo libreta y algoritmoWMS.doc)
	if (wms_active) {
		if (estadoWMS == 0) estadoWMS = 1;
		//if (pets.empty()) ComputeNextPetition();
		ComputeNextPetition();
	} else {
		switch (estadoWMS) {
			case 1: estadoWMS = 0;
					CancelPetitions();
					resetWMS = true;
					break;
			case 2: estadoWMS = 3;
					CancelPetitions();
					break;
		}
	}

   // si hay peticiones pendientes, miramos si han llegado
	if (!pets.empty() && estadoWMS>0 && estadoWMS<3) {

			// si alguna textura no la reclamo nadie, las descartamos
			for (int i=(int)pets.size()-1; i>=0; i--) {
				if (pets[i].TextureWMS.get()) {
					pets.erase (pets.begin()+i);
					printf ("hubo una textura que no reclamó nadie. Quedan %d pendientes", pets.size());
				}
			}

			// si se quedó vacía reiniciamos el flag
			//if (pets.empty()) PET_PEND = false;

			
			//instead of getting and releasing the mutex in every "IsPetitionAttended" call,
			//better call this function to get it only once 
			petman->GainSafeAccess(); 

			// miramos si alguna petición pendiente ha llegado
			for (unsigned int i=0; i<pets.size(); i++) {
				bool result = petman->IsPetitionAttended (pets[i].id_wms, pets[i].TextureWMS);
				if (!result) printf ("hubo una petición errónea");
			}
			petman->ReleaseSafeAccess(); //release mutex
	}

	// calculamos el nuevo factor de blending
	if (last_blending != _blending) {

		// si han movido el slider, cogemos el nuevo valor
		last_blending = blending = _blending;

	} else {

		// si no, lo hacemos en función del tiempo
		switch (estadoWMS) {
			case 0: blending = 0; break;
			case 2: if (blending < _blending) {
						int inc = msec * 255 / BLENDING_DELAY;
						if (inc==0) inc = 1;
						int bl_i = (int) blending + inc;
						blending = (bl_i > _blending)? _blending : (unsigned char) bl_i;
					}
					break;
			case 3: if (blending > 0) {
						int inc = msec * 255 / BLENDING_DELAY;
						if (inc==0) inc = 1;
						int bl_i = (int) blending - inc;
						blending = (bl_i < 0)? 0 : (unsigned char) bl_i;
					}


					// si llegamos a cero cambiamos de estado y reseteamos texturas
					if (blending == 0) { 	
						resetWMS = true;
						if (wms_active) estadoWMS=1; 
						else {
							estadoWMS=0;
							CancelPetitions();
						}
					}
					break;
		}
	}

	// si no hay peticiones pendientes, actualizamos el cronometro
	if (pets.empty()) {
		t0_wms = osg::Timer::instance()->tick(); 
	
	} else {

		// si hace tiempo que no llegan texturas, reseteamos la cola de peticiones
		if (estadoWMS==2 && GetWaitedTimeWMS()>1000*MAX_TIME_OUT) {
			printf ("¡¡¡¡¡¡¡¡¡¡¡¡¡TIME_OUT!!!!!!!!!!!!!!!!");
			CancelPetitions();
			t0_wms = osg::Timer::instance()->tick(); 
			resetPetPend = true;
		}
	}
}
Ejemplo n.º 26
0
void VRPhysics::setGravity(OSG::Vec3f v) { Lock lock(mtx()); if (body) body->setGravity(btVector3 (v.x(),v.y(),v.z())); }
Ejemplo n.º 27
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;

    }
void EnPlayerSound::updatePosition( const osg::Vec3f& pos )
{
    _soundPosition.x = pos.x();
    _soundPosition.y = pos.y();
    _soundPosition.z = pos.z();
}
Ejemplo n.º 29
0
void vecfFunc(osg::Vec3f vec) {
    std::cout << "Got the float vector " << vec.x() << "," << vec.y() << "," << vec.z() << std::endl;
}
Ejemplo n.º 30
0
bool FFTOceanSurfaceVBO::updateLevels(const osg::Vec3f& eye)
{
   int x_offset = 0;
   int y_offset = 0;

   if(_isEndless)
   {
      float xMin = _startPos.x();
      float yMin = _startPos.y()-(_tileResolution*_numTiles);
      
      x_offset = (int) ( (eye.x()-xMin) / _tileResolution );
      y_offset = (int) ( (eye.y()-yMin) / _tileResolution );
      
      x_offset -= ((int)_numTiles)/2;
      y_offset -= ((int)_numTiles)/2;
//      std::cerr <<  "Offset: " << x_offset << "," << y_offset << std::endl;
//      std::cerr <<  "Start: " << _startPos.x() << "," << _startPos.y() << std::endl;
      
      if(x_offset != 0 || y_offset != 0)
      {
         //std::cerr << "Surface Move." << std::endl;
         
         while ((x_offset != 0) || (y_offset != 0))
         {
            if(x_offset < 0)
            {
               osg::Vec3f offset;
               _startPos.x() -= (int)_tileResolution;
               
               for(int r = 0; r < (int)_numTiles; ++r)
               {
                  std::vector< osg::ref_ptr<osgOcean::MipmapGeometryVBO> >& row = _mipmapGeom.at(r);
                  
                  offset.x() = _startPos.x();
                  offset.y() = _startPos.y()-r*(int)_tileResolution;
                  offset.z() = 0;
                  
                  row.insert( row.begin(), row.back() );   // insert the 
                  row.pop_back(); 
                  row.front()->setOffset( offset );         // change offset
               }
               ++x_offset;
            }
            else if (x_offset > 0)
            {
               osg::Vec3f offset;
               _startPos.x() += (int)_tileResolution;
               
               for(int r = 0; r < (int)_numTiles; ++r)
               {
                  std::vector< osg::ref_ptr<osgOcean::MipmapGeometryVBO> >& row = _mipmapGeom.at(r);
                  
                  offset.x() = _startPos.x() + ( (_numTiles-1)*(int)_tileResolution );
                  offset.y() = _startPos.y()-r*(int)_tileResolution;
                  offset.z() = 0;
                  
                  row.insert( row.end(), row.front() );
                  row.erase( row.begin() );
                  row.back()->setOffset( offset );
               } 
               --x_offset;                  
            }
            
            if(y_offset < 0)
            {
               _startPos.y() -= (int)_tileResolution;

               _mipmapGeom.insert( _mipmapGeom.end(), _mipmapGeom.front() );
               _mipmapGeom.erase( _mipmapGeom.begin() );
               
               osg::Vec3f offset;
               
               for(int c = 0; c < (int)_numTiles; c++ )
               {
                  offset.x() = _startPos.x() + c *(int) _tileResolution;
                  offset.y() = _startPos.y()-( (_numTiles-1)*(int)_tileResolution );
                  offset.z() = 0;
                  
                  _mipmapGeom.back().at(c)->setOffset(offset);
               }
               ++y_offset;
            }
            else if(y_offset > 0)
            {
               _startPos.y() += (int)_tileResolution;

               _mipmapGeom.insert( _mipmapGeom.begin(), _mipmapGeom.back() );
               _mipmapGeom.pop_back();
               
               osg::Vec3f offset;
               
               for(int c = 0; c < (int)_numTiles; c++ )
               {
                  offset.x() = _startPos.x() + c * (int)_tileResolution;
                  offset.y() = _startPos.y();
                  offset.z() = 0;
                  
                  _mipmapGeom.front().at(c)->setOffset(offset);
               }
               --y_offset;
            }
         }
      }
   }
   
   unsigned updates=0;
   
   for(int r = _numTiles-1; r>=0; --r )
   {
      for(int c = _numTiles-1; c>=0; --c )
      {
         osgOcean::MipmapGeometryVBO* curGeom = _mipmapGeom.at(r).at(c).get();
         osg::Vec3f centre = curGeom->getBound().center();
         
         float distanceToTile2 = (centre-eye).length2();
         
         unsigned mipmapLevel = 0;
         unsigned rightLevel  = 0;
         unsigned belowLevel  = 0;
         
         for( unsigned int m = 0; m < _minDist.size(); ++m )
         {
            if( distanceToTile2 > _minDist.at(m) )
               mipmapLevel = m;
         }
         
         if( c != _numTiles-1 && r != _numTiles-1 ){
            osgOcean::MipmapGeometryVBO* rightGeom = _mipmapGeom.at(r).at(c+1).get();
            osgOcean::MipmapGeometryVBO* belowGeom = _mipmapGeom.at(r+1).at(c).get();
            rightLevel = rightGeom->getLevel();
            belowLevel = belowGeom->getLevel();
         }
         else 
         {
            if( c != _numTiles-1 ){
               osgOcean::MipmapGeometryVBO* rightGeom = _mipmapGeom.at(r).at(c+1).get();
               rightLevel = rightGeom->getLevel();
            }
            else{
               rightLevel = mipmapLevel;
            }
            
            if( r != _numTiles-1 ){
               osgOcean::MipmapGeometryVBO* belowGeom = _mipmapGeom.at(r+1).at(c).get();
               belowLevel = belowGeom->getLevel();
            }
            else{
               belowLevel = mipmapLevel;
            }
         }

         if( curGeom->updatePrimitives(mipmapLevel,rightLevel,belowLevel) )
            updates++;
      }
   }

#ifdef OSGOCEAN_MIPMAP
   if (updates > 0)
   {
        std::cerr <<  "Updates: " << updates << std::endl;
        for(int r = _numTiles-1; r>=0; --r )
        {
           for(int c = _numTiles-1; c>=0; --c )
           {
              fprintf(stderr, "%d", _mipmapGeom.at(r).at(c)->getLevel());
           }
           fprintf(stderr, "\n");
        }
   }
#endif /*OSGOCEAN_MIPMAP*/

   return updates > 0;
}