Ejemplo n.º 1
0
void Marker::setOpacity(float opacity)
{
    Vec4 color = _shapeDrawable->getColor();
    color.set(color[0], color[1], color[2], opacity);
    setColor(color);
}
Ejemplo n.º 2
0
void FastClusterFit::Compress4( void* block )
{
	Vec4 const one = VEC4_CONST(1.0f);
	Vec4 const zero = VEC4_CONST(0.0f);
	Vec4 const half = VEC4_CONST(0.5f);
	Vec4 const two = VEC4_CONST(2.0);
	Vec4 const onethird = VEC4_CONST( 1.0f/3.0f );
	Vec4 const twothirds = VEC4_CONST( 2.0f/3.0f );

	// declare variables
	Vec4 beststart = VEC4_CONST( 0.0f );
	Vec4 bestend = VEC4_CONST( 0.0f );
	Vec4 besterror = VEC4_CONST( FLT_MAX );

	Vec4 x0 = zero;
	int b0 = 0, b1 = 0, b2 = 0;
	int i = 0;

	// check all possible clusters for this total order
	for( int c0 = 0; c0 <= 16; c0++)
	{	
		Vec4 x1 = zero;
		
		for( int c1 = 0; c1 <= 16-c0; c1++)
		{	
			Vec4 x2 = zero;
			
			for( int c2 = 0; c2 <= 16-c0-c1; c2++)
			{
				Vec4 const constants = Vec4((const float *)&s_fourElement[i]);
				Vec4 const alpha2_sum = constants.SplatX();
				Vec4 const beta2_sum = constants.SplatY();
				Vec4 const alphabeta_sum = constants.SplatZ();
				Vec4 const factor = constants.SplatW();
				i++;
				
				Vec4 const alphax_sum = x0 + MultiplyAdd(x1, twothirds, x2 * onethird);
				Vec4 const betax_sum = m_xsum - alphax_sum;
				
				Vec4 a = NegativeMultiplySubtract(betax_sum, alphabeta_sum, alphax_sum*beta2_sum) * factor;
				Vec4 b = NegativeMultiplySubtract(alphax_sum, alphabeta_sum, betax_sum*alpha2_sum) * factor;
				
				// clamp the output to [0, 1]
				a = Min( one, Max( zero, a ) );
				b = Min( one, Max( zero, b ) );
				
				// clamp to the grid
				Vec4 const grid( 31.0f, 63.0f, 31.0f, 0.0f );
				Vec4 const gridrcp( 0.03227752766457f, 0.01583151765563f, 0.03227752766457f, 0.0f );
				a = Truncate( MultiplyAdd( grid, a, half ) ) * gridrcp;
				b = Truncate( MultiplyAdd( grid, b, half ) ) * gridrcp;
				
				// compute the error
				Vec4 e1 = MultiplyAdd( a, alphax_sum, b*betax_sum );
				Vec4 e2 = MultiplyAdd( a*a, alpha2_sum, b*b*beta2_sum );
				Vec4 e3 = MultiplyAdd( a*b*alphabeta_sum - e1, two, e2 );
				
				// apply the metric to the error term
				Vec4 e4 = e3 * m_metricSqr;
				Vec4 error = e4.SplatX() + e4.SplatY() + e4.SplatZ();
				
				// keep the solution if it wins
				if( CompareAnyLessThan( error, besterror ) )
				{
					besterror = error;
					beststart = a;
					bestend = b;
					b0 = c0;
					b1 = c1;
					b2 = c2;
				}
				
				x2 += m_unweighted[c0+c1+c2];
			}
			
			x1 += m_unweighted[c0+c1];
		}
		
		x0 += m_unweighted[c0];
	}

	// save the block if necessary
	if( CompareAnyLessThan( besterror, m_besterror ) )
	{
		// compute indices from cluster sizes.
		/*uint bestindices = 0;
		{
			int i = b0;
			for(; i < b0+b1; i++) {
				bestindices = 2 << (2 * m_order[i]);
			}
			for(; i < b0+b1+b2; i++) {
				bestindices = 3 << (2 * m_order[i]);
			}
			for(; i < 16; i++) {
				bestindices = 1 << (2 * m_order[i]);
			}
		}*/
		u8 bestindices[16];
		{
			int i = 0;
			for(; i < b0; i++) {
				bestindices[i] = 0;
			}
			for(; i < b0+b1; i++) {
				bestindices[i] = 2;
			}
			for(; i < b0+b1+b2; i++) {
				bestindices[i] = 3;
			}
			for(; i < 16; i++) {
				bestindices[i] = 1;
			}
		}
		
		// remap the indices
		u8 ordered[16];
		for( int i = 0; i < 16; ++i )
			ordered[m_order[i]] = bestindices[i];
		
		// save the block
		WriteColourBlock4( beststart.GetVec3(), bestend.GetVec3(), ordered, block );
		
		// save the error
		m_besterror = besterror;
	}
}
Ejemplo n.º 3
0
QString Cube::saveObject()
{
    QString obj;
    QString aux;
    obj += "c ";
    Vec4 parameters;
    //translacao
    parameters = transform.getTranslateSeted();
    obj += aux.sprintf("%.3f %.3f %.3f ",parameters.x(),parameters.y(),parameters.z());
    //escala
    parameters = transform.getScaleSeted();
    obj += aux.sprintf("%.3f %.3f %.3f ",parameters.x(),parameters.y(),parameters.z());
    //rotação
    parameters = transform.getRotationSeted();
    obj += aux.sprintf("%.3f %.3f %.3f ",parameters.x(),parameters.y(),parameters.z());
    obj += aux.sprintf("%d ",this->getIdMaterial());
    parameters = this->getMesh()->getMaterialM()->getAmbiente();
    obj += aux.sprintf("%.3f %.3f %.3f ",parameters.x(),parameters.y(),parameters.z());
    parameters = this->getMesh()->getMaterialM()->getDiffuse();
    obj += aux.sprintf("%.3f %.3f %.3f ",parameters.x(),parameters.y(),parameters.z());
    parameters = this->getMesh()->getMaterialM()->getSpecular();
    obj += aux.sprintf("%.3f %.3f %.3f ",parameters.x(),parameters.y(),parameters.z());
    obj += aux.sprintf("%.3f ",this->getMesh()->getMaterialM()->getShininess());
    obj += aux.sprintf("%.3f ",this->getMesh()->getMaterialM()->getReflection());
    obj += aux.sprintf("%.3f ",this->getMesh()->getMaterialM()->getRefraction());
    obj += aux.sprintf("%.3f %.3f ",this->getMesh()->getMaterialM()->getGlossyReflection(),this->getMesh()->getMaterialM()->getGlossyRefraction());
    obj += aux.sprintf("%.3f %.3f %.3f ",motion.x(),motion.y(),motion.z());
    if (this->enabled)
        obj += "t ";
    else
        obj += "f ";
    if (this->selected)
        obj += "t ";
    else
        obj += "f ";
    obj +=this->name+"\n";
    return obj;


}
Ejemplo n.º 4
0
 void setVec4Parameter(const std::string name,
                       const Vec4 value,
                       bool isShaderConstant = true)
 { setColorParameter(name,
                     Color(value.x(), value.y(), value.z(), value.w()),
                     isShaderConstant); }
