Example #1
0
UNNAMESPACE_BEGIN


UNNAMESPACE_END

NAMESPACE_BEGIN

/*==============================================================================
   CLASS ParametricPatch
==============================================================================*/

#define APPROX4

//------------------------------------------------------------------------------
//! 
void 
ParametricPatch::init( MetaSurface::Patch& p )
{
   const uint MAX_VALENCE = 64;
   Vec3f f[4][MAX_VALENCE];
   Vec3f vring[MAX_VALENCE];
   Vec3f vdiag[MAX_VALENCE];
   float creases[MAX_VALENCE];
   int creasesID[MAX_VALENCE];
   Vec3f vlim[4];
   Vec3f t0[4];
   Vec3f t1[4];
   float cn[4];
   float sn[4];
   int val[4];

   // Compute per vertex parameters.
   for( uint c = 0; c < 4; ++c )
   {
      // Retrieve ring vertices and compute valence.
      int n                  = 0;
      int cc                 = c;
      int crnum              = 0;
      MetaSurface::Patch* cp = &p;
      do {
         //creases[n] = MetaSurface::crease( *cp, cc ) == 0 ? 2.0f/3.0f : 0.0f;
         if( MetaSurface::crease( *cp, cc ) == 0 )
         {
            creases[n] = 2.0f/3.0f;
         }
         else
         {
            creasesID[crnum++] = n;
            creases[n] = 0.0f;
         }
         vring[n]   = *cp->_controlPts[(cc+1)%4];
         vdiag[n++] = *cp->_controlPts[(cc+2)%4];
         int ne     = (cc+3)%4;
         cc         = MetaSurface::neighborEdge( *cp, ne );
         cp         = MetaSurface::neighborPatch( *cp, ne );
      } while( cp != &p );

      val[c]   = n;
      Vec3f& v = *p._controlPts[c];

#ifdef APPROX4
      if( crnum == 0 )
      {
         // Compute limite vertex and face vertex.
         vlim[c] = Vec3f(0.0f);
         for( int i = 0; i < n; ++i )
         {
            // Face vertex.
            f[c][i] = v*(4.0f/9.0f) + (vring[i]+vring[(i+1)%n])*(2.0f/9.0f) + vdiag[i]*(1.0f/9.0f);

            // Corner vertex.
            vlim[c] += f[c][i];
         }
         vlim[c] = ( vlim[c]*9.0f/(float)n + v*(float(n)-4.0f) )*(1.0f/(float(n)+5.0f));
            
         // Compute t0 and t1.
         Vec3f e0(0.0f);
         Vec3f e1(0.0f);
         for( int i = 0; i < n; ++i )
         {
            float angle = CGConstf::pi2()*(float)i/float(n); 
            Vec3f e     = (f[c][i]+f[c][(i-1+n)%n])*0.5f;
            e0         += e * CGM::cos(angle);
            e1         += e * CGM::sin(angle);
         }
         cn[c]        = CGM::cos( CGConstf::pi2()/float(n) );
         sn[c]        = CGM::sin( CGConstf::pi2()/float(n) );
         float lambda = n == 4 ? 0.5f : ( cn[c] + 5.0f + CGM::sqrt((cn[c]+9.0f)*(cn[c]+1.0f)) ) / 16.0f;
         float k      = 1.0f/(lambda*float(n));
         e0          *= k;
         e1          *= k;
         t0[c]        = vlim[c] + e0;
         t1[c]        = vlim[c] + e0*cn[c] + e1*sn[c];
      }
      else
      {
         // Face and corner vertices.
         vlim[c] = Vec3f(0.0f);
         for( int i = 0; i < n; ++i )
         {
            // Face vertex.
            f[c][i] = v*(4.0f/9.0f) + (vring[i]+vring[(i+1)%n])*(2.0f/9.0f) + vdiag[i]*(1.0f/9.0f);
            
            // Corner vertex.
            vlim[c] += v*float(n) + vring[i]*4.0f + vdiag[i];
         }
         if( crnum < 2 )
         {
            vlim[c] = vlim[c] / float(n*n + 5*n);
         }
         else if( crnum == 2 )
         {
            vlim[c] = (v*4.0f + vring[creasesID[0]] + vring[creasesID[1]])/6.0f;
         }
         else
         {
            vlim[c] = v;
         }

         // Edge vertices.
         if( creases[0] == 0.0f )
         {
            t0[c] = (v*2.0f + vring[0])/3.0f;
         }
         else
         {
            t0[c] = (f[c][0] + f[c][n-1])*0.5f;
         }
         if( creases[1] == 0.0f )
         {
            t1[c] = (v*2.0f + vring[1])/3.0f;
         }
         else
         {
            t1[c] = (f[c][0] + f[c][1])*0.5f;
         }

         cn[c] = CGM::cos( CGConstf::pi2()/float(n) );
         sn[c] = CGM::sin( CGConstf::pi2()/float(n) );
      }
#endif

#ifdef APPROX3
      // Face and corner vertices.
      vlim[c] = Vec3f(0.0f);
      for( int i = 0; i < n; ++i )
      {
         // Face vertex.
         f[c][i] = v*(4.0f/9.0f) + (vring[i]+vring[(i+1)%n])*(2.0f/9.0f) + vdiag[i]*(1.0f/9.0f);
            
         // Corner vertex.
         vlim[c] += v*n + vring[i]*4.0f + vdiag[i];
      }
      if( crnum < 2 )
      {
         vlim[c] = vlim[c] / float(n*n + 5*n);
      }
      else if( crnum == 2 )
      {
         vlim[c] = (v*4.0f + vring[creasesID[0]] + vring[creasesID[1]])/6.0f;
      }
      else
      {
         vlim[c] = v;
      }

      // Edge vertices.
      if( creases[0] == 0.0f )
      {
         t0[c] = (v*2.0f + vring[0])/3.0f;
      }
      else
      {
         t0[c] = (v*(2*n) + vring[0]*4.0f + (vring[1] + vring[n-1])*2.0f + vdiag[0] + vdiag[n-1])/float(2*n+10);
      }
      if( creases[1] == 0.0f )
      {
         t1[c] = (v*2.0f + vring[1])/3.0f;
      }
      else
      {
         t1[c] = (v*(2*n) + vring[1]*4.0f + (vring[2] + vring[0])*2.0f + vdiag[0] + vdiag[1])/float(2*n+10);
      }

      cn[c] = CGM::cos( CGConstf::pi2()/float(n) );
      sn[c] = CGM::sin( CGConstf::pi2()/float(n) );
#endif

#ifdef APPROX2
      // Face and corner vertices.
      vlim[c] = Vec3f(0.0f);
      for( int i = 0; i < n; ++i )
      {
         // Face vertex.
         // FIXME: when creases, should be computed differently.
         f[c][i] = (v*n + (vring[i]+vring[(i+1)%n])*2.0f + vdiag[i])/float(n+5);

         // Corner vertex.
         vlim[c] += f[c][i];
      }
      if( crnum < 2 )
      {
         vlim[c] = vlim[c] / float(n);
      }
      else if( crnum == 2 )
      {
         vlim[c] = (v*4.0f + vring[creasesID[0]] + vring[creasesID[1]])/6.0f;
      }
      else
      {
         vlim[c] = v;
      }

      // Edge vertices.
      if( creases[0] == 0.0f )
      {
         t0[c] = (v*2.0f + vring[0])/3.0f;
      }
      else
      {
         t0[c] = (f[c][0] + f[c][n-1])*0.5f;
      }
      if( creases[1] == 0.0f )
      {
         t1[c] = (v*2.0f + vring[1])/3.0f;
      }
      else
      {
         t1[c] = (f[c][0] + f[c][1])*0.5f; 
      }

      cn[c] = CGM::cos( CGConstf::pi2()/float(n) );
      sn[c] = CGM::sin( CGConstf::pi2()/float(n) );
#endif

#ifdef APPROX1
      // Compute limite vertex and face vertex.
      vlim[c] = Vec3f(0.0f);
      for( int i = 0; i < n; ++i )
      {
         // Face vertex.
         // Change equation when adding crease.
         //f[c][i] = v*(4.0f/9.0f) + (vring[i]+vring[(i+1)%n])*(2.0f/9.0f) + vdiag[i]*(1.0f/9.0f);

         float cr0 = creases[i];
         float cr1 = creases[(i+1)%n];
         f[c][i] = v*((1.0f-cr0)*(1.0f-cr1)) +
                      (v+vring[i])*((1.0f-cr0)*cr1*0.5f) +
                      (v+vring[(i+1)%n])*(cr0*(1.0f-cr1)*0.5f) +
                      (v+vring[i]+vring[(i+1)%n]+vdiag[i])*(cr0*cr1*0.25f);

         // Corner vertex.
         vlim[c] += f[c][i];
      }
      vlim[c] = ( vlim[c]*9.0f/(float)n + v*(float(n)-4.0f) )*(1.0f/(float(n)+5.0f));

      // Compute t0 and t1.
      Vec3f e0(0.0f);
      Vec3f e1(0.0f);
      for( int i = 0; i < n; ++i )
      {
         float angle = CGConstf::pi2()*(float)i/float(n); 
         Vec3f e     = (f[c][i]+f[c][(i-1+n)%n])*0.5f;
         e0         += e * CGM::cos(angle);
         e1         += e * CGM::sin(angle);
      }
      cn[c]        = CGM::cos( CGConstf::pi2()/float(n) );
      sn[c]        = CGM::sin( CGConstf::pi2()/float(n) );
      float lambda = n == 4 ? 0.5f : ( cn[c] + 5.0f + CGM::sqrt((cn[c]+9.0f)*(cn[c]+1.0f)) ) / 16.0f;
      float k      = 1.0f/(lambda*float(n));
      e0          *= k;
      e1          *= k;
      t0[c]        = vlim[c] + e0;
      t1[c]        = vlim[c] + e0*cn[c] + e1*sn[c];
#endif
   }

   // Compute per patch parameters.

   // Do we have a regular patch?
   //if( (val[0] == 4) && (val[1] == 4) && (val[2] == 4) && (val[3] == 4) )
   if( true )
   {
      _regular = true;
      // Cubic patch.
      _b[0]  = vlim[0]; _b[1]  = t0[0];   _b[2]  = t1[1];   _b[3]  = vlim[1];
      _b[4]  = t1[0];   _b[5]  = f[0][0]; _b[6]  = f[1][0]; _b[7]  = t0[1];
      _b[8]  = t0[3];   _b[9]  = f[3][0]; _b[10] = f[2][0]; _b[11] = t1[2];
      _b[12] = vlim[3]; _b[13] = t1[3];   _b[14] = t0[2];   _b[15] = vlim[2];
   }
   else
   {
      _regular = false;
      // P4-Patch.
      // 300, 210 and 120.
      for( uint c = 0; c < 4; ++c )
      {
         _b[c*6+0] = vlim[c];      // 300
         _b[c*6+1] = t0[c];        // 210
         _b[c*6+2] = t1[(c+1)%4];  // 120
      }

      // 211, 121 and 004.
      _b[24] = Vec3f(0.0f);
      for( uint c = 0; c < 4; ++c )
      {
         uint c1    = (c+1)%4;
         float sinv = 1.0f/(sn[c]+sn[c1]);

         Vec3f b310 = _b[c*6+1]*0.75f + _b[c*6]*0.25f;
         Vec3f b130 = _b[c*6+2]*0.75f + _b[c1*6]*0.25f;
         // 211
         _b[c*6+3] = b310 + (_b[c*6+2]-_b[c*6+1])*((1.0f+cn[c])*0.25f)   +
                            (_b[c*6+1]-_b[c*6+0])*((1.0f-cn[c1])*0.125f) +
                            (f[c][0]-f[c][val[c]-1])*(sinv*0.375f);
         // 121
         _b[c*6+4] = b130 + (_b[c*6+1]-_b[c*6+2])*((1.0f+cn[c1])*0.25f) +
                            (_b[c*6+2]-_b[c1*6])*((1.0f-cn[c])*0.125f)  +
                            (f[c1][0]-f[c1][1])*(sinv*0.375f);
         // 004
         _b[24] += _b[c*6] + (t0[c]+t1[c])*3.0f + f[c][0]*9.0f;
      }
      _b[24] /= 64.0f;

      // b112.
      for( uint c = 0; c < 4; ++c )
      {
         uint c1 = (c+1)%4;
         uint c2 = (c+2)%4;
         uint c3 = (c+3)%4;
         _b[c*6+5] = _b[24] + (_b[c*6+3]+_b[c*6+4]-_b[c1*6+4]-_b[c3*6+3])*0.1875f +
                              (_b[c1*6+3]+_b[c3*6+4]-_b[c2*6+3]-_b[c2*6+4])*0.0625f;
      }
   }
}
Example #2
0
#include <QFile>
#include <QString>

#include <QDebug>
#include <QBuffer>

