Esempio n. 1
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());
}
Esempio 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;
}
Esempio n. 3
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;
    }
}
Esempio n. 4
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;
}
Esempio 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);
}
Esempio 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 );
}
Esempio 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);
 }
Esempio n. 10
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));
}
Esempio n. 11
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;
}
Esempio n. 12
0
std::string toString(const osg::Vec3f &value)
{
    std::stringstream str;

    str << value.x() << " " << value.y() << " " << value.z();
    return str.str();
}
Esempio 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()
     );
 }
Esempio 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);
}
Esempio 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));
    }
}
Esempio 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;
}
Esempio n. 17
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;
}
Esempio n. 18
0
void VRPhysics::setGravity(OSG::Vec3f v) { Lock lock(mtx()); if (body) body->setGravity(btVector3 (v.x(),v.y(),v.z())); }
Esempio n. 19
0
bool Water::isUnderwater(const osg::Vec3f &pos) const
{
    return pos.z() < mTop && mToggled && mEnabled;
}
Esempio n. 20
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());
}
Esempio n. 21
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;
		}
	}
}
// constructor
PrecipitationBase::PrecipitationBase(const char * szMaterialName, size_t nParticlesNumber, const osg::Vec3f & vBoxHalfSize, float fMeanLifeTime/* = 10.f*/)
    : m_bActive(false)
    , m_nParticlesNumber(nParticlesNumber)
    , m_vBoxHalf(vBoxHalfSize)
    , m_fIntensity(0.0f)
    , m_fWindSpeed(0.0f)
{
    // base set up
    setUseDisplayList(false);
    setUseVertexBufferObjects(true);
    setDataVariance(osg::Object::STATIC);
    setComputeBoundingBoxCallback(new osg::Drawable::ComputeBoundingBoxCallback());
    


    //
    // create state set
    //

    osg::StateSet * pCurStateSet = getOrCreateStateSet();

    // setup shader defines (scroll scales and so on)
    avCore::Database::ShaderDefineVector cShaderDefines;

    // full box shader definition
    {
        const osg::Vec3f vBoxFull = m_vBoxHalf * 2.0f;
        std::ostringstream stream;
        stream << "vec3(" << vBoxFull.x() << ", " << vBoxFull.y() << ", " << vBoxFull.z() << ")";
        cShaderDefines.push_back(avCore::Database::ShaderDefine("SCROLL_FULL", stream.str().c_str()));
    }
    // full-box rcp shader definition
    {
        const osg::Vec3f vBoxFullRcp = osg::Vec3f(0.5f / m_vBoxHalf.x(), 0.5f / m_vBoxHalf.y(), 0.5f / m_vBoxHalf.z());
        std::ostringstream stream;
        stream << "vec3(" << vBoxFullRcp.x() << ", " << vBoxFullRcp.y() << ", " << vBoxFullRcp.z() << ")";
        cShaderDefines.push_back(avCore::Database::ShaderDefine("SCROLL_RCP", stream.str().c_str()));
    }

    // setup shader
    osg::Program * pCurProgram = new osg::Program;
    pCurProgram->setName(szMaterialName);
    pCurProgram->addShader(avCore::GetDatabase()->LoadShader(std::string(szMaterialName).append(".vs").c_str(), &cShaderDefines, osg::Shader::VERTEX  ));
    pCurProgram->addShader(avCore::GetDatabase()->LoadShader(std::string(szMaterialName).append(".gs").c_str(), NULL           , osg::Shader::GEOMETRY));
    pCurProgram->addShader(avCore::GetDatabase()->LoadShader(std::string(szMaterialName).append(".fs").c_str(), NULL           , osg::Shader::FRAGMENT));
    pCurProgram->setParameter(GL_GEOMETRY_VERTICES_OUT_EXT, 4);
    pCurProgram->setParameter(GL_GEOMETRY_INPUT_TYPE_EXT, GL_POINTS);
    pCurProgram->setParameter(GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_TRIANGLE_STRIP);

    // bind shader
    pCurStateSet->setAttribute(pCurProgram);

    // setup texture for point quads
    pCurStateSet->setTextureAttribute(0, avCore::GetDatabase()->LoadTexture(std::string(szMaterialName).append(".dds").c_str(), osg::Texture::CLAMP_TO_EDGE));

    // box position
    m_uniformScrollLBN = new osg::Uniform("ScrollLBN", osg::Vec3f());
    pCurStateSet->addUniform(m_uniformScrollLBN.get());

    // LTP box offset
    m_uniformWP2LTPBoxOffset = new osg::Uniform("LTPOffset", osg::Vec2f());
    pCurStateSet->addUniform(m_uniformWP2LTPBoxOffset.get());

    // wind vector
    m_uniformWindVec = new osg::Uniform("WindVector", osg::Vec3f());
    pCurStateSet->addUniform(m_uniformWindVec.get());

    // render data
    m_uniformRenderData = new osg::Uniform("RenderData", osg::Vec4f());
    pCurStateSet->addUniform(m_uniformRenderData.get());

    //
    // Construct geometry
    //

    // attach draw call command
    m_dipDrawArrays = new osg::DrawArrays(osg::PrimitiveSet::POINTS);
    addPrimitiveSet(m_dipDrawArrays.get());

    // create vertex array
    Half4Array * aBoxPointsPos = new Half4Array(m_nParticlesNumber);
    // speed deviation factors
    osg::Vec4ubArray * aSpeedFactors = new osg::Vec4ubArray(m_nParticlesNumber);

    // fill every vertex point
    avCore::RandomNumber rndGen;
    for (size_t i = 0; i < m_nParticlesNumber; ++i)
    {
        // random lifetime
        float fLifeTime = rndGen.random_dev(fMeanLifeTime, 0.3f * fMeanLifeTime);
        // get random position
        osg::Vec3f vRandPos;
        vRandPos.x() = rndGen.random_unit_signed() * m_vBoxHalf.x();
        vRandPos.y() = rndGen.random_unit_signed() * m_vBoxHalf.y();
        vRandPos.z() = rndGen.random_unit_signed() * m_vBoxHalf.z();
        // save it
        tagVertexData & curVertex = aBoxPointsPos->at(i);
        curVertex.x = vRandPos.x();
        curVertex.y = vRandPos.y();
        curVertex.z = vRandPos.z();
        curVertex.t = fLifeTime;
        // speed deviation factors
        osg::Vec4ub & curSpeedFactors = aSpeedFactors->at(i);
        curSpeedFactors[0] = rndGen.random_8bit();
        curSpeedFactors[1] = rndGen.random_8bit();
        curSpeedFactors[2] = rndGen.random_8bit();
        curSpeedFactors[3] = rndGen.random_8bit();
    }

    // set vertex array
    aBoxPointsPos->setDataVariance(osg::Object::STATIC);
    setVertexArray(aBoxPointsPos);

    // set factors array
    static const size_t
        idxSpeedFactorsBinding = 5;
    aSpeedFactors->setDataVariance(osg::Object::STATIC);
    setVertexAttribBinding(idxSpeedFactorsBinding, osg::Geometry::BIND_PER_VERTEX);
    setVertexAttribNormalize(idxSpeedFactorsBinding, GL_TRUE);
    setVertexAttribArray(idxSpeedFactorsBinding, aSpeedFactors);


    // exit
    return;
}
void EnPlayerSound::updatePosition( const osg::Vec3f& pos )
{
    _soundPosition.x = pos.x();
    _soundPosition.y = pos.y();
    _soundPosition.z = pos.z();
}
Esempio n. 25
0
void vecfFunc(osg::Vec3f vec) {
    std::cout << "Got the float vector " << vec.x() << "," << vec.y() << "," << vec.z() << std::endl;
}
Esempio n. 26
0
// convert to a Real Axis x,y,z
osg::Vec3f Model::convertToRealAxis(osg::Vec3f aVector) {
	return (osg::Vec3f(aVector.z(), aVector.x(), aVector.y()));
}