Ejemplo n.º 5
0
void BuildJenga (osgViewer::Viewer* const viewer, osg::newtonWorld* const world, const Vec3& location, int high)
{
	dAssert (viewer->getSceneData());
	Group* const rootGroup = viewer->getSceneData()->asGroup();
	dAssert (rootGroup);

	Vec3 blockBoxSize (0.4f, 0.4f * 3.0f, 0.2f);

	// find the floor position
	Vec4 start(Vec4(location, 0.0f) + Vec4 (0.0f, 0.0f, 10.0f, 1.0f));
	Vec4 end (start - Vec4 (0.0f, 0.0f, 20.0f, 1.0f));
	newtonRayCast raycaster(world, DemoExample::m_rayCast); 

	raycaster.CastRay (start, end);
	Vec4 position (raycaster.m_contact + Vec4 (0.0f, 0.0f, blockBoxSize.z() * 0.5f, 1.0f));

	Matrix baseMatrix;
	baseMatrix.setTrans (position.x(), position.y(), position.z());

	// set realistic mass and inertia matrix for each block
	dFloat mass = 5.0f;

	// create a 90 degree rotation matrix
	Matrix rotMatrix (Quat (90.0f * 3.141592f / 180.0f, Vec3 (0.0f, 0.0f, 1.0f)));

	dFloat collisionPenetration = 1.0f / 256.0f;

	// make a box collision shape
	dNewtonCollisionBox boxShape (world, blockBoxSize.x(), blockBoxSize.y(), blockBoxSize.z(), DemoExample::m_all);

	// create a visual for visual representation
	newtonMesh boxMesh (&boxShape);
	boxMesh.Triangulate();

	// create a texture and apply uv to this mesh
	ref_ptr<Texture2D> texture = new Texture2D;
	ref_ptr<Image> image = osgDB::readImageFile("images\\crate.tga");
	texture->setImage (image.get());
	texture->setWrap(Texture::WRAP_S, Texture::REPEAT);
	texture->setWrap(Texture::WRAP_R, Texture::REPEAT);
	texture->setWrap(Texture::WRAP_T, Texture::REPEAT);

	int materialId = boxMesh.AddMaterial(texture);

	// apply uv to this mesh
	boxMesh.ApplyBoxMapping (materialId, materialId, materialId);

	// create a manual object for rendering 
	ref_ptr<Geode> geometryNode = boxMesh.CreateGeodeNode();

	for (int i = 0; i < high; i ++) { 
		Matrix matrix(baseMatrix);
		Vec3 step_x (Matrix::transform3x3 (Vec3(1.0f, 0.0f, 0.0f), matrix)); 

		step_x = step_x * blockBoxSize.x();
		matrix.setTrans (matrix.getTrans() - step_x);

		for (int j = 0; j < 3; j ++) { 
			ref_ptr<MatrixTransform> transformNode = new MatrixTransform(matrix);	
			transformNode->addChild(geometryNode.get());
			rootGroup->addChild(transformNode.get());
			new newtonDynamicBody (world, mass, &boxShape, transformNode.get(), matrix);
			matrix.setTrans (matrix.getTrans() + step_x);
		}

		baseMatrix = rotMatrix * baseMatrix;
		Vec3 step_y (Matrix::transform3x3 (Vec3(0.0f, 0.0f, 1.0f), matrix)); 
		step_y = step_y * (blockBoxSize.z() - collisionPenetration);
		baseMatrix.setTrans (baseMatrix.getTrans() + step_y);
	}
}	
Ejemplo n.º 6
0
//--------------------------------------------------------------------------------------
// The Taylor Series smooths and removes jitter based on a taylor series expansion
//--------------------------------------------------------------------------------------
void FilterTaylorSeries::Update( const SKinSkeletonRawData& pSkeletonData, const float fDeltaTime )
{
    const float fJitterRadius = 0.05f;
    const float fAlphaCoef  = 1.0f - m_fSmoothing;
    const float fBetaCoeff  = (fAlphaCoef * fAlphaCoef ) / ( 2 - fAlphaCoef );

    Vec4 vRawPos;
    // Velocity, acceleration and Jolt are 1st, 2nd and 3rd degree derivatives of position respectively. 
    Vec4 vCurFilteredPos, vEstVelocity, vEstAccelaration, vEstJolt;
    Vec4 vPrevFilteredPos, vPrevEstVelocity, vPrevEstAccelaration, vPrevEstJolt;
    Vec4 vDiff;
    float fDiff;

    Vec4 vPredicted, vError;
    Vec4 vConstants(0.0f, 1.0f, 0.5f, 0.1667f);

    for (int i = 0; i < KIN_SKELETON_POSITION_COUNT; i++)
    {
        vRawPos             = pSkeletonData.vSkeletonPositions[i];
        vPrevFilteredPos    = m_History[i].vPos;
        vPrevEstVelocity    = m_History[i].vEstVelocity;
        vPrevEstAccelaration = m_History[i].vEstAccelaration;
        vPrevEstJolt        = m_History[i].vEstJolt;

        if (!JointPositionIsValid(vPrevFilteredPos))
        {
            vCurFilteredPos = vRawPos;
            vEstVelocity      = Vec4(0,0,0,0);
            vEstAccelaration     = Vec4(0,0,0,0);
            vEstJolt     = Vec4(0,0,0,0);
        }
        else if (!JointPositionIsValid(vRawPos))
        {
            vCurFilteredPos = vPrevFilteredPos;
            vEstVelocity = vPrevEstVelocity;
            vEstAccelaration = vPrevEstAccelaration;
            vEstJolt = vPrevEstJolt;
        }
        else
        {
            // If the current and previous frames have valid data, perform interpolation

            vDiff = vPrevFilteredPos - vRawPos;
            fDiff = fabs(vDiff.GetLength());

            if (fDiff <= fJitterRadius)
            {
                vCurFilteredPos = vRawPos * fDiff/fJitterRadius + vPrevFilteredPos * (1.0f - fDiff/fJitterRadius);
            }
            else
            {
                vCurFilteredPos = vRawPos;
            }

            vPredicted  = vPrevFilteredPos + vPrevEstVelocity;
            vPredicted  = vPredicted + vPrevEstAccelaration * (vConstants.y * vConstants.y * vConstants.z);
            vPredicted  = vPredicted + vPrevEstJolt * (vConstants.y * vConstants.y * vConstants.y * vConstants.w);
            vError      = vCurFilteredPos - vPredicted;

            vCurFilteredPos = vPredicted + vError * fAlphaCoef;
            vEstVelocity = vPrevEstVelocity + vError * fBetaCoeff;
            vEstAccelaration = vEstVelocity - vPrevEstVelocity;
            vEstJolt = vEstAccelaration - vPrevEstAccelaration;
        }

        // Update the state
        m_History[i].vPos = vCurFilteredPos;
        m_History[i].vEstVelocity = vEstVelocity;
        m_History[i].vEstAccelaration = vEstAccelaration;
        m_History[i].vEstJolt = vEstJolt;
      
        // Output the data
        m_FilteredJoints[i]     = vCurFilteredPos;
        m_FilteredJoints[i].w   = 1.0f;
    }
}
Ejemplo n.º 7
0
//==============================================================================
static void setPlane(const Vec4& abcd, Plane& p)
{
	Vec4 n = abcd.xyz0();
	F32 len = n.getLength();
	p = Plane(n / len, -abcd.w() / len);
}
Ejemplo n.º 8
0
Vec4 SpotLight::calculateColor(Vec4 pit, Vec4 n,Vec4 viewer, Material *m,Vec4 pos,Vec4 texColor,int mode_texture)
{
    if(mode_texture==TYPE_ONLY_TEXTURE){
        Vec4 direction(direction_light->x1,direction_light->x2,direction_light->x3);
        Vec4 position(position_light->x1,position_light->x2,position_light->x3);
        Vec4 l = (position-pit)/(position-pit).module();
        float fator = fmax((n*l)/(n.module()*l.module()),0);
        Vec4 Diffuse;
        Diffuse.x1 = (texColor.x() * diffuse_light->x1)*fator;
        Diffuse.x2 = (texColor.y() * diffuse_light->x2)*fator;
        Diffuse.x3 = (texColor.z() * diffuse_light->x3)*fator;

        l = l.unitary();
        Vec4 r = (n*((l*n)*2) - l);
        Vec4 v = (viewer-pit)/(viewer-pit).module();
        r = (r+v)/(r+v).module();

        float fator2 = fmax(pow((r*v),m->shininess*128),0);
        if(r*n<0) fator2 = 0;
        Vec4 especular;
        especular.x1 = (texColor.x() * specular_light->x1)*fator2;
        especular.x2 = (texColor.y() * specular_light->x2)*fator2;
        especular.x3 = (texColor.z() * specular_light->x3)*fator2;

        Vec4 ambiente;
        ambiente.x1 = texColor.x() * ambient_light->x1;
        ambiente.x2 = texColor.y() * ambient_light->x2;
        ambiente.x3 = texColor.z() * ambient_light->x3;

        Vec4 color = ((Diffuse+especular))*isInDualConeSpot(pit)*pow(direction*(l*-1),expoent_light)*attenuation((position-viewer).module());
        return color;

    }else if(mode_texture==TYPE_REPLACE_TEXTURE){

    Vec4 direction(direction_light->x1,direction_light->x2,direction_light->x3);

    //calculo da contribuição difusa

    Vec4 position(position_light->x1,position_light->x2,position_light->x3);
    if ((position-pit).unitary()*n<=0) return Vec4();
    //direction = (direction)/(direction).module();
    Vec4 l = (position-pit)/(position-pit).module();
    float fator = fmax((n*l)/(n.module()*l.module()),0);
    Vec4 Diffuse;
    Diffuse.x1 = (m->diffuse[0] * diffuse_light->x1)*fator;
    Diffuse.x2 = (m->diffuse[1] * diffuse_light->x2)*fator;
    Diffuse.x3 = (m->diffuse[2] * diffuse_light->x3)*fator;

    //calculo da contribuicao especular
    l = l.unitary();
    Vec4 r = (n*((l*n)*2) - l);
    Vec4 v = (viewer-pit)/(viewer-pit).module();
    r = (r+v)/(r+v).module();

    float fator2 = fmax(pow((r*v),m->shininess*128),0);
    if(r*n<0) fator2 = 0;
    Vec4 especular;
    especular.x1 = (m->specular[0] * specular_light->x1)*fator2;
    especular.x2 = (m->specular[1] * specular_light->x2)*fator2;
    especular.x3 = (m->specular[2] * specular_light->x3)*fator2;
    //calculo da contribuição ambiente
    Vec4 ambiente;
    ambiente.x1 = m->ambient[0] * ambient_light->x1;
    ambiente.x2 = m->ambient[1] * ambient_light->x2;
    ambiente.x3 = m->ambient[2] * ambient_light->x3;

    Vec4 color = texColor.mult(((Diffuse+especular))*isInDualConeSpot(pit)*pow(direction*(l*-1),expoent_light)*attenuation((position-viewer).module()));
    return color;
    }else{
        Vec4 direction(direction_light->x1,direction_light->x2,direction_light->x3);

        //calculo da contribuição difusa

        Vec4 position(position_light->x1,position_light->x2,position_light->x3);
        if ((position-pit).unitary()*n<=0) return Vec4();
        //direction = (direction)/(direction).module();
        Vec4 l = (position-pit)/(position-pit).module();
        float fator = fmax((n*l)/(n.module()*l.module()),0);
        Vec4 Diffuse;
        Diffuse.x1 = (m->diffuse[0] * diffuse_light->x1)*fator;
        Diffuse.x2 = (m->diffuse[1] * diffuse_light->x2)*fator;
        Diffuse.x3 = (m->diffuse[2] * diffuse_light->x3)*fator;

        //calculo da contribuicao especular
        l = l.unitary();
        Vec4 r = (n*((l*n)*2) - l);
        Vec4 v = (viewer-pit)/(viewer-pit).module();
        r = (r+v)/(r+v).module();

        float fator2 = fmax(pow((r*v),m->shininess*128),0);
        if(r*n<0) fator2 = 0;
        Vec4 especular;
        especular.x1 = (m->specular[0] * specular_light->x1)*fator2;
        especular.x2 = (m->specular[1] * specular_light->x2)*fator2;
        especular.x3 = (m->specular[2] * specular_light->x3)*fator2;
        //calculo da contribuição ambiente
        Vec4 ambiente;
        ambiente.x1 = m->ambient[0] * ambient_light->x1;
        ambiente.x2 = m->ambient[1] * ambient_light->x2;
        ambiente.x3 = m->ambient[2] * ambient_light->x3;

        Vec4 color = ((Diffuse+especular))*isInDualConeSpot(pit)*pow(direction*(l*-1),expoent_light)*attenuation((position-viewer).module());
        return color;
    }
}
Ejemplo n.º 9
0
void SpotLight::setPosition(Vec4 pos)
{
    position_light = new Vec4(pos.x(),pos.y(),pos.z());
}
Ejemplo n.º 10
0
	Vector(const Vec4& vector) :
		detail::VectorType<4>(vector.x(), vector.y(), vector.z(), 0.0f)
	{
	}