StelTextureSP Nebula::texCircle;
StelTextureSP Nebula::texGalaxy;
StelTextureSP Nebula::texOpenCluster;
StelTextureSP Nebula::texGlobularCluster;
StelTextureSP Nebula::texPlanetaryNebula;
StelTextureSP Nebula::texDiffuseNebula;
StelTextureSP Nebula::texOpenClusterWithNebulosity;
float Nebula::circleScale = 1.f;
float Nebula::hintsBrightness = 0;
Vec3f Nebula::labelColor = Vec3f(0.4,0.3,0.5);
Vec3f Nebula::circleColor = Vec3f(0.8,0.8,0.1);

Nebula::Nebula() :
		M_nb(0),
		NGC_nb(0),
		IC_nb(0),
		C_nb(0)
{
	nameI18 = "";
	angularSize = -1;
}

Nebula::~Nebula()
{
}
Example #3
0
	CubeExample(void)
	 : cube_instr(make_cube.Instructions())
	 , cube_indices(make_cube.Indices())
	 , projection_matrix(prog, "ProjectionMatrix")
	 , camera_matrix(prog, "CameraMatrix")
	 , model_matrix(prog, "ModelMatrix")
	{
		namespace se = oglplus::smart_enums;
		// Set the vertex shader source
		vs.Source(
			"#version 330\n"
			"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
			"in vec4 Position;"
			"in vec3 Normal;"
			"in vec2 TexCoord;"
			"out vec3 vertNormal;"
			"out vec3 vertLight;"
			"out vec2 vertTexCoord;"
			"uniform vec3 LightPos;"
			"void main(void)"
			"{"
			"	vertNormal = mat3(ModelMatrix)*Normal;"
			"	gl_Position = ModelMatrix * Position;"
			"	vertLight = LightPos - gl_Position.xyz;"
			"	vertTexCoord = TexCoord;"
			"	gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
			"}"
		);
		// compile it
		vs.Compile();

		// set the fragment shader source
		fs.Source(
			"#version 330\n"
			"uniform sampler2D TexUnit;"
			"in vec3 vertNormal;"
			"in vec3 vertLight;"
			"in vec2 vertTexCoord;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	float l = length(vertLight);"
			"	float d = l > 0 ? dot(vertNormal, normalize(vertLight)) / l : 0.0;"
			"	float i = 0.3 + 2.0*max(d, 0.0);"
			"	vec4 t  = texture(TexUnit, vertTexCoord);"
			"	fragColor = vec4(t.rgb*i, 1.0);"
			"}"
		);
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		// bind the VAO for the cube
		cube.Bind();

		verts.Bind(se::Array());
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_cube.Positions(data);
			Buffer::Data(se::Array(), data);
			(prog|"Position").Setup(n_per_vertex, se::Float()).Enable();
		}

		normals.Bind(se::Array());
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_cube.Normals(data);
			Buffer::Data(se::Array(), data);
			(prog|"Normal").Setup(n_per_vertex, se::Float()).Enable();
		}

		texcoords.Bind(se::Array());
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_cube.TexCoordinates(data);
			Buffer::Data(se::Array(), data);
			(prog|"TexCoord").Setup(n_per_vertex, se::Float()).Enable();
		}

		// setup the texture
		{
			auto bound_tex = Bind(tex, se::_2D());
			bound_tex.Image2D(images::LoadTexture("concrete_block"));
			bound_tex.MinFilter(se::Linear());
			bound_tex.MagFilter(se::Linear());
			bound_tex.WrapS(se::Repeat());
			bound_tex.WrapT(se::Repeat());
		}
		// set the uniform values
		(prog/"TexUnit") = 0;
		(prog/"LightPos") = Vec3f(1.0f, 2.0f, 3.0f);
		//
		gl.ClearColor(0.1f, 0.1f, 0.1f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(se::DepthTest());

		gl.Enable(se::CullFace());
		gl.FrontFace(make_cube.FaceWinding());
	}
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindow = createNativeWindow();
    TutorialWindow->initWindow();

    TutorialWindow->setDisplayCallback(display);
    TutorialWindow->setReshapeCallback(reshape);

    TutorialKeyListener TheKeyListener;
    TutorialWindow->addKeyListener(&TheKeyListener);
    TutorialMouseListener TheTutorialMouseListener;
    TutorialMouseMotionListener TheTutorialMouseMotionListener;
    TutorialWindow->addMouseListener(&TheTutorialMouseListener);
    TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // Tell the Manager what to manage
    mgr->setWindow(TutorialWindow);
	
	//Particle System Material
	LineChunkRefPtr PSLineChunk = LineChunk::create();
		PSLineChunk->setWidth(1.0f);

	BlendChunkRefPtr PSBlendChunk = BlendChunk::create();
		PSBlendChunk->setSrcFactor(GL_SRC_ALPHA);
		PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);

	MaterialChunkRefPtr PSMaterialChunk = MaterialChunk::create();
		PSMaterialChunk->setAmbient(Color4f(0.3f,0.3f,0.3f,1.0f));
		PSMaterialChunk->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f));
		PSMaterialChunk->setSpecular(Color4f(0.9f,0.9f,0.9f,1.0f));
		PSMaterialChunk->setColorMaterial(GL_AMBIENT_AND_DIFFUSE);
		PSMaterialChunk->setLit(false);

	ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create();
		PSMaterial->addChunk(PSLineChunk);
		PSMaterial->addChunk(PSMaterialChunk);
		PSMaterial->addChunk(PSBlendChunk);

	//Particle System
    ParticleSystemRefPtr ExampleParticleSystem = ParticleSystem::create();
    ExampleParticleSystem->attachUpdateListener(TutorialWindow);


	//Create the particles
    UInt32 NumParticlesToGenerate(2500);

	Distribution3DRefPtr PositionDistribution = createPositionDistribution();
	Distribution3DRefPtr NormalDistribution = createNormalDistribution();
	Distribution3DRefPtr ColorDistribution = createColorDistribution();
	Distribution3DRefPtr SizeDistribution = createSizeDistribution();
	Distribution1DRefPtr LifespanDistribution = createLifespanDistribution();
	Distribution3DRefPtr VelocityDistribution = createVelocityDistribution();
	Distribution3DRefPtr AccelerationDistribution = createAccelerationDistribution();

	Pnt3f PositionReturnValue;
	Vec3f NormalReturnValue = Vec3f(0.0,0.0f,1.0f);
	Color4f ColorReturnValue = Color4f(1.0,1.0f,1.0f, 1.0f);
	Vec3f SizeReturnValue;
	Time LifespanReturnValue = -1;
	Vec3f VelocityReturnValue;
	Vec3f AccelerationReturnValue;


    for(UInt32 i(0) ; i< NumParticlesToGenerate ; ++i)
    {
		if(PositionDistribution != NULL)
		{
			PositionReturnValue.setValue(PositionDistribution->generate().getValues());
		}

		
		if(ColorDistribution != NULL)
		{
            Vec3f ColorRGB = ColorDistribution->generate();
			ColorReturnValue.setValuesRGBA(ColorRGB[0],ColorRGB[1],ColorRGB[2],1.0f);
		}

		
		if(SizeDistribution != NULL)
		{
			SizeReturnValue = SizeDistribution->generate();
		}

		if(LifespanDistribution != NULL)
		{
			LifespanReturnValue = LifespanDistribution->generate();
		}
		if(VelocityDistribution != NULL)
		{
			VelocityReturnValue = VelocityDistribution->generate();
		}

		ExampleParticleSystem->addParticle(PositionReturnValue,
			NormalReturnValue,
			ColorReturnValue,
			SizeReturnValue,
			LifespanReturnValue,
			VelocityReturnValue,
			AccelerationReturnValue
			);
	
    }

	//Particle System Drawer
	LineParticleSystemDrawerRefPtr ExampleParticleSystemDrawer = LineParticleSystemDrawer::create();
		ExampleParticleSystemDrawer->setLineDirectionSource(LineParticleSystemDrawer::DIRECTION_VELOCITY);
		ExampleParticleSystemDrawer->setLineLengthSource(LineParticleSystemDrawer::LENGTH_SIZE_X);
		ExampleParticleSystemDrawer->setEndPointFading(Vec2f(0.0f,1.0f));

	//Particle System Node
    ParticleSystemCoreRefPtr ParticleNodeCore = ParticleSystemCore::create();
		ParticleNodeCore->setSystem(ExampleParticleSystem);
		ParticleNodeCore->setDrawer(ExampleParticleSystemDrawer);
		ParticleNodeCore->setMaterial(PSMaterial);
    
	NodeRefPtr ParticleNode = Node::create();
        ParticleNode->setCore(ParticleNodeCore);


    // Make Main Scene Node and add the Torus
    NodeRefPtr scene = Node::create();
        scene->setCore(Group::create());
        scene->addChild(ParticleNode);

    mgr->setRoot(scene);

    // Show the whole Scene
    mgr->showAll();


    //Open Window
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
    TutorialWindow->openWindow(WinPos,
            WinSize,
            "02DynamicDistribution");

    //Enter main Loop
    TutorialWindow->mainLoop();
    
    osgExit();

    return 0;
}
Example #5
0
bool Cylinder::InitAverage(const MiscLib::Vector< Vec3f > &samples)
{
	if(samples.size() < 4)
		return false;
	// estimate axis from covariance of normal vectors
	MiscLib::Vector< GfxTL::Vector3Df > normals;
	size_t c = samples.size() / 2;
	for(size_t i = c; i < samples.size(); ++i)
	{
		normals.push_back(GfxTL::Vector3Df(samples[i]));
		normals.push_back(GfxTL::Vector3Df(-samples[i]));
	}
	GfxTL::MatrixXX< 3, 3, float > cov, eigenVectors;
	GfxTL::Vector3Df eigenValues;
	GfxTL::CovarianceMatrix(GfxTL::Vector3Df(0, 0, 0),
		normals.begin(), normals.end(), &cov);
	GfxTL::Jacobi(cov, &eigenValues, &eigenVectors);
	// find the minimal eigenvalue and corresponding vector
	float minEigVal = eigenValues[0];
	unsigned int minEigIdx = 0;
	for(unsigned int i = 1; i < 3; ++i)
		if(eigenValues[i] < minEigVal)
		{
			minEigVal = eigenValues[i];
			minEigIdx = i;
		}
	m_axisDir = Vec3f(eigenVectors[minEigIdx]);
	// get a point on the axis from all pairs
	m_axisPos = Vec3f(0, 0, 0);
	m_radius = 0;
	size_t pointCount = 0;
	size_t pairCount = 0;
	for(size_t i = 0; i < c - 1; ++i)
		for(size_t j = i + 1; j < c; ++j)
		{
			// project first normal into plane
			float l = m_axisDir.dot(samples[i + c]);
			Vec3f xdir = samples[i + c] - l * m_axisDir;
			xdir.normalize();
			Vec3f ydir = m_axisDir.cross(xdir);
			ydir.normalize();
			// xdir is the x axis in the plane (y = 0) samples[i] is the origin
			float lineBnx = ydir.dot(samples[j + c]);
			if(abs(lineBnx) < .05f)
				continue;
			float lineBny = -xdir.dot(samples[j + c]);
			// origin of lineB
			Vec3f originB = samples[j] - samples[i];
			float lineBOx = xdir.dot(originB);
			float lineBOy = ydir.dot(originB);
			float lineBd = lineBnx * lineBOx + lineBny * lineBOy;
			// lineB in the plane complete
			// point of intersection is y = 0 and x = lineBd / lineBnx
			float radius = lineBd / lineBnx;
			m_axisPos += samples[i] + radius * xdir;
			m_radius += abs(radius);
			m_radius += std::sqrt((radius - lineBOx) * (radius - lineBOx) + lineBOy * lineBOy);
			++pointCount;
		}
	if(!pointCount)
		return false;
	m_axisPos /= pointCount;
	m_radius /= pointCount * 2;
	if(m_radius > 1e6)
		return false;

	// find point on axis closest to origin
	float lambda = m_axisDir.dot(-m_axisPos);
	m_axisPos = m_axisPos + lambda * m_axisDir;

	m_hcs.FromNormal(m_axisDir);
	m_angularRotatedRadians = 0;
	return true;
}
Example #6
0
	Strip::Strip(std::vector<unsigned int> && i)
	{
		m_indexbuffer.reserve(i.size());
		for (auto it=i.begin(),end=i.end() ; it!=end ; ++it)
			m_indexbuffer.push_back(std::make_pair<>(*it,Vec3f()));
	}
// Initialize GLUT & OpenSG and set up the rootNode
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindowEventProducer = createDefaultWindowEventProducer();
    WindowPtr MainWindow = TutorialWindowEventProducer->initWindow();

    TutorialWindowEventProducer->setDisplayCallback(display);
    TutorialWindowEventProducer->setReshapeCallback(reshape);

    TutorialKeyListener TheKeyListener;
    TutorialWindowEventProducer->addKeyListener(&TheKeyListener);
    TutorialMouseListener TheTutorialMouseListener;
    TutorialMouseMotionListener TheTutorialMouseMotionListener;
    TutorialWindowEventProducer->addMouseListener(&TheTutorialMouseListener);
    TutorialWindowEventProducer->addMouseMotionListener(&TheTutorialMouseMotionListener);


    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

	
    // Tell the Manager what to manage
    mgr->setWindow(TutorialWindowEventProducer->getWindow());

    //Make Torus Node
    TriGeometryBase = makeTorus(.55, 1.5, 16, 16);

    //Make Main Scene Node
	NodePtr scene = makeCoredNode<Group>();
    setName(scene, "scene");
    rootNode = Node::create();
    setName(rootNode, "rootNode");
    ComponentTransformPtr Trans;
    Trans = ComponentTransform::create();
    beginEditCP(rootNode, Node::CoreFieldMask | Node::ChildrenFieldMask);
         rootNode->setCore(Trans);
        // add the torus as a child
        rootNode->addChild(scene);
    endEditCP  (rootNode, Node::CoreFieldMask | Node::ChildrenFieldMask);

    //Setup Physics Scene
    physicsWorld = PhysicsWorld::create();
    beginEditCP(physicsWorld, PhysicsWorld::WorldContactSurfaceLayerFieldMask | 
                              PhysicsWorld::AutoDisableFlagFieldMask | 
                              PhysicsWorld::AutoDisableTimeFieldMask | 
                              PhysicsWorld::WorldContactMaxCorrectingVelFieldMask | 
                              PhysicsWorld::GravityFieldMask);
        physicsWorld->setWorldContactSurfaceLayer(0.005);
        physicsWorld->setAutoDisableFlag(1);
        physicsWorld->setAutoDisableTime(0.75);
        physicsWorld->setWorldContactMaxCorrectingVel(100.0);
        physicsWorld->setGravity(Vec3f(0.0, 0.0, -9.81));
    endEditCP(physicsWorld, PhysicsWorld::WorldContactSurfaceLayerFieldMask | 
                              PhysicsWorld::AutoDisableFlagFieldMask | 
                              PhysicsWorld::AutoDisableTimeFieldMask | 
                              PhysicsWorld::WorldContactMaxCorrectingVelFieldMask | 
                              PhysicsWorld::GravityFieldMask);

    //Create the Collision Space
    physicsSpace = PhysicsHashSpace::create();

    //Setup the default collision parameters
    CollisionContactParametersPtr DefaultCollisionParams = CollisionContactParameters::createEmpty();
    beginEditCP(DefaultCollisionParams);
        DefaultCollisionParams->setMode(dContactApprox1);
        DefaultCollisionParams->setMu(0.3);
        DefaultCollisionParams->setMu2(0.0);
        DefaultCollisionParams->setBounce(0.0);
        DefaultCollisionParams->setBounceSpeedThreshold(0.0);
        DefaultCollisionParams->setSoftCFM(0.1);
        DefaultCollisionParams->setSoftERP(0.2);
        DefaultCollisionParams->setMotion1(0.0);
        DefaultCollisionParams->setMotion2(0.0);
        DefaultCollisionParams->setMotionN(0.0);
        DefaultCollisionParams->setSlip1(0.0);
        DefaultCollisionParams->setSlip2(0.0);
    endEditCP(DefaultCollisionParams);

    beginEditCP(physicsSpace, PhysicsSpace::DefaultCollisionParametersFieldMask);
        physicsSpace->setDefaultCollisionParameters(DefaultCollisionParams);
    endEditCP(physicsSpace, PhysicsSpace::DefaultCollisionParametersFieldMask);

    //Bouncy Sphere collision parameters
    CollisionContactParametersPtr BouncySphereCollisionParams = CollisionContactParameters::createEmpty();
    beginEditCP(BouncySphereCollisionParams);
        BouncySphereCollisionParams->setMode(dContactApprox1 | dContactBounce);
        BouncySphereCollisionParams->setMu(0.3);
        BouncySphereCollisionParams->setMu2(0.0);
        BouncySphereCollisionParams->setBounce(0.8);
        BouncySphereCollisionParams->setBounceSpeedThreshold(0.1);
        BouncySphereCollisionParams->setSoftCFM(0.1);
        BouncySphereCollisionParams->setSoftERP(0.2);
        BouncySphereCollisionParams->setMotion1(0.0);
        BouncySphereCollisionParams->setMotion2(0.0);
        BouncySphereCollisionParams->setMotionN(0.0);
        BouncySphereCollisionParams->setSlip1(0.0);
        BouncySphereCollisionParams->setSlip2(0.0);
    endEditCP(BouncySphereCollisionParams);
    physicsSpace->addCollisionContactCategory(SphereCategory, TerrainCategory, BouncySphereCollisionParams);
    physicsSpace->addCollisionContactCategory(SphereCategory, BoxCategory, BouncySphereCollisionParams);
    physicsSpace->addCollisionContactCategory(SphereCategory, SphereCategory, BouncySphereCollisionParams);
    physicsSpace->addCollisionContactCategory(SphereCategory, TriCategory, BouncySphereCollisionParams);

    //Soft Box collision parameters
    CollisionContactParametersPtr SlickBoxParams = CollisionContactParameters::createEmpty();
    beginEditCP(SlickBoxParams);
        SlickBoxParams->setMode(dContactApprox1);
        SlickBoxParams->setMu(0.01);
        SlickBoxParams->setMu2(0.0);
        SlickBoxParams->setBounce(0.0);
        SlickBoxParams->setBounceSpeedThreshold(0.0);
        SlickBoxParams->setSoftCFM(0.0);
        SlickBoxParams->setSoftERP(0.2);
        SlickBoxParams->setMotion1(0.0);
        SlickBoxParams->setMotion2(0.0);
        SlickBoxParams->setMotionN(0.0);
        SlickBoxParams->setSlip1(0.0);
        SlickBoxParams->setSlip2(0.0);
    endEditCP(SlickBoxParams);
    physicsSpace->addCollisionContactCategory(BoxCategory, TerrainCategory, SlickBoxParams);
    physicsSpace->addCollisionContactCategory(BoxCategory, BoxCategory, SlickBoxParams);
    //physicsSpace->addCollisionContactCategory(BoxCategory, SphereCategory, SlickBoxParams);
    physicsSpace->addCollisionContactCategory(BoxCategory, TriCategory, SlickBoxParams);

    
    TutorialCollisionListener BoxColListener(Path("./Data/click.wav"));
    physicsSpace->addCollisionListener(&BoxColListener,BoxCategory, 2.0);

    TutorialCollisionListener SphereColListener(Path("./Data/pop.wav"));
    physicsSpace->addCollisionListener(&SphereColListener,SphereCategory, 2.0);

    physHandler = PhysicsHandler::create();
    beginEditCP(physHandler, PhysicsHandler::WorldFieldMask | PhysicsHandler::SpacesFieldMask | PhysicsHandler::StepSizeFieldMask | PhysicsHandler::UpdateNodeFieldMask);
        physHandler->setWorld(physicsWorld);
        physHandler->getSpaces().push_back(physicsSpace);
        physHandler->setStepSize(0.001);
        physHandler->setUpdateNode(rootNode);
    endEditCP(physHandler, PhysicsHandler::WorldFieldMask | PhysicsHandler::SpacesFieldMask | PhysicsHandler::StepSizeFieldMask | PhysicsHandler::UpdateNodeFieldMask);
    physHandler->attachUpdateProducer(TutorialWindowEventProducer);

    beginEditCP(rootNode, Node::AttachmentsFieldMask);
        rootNode->addAttachment(physHandler);    
        rootNode->addAttachment(physicsWorld);
        rootNode->addAttachment(physicsSpace);
    endEditCP(rootNode, Node::AttachmentsFieldMask);


	/************************************************************************/
	/* create spaces, geoms and bodys                                                                     */
	/************************************************************************/
    //create a group for our space
    GroupPtr spaceGroup;
	spaceGroupNode = makeCoredNode<Group>(&spaceGroup);
    //create the ground plane
    GeometryPtr plane;
	NodePtr planeNode = makeBox(30.0, 30.0, 1.0, 1, 1, 1);
    plane = GeometryPtr::dcast(planeNode->getCore());
    //and its Material
	SimpleMaterialPtr plane_mat = SimpleMaterial::create();
	beginEditCP(plane_mat);
		plane_mat->setAmbient(Color3f(0.7,0.7,0.7));
		plane_mat->setDiffuse(Color3f(0.9,0.6,1.0));
	endEditCP(plane_mat);
    beginEditCP(plane, Geometry::MaterialFieldMask);
	    plane->setMaterial(plane_mat);
    endEditCP(plane);


    //create Physical Attachments
	PhysicsBoxGeomPtr planeGeom = PhysicsBoxGeom::create();
    beginEditCP(planeGeom, PhysicsBoxGeom::LengthsFieldMask | PhysicsBoxGeom::SpaceFieldMask | PhysicsBoxGeom::CategoryBitsFieldMask);
        planeGeom->setLengths(Vec3f(30.0, 30.0, 1.0));
        //add geoms to space for collision
        planeGeom->setSpace(physicsSpace);
        //Set the Geoms Category - this will be used by the collision space 
        //for determining if collision tests should occur
        //and for selecting the collision contact parameters when a collision does occur
        planeGeom->setCategoryBits(TerrainCategory);
    endEditCP(planeGeom, PhysicsBoxGeom::LengthsFieldMask | PhysicsBoxGeom::SpaceFieldMask | PhysicsBoxGeom::CategoryBitsFieldMask);

	//add Attachments to nodes...
    beginEditCP(spaceGroupNode, Node::AttachmentsFieldMask | Node::ChildrenFieldMask);
	    spaceGroupNode->addAttachment(physicsSpace);
        spaceGroupNode->addChild(planeNode);
    endEditCP(spaceGroupNode, Node::AttachmentsFieldMask | Node::ChildrenFieldMask);

    beginEditCP(planeNode, Node::AttachmentsFieldMask);
        planeNode->addAttachment(planeGeom);
    endEditCP(planeNode, Node::AttachmentsFieldMask);
    
	beginEditCP(scene, Node::ChildrenFieldMask);
	    scene->addChild(spaceGroupNode);
	endEditCP(scene, Node::ChildrenFieldMask);
    
    //Create Statistics Foreground
    SimpleStatisticsForegroundPtr PhysicsStatForeground = SimpleStatisticsForeground::create();
    beginEditCP(PhysicsStatForeground);
        PhysicsStatForeground->setSize(25);
        PhysicsStatForeground->setColor(Color4f(0,1,0,0.7));
        PhysicsStatForeground->addElement(PhysicsHandler::statPhysicsTime, 
            "Physics time: %.3f s");
        PhysicsStatForeground->addElement(PhysicsHandler::statCollisionTime, 
            "Collision time: %.3f s");
        PhysicsStatForeground->addElement(PhysicsHandler::statSimulationTime, 
            "Simulation time: %.3f s");
        PhysicsStatForeground->addElement(PhysicsHandler::statNCollisions, 
            "%d collisions");
        PhysicsStatForeground->addElement(PhysicsHandler::statNCollisionTests, 
            "%d collision tests");
        PhysicsStatForeground->addElement(PhysicsHandler::statNPhysicsSteps, 
            "%d simulation steps per frame");
    endEditCP(PhysicsStatForeground);




    // tell the manager what to manage
    mgr->setRoot  (rootNode);

    beginEditCP(mgr->getWindow()->getPort(0), Viewport::ForegroundsFieldMask);
        mgr->getWindow()->getPort(0)->getForegrounds().push_back(PhysicsStatForeground);
    endEditCP(mgr->getWindow()->getPort(0), Viewport::ForegroundsFieldMask);
    physHandler->setStatistics(&PhysicsStatForeground->getCollector());

    // show the whole rootNode
    mgr->showAll();

    //Attach the Sound Manager to the update and the camera
    SoundManager::the()->attachUpdateProducer(TutorialWindowEventProducer);
    SoundManager::the()->setCamera(mgr->getCamera());
    
    Vec2f WinSize(TutorialWindowEventProducer->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindowEventProducer->getDesktopSize() - WinSize) *0.5);
    TutorialWindowEventProducer->openWindow(WinPos,
            WinSize,
            "21Collisions");

    //Enter main Loop
    TutorialWindowEventProducer->mainLoop();

    osgExit();

    return 0;
}
Example #8
0
//TODO Move somewhere else
void Cedric_ApplyLightingFirstPartRefactor(Entity *io) {

	if(!io)
		return;

	io->special_color = Color3f::white;

	float poisonpercent = 0.f;
	float trappercent = 0.f;
	float secretpercent = 0.f;

	if((io->ioflags & IO_NPC) && io->_npcdata->poisonned > 0.f) {
		poisonpercent = io->_npcdata->poisonned * ( 1.0f / 20 );
		if(poisonpercent > 1.f)
			poisonpercent = 1.f;
	}

	if((io->ioflags & IO_ITEM) && io->poisonous > 0.f && io->poisonous_count) {
		poisonpercent = io->poisonous * (1.0f / 20);
		if(poisonpercent > 1.f)
			poisonpercent = 1.f;
	}

	if((io->ioflags & IO_FIX) && io->_fixdata->trapvalue > -1) {
		trappercent = player.TRAP_DETECT - io->_fixdata->trapvalue;
		if(trappercent > 0.f) {
			trappercent = 0.6f + trappercent * ( 1.0f / 100 );
			trappercent = glm::clamp(trappercent, 0.6f, 1.f);
		}
	}

	if((io->ioflags & IO_FIX) && io->secretvalue > -1) {
		secretpercent = player.TRAP_SECRET - io->secretvalue;
		if(secretpercent > 0.f) {
			secretpercent = 0.6f + secretpercent * ( 1.0f / 100 );
			secretpercent = glm::clamp(secretpercent, 0.6f, 1.f);
		}
	}

	if(poisonpercent > 0.f) {
		io->special_color = Color3f::green;
	}

	if(trappercent > 0.f) {
		io->special_color = Color3f(trappercent, 1.f - trappercent, 1.f - trappercent);
	}

	if(secretpercent > 0.f) {
		io->special_color = Color3f(1.f - secretpercent, 1.f - secretpercent, secretpercent);
	}

	if(io->ioflags & IO_FREEZESCRIPT) {
		io->special_color = Color3f::blue;
	}

	if(io->sfx_flag & SFX_TYPE_YLSIDE_DEATH) {
		if(io->show == SHOW_FLAG_TELEPORTING) {
			io->sfx_time = io->sfx_time + ArxDurationMs(g_framedelay);

			if (io->sfx_time >= arxtime.now())
				io->sfx_time = arxtime.now();
		} else {
			const ArxDuration elapsed = arxtime.now() - io->sfx_time;

			if(elapsed > ArxDuration_ZERO) {
				if(elapsed < ArxDurationMs(3000)) { // 5 seconds to red
					float ratio = toMs(elapsed) * (1.0f / 3000);
					io->special_color = Color3f(1.f, 1.f - ratio, 1.f - ratio);
					io->highlightColor += Color3f(std::max(ratio - 0.5f, 0.f), 0.f, 0.f) * 255;
					AddRandomSmoke(io, 1);
				} else if(elapsed < ArxDurationMs(6000)) { // 5 seconds to White
					float ratio = toMs(elapsed) * (1.0f / 3000);
					io->special_color = Color3f::red;
					io->highlightColor += Color3f(std::max(ratio - 0.5f, 0.f), 0.f, 0.f) * 255;
					AddRandomSmoke(io, 2);
				} else { // SFX finish
					io->sfx_time = ArxInstant_ZERO;

					if(io->ioflags & IO_NPC) {
						MakePlayerAppearsFX(io);
						AddRandomSmoke(io, 50);
						Color3f rgb = io->_npcdata->blood_color.to<float>();
						Sphere sp = Sphere(io->pos, 200.f);
						
						long count = 6;
						while(count--) {
							Sphere splatSphere = Sphere(sp.origin, Random::getf(30.f, 60.f));
							PolyBoomAddSplat(splatSphere, rgb, 1);
							sp.origin.y -= Random::getf(0.f, 150.f);

							ARX_PARTICLES_Spawn_Splat(sp.origin, 200.f, io->_npcdata->blood_color);

							sp.origin = io->pos + randomVec3f() * Vec3f(200.f, 20.f,200.f) - Vec3f(100.f, 10.f, 100.f);
							sp.radius = Random::getf(100.f, 200.f);
						}
						
						EERIE_LIGHT * light = dynLightCreate();
						if(light) {
							light->intensity = Random::getf(0.7f, 2.7f);
							light->fallend = 600.f;
							light->fallstart = 400.f;
							light->rgb = Color3f(1.0f, 0.8f, 0.f);
							light->pos = io->pos + Vec3f(0.f, -80.f, 0.f);
							light->duration = ArxDurationMs(600);
						}

						if(io->sfx_flag & SFX_TYPE_INCINERATE) {
							io->sfx_flag &= ~SFX_TYPE_INCINERATE;
							io->sfx_flag &= ~SFX_TYPE_YLSIDE_DEATH;
							SpellBase * spell = spells.getSpellOnTarget(io->index(), SPELL_INCINERATE);

							if(!spell)
								spell = spells.getSpellOnTarget(io->index(), SPELL_MASS_INCINERATE);

							if(spell) {
								spells.endSpell(spell);
								float damages = 20 * spell->m_level;
								damages = ARX_SPELLS_ApplyFireProtection(io, damages);

								if (ValidIONum(spell->m_caster))
									ARX_DAMAGES_DamageNPC(io, damages, spell->m_caster, true, &entities[spell->m_caster]->pos);
								else
									ARX_DAMAGES_DamageNPC(io, damages, spell->m_caster, true, &io->pos);

								ARX_SOUND_PlaySFX(SND_SPELL_FIRE_HIT, &io->pos);
							}
						} else {
							io->sfx_flag &= ~SFX_TYPE_YLSIDE_DEATH;
							ARX_INTERACTIVE_DestroyIOdelayed(io);
						}
					}
				}
			}
		}
	}
}
void AddFlare(const Vec2s & pos, float sm, short typ, Entity * io, bool bookDraw) {

	long i;
	for(i = 0; i < MAX_FLARES; i++) {
		if(!magicFlares[i].exist) {
			break;
		}
	}
	if(i >= MAX_FLARES) {
		return;
	}

	FLARES * fl = &magicFlares[i];
	fl->exist = 1;
	flarenum++;

	if(!bookDraw)
		fl->bDrawBitmap = 0;
	else
		fl->bDrawBitmap = 1;

	fl->io = io;
	if(io) {
		fl->flags = 1;
		io->flarecount++;
	} else {
		fl->flags = 0;
	}

	fl->x = float(pos.x) - rnd() * 4.f;
	fl->y = float(pos.y) - rnd() * 4.f - 50.f;
	fl->tv.rhw = fl->v.rhw = 1.f;
	fl->tv.specular = fl->v.specular = 1;

	if(!bookDraw) {
		EERIE_CAMERA ka = *Kam;
		ka.angle = Anglef(360.f, 360.f, 360.f) - ka.angle;
		EERIE_CAMERA * oldcam = ACTIVECAM;
		SetActiveCamera(&ka);
		PrepareCamera(&ka);
		fl->v.p += ka.orgTrans.pos;
		EE_RTP(&fl->tv, &fl->v);
		fl->v.p += ka.orgTrans.pos;

		float vx = -(fl->x - subj.center.x) * 0.2173913f;
		float vy = (fl->y - subj.center.y) * 0.1515151515151515f;
		if(io) {
			fl->v.p.x = io->pos.x - EEsin(radians(MAKEANGLE(io->angle.getPitch() + vx))) * 100.f;
			fl->v.p.y = io->pos.y + EEsin(radians(MAKEANGLE(io->angle.getYaw() + vy))) * 100.f - 150.f;
			fl->v.p.z = io->pos.z + EEcos(radians(MAKEANGLE(io->angle.getPitch() + vx))) * 100.f;
		} else {
			fl->v.p.x = float(pos.x - (g_size.width() / 2)) * 150.f / float(g_size.width());
			fl->v.p.y = float(pos.y - (g_size.height() / 2)) * 150.f / float(g_size.width());
			fl->v.p.z = 75.f;
			ka = *oldcam;
			SetActiveCamera(&ka);
			PrepareCamera(&ka);
			float temp = (fl->v.p.y * -ka.orgTrans.xsin) + (fl->v.p.z * ka.orgTrans.xcos);
			fl->v.p.y = (fl->v.p.y * ka.orgTrans.xcos) - (-fl->v.p.z * ka.orgTrans.xsin);
			fl->v.p.z = (temp * ka.orgTrans.ycos) - (-fl->v.p.x * ka.orgTrans.ysin);
			fl->v.p.x = (temp * -ka.orgTrans.ysin) + (fl->v.p.x * ka.orgTrans.ycos);
			fl->v.p += oldcam->orgTrans.pos;
		}
		fl->tv.p = fl->v.p;
		SetActiveCamera(oldcam);
		PrepareCamera(oldcam);
	} else {
		fl->tv.p = Vec3f(fl->x, fl->y, 0.001f);
	}

	switch(PIPOrgb) {
		case 0: {
			fl->rgb = Color3f(rnd() * (2.f/3) + .4f, rnd() * (2.f/3), rnd() * (2.f/3) + .4f);
			break;
		}
		case 1: {
			fl->rgb = Color3f(rnd() * .625f + .5f, rnd() * .625f + .5f, rnd() * .55f);
			break;
		}
		case 2: {
			fl->rgb = Color3f(rnd() * (2.f/3) + .4f, rnd() * .55f, rnd() * .55f);
			break;
		}
	}

	if(typ == -1) {
		float zz = (EERIEMouseButton & 1) ? 0.29f : ((sm > 0.5f) ? rnd() : 1.f);
		if(zz < 0.2f) {
			fl->type = 2;
			fl->size = rnd() * 42.f + 42.f;
			fl->tolive = (800.f + rnd() * 800.f) * FLARE_MUL;
		} else if(zz < 0.5f) {
			fl->type = 3;
			fl->size = rnd() * 52.f + 16.f;
			fl->tolive = (800.f + rnd() * 800.f) * FLARE_MUL;
		} else {
			fl->type = 1;
			fl->size = (rnd() * 24.f + 32.f) * sm;
			fl->tolive = (1700.f + rnd() * 500.f) * FLARE_MUL;
		}
	} else {
		fl->type = (rnd() > 0.8f) ? 1 : 4;
		fl->size = (rnd() * 38.f + 64.f) * sm;
		fl->tolive = (1700.f + rnd() * 500.f) * FLARE_MUL;
	}

	fl->dynlight = -1;
	fl->move = OPIPOrgb;

	for(long kk = 0; kk < 3; kk++) {

		if(rnd() < 0.5f) {
			continue;
		}

		PARTICLE_DEF * pd = createParticle();
		if(!pd) {
			break;
		}

		if(!bookDraw) {
			pd->special = FADE_IN_AND_OUT | ROTATING | MODULATE_ROTATION | DISSIPATING;
			if(!io) {
				pd->special |= PARTICLE_NOZBUFFER;
			}
		} else {
			pd->special = FADE_IN_AND_OUT;
		}

		pd->ov = fl->v.p + randomVec(-5.f, 5.f);
		pd->move = Vec3f(0.f, 5.f, 0.f);
		pd->scale = Vec3f(-2.f);
		pd->tolive = 1300 + kk * 100 + Random::get(0, 800);
		pd->tc = fire2;
		if(kk == 1) {
			pd->move.y = 4.f;
			pd->siz = 1.5f;
		} else {
			pd->siz = 1.f + rnd();
		}
		pd->rgb = Color3f(fl->rgb.r * (2.f/3), fl->rgb.g * (2.f/3), fl->rgb.b * (2.f/3));
		pd->fparam = 1.2f;

		if(bookDraw)
			pd->type = PARTICLE_2D;
	}
}
Example #10
0
//没用 weight
Vec3f RayTracer::traceRay(Ray &ray, float tmin, int bounces, float indexOfRefraction, Hit &hit, Grid *grid) const
{
	if(bounces >= max_bounces)
		return Vec3f(0,0,0);
	RayTracingStats::IncrementNumNonShadowRays();
	//Group *group = s->getGroup();
	//group->intersect(ray,hit,tmin);  这里是没用grid的代码
	grid->intersect(ray,hit,tmin);
	
	if(hit.getMaterial()==NULL)
		return s->getBackgroundColor();
	else
	{
		RayTracingStats::IncrementNumShadowRays();
		Vec3f col(0,0,0);
		Vec3f hitPoint = hit.getIntersectionPoint();
		Vec3f tempAmb;
		Vec3f::MultRow(tempAmb,s->getAmbientLight(),hit.getMaterial()->getDiffuse(hitPoint));  //Kd La
		col += tempAmb;
		int lightNumber = s->getNumLights();
		Light *light;
		for(int i=0; i<lightNumber; i++)
		{
			light = s->getLight(i);
			Vec3f lightColor;
			Vec3f dirToLight;
			//Vec3f interPoint = hit.getIntersectionPoint();
			float distanceToLight;
			light->getIllumination(hitPoint,dirToLight,lightColor,distanceToLight);
			if(!castShadowRayGrid(hitPoint-ray.getDirection()*EPSILON,dirToLight,distanceToLight,grid))
			{
				Vec3f tempShade = hit.getMaterial()->Shade(ray,hit,dirToLight,lightColor);  //diffuse specular
				col += tempShade;
			}
		}
		if(hit.getMaterial()->isReflect(hitPoint))  
		{
			Ray rayReflect(mirrorDirection(hit.getNormal(),ray.getDirection()),hitPoint);
			Vec3f tempRefl;
			Hit hit2(1000,NULL,Vec3f(1,1,1));
			Vec3f::MultRow(tempRefl,hit.getMaterial()->getReflect(hitPoint),traceRay(rayReflect,tmin,bounces+1,indexOfRefraction,hit2,grid)); //weight,indexOfRefrection
			col += tempRefl;
		}
		if(hit.getMaterial()->isTransparent(hitPoint))
		{
			bool notTotalReflective;
			Vec3f transmittedDir;
			if(ray.getDirection().Dot3(hit.getNormal())>0) //ray is inside the object
			{
				notTotalReflective = transmittedDirection(hit.getNormal()*(-1.0f),ray.getDirection(),hit.getMaterial()->getIndexOfRefrac(hitPoint),indexOfRefraction,transmittedDir);
			}
			else  //outside
			{
				notTotalReflective = transmittedDirection(hit.getNormal(),ray.getDirection(),indexOfRefraction,hit.getMaterial()->getIndexOfRefrac(hitPoint),transmittedDir);
			}
			
			if(notTotalReflective)
			{
				Ray rayTransparent(transmittedDir,hitPoint);
				Vec3f tempTrans;
				Hit hit3(10000,NULL,Vec3f(1,1,1));
				Vec3f::MultRow(tempTrans,hit.getMaterial()->getTrans(hitPoint),traceRay(rayTransparent,tmin,bounces+1,indexOfRefraction,hit3,grid));
				col += tempTrans;
			}
			else
			{
				Vec3f tempTotalTrans;
				Vec3f::MultRow(tempTotalTrans,hit.getMaterial()->getTrans(hitPoint),hit.getMaterial()->getDiffuse(hitPoint));
				col += tempTotalTrans;
			}
		}
		return col;
	}
}
Example #11
0
//grid castShadowRay
bool RayTracer::castShadowRayGrid(Vec3f point, Vec3f lightDir, float distanceToLight, Grid *grid) const
{
	Ray r(lightDir,point);
	Hit hit(distanceToLight,NULL,Vec3f(1,1,1));
	return grid->shadowIntersect(r,hit,EPSILON);  //又是因为这里没加EPSILON,又出现了影子的乱点情况
}
Example #12
0
//---------------------------------------------------------------------------
void DeveloperConsole::RenderConsole( const unsigned int shaderProgramID )
{
	float inputBoxOffset = 5.f;
	Vertex3D vertices[ 8 ];
	Vec2f inputWindowMins( 0.f, 0.f );
	Vec2f inputWindowMaxes( GAME_WINDOW_X, m_fontCellHeight + inputBoxOffset );
	Vec2f logWindowMins( 0.f, m_fontCellHeight + inputBoxOffset * 2.f );
	Vec2f logWindowMaxes( GAME_WINDOW_X, GAME_WINDOW_Y );
	Rgba windowColor( 0, 0, 0, 125 );
	Rgba commandTextColor( Colors::WHITE );

// 	g_theRenderer->VennLoadIdentity();
// 	g_theRenderer->VennOrtho( 0.f, GAME_WINDOW_X, 0.f, GAME_WINDOW_Y, 0.f, 1.f );
//	g_theRenderer->ApplyOrthoProjection( 0.f, GAME_WINDOW_X, 0.f, GAME_WINDOW_Y, 0.f, 1.f );

	// the input window
	vertices[ 0 ].m_position = Vec3f( inputWindowMins.x, inputWindowMins.y, 0.f );
	vertices[ 0 ].m_color = windowColor;

	vertices[ 1 ].m_position = Vec3f( inputWindowMins.x, inputWindowMaxes.y, 0.f );
	vertices[ 1 ].m_color = windowColor;

	vertices[ 2 ].m_position = Vec3f( inputWindowMaxes.x, inputWindowMaxes.y, 0.f );
	vertices[ 2 ].m_color = windowColor;

	vertices[ 3 ].m_position = Vec3f( inputWindowMaxes.x, inputWindowMins.y, 0.f );
	vertices[ 3 ].m_color = windowColor;

	// render the log window
	vertices[ 4 ].m_position = Vec3f( logWindowMins.x, logWindowMins.y, 0.f );
	vertices[ 4 ].m_color = windowColor;

	vertices[ 5 ].m_position = Vec3f( logWindowMins.x, logWindowMaxes.y, 0.f );
	vertices[ 5 ].m_color = windowColor;

	vertices[ 6 ].m_position = Vec3f( logWindowMaxes.x, logWindowMaxes.y, 0.f );
	vertices[ 6 ].m_color = windowColor;

	vertices[ 7 ].m_position = Vec3f( logWindowMaxes.x, logWindowMins.y, 0.f );
	vertices[ 7 ].m_color = windowColor;

// 	g_theRenderer->VennEnableClientState( V_VERTEX_ARRAY );
// 	g_theRenderer->VennEnableClientState( V_COLOR_ARRAY );
// 
// 	g_theRenderer->VennVertexPointer( 3, V_FLOAT, sizeof( Vertex3D ), &vertices[0].m_position );
// 	g_theRenderer->VennColorPointer( 4, V_FLOAT, sizeof( Vertex3D ), &vertices[0].m_color );
// 
// 	g_theRenderer->VennDrawArrays( V_QUADS, 0, 8 );
// 
// 	g_theRenderer->VennDisableClientState( V_VERTEX_ARRAY );
// 	g_theRenderer->VennDisableClientState( V_COLOR_ARRAY );
	RenderVertexArrayWithShader( vertices, 8, shaderProgramID, V_QUADS );

	// render current command string
	m_textRenderer->RenderText2D( m_currentConsoleCommandString.c_str(), m_fontCellHeight, Vec2f( inputWindowMins.x, inputWindowMins.y ), commandTextColor, shaderProgramID );

	// render log lines
	for ( unsigned int index = m_logLines.size(); index > 0; --index )
	{
		if ( logWindowMins.y >= GAME_WINDOW_Y ) break;

		CommandLogLine& currentLine = m_logLines[ index - 1 ];
		m_textRenderer->RenderText2D( currentLine.m_text.c_str(), m_fontCellHeight, logWindowMins, currentLine.m_color, shaderProgramID );

		logWindowMins.y += m_fontCellHeight + inputBoxOffset;
	}
}
TestGrouping::TestGrouping()
{
	m_aabb.SetCenter(Vec3f(0.0f, 16.0f, 0.0f));

	m_aabb.SetHalfDims(Vec3f(100.0f, 0.1f, 100.0f));
}
Example #14
0
 template<> Vec3f CoronaLoader::load<Vec3f>(const Ref<XML>& xml) {
   if (xml->body.size() < 3) THROW_RUNTIME_ERROR(xml->loc.str()+": wrong float3 body");
   return Vec3f(xml->body[0].Float(),xml->body[1].Float(),xml->body[2].Float());
 }
	CubeExample(void)
	 : cube_instr(make_cube.Instructions())
	 , cube_indices(make_cube.Indices())
	 , light_pos(prog, "LightPos")
	 , projection_matrix(prog, "ProjectionMatrix")
	 , tex_projection_matrix(prog, "TexProjectionMatrix")
	 , model_matrix(prog, "ModelMatrix")
	{
		// Set the vertex shader source
		vs.Source(
			"#version 330\n"
			"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
			"uniform mat4 TexProjectionMatrix;"
			"in vec4 Position;"
			"in vec3 Normal;"
			"out vec3 vertNormal;"
			"out vec3 vertLight;"
			"out vec4 vertTexCoord;"
			"uniform vec3 LightPos;"
			"void main(void)"
			"{"
			"	vertNormal = ("
			"		ModelMatrix *"
			"		vec4(-Normal, 0.0)"
			"	).xyz;"
			"	vertLight = ("
			"		vec4(LightPos, 0.0)-"
			"		ModelMatrix * Position"
			"	).xyz;"
			"	vertTexCoord = "
			"		TexProjectionMatrix *"
			"		ModelMatrix *"
			"		Position;"
			"	gl_Position = "
			"		ProjectionMatrix *"
			"		CameraMatrix *"
			"		ModelMatrix *"
			"		Position;"
			"}"
		);
		// compile it
		vs.Compile();

		// set the fragment shader source
		fs.Source(
			"#version 330\n"
			"uniform sampler2D TexUnit;"
			"in vec3 vertNormal;"
			"in vec3 vertLight;"
			"in vec4 vertTexCoord;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	float l = length(vertLight);"
			"	float d = l != 0.0 ? dot("
			"		vertNormal, "
			"		normalize(vertLight)"
			"	) / l : 0.0;"
			"	float i = 0.1 + 4.2*max(d, 0.0);"
			"	vec2 coord = vertTexCoord.st/vertTexCoord.q;"
			"	vec4 t  = texture(TexUnit, coord*0.5 + 0.5);"
			"	fragColor = vec4(t.rgb*i*sqrt(1.0-t.a), 1.0);"
			"}"
		);
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		// bind the VAO for the cube
		cube.Bind();

		verts.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_cube.Positions(data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexArrayAttrib attr(prog, "Position");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		normals.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_cube.Normals(data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexArrayAttrib attr(prog, "Normal");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// setup the texture
		gl.Direct(Texture::Target::_2D, tex)
			.Image2D(images::LoadTexture("flower_glass"))
			.GenerateMipmap()
			.BorderColor(Vec4f(1.0f, 1.0f, 1.0f, 0.0f))
			.MinFilter(TextureMinFilter::LinearMipmapLinear)
			.MagFilter(TextureMagFilter::Linear)
			.WrapS(TextureWrap::ClampToBorder)
			.WrapT(TextureWrap::ClampToBorder)
			.Bind();

		UniformSampler(prog, "TexUnit").Set(0);
		Uniform<Mat4f>(prog, "CameraMatrix").Set(
			CamMatrixf::LookingAt(Vec3f(0.0f, 1.0f, 2.0f), Vec3f())
		);

		gl.ClearColor(0.1f, 0.1f, 0.1f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);
		gl.Enable(Capability::CullFace);
		gl.FrontFace(make_cube.FaceWinding());
	}
Example #16
0
void IgnitSpell::Launch()
{
	m_duration = 500;
	
	if(m_hand_group != -1) {
		m_srcPos = m_hand_pos;
	} else {
		m_srcPos = m_caster_pos - Vec3f(0.f, 50.f, 0.f);
	}
	
	LightHandle id = GetFreeDynLight();
	if(lightHandleIsValid(id)) {
		EERIE_LIGHT * light = lightHandleGet(id);
		
		light->intensity = 1.8f;
		light->fallend   = 450.f;
		light->fallstart = 380.f;
		light->rgb       = Color3f(1.f, 0.75f, 0.5f);
		light->pos       = m_srcPos;
		light->duration  = 300;
	}
	
	float fPerimeter = 400.f + m_level * 30.f;
	
	m_lights.clear();
	m_elapsed = 0;
	
	CheckForIgnition(m_srcPos, fPerimeter, 1, 1);
	
	for(size_t ii = 0; ii < MAX_LIGHTS; ii++) {
		EERIE_LIGHT * light = GLight[ii];
		
		if(!light || !(light->extras & EXTRAS_EXTINGUISHABLE)) {
			continue;
		}
		
		if(m_caster == PlayerEntityHandle && (light->extras & EXTRAS_NO_IGNIT)) {
			continue;
		}
		
		if(!(light->extras & EXTRAS_SEMIDYNAMIC)
		  && !(light->extras & EXTRAS_SPAWNFIRE)
		  && !(light->extras & EXTRAS_SPAWNSMOKE)) {
			continue;
		}
		
		if(light->m_ignitionStatus) {
			continue;
		}
		
		if(!fartherThan(m_srcPos, light->pos, fPerimeter)) {
			
			T_LINKLIGHTTOFX entry;
			
			entry.iLightNum = ii;
			entry.poslight = light->pos;
		
			entry.idl = GetFreeDynLight();
		
			if(lightHandleIsValid(entry.idl)) {
				EERIE_LIGHT * light = lightHandleGet(entry.idl);
				
				light->intensity = 0.7f + 2.f * rnd();
				light->fallend = 400.f;
				light->fallstart = 300.f;
				light->rgb = Color3f(1.f, 1.f, 1.f);
				light->pos = entry.poslight;
			}
		
			m_lights.push_back(entry);
		}
	}
	
	for(size_t n = 0; n < MAX_SPELLS; n++) {
		SpellBase * spell = spells[SpellHandle(n)];
		
		if(!spell) {
			continue;
		}
		if(spell->m_type == SPELL_FIREBALL) {
			CSpellFx * pCSpellFX = spell->m_pSpellFx;
			if(pCSpellFX) {
				CFireBall * pCF = (CFireBall *)pCSpellFX;
				float radius = std::max(m_level * 2.f, 12.f);
				if(closerThan(m_srcPos, pCF->eCurPos,
				              fPerimeter + radius)) {
					spell->m_level += 1;
				}
			}
		}
	}
}
inline Vec3f getXYW				(const Vec4f v)						{ return Vec3f(v.x,v.y,v.w); }
Example #18
0
// Initializes the BallBlob Creature object
MetaballEnemy::MetaballEnemy(Eigen::Vector3f center, int numBlobs, float radius)
{
	this->numBlobs = numBlobs;
	this->center.x = center(0);
	this->center.y = center(1);
	this->center.z = center(2);
	this->radius = radius;
	
	this->increment = this->radius * 2 / DEFAULT_NUM_CUBES_PER_DIMENSION;
	
	float fieldStrengthConstant = 0.707 / (DEFAULT_FIELD_STRENGTH_CUTOFF * this->radius);
	this->fieldStrengthConstantSquared = fieldStrengthConstant * fieldStrengthConstant;
	this->fieldStrengthConstantSquaredSquared = fieldStrengthConstantSquared * fieldStrengthConstantSquared;
	this->fieldStrengthDistanceSquaredThreshold = 0.5f / fieldStrengthConstantSquared;
	
	srand(time(NULL)); //Initializes random number generator
	
	this->blobs = new BallBlob[numBlobs];
	
	for (int i = 0; i < numBlobs; i++)
	{
		BallBlob blob;
		
		Vertex tempCenter;
		tempCenter.x = 0.f;
		tempCenter.y = 0.f;
		tempCenter.z = 0.f;
		blob.center = this->center;
		
		blob.speed = DEFAULT_BLOB_SPEED * this->radius;
		blob.direction = generateRandomNormalizedDirection();
		blob.pastCenter = false;
		
		blobs[i] = blob;
	}
	
	this->maxBlobRadius = getMaxBlobRadius();
	
	//initializeVTable();
	
	this->addedSize2D =  DEFAULT_NUM_CUBES_PER_DIMENSION * DEFAULT_NUM_CUBES_PER_DIMENSION;
	
	this->addedSize3D = addedSize2D * DEFAULT_NUM_CUBES_PER_DIMENSION;
	
	this->added = new bool[addedSize3D];
	
	this->strengthSize2D = (DEFAULT_NUM_CUBES_PER_DIMENSION + 1) * (DEFAULT_NUM_CUBES_PER_DIMENSION + 1);
	
	this->strengthSize3D = strengthSize2D * (DEFAULT_NUM_CUBES_PER_DIMENSION + 1);
	
	this->neighborsSize = DEFAULT_NEIGHBORS_SIZE;
	
	this->fieldStrengths = new FieldStrength[strengthSize3D];
	
	this->neighbors = new Index[neighborsSize];
	
	this->speed = DEFAULT_BLOB_CREATURE_SPEED * this->radius;
	Vertex direction = generateRandomNormalizedDirection();
	this->velocity = Vec3f(direction.x * this->speed, direction.y * this->speed, direction.z * this->speed);
	this->angularVelocity = Vec4f();
	
	vector<Vec3f> tempBoundingBox;
	Vec3f v(-this->radius, this->radius, this->radius);
	tempBoundingBox.push_back(v);
	v = Vec3f(this->radius, this->radius, this->radius);
	tempBoundingBox.push_back(v);
	v = Vec3f(-this->radius, -this->radius, this->radius);
	tempBoundingBox.push_back(v);
	v = Vec3f(this->radius, -this->radius, this->radius);
	tempBoundingBox.push_back(v);
	v = Vec3f(-this->radius, this->radius, -this->radius);
	tempBoundingBox.push_back(v);
	v = Vec3f(this->radius, this->radius, -this->radius);
	tempBoundingBox.push_back(v);
	v = Vec3f(-this->radius, -this->radius, -this->radius);
	tempBoundingBox.push_back(v);
	v = Vec3f(this->radius, -this->radius, -this->radius);
	tempBoundingBox.push_back(v);
	
	this->boundingBox = tempBoundingBox;
	
	this->fireCounter = 0;
	
	this->hasCollided = false;
	
	float tempBlobMaterialAmbient[] = {0.2, 0.2, 0.6, 1.0};
	float tempBlobMaterialDiffuse[]  = {0.2, 0.2, 0.6, 1.0};
	float tempBlobMaterialSpecular[] = {0.8, 0.8, 0.8, 1.0};
	float tempBlobShininess = 8.0;
	
	float tempCenterMaterialAmbient[] = {.2, 0., 0., 1.0};
	float tempCenterMaterialDiffuse[]  = {.2, 0., 0., 1.0};
	float tempCenterMaterialSpecular[] = {.2, 0., 0., 1.0};
	float tempCenterShininess = 8.0;
	
	memcpy(blobMaterialAmbient, tempBlobMaterialAmbient, 4 * sizeof(float));
	memcpy(blobMaterialDiffuse, tempBlobMaterialDiffuse, 4 * sizeof(float));
	memcpy(blobMaterialSpecular, tempBlobMaterialSpecular, 4 * sizeof(float));
	blobShininess = tempBlobShininess;
	
	memcpy(centerMaterialAmbient, tempCenterMaterialAmbient, 4 * sizeof(float));
	memcpy(centerMaterialDiffuse, tempCenterMaterialDiffuse, 4 * sizeof(float));
	memcpy(centerMaterialSpecular, tempCenterMaterialSpecular, 4 * sizeof(float));
	centerShininess = tempCenterShininess;
}
	void RungeKuttaIntegrator::step( const float &deltaT )
	{	
		allocateParticles();
		/////////////////////////////////////////////////////////
		// save original position and velocities
		
		for ( size_t i = 0; i < s->particles.size(); ++i )
		{
			Particle* p = s->particles[i];
			if ( !p->fixed )
			{		
				originalPositions[i]= ( p->position );
				originalVelocities[i]=( p->velocity );
			}
			
			p->force=Vec3f(0,0,0);	// and clear the forces
		}
		
		////////////////////////////////////////////////////////
		// get all the k1 values
		 
		s->applyForces(); 

		// save the intermediate forces
		for ( size_t i = 0; i < s->particles.size(); ++i )
		{
			Particle* p = s->particles[i];
			if ( !p->fixed )
			{
				k1Forces[i]= p->force ;
				k1Velocities[i]=  p->velocity ;                
			}
			
			p->force=Vec3f(0,0,0);	// and clear the forces
		}
		
		////////////////////////////////////////////////////////////////
		// get k2 values
		 
		for ( size_t i = 0; i < s->particles.size(); ++i )
		{
			Particle* p = s->particles[i];
			if ( !p->fixed )
			{
				Vec3f originalPosition = originalPositions[i];
				Vec3f k1Velocity = k1Velocities[i];
				
                p->position=  originalPosition + (k1Velocity * (0.5f * deltaT)) ;
				
				Vec3f originalVelocity = originalVelocities[i];
				Vec3f k1Force = k1Forces[i];

				p->velocity=  originalVelocity + k1Force * 0.5f * deltaT / p->mass ;
			}
		}
		
		s->applyForces();

		// save the intermediate forces
		for ( size_t i = 0; i < s->particles.size(); ++i )
		{
			Particle* p = s->particles[i];
			if ( !p->fixed )
			{
				k2Forces[i]= ( p->force );
				k2Velocities[i]= ( p->velocity );                
			}
			
			p->force=Vec3f(0,0,0);	// and clear the forces now that we are done with them
		}
		
		
		/////////////////////////////////////////////////////
		// get k3 values
		
		for ( size_t i = 0; i < s->particles.size(); ++i )
		{
			Particle* p = s->particles[i];
			if ( !p->fixed )
			{
                Vec3f originalPosition = originalPositions[i];
                Vec3f k2Velocity = k2Velocities[i];
				
                p->position= ( originalPosition + k2Velocity * 0.5f * deltaT );
				
                Vec3f originalVelocity = originalVelocities[i];
                Vec3f k2Force = k2Forces[i];

                p->velocity= ( originalVelocity + k2Force * 0.5f * deltaT / p->mass );
			}
		}
        
		s->applyForces();
		
		// save the intermediate forces
		for ( size_t i = 0; i < s->particles.size(); ++i )
		{
			Particle* p = s->particles[i];
			if ( !p->fixed )
			{
				k3Forces[i]= ( p->force );
				k3Velocities[i]= ( p->velocity );                
			}
			
			p->force=Vec3f(0,0,0);	// and clear the forces now that we are done with them
		}
		
		
		//////////////////////////////////////////////////
		// get k4 values
		 
		for ( size_t i = 0; i < s->particles.size(); ++i )
		{
			Particle* p = s->particles[i];
			if ( !p->fixed )
			{
                Vec3f originalPosition = originalPositions[i];
				Vec3f k3Velocity = k3Velocities[i];
				
				p->position= ( originalPosition + k3Velocity * deltaT);
				
				Vec3f originalVelocity = originalVelocities[i];
				Vec3f k3Force = k3Forces[i];

				p->velocity= ( originalVelocity + k3Force * deltaT / p->mass );
			}
		}
		
		s->applyForces();

		// save the intermediate forces
		for ( size_t i = 0; i < s->particles.size(); ++i )
		{
			Particle* p = s->particles[i];
			if ( !p->fixed )
			{
				k4Forces[i]= ( p->force );
				k4Velocities[i]= ( p->velocity );                
			}			
		}
		
		
		
		/////////////////////////////////////////////////////////////
		// put them all together and what do you get?
		
		for ( size_t i = 0; i < s->particles.size(); ++i )
		{
			Particle* p = s->particles[i];
            p->age += deltaT;
			 
			if ( !p->fixed )
			{
				// update position
				
                Vec3f originalPosition = originalPositions[i];
				Vec3f k1Velocity = k1Velocities[i];
				Vec3f k2Velocity = k2Velocities[i];
				Vec3f k3Velocity = k3Velocities[i];
				Vec3f k4Velocity = k4Velocities[i];
				
				p->position= ( originalPosition + deltaT / 6.0f * ( k1Velocity + 2.0f*k2Velocity + 2.0f*k3Velocity + k4Velocity ) );
				
				// update velocity
				
                Vec3f originalVelocity = originalVelocities[i];
				Vec3f k1Force = k1Forces[i];
				Vec3f k2Force = k2Forces[i];
				Vec3f k3Force = k3Forces[i];
				Vec3f k4Force = k4Forces[i];
				
				
                p->velocity= ( originalVelocity + deltaT / ( 6.0f * p->mass ) * ( k1Force + 2.0f*k2Force + 2.0f*k3Force + k4Force ) );

				 
			}
		}
		 
	}
Example #20
0
void CCreateField::Render()
{
	if(!VisibleSphere(Sphere(eSrc - Vec3f(0.f, 120.f, 0.f), 400.f)))
		return;
	
	//-------------------------------------------------------------------------
	// rendu
	if(youp) {
		fglow += 0.5f;

		if(fglow >= 50) {
			youp = false;
		}
	} else {
		fglow -= 0.5f;

		if(fglow <= 0) {
			youp = true;
		}
	}
	
	float ysize = std::min(1.0f, m_elapsed / GameDurationMs(1000));
	
	if(ysize >= 1.0f) {
		size = std::min(1.0f, (m_elapsed - GameDurationMs(1000)) / GameDurationMs(1000));
		size = std::max(size, 0.1f);
	}

	// ondulation
	ft += 0.01f;

	if(ft > 360.0f) {
		ft = 0.0f;
	}

	falpha = glm::sin(glm::radians(fglow)) + Random::getf(0.f, 0.2f);
	falpha = glm::clamp(falpha, 0.f, 1.f);
	
	float smul = 100 * size;

	// bottom points
	Vec3f b[4] = {
		eSrc + Vec3f(-smul, 0.f, -smul),
		eSrc + Vec3f(smul, 0.f, -smul),
		eSrc + Vec3f(smul, 0.f, smul),
		eSrc + Vec3f(-smul, 0.f, smul)
	};
	
	// top points
	Vec3f t[4] = {
		b[0] + Vec3f(0.f, -250 * ysize, 0.f),
		b[1] + Vec3f(0.f, -250 * ysize, 0.f),
		b[2] + Vec3f(0.f, -250 * ysize, 0.f),
		b[3] + Vec3f(0.f, -250 * ysize, 0.f)
	};
	
	fwrap -= 5.0f; // TODO ignores the frame delay
	while(fwrap < 0) {
		fwrap += 360;
	}
	
	RenderMaterial mat;
	mat.setTexture(tex_jelly);
	mat.setDepthTest(true);
	mat.setBlendType(RenderMaterial::Additive);
	
	RenderSubDivFace(b, b, 0, 1, 2, 3, mat);
	RenderSubDivFace(t, t, 0, 3, 2, 1, mat);
	RenderSubDivFace(b, t, 1, 0, 0, 1, mat);
	RenderSubDivFace(b, t, 3, 2, 2, 3, mat);
	RenderSubDivFace(b, t, 0, 3, 3, 0, mat);
	RenderSubDivFace(b, t, 2, 1, 1, 2, mat);
	
	EERIE_LIGHT * light = lightHandleGet(lLightId);
	if(light) {
		light->intensity = 0.7f + 2.3f * falpha;
		light->fallend = 500.f;
		light->fallstart = 400.f;
		light->rgb = Color3f(0.8f, 0.0f, 1.0f);
		light->pos = eSrc + Vec3f(0.f, -150.f, 0.f);
		light->duration = GameDurationMs(800);
	}
	
}
//////////////////////////////////////////////////////////////////////////
//! trimesh defined by filenode will be loaded
//////////////////////////////////////////////////////////////////////////
void buildTriMesh(void)
{
    //NodePtr tri = makeTorus(0.5, 1.0, 24, 12);
    //NodePtr tri = makeBox(10.0, 10.0, 10.0, 1, 1, 1);
    NodePtr tri = Node::Ptr::dcast(TriGeometryBase->shallowCopy());
    if(tri!=NullFC)
    {
        GeometryPtr triGeo = GeometryPtr::dcast(tri->getCore()); 
        Matrix m;
        SimpleMaterialPtr tri_mat = SimpleMaterial::create();
        beginEditCP(tri_mat);
        tri_mat->setAmbient(Color3f(0.1,0.1,0.2));
        tri_mat->setDiffuse(Color3f(1.0,0.1,0.7));
        endEditCP(tri_mat);
        triGeo->setMaterial(tri_mat);
        TransformPtr triTrans;
        NodePtr triTransNode = makeCoredNode<Transform>(&triTrans);
        m.setIdentity();
        Real32 randX = frand()*10.0-5.0;
        Real32 randY = frand()*10.0-5.0;
        m.setTranslate(randX, randY, 18.0);
        triTrans->setMatrix(m);

        //create ODE data
        Vec3f GeometryBounds(calcMinGeometryBounds(triGeo));
        PhysicsBodyPtr triBody = PhysicsBody::create(physicsWorld);
        beginEditCP(triBody, PhysicsBody::PositionFieldMask | PhysicsBody::LinearDampingFieldMask | PhysicsBody::AngularDampingFieldMask);
            triBody->setPosition(Vec3f(randX, randY, 18.0));
            triBody->setLinearDamping(0.0001);
            triBody->setAngularDamping(0.0001);
        endEditCP(triBody, PhysicsBody::PositionFieldMask | PhysicsBody::LinearDampingFieldMask | PhysicsBody::AngularDampingFieldMask);
            triBody->setBoxMass(1.0,GeometryBounds.x(), GeometryBounds.y(), GeometryBounds.z());
        PhysicsGeomPtr triGeom;
        if(true)
        {
            triGeom = PhysicsTriMeshGeom::create();
            beginEditCP(triGeom, PhysicsTriMeshGeom::BodyFieldMask | 
                            PhysicsTriMeshGeom::SpaceFieldMask | 
                            PhysicsTriMeshGeom::GeometryNodeFieldMask);
                triGeom->setBody(triBody);
                //add geom to space for collision
                triGeom->setSpace(physicsSpace);
                //set the geometryNode to fill the ode-triMesh
                PhysicsTriMeshGeom::Ptr::dcast(triGeom)->setGeometryNode(tri);
            endEditCP(triGeom, PhysicsTriMeshGeom::BodyFieldMask | 
                            PhysicsTriMeshGeom::SpaceFieldMask | 
                            PhysicsTriMeshGeom::GeometryNodeFieldMask);
        }
        else
        {

            triGeom = PhysicsBoxGeom::create();
            beginEditCP(triGeom, PhysicsBoxGeom::BodyFieldMask | PhysicsBoxGeom::SpaceFieldMask | PhysicsBoxGeom::LengthsFieldMask);
                triGeom->setBody(triBody);
                triGeom->setSpace(physicsSpace);
                PhysicsBoxGeom::Ptr::dcast(triGeom)->setLengths(GeometryBounds);

            endEditCP(triGeom, PhysicsBoxGeom::BodyFieldMask | PhysicsBoxGeom::SpaceFieldMask | PhysicsBoxGeom::LengthsFieldMask);
        }
        beginEditCP(triGeom, PhysicsGeom::CategoryBitsFieldMask);
            triGeom->setCategoryBits(TriCategory);
        endEditCP(triGeom, PhysicsGeom::CategoryBitsFieldMask);
        
        //add attachments
        tri->addAttachment(triGeom);
        triTransNode->addAttachment(triBody);
        //add to SceneGraph
        triTransNode->addChild(tri);
        spaceGroupNode->addChild(triTransNode);
    }
    else
    {
        SLOG << "Could not read MeshData!" << endLog;
    }
}
Vec3f toVec3f( const Leap::Vector& v )
{
	return Vec3f( v.x, v.y, v.z );
}
Example #23
0
const Vec3f Cylinder::AngularDirection() const
{
	return Vec3f(m_hcs[0].Data());
}
Example #24
0
Vec3f Nova::getInfoColor(void) const
{
	return Vec3f(1.0, 1.0, 1.0);
}
Example #25
0
bool EERIECreateSprite(TexturedQuad& sprite, const Vec3f & in, float siz, Color color, float Zpos, float rot = 0) {

	TexturedVertex out;
	EE_RTP(in, &out);
	out.rhw *= 3000.f;

	if(   out.p.z > 0.f
	   && out.p.z < 1000.f
	   && out.p.x > -1000.f
	   && out.p.x < 2500.f
	   && out.p.y > -500.f
	   && out.p.y < 1800.f
	) {
		float use_focal=BASICFOCAL*g_sizeRatio.x;
		float t;

		if(siz < 0) {
			t = -siz;
		} else {
			t = siz * ((out.rhw-1.f)*use_focal*0.001f);

			if(t <= 0.f)
				t = 0.00000001f;
		}
		
		if(Zpos <= 1.f) {
			out.p.z = Zpos;
			out.rhw = 1.f - out.p.z;
		} else {
			out.rhw *= (1.f/3000.f);
		}		
		
		ColorRGBA col = color.toRGBA();
		
		sprite.v[0] = TexturedVertex(Vec3f(), out.rhw, col, Vec2f_ZERO);
		sprite.v[1] = TexturedVertex(Vec3f(), out.rhw, col, Vec2f_X_AXIS);
		sprite.v[2] = TexturedVertex(Vec3f(), out.rhw, col, Vec2f(1.f, 1.f));
		sprite.v[3] = TexturedVertex(Vec3f(), out.rhw, col, Vec2f_Y_AXIS);
		
		if(rot == 0) {
			Vec3f maxs = out.p + t;
			Vec3f mins = out.p - t;

			sprite.v[0].p = Vec3f(mins.x, mins.y, out.p.z);
			sprite.v[1].p = Vec3f(maxs.x, mins.y, out.p.z);
			sprite.v[2].p = Vec3f(maxs.x, maxs.y, out.p.z);
			sprite.v[3].p = Vec3f(mins.x, maxs.y, out.p.z);
		} else {
			for(long i=0;i<4;i++) {
				float tt = glm::radians(MAKEANGLE(rot+90.f*i+45+90));
				sprite.v[i].p.x = std::sin(tt) * t + out.p.x;
				sprite.v[i].p.y = std::cos(tt) * t + out.p.y;
				sprite.v[i].p.z = out.p.z;
			}
		}

		return true;
	}

	return false;
}
void ShowInfoText() {
	
	DebugBox frameInfo = DebugBox(Vec2i(10, 10), "FrameInfo");
	frameInfo.add("Prims", EERIEDrawnPolys);
	frameInfo.add("Particles", getParticleCount());
	frameInfo.add("Polybooms", long(polyboom.size()));
	frameInfo.add("TIME", static_cast<long>(arxtime.now_ul() / 1000));
	frameInfo.print();
	
	DebugBox playerBox = DebugBox(Vec2i(10, frameInfo.size().y + 5), "Player");
	playerBox.add("Position", player.pos);
	playerBox.add("AnchorPos", player.pos - Mscenepos);
	playerBox.add("Rotation", player.angle);
	playerBox.add("Velocity", player.physics.velocity);
	
	EERIEPOLY * ep = CheckInPoly(player.pos);
	float truePolyY = -666.66f;
	if(ep) {
		float tempY = 0.f;
		if(GetTruePolyY(ep, player.pos, &tempY)) {
			truePolyY = tempY;
		}
	}
	
	ep = CheckInPoly(player.pos + Vec3f(0.f, -10.f, 0.f));
	float slope = 0.f;
	if(ep)
		slope = ep->norm.y;
	
	long zap = IsAnyPolyThere(player.pos.x,player.pos.z);
	
	playerBox.add("Ground Slope", slope);
	playerBox.add("Ground truePolyY", truePolyY);
	playerBox.add("Ground POLY", zap);
	playerBox.add("Color", CURRENT_PLAYER_COLOR);
	playerBox.add("Stealth", GetPlayerStealth());
	
	playerBox.add("Jump", player.jumplastposition);
	playerBox.add("OFFGRND", (!player.onfirmground ? "OFFGRND" : ""));
	
	playerBox.add("Life", player.lifePool);
	playerBox.add("Mana", player.manaPool);
	playerBox.add("Poisoned", player.poison);
	playerBox.add("Hunger", player.hunger);
	playerBox.add("Magic", static_cast<long>(player.doingmagic));
	playerBox.print();
	
	DebugBox miscBox = DebugBox(Vec2i(10, playerBox.size().y + 5), "Misc");
	miscBox.add("Arx version", arx_version);
	miscBox.add("Level", LastLoadedScene.string().c_str());
	miscBox.add("Spell failed seq", LAST_FAILED_SEQUENCE.c_str());
	miscBox.add("Camera focal", ACTIVECAM->focal);
	miscBox.add("Cinema", CINEMA_DECAL);
	miscBox.add("Mouse", Vec2i(DANAEMouse));
	miscBox.add("Pathfind queue", EERIE_PATHFINDER_Get_Queued_Number());
	miscBox.add("Pathfind status", (PATHFINDER_WORKING ? "Working" : "Idled"));
	miscBox.print();
	
	{
	struct ScriptDebugReport {
		std::string entityName;
		long events;
		long sends;
		
		ScriptDebugReport()
			: entityName("")
			, events(0)
			, sends(0)
		{}
	};
	
	ScriptDebugReport maxEvents;
	Entity * io = ARX_SCRIPT_Get_IO_Max_Events();
	if(io) {
		maxEvents.entityName = io->idString();
		maxEvents.events = io->stat_count;
	}
	
	ScriptDebugReport maxSender;
	io = ARX_SCRIPT_Get_IO_Max_Events_Sent();
	if(io) {
		maxSender.entityName = io->idString();
		maxSender.sends = io->stat_sent;
	}
	
	DebugBox scriptBox = DebugBox(Vec2i(10, miscBox.size().y + 5), "Script");
	scriptBox.add("Events", ScriptEvent::totalCount);
	scriptBox.add("Timers", ARX_SCRIPT_CountTimers());
	scriptBox.add("Max events", maxEvents.entityName);
	scriptBox.add("Max events#", maxEvents.events);
	scriptBox.add("Max sender", maxSender.entityName);
	scriptBox.add("Max sender#", maxSender.sends);
	scriptBox.print();
	}
	
	if(ValidIONum(LastSelectedIONum)) {
		Entity * io = entities[LastSelectedIONum];

		if(io) {
			DebugBox entityBox = DebugBox(Vec2i(500, 10), "Entity " + io->idString());
			entityBox.add("Pos", io->pos);
			entityBox.add("Angle", io->angle);
			entityBox.add("Room", static_cast<long>(io->room));
			entityBox.add("Move", io->move);
			entityBox.add("Flags", flagNames(EntityFlagNames, io->ioflags));
			entityBox.add("Show", entityVisilibityToString(io->show));
			entityBox.print();
			
			if(io->ioflags & IO_NPC) {
				IO_NPCDATA * npcData = io->_npcdata;
				
				DebugBox npcBox = DebugBox(Vec2i(500, entityBox.size().y + 5), "NPC");
				npcBox.add("Life", npcData->lifePool);
				npcBox.add("Mana", npcData->manaPool);
				npcBox.add("Poisoned", npcData->poisonned);
				npcBox.add("ArmorClass", ARX_INTERACTIVE_GetArmorClass(io));
				npcBox.add("Absorb", npcData->absorb);
				
				npcBox.add("Moveproblem", npcData->moveproblem);
				npcBox.add("Pathfind listpos", static_cast<long>(npcData->pathfind.listpos));
				npcBox.add("Pathfind listnb", npcData->pathfind.listnb);
				npcBox.add("Pathfind targ", npcData->pathfind.truetarget.handleData());
				npcBox.add("Behavior", flagNames(BehaviourFlagNames, npcData->behavior));
				
				// TODO should those really be flags ?
				PathfindFlags pflag = io->_npcdata->pathfind.flags;
				std::string pflags;
				if(pflag & PATHFIND_ALWAYS)    pflags += "ALWAYS ";
				if(pflag & PATHFIND_ONCE)      pflags += "ONCE ";
				if(pflag & PATHFIND_NO_UPDATE) pflags += "NO_UPDATE ";
				npcBox.add("Pathfind flgs", pflags);
				
				npcBox.print();
			}

			if(io->ioflags & (IO_FIX | IO_ITEM)) {
				DebugBox itemBox = DebugBox(Vec2i(500, entityBox.size().y + 5), "Item");
				
				itemBox.add("Durability", io->durability);
				itemBox.add("Durability max", io->max_durability);
				itemBox.add("Poisonous", static_cast<long>(io->poisonous));
				itemBox.add("Poisonous count", static_cast<long>(io->poisonous_count));
				itemBox.print();
			}
		}
	}
	
	ARX_SCRIPT_Init_Event_Stats();
}
Example #27
0
Vec3f Physics3DContactTest::get_hit_normal(int index) const
{
	btVector3 &v = impl->contacts[index].hit_normal;
	return Vec3f(v.x(), v.y(), v.z());
}
Example #28
0
	TorusExample(void)
	 : make_torus()
	 , torus_instr(make_torus.Instructions())
	 , torus_indices(make_torus.Indices())
	{
		// Set the vertex shader source
		vs.Source(
			"#version 150\n"
			"uniform mat4 ProjectionMatrix, CameraMatrix;"
			"in vec4 Position;"
			"in vec3 Normal;"
			"in vec3 Color;"
			"out vec3 vertColor;"
			"out vec3 vertNormal;"
			"out vec3 vertViewDir;"
			"void main(void)"
			"{"
			"	vertColor = normalize(vec3(1,1,1)-Color);"
			"	vertNormal = Normal;"
			"	vertViewDir = ("
			"		vec4(0.0, 0.0, 1.0, 1.0)*"
			"		CameraMatrix"
			"	).xyz;"
			"	gl_Position = "
			"		ProjectionMatrix *"
			"		CameraMatrix *"
			"		Position;"
			"}"
		);
		// compile it
		vs.Compile();

		// set the fragment shader source
		fs.Source(
			"#version 150\n"
			"in vec3 vertColor;"
			"in vec3 vertNormal;"
			"in vec3 vertViewDir;"
			"out vec4 fragColor;"
			"uniform vec3 LightPos[3];"
			"void main(void)"
			"{"
			"	float amb = 0.2;"
			"	float diff = 0.0;"
			"	float spec = 0.0;"
			"	for(int i=0;i!=3;++i)"
			"	{"
			"		diff += max("
			"			dot(vertNormal,  LightPos[i])/"
			"			dot(LightPos[i], LightPos[i]),"
			"			0.0"
			"		);"
			"		float k = dot(vertNormal, LightPos[i]);"
			"		vec3 r = 2.0*k*vertNormal - LightPos[i];"
			"		spec += pow(max("
			"			dot(normalize(r), vertViewDir),"
			"			0.0"
			"		), 32.0 * dot(r, r));"
			"	}"
			"	fragColor = "
			"		vec4(vertColor, 1.0)*(amb+diff)+"
			"		vec4(1.0, 1.0, 1.0, 1.0)*spec;"
			"}"
		);
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		// bind the VAO for the torus
		torus.Bind();

		// bind the VBO for the torus vertex positions
		positions.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_torus.Positions(data);
			// upload the data
			Buffer::Data(Buffer::Target::Array, data);
			// setup the vertex attribs array for the vertices
			VertexArrayAttrib attr(prog, "Position");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// bind the VBO for the torus normals
		normals.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_torus.Normals(data);
			// upload the data
			Buffer::Data(Buffer::Target::Array, data);
			// setup the vertex attribs array for the vertices
			VertexArrayAttrib attr(prog, "Normal");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// bind the VBO for the torus colors
		colors.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_torus.Tangents(data);
			// upload the data
			Buffer::Data(Buffer::Target::Array, data);
			// setup the vertex attribs array for the vertices
			VertexArrayAttrib attr(prog, "Color");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// set the light positions
		Uniform<Vec3f> light_pos(prog, "LightPos");
		light_pos[0].Set(Vec3f(2.0f,-1.0f, 0.0f));
		light_pos[1].Set(Vec3f(0.0f, 3.0f,-1.0f));
		light_pos[2].Set(Vec3f(0.0f,-1.0f, 4.0f));
		//
		gl.ClearColor(0.8f, 0.8f, 0.7f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);
		gl.Enable(Capability::CullFace);
		gl.FrontFace(make_torus.FaceWinding());
		gl.CullFace(Face::Back);
	}
Example #29
0
File: BBox.cpp Project: janba/GEL
/*

bool BBox::intersect_triangle_left(ISectTri &tri, double plane, int axis) {
	if (tri.point0[axis]<=plane)
		return true;
	if (tri.point1[axis]<=plane)
		return true;
	if (tri.point2[axis]<=plane)
		return true;
	return false;
}

bool BBox::intersect_triangle_right(ISectTri &tri, double plane, int axis) {
	if (tri.point0[axis]>=plane)
		return true;
	if (tri.point1[axis]>=plane)
		return true;
	if (tri.point2[axis]>=plane)
		return true;
	return false;
}
*/
  bool BBox::intersect_triangle(ISectTri &tri) 
  {
    Vec3f tmin_corner = min_corner - Vec3f(f_eps);
    Vec3f tmax_corner = max_corner + Vec3f(f_eps);

    // Vertex in box test:
    // If any of the triangle vertices are inside the box then 
    // the triangle intersects the box
    if (in_interval(tmin_corner[0],tri.point0[0],tmax_corner[0]) && in_interval(tmin_corner[1],tri.point0[1],tmax_corner[1]) && in_interval(tmin_corner[2],tri.point0[2],tmax_corner[2]))
      return true;
    if (in_interval(tmin_corner[0],tri.point1[0],tmax_corner[0]) && in_interval(tmin_corner[1],tri.point1[1],tmax_corner[1]) && in_interval(tmin_corner[2],tri.point1[2],tmax_corner[2]))
      return true;
    if (in_interval(tmin_corner[0],tri.point2[0],tmax_corner[0]) && in_interval(tmin_corner[1],tri.point2[1],tmax_corner[1]) && in_interval(tmin_corner[2],tri.point2[2],tmax_corner[2]))
      return true;

    // Triangle outside box test:
    // If all of the triangle vertices are outside one of the planes 
    // defining the sides of the box then the triangle can be trivially
    // rejected as outside
    int i;
    for(i=0;i<3;i++)
      if (tri.point0[i]<tmin_corner[i] && tri.point1[i]<tmin_corner[i] && tri.point2[i]<tmin_corner[i])
	return false;
    
    for(i=0;i<3;i++)
      if (tri.point0[i]>tmax_corner[i] && tri.point1[i]>tmax_corner[i] && tri.point2[i]>tmax_corner[i])
	return false;

    // Triangle edges - box intersection test
    if (intersect_edge_box(tri.point0, tri.point1))
      return true;
		
    if (intersect_edge_box(tri.point1, tri.point2))
      return true;

    if (intersect_edge_box(tri.point2, tri.point0))
      return true;

    // Box diagonal - triangle intersection test, 4 tests in total
    Vec3f corner0;
    Vec3f corner1;

    Vec3f tmin_corner_e = tmin_corner;
    Vec3f tmax_corner_e = tmax_corner;

    corner0.set(tmin_corner_e[0],tmin_corner_e[1],tmin_corner_e[2]);
    corner1.set(tmax_corner_e[0],tmax_corner_e[1],tmax_corner_e[2]);
    if (ray_triangle(corner0, corner1, tri))
      return true;

    corner0.set(tmax_corner_e[0],tmin_corner_e[1],tmin_corner_e[2]);
    corner1.set(tmin_corner_e[0],tmax_corner_e[1],tmax_corner_e[2]);
    if (ray_triangle(corner0, corner1, tri))
      return true;

    corner0.set(tmin_corner_e[0],tmax_corner_e[1],tmin_corner_e[2]);
    corner1.set(tmax_corner_e[0],tmin_corner_e[1],tmax_corner_e[2]);
    if (ray_triangle(corner0, corner1, tri))
      return true;

    corner0.set(tmin_corner_e[0],tmin_corner_e[1],tmax_corner_e[2]);
    corner1.set(tmax_corner_e[0],tmax_corner_e[1],tmin_corner_e[2]);
    if (ray_triangle(corner0, corner1, tri))
      return true;

    // None succeded 
    return false;
  }
Example #30
0
void ShapeDetection::onDepth( openni::VideoFrameRef frame, const OpenNI::DeviceOptions& deviceOptions )
{
    // convert frame from the camera to an OpenCV matrix
    mInput = toOcv( OpenNI::toChannel16u(frame) );
    
    cv::Mat thresh;
    cv::Mat eightBit;
    cv::Mat withoutBlack;
    
    // remove black pixels from frame which get detected as noise
    withoutBlack = removeBlack( mInput, mNearLimit, mFarLimit );
    
    // convert matrix from 16 bit to 8 bit with some color compensation
    withoutBlack.convertTo( eightBit, CV_8UC3, 0.1/1.0 );
    
    // invert the image
    cv::bitwise_not( eightBit, eightBit );
    
    mContours.clear();
    mApproxContours.clear();
    
    // using a threshold to reduce noise
    cv::threshold( eightBit, thresh, mThresh, mMaxVal, CV_8U );
    
    // draw lines around shapes
    cv::findContours( thresh, mContours, mHierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE );
    
    vector<cv::Point> approx;
    // approx number of points per contour
    for ( int i = 0; i < mContours.size(); i++ ) {
        cv::approxPolyDP(mContours[i], approx, 1, true );
        mApproxContours.push_back( approx );
    }
    
    mShapes.clear();
    // get data that we can later compare
    mShapes = getEvaluationSet( mApproxContours, 75, 100000 );
    
    // find the nearest match for each shape
    for ( int i = 0; i < mTrackedShapes.size(); i++ ) {
        Shape* nearestShape = findNearestMatch( mTrackedShapes[i], mShapes, 5000 );
        
        // a tracked shape was found, update that tracked shape with the new shape
        if ( nearestShape != NULL ) {
            nearestShape->matchFound = true;
            mTrackedShapes[i].centroid = nearestShape->centroid;
            // get depth value from center point
            float centerDepth = (float)mInput.at<short>( mTrackedShapes[i].centroid.y, mTrackedShapes[i].centroid.x );
            // map 10 10000 to 0 1
            mTrackedShapes[i].depth = lmap( centerDepth, (float)mNearLimit, (float)mFarLimit, 0.0f, 1.0f );
            mTrackedShapes[i].lastFrameSeen = ci::app::getElapsedFrames();
            mTrackedShapes[i].hull.clear();
            mTrackedShapes[i].hull = nearestShape->hull;
            mTrackedShapes[i].motion = nearestShape->motion;
            Vec3f centerVec = Vec3f( mTrackedShapes[i].centroid.x, mTrackedShapes[i].centroid.y, 0.0f );
            mTrackedShapes[i].mTrailPoint.arrive(centerVec);
            mTrackedShapes[i].mTrailPoint.updateTrail();
        }
    }
    
    // if shape->matchFound is false, add it as a new shape
    for ( int i = 0; i < mShapes.size(); i++ ) {
        if( mShapes[i].matchFound == false ){
            // assign an unique ID
            mShapes[i].ID = shapeUID;
            mShapes[i].lastFrameSeen = ci::app::getElapsedFrames();
            // starting point of the trail
            mShapes[i].mTrailPoint.mLocation = Vec3f( mShapes[i].centroid.x, mShapes[i].centroid.y, 0.0f );
            // add this new shape to tracked shapes
            mTrackedShapes.push_back( mShapes[i] );
            shapeUID++;
        }
    }
    
    // if we didn't find a match for x frames, delete the tracked shape
    for ( vector<Shape>::iterator it = mTrackedShapes.begin(); it != mTrackedShapes.end(); ) {
        if ( ci::app::getElapsedFrames() - it->lastFrameSeen > 20 ) {
            // remove the tracked shape
            it = mTrackedShapes.erase(it);
        } else {
            ++it;
        }
    }
    mSurfaceDepth = Surface8u( fromOcv( mInput  ) );
    mSurfaceSubtract = Surface8u( fromOcv(eightBit) );
}