Ejemplo n.º 11
0
//==============================================================================
void FollowPathEvent::update(F32 prevUpdateTime, F32 crntTime)
{
	MoveComponent& move = movableSceneNode->getComponent<MoveComponent>();

	I pointA = 0;
	I pointB = 0;

	// Calculate the current distance. Clamp it to max distance
	F32 crntDistance = distPerTime * (crntTime - getStartTime());
	ANKI_ASSERT(crntDistance >= 0.0);
	crntDistance = std::min(crntDistance, path->getDistance());

	const I pointsCount = path->getPoints().size();
	ANKI_ASSERT(pointsCount > 1);

	// Find the points that we lie between
	for(I i = 1; i < pointsCount; i++)
	{
		const PathPoint& ppa = path->getPoints()[i - 1];
		const PathPoint& ppb = path->getPoints()[i];

		if(crntDistance > ppa.getDistanceFromFirst() 
			&& crntDistance <= ppb.getDistanceFromFirst())
		{
			pointA = i - 1;
			pointB = i;
			break;
		}
	}

	ANKI_ASSERT(pointA < pointsCount && pointB < pointsCount);

	I preA = std::max((I)0, pointA - 1);
	I postB = std::min(pointsCount - 1, pointB + 1);
	/*I pminus2 = std::max((I)0, pointA - 2);
	I pminus1 = std::max((I)0, pointA - 1);*/

	// Calculate the u [0.0, 1.0]
	F32 u = path->getPoints()[pointB].getDistance() + getEpsilon<F32>();
	ANKI_ASSERT(u != 0.0);

	const F32 c = crntDistance 
		- path->getPoints()[pointA].getDistanceFromFirst();

	u = c / u;

	// Calculate and set new position and rotation for the movable
	/*Vec3 newPos = cubicInterpolate(
		path->getPoints()[preA].getPosition(),
		path->getPoints()[pointA].getPosition(),
		path->getPoints()[pointB].getPosition(),
		path->getPoints()[postB].getPosition(),
		u);*/
	Vec3 newPos = interpolate(
		path->getPoints()[pointA].getPosition(),
		path->getPoints()[pointB].getPosition(),
		u);

	{
		F32 u2 = u * u;
		Vec4 us(1, u, u2, u2 * u);
		F32 t = 0.7;
		
		Mat4 tentionMat(
			0.0, 1.0, 0.0, 0.0,
			-t, 0.0, t, 0.0,
			2.0 * t, t - 3.0, 3.0 - 2.0 * t, -t,
			-t, 2.0 - t, t - 2.0, t);

		Vec4 tmp = us * tentionMat;

		Mat4 posMat;
		posMat.setRows(
			Vec4(path->getPoints()[preA].getPosition(), 1.0),
			Vec4(path->getPoints()[pointA].getPosition(), 1.0),
			Vec4(path->getPoints()[pointB].getPosition(), 1.0),
			Vec4(path->getPoints()[postB].getPosition(), 1.0));

		Vec4 finalPos = tmp * posMat;

		newPos = finalPos.xyz();
	}

	Quat newRot = path->getPoints()[pointA].getRotation().slerp(
			path->getPoints()[pointB].getRotation(),
			u);

	F32 scale = move.getLocalTransform().getScale();
	Transform trf;
	trf.setOrigin(newPos);
	trf.setRotation(Mat3(newRot));
	trf.setScale(scale);
	move.setLocalTransform(trf);
}
Ejemplo n.º 12
0
 void GLFunctions::cylinder( float _radius,const float _height, int _slices, int _stacks )
 {
  /* Step in z and radius as stacks are drawn. */

  double z0,z1;
  const double zStep = _height / ( ( _stacks > 0 ) ? _stacks : 1 );

  /* Pre-computed circle */

  double *sint,*cost;
  Vec4 vertex;
  Vec4 normal;
  fghCircleTable(&sint,&cost,-_slices);
  /* Do the stacks */
  z0 = 0.0;
  z1 = zStep;
  glBegin(GL_TRIANGLES);
    for(int i=1; i<=_stacks+1; ++i )
    {
      if(i==_stacks)
      {
        z1 = _height;
      }
      for(int j=0; j<=_slices-1; ++j)
      {
        // vert 1;
        normal.set(sint[j],cost[j],0.0f);
        vertex.set(sint[j]*_radius,cost[j]*_radius,-z0/2.0);
        normal.normalGL();
        vertex.vertexGL();
        // vert 2
        vertex.set(sint[j]*_radius,cost[j]*_radius,-z1/2.0);
        vertex.vertexGL();

        vertex.set(sint[j+1]*_radius,cost[j+1]*_radius,-z0/2.0);
        normal.set(sint[j+1],cost[j+1],0.0f);
        normal.normalGL();
        vertex.vertexGL();

        vertex.set(sint[j+1]*_radius,cost[j+1]*_radius,-z0/2.0);
        normal.set(sint[j+1],cost[j+1],0.0f);
        normal.normalGL();
        vertex.vertexGL();

        vertex.set(sint[j]*_radius,cost[j]*_radius,-z1/2.0);
        normal.set(sint[j],cost[j],0.0f);
        normal.normalGL();
        vertex.vertexGL();

        vertex.set(sint[j+1]*_radius,cost[j+1]*_radius,-z1/2.0);
        normal.set(sint[j+1],cost[j+1],0.0f);
        normal.normalGL();
        vertex.vertexGL();

      }
    z0 = z1; z1 += zStep;
    }
  glEnd();
  /* Release sin and cos tables */

  delete [] sint;
  delete [] cost;
 }
Ejemplo n.º 13
0
// This method needs to be broken up
void tcHookInfo::DrawTrack(long anID) 
{
    std::string s;
    char zBuff[128];
    float ftextx = 10.0f;
    float ftexty = 22.0f;
    UINT8 nOwnAlliance = mpUserInfo->GetOwnAlliance();
	Vec4 color;

    tcSensorMapTrack* pSMTrack = mpSS->mcSensorMap.GetSensorMapTrack(anID, nOwnAlliance);
    if (pSMTrack == 0) return;

    const tcTrack *pTrack = pSMTrack->GetTrack();
    // classification
    ClassificationToString(pTrack->mnClassification, zBuff);
	strcat(zBuff, " track");
	color.set(0.4f, 1.0f, 0.4f, 1.0f);
    
	if (!pSMTrack->IsIdentified())
	{
		DrawTextR(zBuff, ftextx-2.0f, ftexty, defaultFont.get(), 
			color, fontSizeLarge, LEFT_BASE_LINE);
		ftexty += 20.0f;
	}
	else // track is identified, look up class name
	{
		if (tcDatabaseObject* databaseObj = database->GetObject(pSMTrack->GetDatabaseId()))
		{
            s = databaseObj->GetDisplayName();
		}
		else // error, not found in database
		{
			s = "Error";
		}

		DrawTextR(s.c_str(), ftextx-2.0f, ftexty, 
			defaultFont.get(), color, fontSizeLarge, LEFT_BASE_LINE);
		ftexty += 15.0f;

		DrawTextR(zBuff, ftextx, ftexty, 
			defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
		ftexty += 20.0f;
	}


    // speed, heading, altitude, terrain info
    s = "";
    if (pTrack->mnFlags & TRACK_HEADING_VALID) 
    {

        //if (heading_deg < 0) heading_deg += 360;

        if (pTrack->mnFlags & TRACK_BEARING_ONLY) 
        {
            int bearing_deg(C_180OVERPI*pTrack->bearing_rad + 0.5f);
            bearing_deg = bearing_deg + int(bearing_deg < 0)*360;
            sprintf(zBuff,"BRG %03d ", bearing_deg);
        }
        else 
        {       
            int heading_deg(C_180OVERPI*pTrack->mfHeading_rad + 0.5f);
            heading_deg = heading_deg + int(heading_deg < 0)*360;
            sprintf(zBuff,"HDG %03d ", heading_deg);
        }
        s += zBuff;
    }
    if (pTrack->mnFlags & TRACK_SPEED_VALID) 
    {
        sprintf(zBuff," SPD %s ", units->GetUserSpeedString(pTrack->mfSpeed_kts));
        s += zBuff;
    }
    if ((pTrack->mnClassification & (PTYPE_AIR | PTYPE_MISSILE))
        &&(pTrack->mnFlags & TRACK_ALT_VALID)) 
    {
        sprintf(zBuff," ALT %s", units->GetUserAltitudeString(pTrack->mfAlt_m));
        s += zBuff;
    }

	DrawTextR(s.c_str(), ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
    ftexty += 15;

    // Draw reporting platform info
    size_t nContributors = pSMTrack->GetContributorCount();
    s = "Detected by: ";
    for (size_t k=0; k<nContributors; k++)
    {
        s += std::string(pSMTrack->GetContributorName(k));
        if (k < nContributors-1) s += ",";
    }
	if (s.size() > 35)
	{
		s = s.substr(0, 35);
	}

    DrawTextR(s.c_str(), ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
    ftexty += 15;

    // Draw contact update time
    double t = mpSS->GetTime();
    float dt_s = float(t - pSMTrack->GetLastReportTime());
    int mm = int(floor((1.0/60.0)*dt_s));
    int ss = int(floor(dt_s - 60.0f*float(mm)));
    mm = std::min(mm, 99); // max at 99 for display
    tcDateTime dateTime = mpSS->GetDateTime();
    dateTime.AdjustTimeSeconds(-dt_s);
    wxString s2;
    s2.Printf("%s (-%02d:%02d)", dateTime.asStringTOD(), mm, ss);
    DrawTextR(s2.c_str(), ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
    ftexty += 15;

    // Draw emitter info
    int nEmitters = pSMTrack->GetEmitterCount();
    if (nEmitters) 
    {
		DrawTextR("Emitters:", ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
        ftexty+=15;
    }
    else 
    {
		DrawTextR("No emitters detected", ftextx, ftexty, defaultFont.get(), 
			color, fontSize, LEFT_BASE_LINE);
        ftexty += 15;
    }

    for (int n=0; n<nEmitters; n++) 
    {
        const EmitterInfo *pEmitterInfo = pSMTrack->GetEmitter(n);
        long nEmitterID = pEmitterInfo->mnEmitterID;
        tcDatabaseObject *pDBObj = mpSS->mpDatabase->GetObject(nEmitterID);
        if (pDBObj != NULL) 
        {
            strncpy(zBuff, pDBObj->mzClass.c_str(), 127);
        }
        else 
        {
            strcpy(zBuff,"Error");
        }
		DrawTextR(zBuff, ftextx + 3.0f, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);

        ftexty += 15;
    }

	ftexty += 5;

	/* Platform ambiguity list, update if at least one emitter
	** is detected, and detailed identification is not 
	** available */
	if ((nEmitters > 0) && (!pSMTrack->IsIdentified()))
	{
		unsigned nCandidates = pSMTrack->ambiguityList.size();
		if (nCandidates) 
		{
			sprintf(zBuff, "Ambiguity list (%d):", nCandidates);
			DrawTextR(zBuff, ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
			ftexty+=15;
		}
		else 
		{
			DrawTextR("Ambiguity list not available", ftextx, ftexty, defaultFont.get(), 
				color, fontSize, LEFT_BASE_LINE);
			ftexty += 15;
		}

		unsigned int currentCount = tcTime::Get()->Get30HzCount();
		if (currentCount - lastCycleCount > 75) // 2.5 seconds
		{
			lastCycleCount = currentCount;
			if (nCandidates > 4)
			{
				ambiguityIdx += 4;
			}
		}
		if (ambiguityIdx >= nCandidates) ambiguityIdx = 0;

		for (unsigned int n=ambiguityIdx; (n < ambiguityIdx+4) && (n < nCandidates); n++) 
		{
			long candidateID = pSMTrack->ambiguityList[n];
			tcDatabaseObject* dbObj = mpSS->mpDatabase->GetObject(candidateID);
			if (dbObj) 
			{
				strncpy(zBuff, dbObj->mzClass.c_str(), 127);
			}
			else 
			{
				strcpy(zBuff, "Error");
			}
			DrawTextR(zBuff, ftextx + 3.0f, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);

			ftexty += 10;
		}

	}








    //*********** draw engagement info **************
    DrawTrackEngaged(pSMTrack, ftextx, ftexty);

}
Ejemplo n.º 14
0
void tcHookInfo::DrawOwn(tcGameObject *pHookedObj) 
{

    std::string s;
    char zBuff[128];
    float ftextx = 10.0f;
    float ftexty = 22.0f;
	Vec4 color;

    if (pHookedObj == NULL) {return;}


    s = pHookedObj->mzUnit.c_str();
	color.set(0.4f, 1.0f, 0.4f, 1.0f);
	DrawTextR(s.c_str(), ftextx-2.0f, ftexty, defaultFont.get(), color, fontSizeLarge, LEFT_BASE_LINE,
        180.0f);
    ftexty += 20.0f;

    sprintf(zBuff, "%s (id %d)", pHookedObj->GetDisplayClassName(), pHookedObj->mnID);
    s = zBuff;
	DrawTextR(s.c_str(), ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
    ftexty += 20.0f;

    /*** mnClassID, mnModelType, mnType (classification) ***/
    GetObjectInfo(s, pHookedObj->mpDBObject, pHookedObj);
	DrawTextR(s.c_str(), ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
    ftexty += 15.0f;

    // speed, heading, altitude, terrain info
    tcKinematics *pkin = &pHookedObj->mcKin;
    
    int heading_deg = int(C_180OVERPI*pkin->mfHeading_rad + 0.5f);
    heading_deg = heading_deg + (int(heading_deg < 0) - int(heading_deg >= 360))*360;

    sprintf(zBuff,"%s, hdg %03d, alt %s",
        units->GetUserSpeedString(pkin->mfSpeed_kts), heading_deg, 
        units->GetUserAltitudeString(pkin->mfAlt_m));

    s = zBuff;
	DrawTextR(s.c_str(), ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
    ftexty += 15;

    sprintf(zBuff, "Terrain %s", units->GetUserAltitudeString(pHookedObj->mcTerrain.mfHeight_m));
    s = zBuff;
	DrawTextR(s.c_str(), ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
    ftexty+=15;

    // lat, lon
    LonLatToStringB(C_180OVERPI*(float)pkin->mfLon_rad,C_180OVERPI*(float)pkin->mfLat_rad,s);
	DrawTextR(s.c_str(), ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
    ftexty += 15;

    /*** damage ***/
	float damageLevelPercent = 100.0f * pHookedObj->GetDamageLevel();
	if (damageLevelPercent > 100.0f) damageLevelPercent = 100.0f;

    if (damageLevelPercent == 0) 
    {
        strcpy(zBuff,"Damage: none");
    }
    else if (damageLevelPercent >= 50.0f) 
    {   
		color.set(1.0f, 0.4f, 0.4f, 1.0f);
        sprintf(zBuff, "Damage: %2.0f%%", damageLevelPercent);
    }
    else 
	{
		color.set(1.0f, 1.0f, 0.4f, 1.0f);
        sprintf(zBuff, "Damage: %2.0f%%", damageLevelPercent);
    }
    s = zBuff;
	DrawTextR(s.c_str(), ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
    ftexty += 15;
	color.set(0.4f, 1.0f, 0.4f, 1.0f);


	// multiplayer info
	if (mpSS->IsMultiplayerActive())
	{
		const std::string& controller = pHookedObj->GetController();

		if (controller.size())
		{
			s = "Controlled by ";
			s += controller;
		}
		else
		{
			s = "No controller";
		}

		DrawTextR(s.c_str(), ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
		ftexty += 15;
		color.set(0.4f, 1.0f, 0.4f, 1.0f);
	}
	

    // AI action text for platform objects
    tcPlatformObject* pPlatformObj = dynamic_cast<tcPlatformObject*>(pHookedObj);
    if (pPlatformObj != NULL) 
    {
        std::string text = pPlatformObj->GetBrain()->GetActionText();
        s = "Action: ";
        s += text;
		DrawTextR(s.c_str(), ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
        ftexty += 15;
    }
    if (tcMissileObject* missile = dynamic_cast<tcMissileObject*>(pHookedObj))
    {
        sprintf(zBuff, "Runtime: %.1f", missile->RuntimeRemaining());

		DrawTextR(zBuff, ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
        ftexty += 15;

        sprintf(zBuff, "Distance: %s", units->GetUserDistanceString(missile->GetDistanceFromLaunch()));

		DrawTextR(zBuff, ftextx, ftexty, defaultFont.get(), color, fontSize, LEFT_BASE_LINE);
        ftexty += 15;
        
    }

}
Ejemplo n.º 15
0
//--------------------------------------------------------------------------------------
// Name: CombiJointFilter()
// Desc: A filter for the positional data.  This filter uses a combination of velocity 
//       position history to filter the joint positions.
//--------------------------------------------------------------------------------------
void FilterCombination::Update( const SKinSkeletonRawData& pSkeletonData, const float fDeltaTime )
{
    // Process each joint
    for ( uint32 nJoint = 0; nJoint < KIN_SKELETON_POSITION_COUNT; ++nJoint )
    {
        // Remember where the camera thinks this joint should be
        m_History[ nJoint ].m_vWantedPos = pSkeletonData.vSkeletonPositions[ nJoint ];

        Vec4 vDelta;
        vDelta = m_History[ nJoint ].m_vWantedPos - m_History[ nJoint ].m_vLastWantedPos;
        {
            Vec4 vBlended;

            // Calculate the vBlended value - could optimize this by remembering the running total and
            // subtracting the oldest value and then adding the newest. Saves adding them all up on each frame.
            vBlended = Vec4(0,0,0,0);
            for( uint32 k = 0; k < m_nUseTaps; ++k)
            {
                vBlended = vBlended + m_History[ nJoint ].m_vPrevDeltas[k];
            }
            vBlended = vBlended / ((float)m_nUseTaps);

						vBlended.w = 0.0f;
						vDelta.w = 0.0f;

            float fDeltaLength = vDelta.GetLength();
            float fBlendedLength = vBlended.GetLength();
            m_History[ nJoint ].m_fWantedLocalBlendRate = m_fDefaultApplyRate;
            m_History[ nJoint ].m_bActive[0] = false;
            m_History[ nJoint ].m_bActive[1] = false;
            m_History[ nJoint ].m_bActive[2] = false;

            // Does the current velocity and history have a reasonable magnitude?
            if( fDeltaLength   >= m_fDeltaLengthThreshold &&
                fBlendedLength >= m_fBlendedLengthThreshold )
            {
                float fDotProd;
                float fConfidence;

                if( m_bDotProdNormalize )
                {
                    Vec4 vDeltaOne = vDelta;
										vDeltaOne.Normalize();
                    Vec4 vBlendedOne = vBlended;
										vBlendedOne.Normalize();

                    fDotProd = vDeltaOne.Dot( vBlendedOne );
                }
                else
                {
										fDotProd = vDelta.Dot(vBlended);
                }

                // Is the current frame aligned to the recent history?
                if( fDotProd >= m_fDotProdThreshold )
                {
                    fConfidence = fDotProd;
                    m_History[ nJoint ].m_fWantedLocalBlendRate = min( fConfidence, 1.0f );
                    m_History[ nJoint ].m_bActive[0] = true;
                }
            }

            assert( m_History[ nJoint ].m_fWantedLocalBlendRate <= 1.0f );
        }

        // Push the previous deltas down the history
        for( int j = m_nUseTaps-2; j >= 0; --j )
        {
            m_History[ nJoint ].m_vPrevDeltas[j+1] = m_History[ nJoint ].m_vPrevDeltas[j];
        }

        // Store the current history
        m_History[ nJoint ].m_vPrevDeltas[0] = vDelta;	

        // Remember where the camera thought this joint was on the this frame
        m_History[ nJoint ].m_vLastWantedPos = m_History[ nJoint ].m_vWantedPos;
    }

    // Secondary and tertiary blending
    for ( uint32 pass = 0; pass < 2; ++pass )
    {
        for ( uint32 bone = 0; bone < g_numBones; ++bone )
        {
            float fRate1;
            float fRate2;

            fRate1 = m_History[ g_Bones[bone].startJoint ].m_fWantedLocalBlendRate;
            fRate2 = m_History[ g_Bones[bone].endJoint ].m_fWantedLocalBlendRate;

            // Blend down? Start to end
            if( (fRate1 * m_fDownBlendRate) > fRate2)
            {
                // Yes, apply
                m_History[ g_Bones[bone].endJoint ].m_fWantedLocalBlendRate = ( fRate1 * m_fDownBlendRate );

                // Flag
                m_History[ g_Bones[bone].endJoint ].m_bActive[pass+1] = true;
            }
            // Blend down? End to start
            if( ( fRate2 * m_fDownBlendRate ) > fRate1)
            {
                // Yes, apply
                m_History[ g_Bones[bone].startJoint ].m_fWantedLocalBlendRate = ( fRate2 * m_fDownBlendRate );

                // Flag
                m_History[ g_Bones[bone].startJoint ].m_bActive[pass+1] = true;
            }
        }
    }

    // Apply
    for ( uint32 joint = 0; joint < KIN_SKELETON_POSITION_COUNT; ++joint )
    {
        // Blend the blend rate
        m_History[ joint ].m_fActualLocalBlendRate = 
                Lerp(m_History[ joint ].m_fActualLocalBlendRate,
                     m_History[ joint ].m_fWantedLocalBlendRate,
                     m_fBlendBlendRate);

        // Blend the actual position towards the wanted positon
        m_History[ joint ].m_vPos = 
                Lerp(m_History[ joint ].m_vPos,
                             m_History[ joint ].m_vWantedPos,
                             m_History[ joint ].m_fActualLocalBlendRate);
        m_FilteredJoints[ joint ] = m_History[ joint ].m_vPos;
    }
}
Ejemplo n.º 16
0
void SpotLight::setDirection(Vec4 pos)
{
    direction_light = new Vec4(pos.x(),pos.y(),pos.z());
}
Ejemplo n.º 17
0
void FilterDoubleExponential::Update( const SKinSkeletonRawData& pSkeletonData, uint32 i, const KIN_TRANSFORM_SMOOTH_PARAMETERS& smoothingParams )
{
    Vec4 vPrevRawPosition;
    Vec4 vPrevFilteredPosition;
    Vec4 vPrevTrend;
    Vec4 vRawPosition;
    Vec4 vFilteredPosition;
    Vec4 vPredictedPosition;
    Vec4 vDiff;
    Vec4 vTrend;
    Vec4 vLength;
    float fDiff;
    BOOL bJointIsValid;

    const Vec4* __restrict pJointPositions = pSkeletonData.vSkeletonPositions;

    vRawPosition            = pJointPositions[i];
    vPrevFilteredPosition   = m_History[i].m_vFilteredPosition;
    vPrevTrend              = m_History[i].m_vTrend;
    vPrevRawPosition        = m_History[i].m_vRawPosition;
    bJointIsValid           = JointPositionIsValid(vRawPosition);

    // If joint is invalid, reset the filter
    if (!bJointIsValid)
    {
        m_History[i].m_dwFrameCount = 0;
    }

    // Initial start values
    if (m_History[i].m_dwFrameCount == 0)
    {
        vFilteredPosition = vRawPosition;
        vTrend = Vec4(0,0,0,0);
        m_History[i].m_dwFrameCount++;
    }
    else if (m_History[i].m_dwFrameCount == 1)
    {
        vFilteredPosition = (vRawPosition + vPrevRawPosition) * 0.5f;
        vDiff = vFilteredPosition - vPrevFilteredPosition;
        vTrend = (vDiff * smoothingParams.m_fCorrection) + (vPrevTrend *  (1.0f - smoothingParams.m_fCorrection));
        m_History[i].m_dwFrameCount++;
    }
    else
    {              
        // First apply jitter filter
        vDiff = vRawPosition - vPrevFilteredPosition;
        fDiff = fabs(vDiff.GetLength());

        if (fDiff <= smoothingParams.m_fJitterRadius)
        {
            vFilteredPosition = vRawPosition * (fDiff/smoothingParams.m_fJitterRadius) + vPrevFilteredPosition * (1.0f - fDiff/smoothingParams.m_fJitterRadius);
        }
        else
        {
            vFilteredPosition = vRawPosition;
        }

        // Now the double exponential smoothing filter
        vFilteredPosition = vFilteredPosition * (1.0f - smoothingParams.m_fSmoothing) + (vPrevFilteredPosition + vPrevTrend) * smoothingParams.m_fSmoothing;


        vDiff = vFilteredPosition - vPrevFilteredPosition;
        vTrend = vDiff * smoothingParams.m_fCorrection + vPrevTrend * (1.0f - smoothingParams.m_fCorrection); 
    }      

    // Predict into the future to reduce latency
    vPredictedPosition = vFilteredPosition + (vTrend * smoothingParams.m_fPrediction);

    // Check that we are not too far away from raw data
    vDiff = vPredictedPosition - vRawPosition;
    fDiff = fabs(vDiff.GetLength());

    if (fDiff > smoothingParams.m_fMaxDeviationRadius)
    {
        vPredictedPosition = vPredictedPosition * smoothingParams.m_fMaxDeviationRadius/fDiff + vRawPosition * (1.0f - smoothingParams.m_fMaxDeviationRadius/fDiff);
    }

    // Save the data from this frame
    m_History[i].m_vRawPosition      = vRawPosition;
    m_History[i].m_vFilteredPosition = vFilteredPosition;
    m_History[i].m_vTrend            = vTrend;
    
    // Output the data
    m_FilteredJoints[i] = vPredictedPosition;
    m_FilteredJoints[i].w = 1.0f;
}
Ejemplo n.º 18
0
void SpotLight::setAttenuation(Vec4 pos)
{
    factor_attenuation = new Vec4(pos.x(),pos.y(),pos.z());
}
Ejemplo n.º 19
0
bool Sphere::Intersect( Ray const &ray, float *tHit, float *epsilon, DifferentialGeometry *geom ) const {
    Transform tf = Tform();
    Ray r = ray * Inverse( tf );

    float t;
    if( !Intersect( ray, &t ) )
        return false;

    // compute differential geometry
    Vec4 p = ray.Point( t );

    float x = p.X();
    float y = p.Y();
    float z = p.Z();

    if( x == 0.0f && z == 0.0f ) {
        // can't have both atan2 arguments be zero
        z = kEpsilon * m_radius;
    }
    float theta = atan2( p.X(), p.Z() );

    if( theta < 0.0f ) {
        // remap theta to [0, 2pi] to match sphere's definition
        theta += k2Pi;
    }

    float phi = Acos( Clamp( z / m_radius, -1.0f, 1.0f ) );

    // parameterize sphere hit
    float u = theta * kInv2Pi;
    float v = phi * kInvPi;

    float sTheta, cTheta;
    float sPhi, cPhi;
    SinCos( theta, &sTheta, &cTheta );
    SinCos( phi, &sPhi, &cPhi );

    Vec4 dpdu( k2Pi * z, 0.0f, -k2Pi * x, 0.0f );
    Vec4 dpdv( kPi * y * sTheta, -kPi * m_radius * sPhi, kPi * y * cTheta, 0.0f );
    Vec4 d2pdu2( -k2Pi * k2Pi * x, 0.0f, -k2Pi * k2Pi * z, 0.0f );
    Vec4 d2pduv( k2Pi * kPi * y * cTheta, 0.0f, -k2Pi * kPi * y * sTheta, 0.0f );
    Vec4 d2pdv2( -kPi * kPi * x, -kPi * kPi * y, -kPi * kPi * z, 0.0f );

    // change in normal is computed using Weingarten equations
    Scalar E = Dot( dpdu, dpdu );
    Scalar F = Dot( dpdu, dpdv );
    Scalar G = Dot( dpdv, dpdv );
    Vec4 N = Normalize( Cross(  dpdu, dpdv ) );
    Scalar e = Dot( N, d2pdu2 );
    Scalar f = Dot( N, d2pduv );
    Scalar g = Dot( N, d2pdv2 );

    Scalar h = 1.0f / ( E * G - F * F );
    Vec4 dndu = ( f * F - e * G ) * h * dpdu + ( e * F - f * E ) * h * dpdv;
    Vec4 dndv = ( g * F - f * G ) * h * dpdu + ( f * F - g * E ) * h * dpdv;

    *tHit = t;
    *epsilon = 5e-4f * t;

    // return world space differential geometry
    *geom = DifferentialGeometry( Handle(), p * tf, dpdu * tf, dpdv * tf, Normal( dndu ) * tf, Normal( dndv ) * tf, u, v );

    return true;
}
Ejemplo n.º 20
0
void RationalBilinearInverter::solve(
	Vec2 const & p,
	Vec4 const & p00, Vec4 const & p10,
	Vec4 const & p01, Vec4 const & p11
)
{
	double m[4][6] = {
		{ p00.x(), p10.x(), p01.x(), -p.x(), 0, -p11.x() },
		{ p00.y(), p10.y(), p01.y(), -p.y(), 0, -p11.y() },
		{ p00.z(), p10.z(), p01.z(),     -1, 0, -p11.z() },
		{ p00.w(), p10.w(), p01.w(),      0, 1, -p11.w() }
	};

	for (int j = 0; j < 4; ++j) {
		double a = 0.0;

		std::for_each(m[j], m[j + 1], [&] (double & f) { a = (std::max)(a, fabs(f)); });
		std::for_each(m[j], m[j + 1], [&] (double & f) { f /= a; });
	}

	for (int j = 0; j < 4; ++j) {
		int pivot_row = j; double pivot_value = fabsf(m[j][j]);

		for (int k = j + 1; k < 4; ++k) {
			auto t = fabsf(m[k][j]);
			if (t > pivot_value) {
				pivot_value = t;
				pivot_row = k;
			}
		}

		if (pivot_row != j) { swap(m[j], m[pivot_row]); }

		double * row = m[j] + j, * end = m[j + 1];
		normalize_front(row, end);

		for (int k = j + 1; k < 4; ++k) {
			scale_and_subtract_row(m[k] + j, m[k + 1], m[k][j], row);
		}
	}

	for (int i = 3; i > 0; --i) {
		for (int j = i - 1; j >= 0; --j) {
			scale_and_subtract_row(m[j] + i, m[j + 1], m[j][i], m[i] + i);
		}
	}

    double quad_a = m[0][5] - m[1][5] * m[2][5],
           quad_b = m[0][4] - m[1][4] * m[2][5] - m[1][5] * m[2][4],
           quad_c = - m[1][4] * m[2][4];

    if (-1e-3 < quad_a && quad_a < 1e-3) { quad_a = 0.; }
    if (-1e-3 < quad_b && quad_b < 1e-3) { quad_b = 0.; }
    if (-1e-3 < quad_c && quad_c < 1e-3) { quad_c = 0.; }

	QuadraticSolver<double> q(quad_a, quad_b, quad_c);

	for (auto it = q.begin(); it != q.end(); ++it) {
		double D = *it,
			alpha = m[3][4] + m[3][5] * D;

		if (alpha < 1.0 - 1e-3) { continue; }

		double A = m[0][4] + m[0][5] * D,
			B = m[1][4] + m[1][5] * D,
			C = m[2][4] + m[2][5] * D,
			d = A + B + C + D;
		
		if (!d || d != d) { continue; }

		double r = 1.0 / d,
			u = (B + D) * r,
			v = (C + D) * r;

		if (u < -1e-3 || u >= 1.0-1e-3) { continue; }
		if (v < -1e-3 || v >= 1.0-1e-3) { continue; }

		solutions_[size_++] = std::make_pair(alpha, Vec2(u, v));
	}
	
	if (size_ == 2 && solutions_[0].first > solutions_[1].first)
		{ std::swap(solutions_[0], solutions_[1]); }
}
Ejemplo n.º 21
0
void Light::setNormal(Vec4<GLfloat> normal)
{
        UBOUniform normalUbo = uniforms[std::string("normal")];
        size_t size = normalUbo.getSize() * typeSize(normalUbo.getType());
        memcpy(lightData + normalUbo.getOffset(), normal.getData(), size);
}
Ejemplo n.º 22
0
bool Grid::collision()
{
	bool ret = false;
	if(!current)
	{
		return false;
	}
	Vec4<Vec2i> blocks = current->getBricks();
	if(blocks.X().Y() < H && (blocks.X().Y() == 0 || GD[((blocks.X().Y()-1)*W)+blocks.X().X()]))
	{
		ret = true;
	}
	if(blocks.Y().Y() < H && (blocks.Y().Y() == 0 || GD[((blocks.Y().Y()-1)*W)+blocks.Y().X()]))
	{
		ret = true;
	}
	if(blocks.Z().Y() < H && (blocks.Z().Y() == 0 || GD[((blocks.Z().Y()-1)*W)+blocks.Z().X()]))
	{
		ret = true;
	}
	if(blocks.W().Y() < H && (blocks.W().Y() == 0 || GD[((blocks.W().Y()-1)*W)+blocks.W().X()]))
	{
		ret = true;
	}



	return ret;
}
Ejemplo n.º 23
0
void newtonRayCast::CastRay (const Vec4& p0, const Vec4& p1, int threadIndex)
{
	m_param = 1.2f;
	m_bodyHit = NULL;
	dNewtonRayCast::CastRay(p0.ptr(), p1.ptr());
}
Ejemplo n.º 24
0
bool Grid::canNudge(bool left)
{

	bool ret = true;
	if(!current)
	{
		return false;
	}
	int direction = 1;
	if(left)
	{
		direction = -1;
	}
	Vec4<Vec2i> blocks = current->getBricks();
	if(blocks.X().Y() < H && (blocks.X().X()+direction > 0) && (blocks.X().X() + direction < (W-1)) && GD[((blocks.X().Y())*W)+blocks.X().X()+direction])
	{
		ret = false;
	}
	if(blocks.Y().Y() < H && (blocks.Y().X()+direction > 0) && (blocks.Y().X() + direction < (W-1)) && GD[((blocks.Y().Y())*W)+blocks.Y().X()+direction])
	{
		ret = false;
	}
	if(blocks.Z().Y() < H && (blocks.Z().X()+direction > 0) && (blocks.Z().X() + direction < (W-1)) && GD[((blocks.Z().Y())*W)+blocks.Z().X()+direction])
	{
		ret = false;
	}
	if(blocks.W().Y() < H && (blocks.W().X()+direction > 0) && (blocks.W().X() + direction < (W-1)) && GD[((blocks.W().Y())*W)+blocks.W().X()+direction])
	{
		ret = false;
	}

	return ret;


}
Ejemplo n.º 25
0
Array* Array_readLocalData(Input& fr)
{
    if (fr[0].matchWord("Use"))
    {
        if (fr[1].isString())
        {
            Object* obj = fr.getObjectForUniqueID(fr[1].getStr());
            if (obj)
            {
                fr+=2;
                return dynamic_cast<Array*>(obj);
            }
        }

        osg::notify(osg::WARN)<<"Warning: invalid uniqueID found in file."<<std::endl;
        return NULL;
    }

    std::string uniqueID;
    if (fr[0].matchWord("UniqueID") && fr[1].isString())
    {
        uniqueID = fr[1].getStr();
        fr += 2;
    }


    int entry = fr[0].getNoNestedBrackets();

    const char* arrayName = fr[0].getStr();

    unsigned int capacity = 0;
    fr[1].getUInt(capacity);
    ++fr;

    fr += 2;


    Array* return_array = 0;

    if (strcmp(arrayName,"ByteArray")==0)
    {
        ByteArray* array = new ByteArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            int int_value;
            if (fr[0].getInt(int_value))
            {
                ++fr;
                array->push_back(int_value);
            }
            else ++fr;
        }
        ++fr;

        return_array = array;
    }
    else if (strcmp(arrayName,"ShortArray")==0)
    {
        ShortArray* array = new ShortArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            int int_value;
            if (fr[0].getInt(int_value))
            {
                ++fr;
                array->push_back(int_value);
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"IntArray")==0)
    {
        IntArray* array = new IntArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            int int_value;
            if (fr[0].getInt(int_value))
            {
                ++fr;
                array->push_back(int_value);
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"UByteArray")==0)
    {
        UByteArray* array = new UByteArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            unsigned int uint_value;
            if (fr[0].getUInt(uint_value))
            {
                ++fr;
                array->push_back(uint_value);
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"UShortArray")==0)
    {
        UShortArray* array = new UShortArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            unsigned int uint_value;
            if (fr[0].getUInt(uint_value))
            {
                ++fr;
                array->push_back(uint_value);
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"UIntArray")==0)
    {
        UIntArray* array = new UIntArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            unsigned int uint_value;
            if (fr[0].getUInt(uint_value))
            {
                ++fr;
                array->push_back(uint_value);
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"UVec4bArray")==0 || strcmp(arrayName,"Vec4ubArray")==0)
    {
        Vec4ubArray* array = new Vec4ubArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            unsigned int r,g,b,a;
            if (fr[0].getUInt(r) &&
                fr[1].getUInt(g) &&
                fr[2].getUInt(b) &&
                fr[3].getUInt(a))
            {
                fr+=4;
                array->push_back(osg::Vec4ub(r,g,b,a));
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"FloatArray")==0)
    {
        FloatArray* array = new FloatArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            float float_value;
            if (fr[0].getFloat(float_value))
            {
                ++fr;
                array->push_back(float_value);
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"DoubleArray")==0)
    {
        DoubleArray* array = new DoubleArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            double double_value;
            if (fr[0].getFloat(double_value))
            {
                ++fr;
                array->push_back(double_value);
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"Vec2Array")==0)
    {
        Vec2Array* array = new Vec2Array;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            Vec2 v;
            if (fr[0].getFloat(v.x()) && fr[1].getFloat(v.y()))
            {
                fr += 2;
                array->push_back(v);
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"Vec2dArray")==0)
    {
        Vec2dArray* array = new Vec2dArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            Vec2d v;
            if (fr[0].getFloat(v.x()) && fr[1].getFloat(v.y()))
            {
                fr += 2;
                array->push_back(v);
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"Vec3Array")==0)
    {
        Vec3Array* array = new Vec3Array;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            Vec3 v;
            if (fr[0].getFloat(v.x()) && fr[1].getFloat(v.y()) && fr[2].getFloat(v.z()))
            {
                fr += 3;
                array->push_back(v);
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"Vec3dArray")==0)
    {
        Vec3dArray* array = new Vec3dArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            Vec3d v;
            if (fr[0].getFloat(v.x()) && fr[1].getFloat(v.y()) && fr[2].getFloat(v.z()))
            {
                fr += 3;
                array->push_back(v);
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"Vec4Array")==0)
    {
        Vec4Array* array = new Vec4Array;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            Vec4 v;
            if (fr[0].getFloat(v.x()) && fr[1].getFloat(v.y()) && fr[2].getFloat(v.z()) && fr[3].getFloat(v.w()))
            {
                fr += 4;
                array->push_back(v);
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"Vec4dArray")==0)
    {
        Vec4dArray* array = new Vec4dArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            Vec4d v;
            if (fr[0].getFloat(v.x()) && fr[1].getFloat(v.y()) && fr[2].getFloat(v.z()) && fr[3].getFloat(v.w()))
            {
                fr += 4;
                array->push_back(v);
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"Vec2bArray")==0)
    {
        Vec2bArray* array = new Vec2bArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            unsigned int r,g;
            if (fr[0].getUInt(r) &&
                fr[1].getUInt(g))
            {
                fr+=2;
                array->push_back(osg::Vec2b(r,g));
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"Vec3bArray")==0)
    {
        Vec3bArray* array = new Vec3bArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            unsigned int r,g,b;
            if (fr[0].getUInt(r) &&
                fr[1].getUInt(g) &&
                fr[2].getUInt(b))
            {
                fr+=3;
                array->push_back(osg::Vec3b(r,g,b));
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"Vec4bArray")==0)
    {
        Vec4bArray* array = new Vec4bArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            unsigned int r,g,b,a;
            if (fr[0].getUInt(r) &&
                fr[1].getUInt(g) &&
                fr[2].getUInt(b) &&
                fr[3].getUInt(a))
            {
                fr+=4;
                array->push_back(osg::Vec4b(r,g,b,a));
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"Vec2sArray")==0)
    {
        Vec2sArray* array = new Vec2sArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            unsigned int r,g;
            if (fr[0].getUInt(r) &&
                fr[1].getUInt(g))
            {
                fr+=2;
                array->push_back(osg::Vec2s(r,g));
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"Vec3sArray")==0)
    {
        Vec3sArray* array = new Vec3sArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            unsigned int r,g,b;
            if (fr[0].getUInt(r) &&
                fr[1].getUInt(g) &&
                fr[2].getUInt(b))
            {
                fr+=3;
                array->push_back(osg::Vec3s(r,g,b));
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }
    else if (strcmp(arrayName,"Vec4sArray")==0)
    {
        Vec4sArray* array = new Vec4sArray;
        array->reserve(capacity);
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            unsigned int r,g,b,a;
            if (fr[0].getUInt(r) &&
                fr[1].getUInt(g) &&
                fr[2].getUInt(b) &&
                fr[3].getUInt(a))
            {
                fr+=4;
                array->push_back(osg::Vec4s(r,g,b,a));
            }
            else ++fr;
        }
        ++fr;
        return_array = array;
    }

    if (return_array)
    {
        if (!uniqueID.empty()) fr.registerUniqueIDForObject(uniqueID.c_str(),return_array);
    }

    return return_array;
}
Ejemplo n.º 26
0
void Grid::Update()
{
	if(GameOver())
	{
		return;
	}

	if(current)
	{
		current->Update();
		//check for boundaries
		Vec4<Vec2i> blocks = current->getBricks();
		int minX = blocks.X().X();
		int maxX = blocks.X().X();
		if (blocks.Y().X() < minX)
		{
			minX = blocks.Y().X();
		}
		if (blocks.Y().X() > maxX)
		{
			maxX = blocks.Y().X();
		}
		if (blocks.Z().X() < minX)
		{
			minX = blocks.Z().X();
		}
		if (blocks.Z().X() > maxX)
		{
			maxX = blocks.Z().X();
		}
		if (blocks.W().X() < minX)
		{
			minX = blocks.W().X();
		}
		if (blocks.W().X() > maxX)
		{
			maxX = blocks.W().X();
		}
		if (minX < 0)
		{
			current->nudge(-minX,0);
		}
		if (maxX >= W)
		{
			current->nudge((W-maxX)-1,0);
		}

		if(collision())
		{
			
			Brick* b = new Brick(Vec3f(blocks.X().X()*2,blocks.X().Y()*2,0));
			Game::instance()->addObject(b);
			int a = blocks.X().Y()*W+blocks.X().X();
			if(a < GD.size())
			{
				GD[a] = b;
			}
			b = new Brick(Vec3f(blocks.Y().X()*2,blocks.Y().Y()*2,0));
			Game::instance()->addObject(b);
			a = blocks.Y().Y()*W+blocks.Y().X();
			if(a < GD.size())
			{
				GD[a] = b;
			}
			b =  new Brick(Vec3f(blocks.Z().X()*2,blocks.Z().Y()*2,0));
			Game::instance()->addObject(b);
			a = blocks.Z().Y()*W+blocks.Z().X();
			if(a < GD.size())
			{
				GD[a] = b;
			}
			b =  new Brick(Vec3f(blocks.W().X()*2,blocks.W().Y()*2,0));
			Game::instance()->addObject(b);
			a = blocks.W().Y()*W+blocks.W().X();
			if(a < GD.size())
			{
				GD[a] = b;
			}
			delete current;
			current = 0;
			lines();
			if(GameOver())
			{

				SoundManager::instance()->playSound(failfx);
			}
			else
			{
				SoundManager::instance()->playSound(dropfx);
			}
		}

	}
	else
	{
		current = new Tetrad();
		current->setPivot(Vec2i(5,17));
		int lf =  -linecount/7;
		current->setVel(Vec3f(0,-1+lf,0));
		current->setPos(Vec3f(2*5,2*17,0));
	}





}
Ejemplo n.º 27
0
Cube Cube::setCube(Vec4 min, Vec4 max)
{
    Cube cube = Cube();
    cube.transform.setIdentity();
    Matrix4x4 t;
    t.setIdentity();
    Vec4 center = (max+min)/2.0;

    //float s = (min-max).module()*sqrt(3.0)/3.0; //escala
    //this->transform.setIdentity();
    float diag = (max - center).module();
    float h    = (max - Vec4(max.x(),center.y(),max.z())).module(); //eixo y
    float c    = (Vec4(max.x(),center.y(),center.z())-Vec4(max.x(),center.y(),max.z())).module(); //eixo z
    float l    = (center - Vec4(max.x(),center.y(),center.z())).module();

    t.scale(2*l,2*h,2*c);
    t.translate(center);
    cube.setTransform(t);
    return cube;

}
void WeightedClusterFit::Compress4( void* block )
{
    int const count = m_colours->GetCount();
    Vec4 const one = VEC4_CONST(1.0f);
    Vec4 const zero = VEC4_CONST(0.0f);
    Vec4 const half = VEC4_CONST(0.5f);
    Vec4 const two = VEC4_CONST(2.0);
    Vec4 const onethird( 1.0f/3.0f, 1.0f/3.0f, 1.0f/3.0f, 1.0f/9.0f );
    Vec4 const twothirds( 2.0f/3.0f, 2.0f/3.0f, 2.0f/3.0f, 4.0f/9.0f );
    Vec4 const twonineths = VEC4_CONST( 2.0f/9.0f );
    Vec4 const grid( 31.0f, 63.0f, 31.0f, 0.0f );
    Vec4 const gridrcp( 1.0f/31.0f, 1.0f/63.0f, 1.0f/31.0f, 0.0f );

    // declare variables
    Vec4 beststart = VEC4_CONST( 0.0f );
    Vec4 bestend = VEC4_CONST( 0.0f );
    Vec4 besterror = VEC4_CONST( FLT_MAX );

    Vec4 x0 = zero;
    int b0 = 0, b1 = 0, b2 = 0;

    // check all possible clusters for this total order
    for( int c0 = 0; c0 < count; c0++)
    {
        Vec4 x1 = zero;

        for( int c1 = 0; c1 < count-c0; c1++)
        {
            Vec4 x2 = zero;

            for( int c2 = 0; c2 < count-c0-c1; c2++)
            {
                Vec4 const x3 = m_xsum - x2 - x1 - x0;

                //Vec3 const alphax_sum = x0 + x1 * (2.0f / 3.0f) + x2 * (1.0f / 3.0f);
                //float const alpha2_sum = w0 + w1 * (4.0f/9.0f) + w2 * (1.0f/9.0f);
                Vec4 const alphax_sum = MultiplyAdd(x2, onethird, MultiplyAdd(x1, twothirds, x0)); // alphax_sum, alpha2_sum
                Vec4 const alpha2_sum = alphax_sum.SplatW();

                //Vec3 const betax_sum = x3 + x2 * (2.0f / 3.0f) + x1 * (1.0f / 3.0f);
                //float const beta2_sum = w3 + w2 * (4.0f/9.0f) + w1 * (1.0f/9.0f);
                Vec4 const betax_sum = MultiplyAdd(x2, twothirds, MultiplyAdd(x1, onethird, x3)); // betax_sum, beta2_sum
                Vec4 const beta2_sum = betax_sum.SplatW();

                //float const alphabeta_sum = (w1 + w2) * (2.0f/9.0f);
                Vec4 const alphabeta_sum = twonineths*( x1 + x2 ).SplatW(); // alphabeta_sum

                // float const factor = 1.0f / (alpha2_sum * beta2_sum - alphabeta_sum * alphabeta_sum);
                Vec4 const factor = Reciprocal( NegativeMultiplySubtract(alphabeta_sum, alphabeta_sum, alpha2_sum*beta2_sum) );

                Vec4 a = NegativeMultiplySubtract(betax_sum, alphabeta_sum, alphax_sum*beta2_sum) * factor;
                Vec4 b = NegativeMultiplySubtract(alphax_sum, alphabeta_sum, betax_sum*alpha2_sum) * factor;

                // clamp to the grid
                a = Min( one, Max( zero, a ) );
                b = Min( one, Max( zero, b ) );
                a = Truncate( MultiplyAdd( grid, a, half ) ) * gridrcp;
                b = Truncate( MultiplyAdd( grid, b, half ) ) * gridrcp;

                // compute the error (we skip the constant xxsum)
                Vec4 e1 = MultiplyAdd( a*a, alpha2_sum, b*b*beta2_sum );
                Vec4 e2 = NegativeMultiplySubtract( a, alphax_sum, a*b*alphabeta_sum );
                Vec4 e3 = NegativeMultiplySubtract( b, betax_sum, e2 );
                Vec4 e4 = MultiplyAdd( two, e3, e1 );

                // apply the metric to the error term
                Vec4 e5 = e4 * m_metricSqr;
                Vec4 error = e5.SplatX() + e5.SplatY() + e5.SplatZ();

                // keep the solution if it wins
                if( CompareAnyLessThan( error, besterror ) )
                {
                    besterror = error;
                    beststart = a;
                    bestend = b;
                    b0 = c0;
                    b1 = c1;
                    b2 = c2;
                }

                x2 += m_weighted[c0+c1+c2];
            }

            x1 += m_weighted[c0+c1];
        }

        x0 += m_weighted[c0];
    }

    // save the block if necessary
    if( CompareAnyLessThan( besterror, m_besterror ) )
    {
        // compute indices from cluster sizes.
        u8 bestindices[16];
        {
            int i = 0;
            for(; i < b0; i++) {
                bestindices[i] = 0;
            }
            for(; i < b0+b1; i++) {
                bestindices[i] = 2;
            }
            for(; i < b0+b1+b2; i++) {
                bestindices[i] = 3;
            }
            for(; i < count; i++) {
                bestindices[i] = 1;
            }
        }

        // remap the indices
        u8 ordered[16];
        for( int i = 0; i < count; ++i )
            ordered[m_order[i]] = bestindices[i];

        m_colours->RemapIndices( ordered, bestindices );

        // save the block
        WriteColourBlock4( beststart.GetVec3(), bestend.GetVec3(), bestindices, block );

        // save the error
        m_besterror = besterror;
    }
}
Ejemplo n.º 29
0
Cube::Cube(Vec4 min, Vec4 max,Vec4 center)
{
    motion = Vec4();
    //Cube c = Cube();
    double side = 1.0;
    //lista das normais da face
    vertexs[0].setVec4((-0.5)*side  ,(-0.5)*side  ,(-0.5)*side );
    vertexs[1].setVec4((-0.5)*side  ,(-0.5)*side  ,(0.5)*side);
    vertexs[2].setVec4((0.5)*side ,(-0.5)*side  ,(0.5)*side);
    vertexs[3].setVec4((0.5)*side ,(-0.5)*side  ,(-0.5)*side );
    vertexs[4].setVec4((-0.5)*side  ,(0.5)*side  ,(-0.5)*side );
    vertexs[5].setVec4((-0.5)*side  ,(0.5)*side ,(0.5)*side);
    vertexs[6].setVec4((0.5)*side ,(0.5)*side ,(0.5)*side);
    vertexs[7].setVec4((0.5)*side ,(0.5)*side ,(-0.5)*side );
    initvertexs[0].setVec4((-0.5)*side  ,(-0.5)*side  ,(-0.5)*side );
    initvertexs[1].setVec4((-0.5)*side  ,(-0.5)*side  ,(0.5)*side);
    initvertexs[2].setVec4((0.5)*side ,(-0.5)*side  ,(0.5)*side);
    initvertexs[3].setVec4((0.5)*side ,(-0.5)*side  ,(-0.5)*side );
    initvertexs[4].setVec4((-0.5)*side  ,(0.5)*side  ,(-0.5)*side );
    initvertexs[5].setVec4((-0.5)*side  ,(0.5)*side ,(0.5)*side);
    initvertexs[6].setVec4((0.5)*side ,(0.5)*side ,(0.5)*side);
    initvertexs[7].setVec4((0.5)*side ,(0.5)*side ,(-0.5)*side );
    transform.setIdentity();
    refreshNormals();
    mesh = new Mesh();

    Face face[6];
    face[0].vertexs.push_back(&vertexs[0]);
    face[0].vertexs.push_back(&vertexs[3]);
    face[0].vertexs.push_back(&vertexs[2]);
    face[0].vertexs.push_back(&vertexs[1]);
    face[0].normals.push_back(&normals[0]);
//    face[0].normals.push_back(&normals[0]);
//    face[0].normals.push_back(&normals[0]);
//    face[0].normals.push_back(&normals[0]);
    mesh->faces.push_back(face[0]);
    face[1].vertexs.push_back(&vertexs[4]);
    face[1].vertexs.push_back(&vertexs[5]);
    face[1].vertexs.push_back(&vertexs[6]);
    face[1].vertexs.push_back(&vertexs[7]);
    face[1].normals.push_back(&normals[1]);
//    face[1].normals.push_back(&normals[1]);
//    face[1].normals.push_back(&normals[1]);
//    face[1].normals.push_back(&normals[1]);
    mesh->faces.push_back(face[1]);
    face[2].vertexs.push_back(&vertexs[2]);
    face[2].vertexs.push_back(&vertexs[6]);
    face[2].vertexs.push_back(&vertexs[5]);
    face[2].vertexs.push_back(&vertexs[1]);
    face[2].normals.push_back(&normals[2]);
//    face[2].normals.push_back(&normals[2]);
//    face[2].normals.push_back(&normals[2]);
//    face[2].normals.push_back(&normals[2]);
    mesh->faces.push_back(face[2]);
    face[3].vertexs.push_back(&vertexs[3]);
    face[3].vertexs.push_back(&vertexs[7]);
    face[3].vertexs.push_back(&vertexs[6]);
    face[3].vertexs.push_back(&vertexs[2]);
    face[3].normals.push_back(&normals[3]);
//    face[3].normals.push_back(&normals[3]);
//    face[3].normals.push_back(&normals[3]);
//    face[3].normals.push_back(&normals[3]);
    mesh->faces.push_back(face[3]);
    face[4].vertexs.push_back(&vertexs[0]);
    face[4].vertexs.push_back(&vertexs[4]);
    face[4].vertexs.push_back(&vertexs[7]);
    face[4].vertexs.push_back(&vertexs[3]);
    face[4].normals.push_back(&normals[5]);
//    face[4].normals.push_back(&normals[5]);
//    face[4].normals.push_back(&normals[5]);
//    face[4].normals.push_back(&normals[5]);
    mesh->faces.push_back(face[4]);
    face[5].vertexs.push_back(&vertexs[4]);
    face[5].vertexs.push_back(&vertexs[0]);
    face[5].vertexs.push_back(&vertexs[1]);
    face[5].vertexs.push_back(&vertexs[5]);
    face[5].normals.push_back(&normals[4]);
//    face[5].normals.push_back(&normals[4]);
//    face[5].normals.push_back(&normals[4]);
//    face[5].normals.push_back(&normals[4]);
    mesh->faces.push_back(face[5]);
    Matrix4x4 t;
    t.setIdentity();
    //Vec4 med = (max-min)/2.0;
    //float s = (min-max).module()*sqrt(3.0)/3.0; //escala

    //center = center/2.0;
    //min = min - center;
    //max = max - center;
    //t.set
    transform.setIdentity();
    center = (max+min)/2.0;
    //float diag = (max - center).module();
    float h    = (max - Vec4(max.x(),center.y(),max.z())).module(); //eixo y
    float c    = (Vec4(max.x(),center.y(),center.z())-Vec4(max.x(),center.y(),max.z())).module(); //eixo z
    float l    = (center - Vec4(max.x(),center.y(),center.z())).module();

    t.scale(2*l,2*h,2*c);
    t.translate(center);
    transform = t;
    //this->refreshVertexs();
    //this->draw();
}
Ejemplo n.º 30
0
 void print(){
   position.print();
   color.print();
 }