コード例 #1
0
ファイル: EnemyShip.cpp プロジェクト: pokelege/GeometryWars
bool EnemyShip::Update(const float& dt, bool& warp, ParticleSystem& Psystem, BulletSystem& Bsystem, Spaceship* target, Walls& walls)
{
	changeTarget(target);
	turret.update(dt, shipPosition, Bsystem, (rand.RandomFloat() < 0.1));
	outofBoundsCheck(Psystem, warp);
	changeVelocity(dt, Psystem);

	Vector2 collision = walls.getCollisionVelocity(shipPosition, velocity);

	if (Engine::LengthSquared(collision) != 0)
	{
		Psystem.AddParticle(new COLLISIONPARTICLE);
	}

	velocity = velocity + collision;
	shipPosition = shipPosition + velocity;
	return (life > 0);
}
コード例 #2
0
ファイル: CCParticleBatchNode.cpp プロジェクト: CryQ/coclua
void ParticleBatchNode::addChild(Node * aChild, int zOrder, int tag)
{
    CCASSERT( aChild != NULL, "Argument must be non-NULL");
    CCASSERT( dynamic_cast<ParticleSystem*>(aChild) != NULL, "CCParticleBatchNode only supports QuadParticleSystems as children");
    ParticleSystem* child = static_cast<ParticleSystem*>(aChild);
    CCASSERT( child->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "CCParticleSystem is not using the same texture id");
    // If this is the 1st children, then copy blending function
    if( _children->count() == 0 ) 
    {
        setBlendFunc(child->getBlendFunc());
    }

    CCASSERT( _blendFunc.src  == child->getBlendFunc().src && _blendFunc.dst  == child->getBlendFunc().dst, "Can't add a PaticleSystem that uses a different blending function");

    //no lazy sorting, so don't call super addChild, call helper instead
    unsigned int pos = addChildHelper(child,zOrder,tag);

    //get new atlasIndex
    int atlasIndex = 0;

    if (pos != 0) 
    {
        ParticleSystem* p = (ParticleSystem*)_children->getObjectAtIndex(pos-1);
        atlasIndex = p->getAtlasIndex() + p->getTotalParticles();

    }
    else
    {
        atlasIndex = 0;
    }

    insertChild(child, atlasIndex);

    // update quad info
    child->setBatchNode(this);
}
コード例 #3
0
bool ParticleSystem::DxDt(double t, nvectord &x, nvectord &xdot, void *userData)
{
    ParticleSystem *pThis = static_cast<ParticleSystem *>(userData);
    assert(pThis);
        
    // Put data in x[] into particles
    pThis->ParticlesArrayToState(&x[0]);
        
    pThis->ClearForces();

    // evaluate all forces
    pThis->ApplyRegularForces();
    pThis->ApplyDragForces();
    pThis->ApplyConstraintForces();

    pThis->LimitStateChanges();

    pThis->DdtParticlesStateToArray(&xdot[0]);

    return false;
}
コード例 #4
0
ファイル: partTest2.cpp プロジェクト: C-Compton/OpenGL
// Initialization: load and compile shaders, initialize camera(s), load models.
void init() {
  
  GLuint particleSystemShader;
  Screen *primScreen = Engine::instance()->mainScreen();
  Scene *rootScene = Engine::instance()->rootScene();
  
  particleSystemShader = Angel::InitShader( "shaders/vParticle2.glsl",
                                            "shaders/fParticle2.glsl",
                                            "shaders/gParticle.glsl",//"shaders/gParticle.glsl",
      GL_TRIANGLES, GL_TRIANGLE_STRIP, 12 );
  
  rootScene->shader( particleSystemShader );
  primScreen->_camList.shader( particleSystemShader );
  
  {
    ParticleSystem *particleSystem = new ParticleSystem( numberOfParticles, 
							 "emitter", 
							 particleSystemShader );

    particleSystem->setLifespan(8.0, 16.0);
    //particleSystem->setVectorField( ParticleFieldFunctions::userSupplied ) ;
    particleSystem->setVectorField( ParticleFieldFunctions::flame );
    particleSystem->setColorFunc( ColorFunctions::flame ) ;
    particleSystem->setEmitterRadius( 0.04 ) ;
    particleSystem->setEmitterShape(PS_HEMI_D);
    particleSystem->drawMode( GL_TRIANGLES ) ; // NEED THIS IF WE USE A GEOMETRY SHADER!
    //particleSystem->setSlaughterHeight(0.2455);
    //particleSystem->_trans._displacement.set(0.0, 0.25, 0.0);
    //particleSystem->_trans._offset.set( 0.0, 0.2, 0.0 );
    particleSystem->propagateOLD();
    //particleSystem->fillSystemWithParticles();
    rootScene->insertObject( particleSystem );
    // PARTICLE SYSTEMS buffer() THEMSELVES
  }
  
  glClearColor( 0.0, 0.0, 0.0, 1.0 );
  // if not using geo shader, we need this to render visible points
  // glPointSize( 1.1 );
}
コード例 #5
0
void Fluid2DParticlesApp::draw()
{
    // clear out the window with black
    gl::clear( Color( 0, 0, 0 ) );

    gl::color( ColorAf( 1.0f, 1.0f, 1.0f, 0.999f ) );
    float* data = const_cast<float*>( (float*)mFluid2D.rgb().data() );
    Surface32f surf( data, mFluid2D.resX(), mFluid2D.resY(), mFluid2D.resX()*sizeof(Colorf), SurfaceChannelOrder::RGB );


    if ( ! mTex ) {
        mTex = gl::Texture::create( surf );
    } else {
        mTex->update( surf );
    }
    gl::draw( mTex, getWindowBounds() );
    mTex->unbind();
    mParticles.draw();
    mParams.draw();
}
コード例 #6
0
ファイル: ex1.cpp プロジェクト: rd3k/WaterSprinkler
void loadOptions (Options opts) {
	currentCamera = opts.currentCamera;
	cameraAngle = opts.cameraAngle;
	cameraElevation = opts.cameraElevation;
	cameraDistance = opts.cameraDistance;
	Particle::initialVelocity = opts.initialVelocity;
	gravityIntensity = opts.gravityIntensity;
	Particle::startLifeSpan = opts.startLifeSpan;
	renderMode = opts.renderMode;
	Particle::renderMode = (PARTICLERENDERMODE)renderMode;
	emitterCount = opts.emitterCount;
	emitterSpacing = opts.emitterSpacing;
	Particle::airResistance = opts.airResistance;
	emitFrequency = opts.emitFrequency;
	particleSystem.setEmitTicks(emitFrequency);
	ParticleEmitter::emitSpread = opts.emitSpread;
	ParticleSystem::perEmit = opts.perEmit;
	ParticleEmitter::show = opts.showEmitters;
	wireframe = opts.wireframe;
	makeSprinkler();
}
コード例 #7
0
ファイル: SampleParticles.cpp プロジェクト: akurt5/AIEShit
void SampleParticles::createParticleSystems()
{
	// create waterfall fluid
	{
		PxParticleFluid* px_fluid = createFluid(mFluidParticleCount, 0.3f, 60.0f, 45.0f, 0.001f, 0.8f);
		px_fluid->setSimulationFilterData(collisionGroupWaterfall);
		// This will be deleted by RenderParticleSystemActor
		ParticleSystem* fluid = SAMPLE_NEW(ParticleSystem)(px_fluid);
		mWaterfallParticleSystem = SAMPLE_NEW(RenderParticleSystemActor)(*getRenderer(), fluid, false);
		mWaterfallParticleSystem->setRenderMaterial(getMaterial(MATERIAL_WATERFALL));
		addRenderParticleSystemActor(*mWaterfallParticleSystem);
	}

	// create smoke particle system
	{
		PxParticleBase* px_ps = createParticleSystem(mSmokeParticleCount);
		px_ps->setDamping(0.5f);
		px_ps->setRestitution(0.0f);
		px_ps->setDynamicFriction(0.0f);
		px_ps->setExternalAcceleration(PxVec3(0.0f, 17.0f, 0.0f));
		px_ps->setSimulationFilterData(collisionGroupSmoke);
		// This will be deleted by RenderParticleSystemActor
		ParticleSystem* ps = SAMPLE_NEW(ParticleSystem)(px_ps, false);
		ps->setUseLifetime(true);
		ps->setLifetime(mSmokeLifetime);
		mSmokeParticleSystem = SAMPLE_NEW(RenderParticleSystemActor)(*getRenderer(), ps, false, true, mSmokeLifetime*1.5f);
		mSmokeParticleSystem->setRenderMaterial(getMaterial(MATERIAL_SMOKE));
		addRenderParticleSystemActor(*mSmokeParticleSystem);
	}

	// create debris particle system
#if !defined(RENDERER_ENABLE_GLES2)
	{
		PxParticleBase* px_ps = createParticleSystem(mDebrisParticleCount);
		px_ps->setStaticFriction(10.0f);
		px_ps->setSimulationFilterData(collisionGroupDebris);
		// This will be deleted by RenderParticleSystemActor
		ParticleSystem* ps = SAMPLE_NEW(ParticleSystem)(px_ps, true);
		ps->setUseLifetime(true);
		ps->setLifetime(5.0f);
		mDebrisParticleSystem = SAMPLE_NEW(RenderParticleSystemActor)(*getRenderer(), ps, true, false, 4.0f, 0.3f);
		mDebrisParticleSystem->setRenderMaterial(getMaterial(MATERIAL_DEBRIS));
		addRenderParticleSystemActor(*mDebrisParticleSystem);
	}
#endif
}
コード例 #8
0
int main(int argc, char** argv) {
  pSystem = ParticleSystem(Vector(0,-9.8, 0));
  determineFunction(argc, argv);
  createParticles();
  pSystem.initialize(dt);
  // dont need this now that we have opengl.
  // but we can use this if we don't want to display...i guess
  /*for(float j = 0; j < totalTime; j+=dt) {*/
  //cout << "//===========================================//" << endl
  //<< "// totalTime: " << j << "                                 //" << endl
  //<< "//===========================================//" << endl;
  //pSystem.update(dt);
  /*}*/
  glutInit(&argc, argv);
  glutInitWindowSize(frameWidth, frameHeight);
  glutInitWindowPosition(0, 0);
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
  glutCreateWindow("CS184 Final");
  glClearColor(0.0, 0.0, 0.0, 1.0);
  glEnable(GL_POINT_SMOOTH);
  glHint(GL_POINT_SMOOTH_HINT, GL_FASTEST);
  glPointSize(5.0f);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glEnable(GL_BLEND);
  glutKeyboardFunc(keyboard);

  if (useCubes) {
      mesh = Mesh(32, 33, 18, 1.0, -1.0, .5, -1.5, .5, -.5);
	  glutDisplayFunc(displayFunc1);
	  glutIdleFunc(displayFunc1);
  } else {
	  glutDisplayFunc(displayFunc);
	  glutIdleFunc(displayFunc);
  }
  glutReshapeFunc(changeSize);
  glutMainLoop();
  return 0;
}
コード例 #9
0
void Fluid2DParticlesApp::mouseDrag( MouseEvent event )
{
    float x = (event.getX()/(float)getWindowWidth())*mFluid2D.resX();
    float y = (event.getY()/(float)getWindowHeight())*mFluid2D.resY();
    float s = 10;

    if( event.isLeftDown() ) {
        vec2 dv = vec2( event.getPos() ) - mPrevPos;
        mFluid2D.splatVelocity( x, y, mVelScale*dv );
        mFluid2D.splatRgb( x, y, mRgbScale*mColor );
        if( mFluid2D.isBuoyancyEnabled() ) {
            mFluid2D.splatDensity( x, y, mDenScale );
        }
        //
        for( int i = 0; i < 10; ++i ) {
            vec2 partPos = vec2( event.getPos() ) + vec2( Rand::randFloat( -s, s ), Rand::randFloat( -s, s ) );
            float life = Rand::randFloat( 2.0f, 4.0f );
            mParticles.append( Particle( partPos, life, mColor ) );
        }
    }

    mPrevPos = event.getPos();
}
コード例 #10
0
void msaFluidParticlesApp::setup()
{
	console() << "ciMSAFluid Demo | (c) 2009 Mehmet Akten | www.memo.tv" << std::endl;
	
	// setup fluid stuff
	fluidSolver.setup(100, 100);
    fluidSolver.enableRGB(true).setFadeSpeed(0.002).setDeltaT(0.5).setVisc(0.00015).setColorDiffusion(0);
	fluidDrawer.setup( &fluidSolver );
	particleSystem.setFluidSolver( &fluidSolver );
	
	fluidCellsX			= 150;
	
	drawFluid			= true;
	drawParticles		= true;
	renderUsingVA		= true;
	
	setFrameRate( 60.0f );
	
	pMouse = getWindowCenter();
	resizeFluid			= true;
	
	gl::enableAlphaBlending();
}
コード例 #11
0
ファイル: Particles.cpp プロジェクト: linuxbandit/Particles
void renderScene(){
        
    // Clear framebuffer & depth buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //where should the camera look at?
    cameraTransform();

    glDisable(GL_LIGHTING);//disable lighting not to affect the drawings of meta-objects

    drawAxes();

    drawGrid();

    glEnable(GL_LIGHTING);//resume lighting

    //WITH = All the light will NOT move with the camera (light fixed even if i rotate)
    //Because i tell at every frame to fix the light at those 2 points
    glLightfv(GL_LIGHT0, GL_POSITION, left_light_position);
    glLightfv(GL_LIGHT1, GL_POSITION, right_light_position);

    glColor3f(0.5,0.5,0.5);

    field.getCollisionPlane().draw(Vector3f(0.93, 0.82, 0)); //WTF only certain colors work. JK it's because number must be float.. then why tf there are some 255 every now and then (e.g. axes)


    glPushMatrix();
    glTranslatef(field.getBlackHoleCentre().x,field.getBlackHoleCentre().y,field.getBlackHoleCentre().z);
    glColor3f(0.7,0.5,0);
    glutSolidSphere(0.1f,4,4);
    glPopMatrix();

    field.draw();


    //TODO pause button
    field.update();
	
	glutSwapBuffers();
        
}
コード例 #12
0
ファイル: ParticleIO.cpp プロジェクト: ashleygwinnell/ark2d
		ParticleSystem* ParticleIO::loadConfiguredSystem(string ref, const Color& mask) {
			TiXmlDocument m_xmldocument(ref.c_str());
			bool loadOkay = m_xmldocument.LoadFile();
			if (!loadOkay) {
				ErrorDialog::createAndShow(StringUtil::append("Could not load Particle System: ", ref));
				exit(0);
			}

			ParticleSystem* sys = new ParticleSystem(new Image("data/particle.png", mask));

			TiXmlElement* rootelement = m_xmldocument.FirstChildElement("system");
			if (rootelement == NULL) {
				ErrorDialog::createAndShow(string("Invalid particle system file. Root node must be <system>."));
			}
			if (strcmp(rootelement->Attribute("additive"), "true") == 0) {
				sys->setBlendingMode(ParticleSystem::BLEND_ADDITIVE);
			} else {
				sys->setBlendingMode(ParticleSystem::BLEND_COMBINE);
			}

			const char* points = rootelement->Attribute("points");
			if (points != NULL) {
				sys->setUsePoints(strcmp(points, "true") == 0);
			}

			TiXmlElement* emitter = 0;
			for (emitter = rootelement->FirstChildElement("emitter");
					emitter;
					emitter = emitter->NextSiblingElement("emitter")) {
				ConfigurableEmitter* e = new ConfigurableEmitter("new");
				elementToEmitter(e, emitter);
				sys->addEmitter(e);
			}

			sys->setRemoveCompletedEmitters(false);
			return sys;
		}
コード例 #13
0
ファイル: ParticleFactory.cpp プロジェクト: brucelane/f2_Orbs
void ParticleFactory::create(const double elapsedSeconds, const Vec2f origin, const Listener& list, ParticleSystem & ps)
{
	ps.mUnderlays = 3;
	switch (d_particleToCreate)
	{
	
	case PARTICLE_A:{
		for (int i = 0; i < 3; ++i)
		{
			Particle* particle = new ParticleA(origin, list);
			particle->mOrientation = ps.mOrientation;
			ps.addParticle(particle);
		}
	}break;
	case PARTICLE_B:{
		Particle* particle = new ParticleB(origin, list);
			ps.addParticle(particle);
	}break;
	case PARTICLE_C:{
		Particle* particle = new ParticleC(origin, list);
			ps.addParticle(particle);
	}break;
	case PARTICLE_D:{
		for (int i = 0; i < (int)(list.getVolume()*20.f); ++i)
		{
			Particle* particle = new ParticleD(origin, list);
			ps.addParticle(particle);
		}
	}break;
	case PARTICLE_E:{
			Particle* particle = new ParticleE(origin, list);
			particle->mOrientation = ps.mOrientation;
			ps.addParticle(particle);
	}break;
	case PARTICLE_F:{
		for (int i = 0; i < 4; ++i)
		{
			Particle* particle = new ParticleF(origin, list);
			particle->mOrientation = ps.mOrientation;
			ps.addParticle(particle);
		}
	}break;
	case PARTICLE_G:{
			while (ps.mParticles.size() < 3)
			{
				Particle* particle = new ParticleG(origin, list);
				ps.addParticle(particle);
			}
	}break;
	case PARTICLE_H:{
		for (int i = 0; i < 4; ++i)
		{
			Particle* particle = new ParticleH(origin, list);
			ps.addParticle(particle);
		}
	}break;
	case PARTICLE_I:{
			Particle* particle = new ParticleI(origin, list);
			ps.addParticle(particle);
	}break;
	case PARTICLE_J:{
		Particle* particle = new ParticleJ(origin, list);
		ps.addParticle(particle);
	}break;
	case PARTICLE_K:{
		Particle* particle = new ParticleK(origin, list);
		ps.addParticle(particle);
	}break;
	case PARTICLE_L:{
		Particle* particle = new ParticleL(origin, list);
		ps.addParticle(particle);
	}break;
	case PARTICLE_M:{
		Particle* particle = new ParticleM(origin, list);
		particle->mOrientation = ps.mOrientation;
		ps.addParticle(particle);
		ps.mUnderlays = 1;
	}break;
	case PARTICLE_N:{
		Particle* particle = new ParticleN(origin, list);
		ps.addParticle(particle);
	}break;
	default:
		ci::app::console() << "UNKNOWN PARTICLE: " << d_particleToCreate;
		break;
	}
}
コード例 #14
0
ファイル: main.cpp プロジェクト: danepowell/openhaptics
// Handle menu commands
void HandleMenuCommand(int option)
{
	switch(option)
	{
		case 'de':
			mDesign = !mDesign;
			
			if (mDesign)
			{
				mPS.StartConstructingSystem();
			}
			else
			{
				mPS.FinishConstructingSystem();
			}
			break;
		
		case 'cs':
			if (!mDesign)
			{
				mDesign = true;
				mPS.StartConstructingSystem();
			}
			mPS.ClearSystem();
			break;
		
		case 'mp':
			mMode = designMode_Particle;
			break;

		case 'mn':
			mMode = designMode_Nail;
			break;

		case 'ms':
			mMode = designMode_Spring;
			break;
		
		case 'd':
			mSurfaceConditionsName = "Default";
			mSurface.SetAmbientColor( 0.0, 0.0, 1.0, 1.0 );
			mSurface.SetDiffuseColor( 0.0, 0.0, 1.0, 1.0 );
			mSurface.SetSpecularColor( 0.5, 0.5, 0.5, 0.5 );
			mSurface.SetShininess( 10.0 );
			mPS.gravity = 9.8;
			mPS.drag = 0.01;
			mPS.SetSpringConstant(5);
			mPS.SetSpringDampingConstant(1);
			mSurface.SetMassProportion(1); // proportional to numer of particles in x
			break;

		case 't':
			mSurfaceConditionsName = "Trampoline";
			mSurface.SetAmbientColor( 0.1, 0.1, 0.3, 1.0 );
			mSurface.SetDiffuseColor( 0.0, 0.0, 0.6, 1.0 );
			mSurface.SetSpecularColor( 0.5, 1.0, 1.0, 1.0 );
			mSurface.SetShininess( 70.0 );
			mPS.gravity = 9.8;
			mPS.drag = 0.001;
			mPS.SetSpringConstant(10);
			mPS.SetSpringDampingConstant(1);
			mSurface.SetMassProportion(0.5); // proportional to numer of particles in x
			break;

		case 'f':
			mSurfaceConditionsName = "Foam";
			mSurface.SetAmbientColor( 1.0, 1.0, 1.0, 1.0 );
			mSurface.SetDiffuseColor( 0.8, 0.8, 1.0, 1.0 );
			mSurface.SetShininess( 10.0 );
			mPS.gravity = 0.5;
			mPS.drag = 1.0;
			mPS.SetSpringConstant(1);
			mPS.SetSpringDampingConstant(1);
			mSurface.SetMassProportion(1); // proportional to numer of particles in x
			break;

		case 'c':
			mSurfaceConditionsName = "Clay";
			mSurface.SetAmbientColor( 0.6, 0.6, 0.4, 1.0 );
			mSurface.SetDiffuseColor( 0.3, 0.3, 0.2, 1.0 );
			mSurface.SetSpecularColor( 0.2, 0.2, 0.2, 1.0 );
			mSurface.SetShininess( 10.0 );
			mPS.gravity = 1.0;
			mPS.drag = 2.0;
			mPS.SetSpringConstant(0.5);
			mPS.SetSpringDampingConstant(1);
			mSurface.SetMassProportion(1); // proportional to numer of particles in x
			break;

		case 'j':
			mSurfaceConditionsName = "Jello";
			mSurface.SetAmbientColor( 1.0, 0.0, 0.0, 1.0 );
			mSurface.SetDiffuseColor( 1.0, 0.0, 0.0, 1.0 );
			mSurface.SetSpecularColor( 1.0, 1.0, 1.0, 1.0 );
			mSurface.SetShininess( 100.0 );
			mPS.gravity = 0;
			mPS.drag = 0.1;
			mPS.SetSpringConstant(10);
			mPS.SetSpringDampingConstant(2);
			mSurface.SetMassProportion(1); // proportional to numer of particles in x
			break;

		case 'w':
			mSurfaceConditionsName = "Waterbed";
			mSurface.SetAmbientColor( 0.4, 1.0, 0.2, 1.0 );
			mSurface.SetDiffuseColor( 0.1, 0.8, 0.5, 1.0 );
			mSurface.SetSpecularColor( 0.6, 0.6, 1.0, 1.0 );
			mSurface.SetShininess( 200.0 );
			mPS.gravity = 2;
			mPS.drag = 0.001;
			mPS.SetSpringConstant(1);
			mPS.SetSpringDampingConstant(1);
			mSurface.SetMassProportion(1); // proportional to numer of particles in x
			break;

		case '1':
			mSurfaceParticles = 3;
			ConstructSurface(mSurfaceParticles);
			break;

		case '2':
			mSurfaceParticles = 5;
			ConstructSurface(mSurfaceParticles);
			break;

		case '3':
			mSurfaceParticles = 10;
			ConstructSurface(mSurfaceParticles);
			break;

		case '4':
			mSurfaceParticles = 15;
			ConstructSurface(mSurfaceParticles);
			break;
		
		case '5':
			mSurfaceParticles = 20;
			ConstructSurface(mSurfaceParticles);
			break;
		
		case '6':
			mSurfaceParticles = 25;
			ConstructSurface(mSurfaceParticles);
			break;
		
		case '7':
			mSurfaceParticles = 30;
			ConstructSurface(mSurfaceParticles);
			break;
		
		case '8':
			mSurfaceParticles = 35;
			ConstructSurface(mSurfaceParticles);
			break;
		
		case '9':
			mSurfaceParticles = 40;
			ConstructSurface(mSurfaceParticles);
			break;
		
		case '0':
			mSurfaceParticles = 50;
			ConstructSurface(mSurfaceParticles);
			break;
		
		case 'n':
			mDrawNormals = !mDrawNormals;
			break;

		case 'i':
			mDrawInfo = (EDrawInfo)(mDrawInfo + 1);
			if (mDrawInfo >= drawInfo_PastEndOfList)
				mDrawInfo = drawInfo_StartOfList;
			break;

		case 's':
			mDrawSurface = !mDrawSurface;
			mPS.useDepthForMouseZ = mDrawSurface;
			break;

		case 'p':
			mDrawSystem = !mDrawSystem;
			break;

		case 'm':
			if (mPause)
				AdvanceTime(mManualTimeStep);
			break;

		case 'x':
			mUseFixedTimeStep = !mUseFixedTimeStep;
			break;
			
		case ' ':
			mPause = !mPause;
			break;

		case 'q':		// quit
			exit(0);
			break;

		default:
			//printf("Invalid menu choice: %c", option);
			break;
	}
}
コード例 #15
0
ファイル: main.cpp プロジェクト: danepowell/openhaptics
/*
 	Function:	HandleMouseButton
 	Usage:		HandleMouseButton(button, state, x, y);
 	---------------------------------------------------------------------------
	mouse press/release handler
	  
	   left button:		
	   		simulating:	pull at particle
	   		designing:	add particle/constraint
	   		
	   middle button:	unused
	   right button:	unused (mapped to pull-down menu)
*/
void HandleMouseButton(int button, int state, int x, int y)
{
	int part;	// index of a particle
	
	if (mDesign)
	{
		if (button == GLUT_LEFT_BUTTON)
		{
			switch (state)
			{
				case GLUT_DOWN:
					switch (mMode)
					{
						case designMode_Particle:
							mPS.AddParticle(x,y);
							break;
						case designMode_Nail:
							if ((part = mPS.GetClosestParticle(x, y)) != -1)
								mPS.AddNailConstraint(part);
							break;
						case designMode_Spring:
							if ((part = mPS.GetClosestParticle(x, y)) != -1)
								mCurrSpringConstraint = mPS.AddSpringConstraint(part, part);
							break;
					}
					break;

				case GLUT_UP:
					switch (mMode)
					{
						case designMode_Spring:
							if (mCurrSpringConstraint != NULL)
							{
								if ((part = mPS.GetClosestParticle(x, y)) != -1)
								{
									mCurrSpringConstraint->SetParticle(part);
									
									if (mCurrSpringConstraint->ParticlesAreValid())
									{
										// keep the constraint
									}
									else
									{
										mPS.DeleteConstraint(mCurrSpringConstraint);
									}
								}
								else
								{
									mPS.DeleteConstraint(mCurrSpringConstraint);
								}
								
								mCurrSpringConstraint = NULL;
							}
							break;
					}
					break;
			}
		}    
		else if (button == GLUT_MIDDLE_BUTTON)
		{ 
			switch (state)
			{
				case GLUT_DOWN:
					break;
				case GLUT_UP:
					break;
			}
		}
	}
	else
	{
		if (button == GLUT_LEFT_BUTTON)
		{
			switch (state)
			{
				case GLUT_DOWN:
					mPS.ActivateMouseSpring(x, y);
					break;

				case GLUT_UP:
					mPS.DeactivateMouseSpring();
					break;
			}
		}    
	}
}
コード例 #16
0
ファイル: main.cpp プロジェクト: MaikKlein/GeKo
int main()
{
	glfwInit();

	GLFWwindow* window;
	window = glfwCreateWindow(800, 600, "ParticleSystemScene", NULL, NULL);
	glfwMakeContextCurrent(window);

	//CAM
	cam.setKeySpeed(4.0);
	iH.setAllInputMaps(cam);
	glfwSetKeyCallback(window, key_callback);
	cam.setFOV(50);
	cam.setNearFar(1, 100);

	glewInit();

	//TEXTURES
	Texture* smokeWhiteTex1 = new Texture((char*)RESOURCES_PATH "/ParticleSystem/smoke/smokeWhite/smokeWhite01.png");
	Texture* smokeWhiteTex2 = new Texture((char*)RESOURCES_PATH "/ParticleSystem/smoke/smokeWhite/smokeWhite02.png");
	Texture* smokeBlackTex1 = new Texture((char*)RESOURCES_PATH "/ParticleSystem/smoke/smokeBlack/smokeBlack01.png");
	Texture* smokeBlackTex2 = new Texture((char*)RESOURCES_PATH "/ParticleSystem/smoke/smokeBlack/smokeBlack02.png");
	Texture* snowTex = new Texture((char*)RESOURCES_PATH "/ParticleSystem/particle/snowflake.png"); //TODO better Resolution

	//FINAL EMITTER SNOW
	Emitter* snow = new Emitter(0, glm::vec3(0.0, 10.0, -5.0), 0.0, 0.166, 100, 30.0, true);
	snow->setVelocity(0);
	snow->usePhysicDirectionGravity(glm::vec4(0.0, -1.0, 0.0, 1.0), 0.5f);
	snow->setAreaEmitting(false, true, 10.0, 10000);
	snow->addTexture(snowTex, 0.0);
	snow->defineLook(true, 0.04, 2.0);
	snow->setMovable(true);

	//FINAL EMITTER WHITE SMOKE
	Emitter* smokeWhite = new Emitter(0, glm::vec3(0.0, 0.0, 5.0), 0.0, 0.4, 1, 8.0, true);
	smokeWhite->setVelocity(2);
	smokeWhite->usePhysicDirectionGravity(glm::vec4(0.0, -1.0, 0.0, -0.8), 0.3f);
	smokeWhite->addTexture(smokeWhiteTex1, 1.0);
	smokeWhite->addTexture(smokeWhiteTex2, 0.25);
	std::vector<float> smokeWhiteSize{ 0.05f, 0.5f, 0.75f, 1.2f };
	std::vector<float> smokeWhiteTime{ 0.0f, 0.4f, 0.75f, 1.0f };
	smokeWhite->defineLook(true, smokeWhiteSize, smokeWhiteTime, 1.0, 4.0, 4.0, false, 0.3);
	smokeWhite->switchToGeometryShader();

	//FINAL EMITTER BLACK SMOKE
	Emitter* smokeBlack = new Emitter(0, glm::vec3(0.0, 0.0, -10.0), 0.0, 0.4, 1, 8.0, true);
	smokeBlack->setVelocity(2);
	smokeBlack->usePhysicDirectionGravity(glm::vec4(0.0, -1.0, 0.0, -0.8), 0.3f);
	smokeBlack->addTexture(smokeBlackTex1, 1.0);
	smokeBlack->addTexture(smokeBlackTex2, 0.08);
	std::vector<float> smokeBlackSize{ 0.1f, 0.4f, 0.8f, 1.2f };
	std::vector<float> smokeBlackTime{ 0.0f, 0.2f, 0.75f, 1.0f };
	smokeBlack->defineLook(true, smokeBlackSize, smokeBlackTime, 1.0, 4.0, 4.0, false, 0.3);
	smokeBlack->switchToGeometryShader();

	//PARTICLE SYSTEM
	Effect* sn = new Effect();
	sn->addEmitter(snow);
	ParticleSystem* psSnow = new ParticleSystem(glm::vec3(0, 2, -5), sn);
	Node snowNode("snowNode");
	snowNode.setParticleActive(true);
	snowNode.setCamera(&cam);
	snowNode.addParticleSystem(psSnow);
	
	Effect* smWhi = new Effect();
	smWhi->addEmitter(smokeWhite);
	ParticleSystem* psSmokeWhite = new ParticleSystem(glm::vec3(0, 0, 3), smWhi);
	Node whiteSmokeNode("whiteSmokeNode");
	whiteSmokeNode.setParticleActive(true);
	whiteSmokeNode.setCamera(&cam);
	whiteSmokeNode.addParticleSystem(psSmokeWhite);
	
	Effect* smBla = new Effect();
	smBla->addEmitter(smokeBlack);
	ParticleSystem* psSmokeBlack = new ParticleSystem(glm::vec3(0, 0, -3), smBla);
	Node blackSmokeNode("blackSmokeNode");
	blackSmokeNode.setParticleActive(true);
	blackSmokeNode.setCamera(&cam);
	blackSmokeNode.addParticleSystem(psSmokeBlack);
	
	// Shader
	VertexShader vs(loadShaderSource(SHADERS_PATH + std::string("/ColorShader3D/ColorShader3D.vert")));
	FragmentShader fs(loadShaderSource(SHADERS_PATH + std::string("/ColorShader3D/ColorShader3D.frag")));
	ShaderProgram shader(vs, fs);

	// Renderer
	OpenGL3Context context;
	Renderer renderer(context);

	// Object
	Teapot teapot;
	teapot.loadBufferData();
	Node teapotNode("teapotNode");
	teapotNode.addGeometry(&teapot);
	teapotNode.setCamera(&cam);
	teapotNode.setModelMatrix(glm::translate(teapotNode.getModelMatrix(), glm::vec3(0.0, 0.0, -7.0)));
	
	//need scene here mainly because of input
	Level testLevel("testLevel");
	Scene testScene("testScene");
	testLevel.addScene(&testScene);
	testLevel.changeScene("testScene");

	//Add Camera to Scene
	testScene.getScenegraph()->addCamera(&cam);
	testScene.getScenegraph()->setActiveCamera("Pilotview");

	//Set Input-Maps and activate one
	iH.setAllInputMaps(*(testScene.getScenegraph()->getActiveCamera()));
	iH.changeActiveInputMap("Pilotview");

	//Add Objects to the Scene
	testScene.getScenegraph()->getRootNode()->addChildrenNode(&teapotNode);	
	testScene.getScenegraph()->getRootNode()->addChildrenNode(&blackSmokeNode);	
	testScene.getScenegraph()->getRootNode()->addChildrenNode(&whiteSmokeNode);
	testScene.getScenegraph()->getRootNode()->addChildrenNode(&snowNode);

	//start the ParticleSystems
	psSmokeBlack->start();
	psSmokeWhite->start();
	psSnow->start();

	// getting the start time
	double startTime = glfwGetTime();

	while (!glfwWindowShouldClose(window))
	{
		cam.setSensitivity(glfwGetTime() - startTime);
		startTime = glfwGetTime();

		glEnable(GL_DEPTH);
		glEnable(GL_DEPTH_TEST);
		glEnable(GL_BLEND);

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		shader.bind();
		shader.sendMat4("modelMatrix", teapotNode.getModelMatrix());
		shader.sendMat4("viewMatrix", cam.getViewMatrix());
		shader.sendMat4("projectionMatrix", cam.getProjectionMatrix());
		testScene.render(shader);
		shader.unbind();

		glfwSwapBuffers(window);
		glfwPollEvents();
	}
	glfwDestroyWindow(window);
	glfwTerminate();

	return 0;
}
コード例 #17
0
ファイル: main.cpp プロジェクト: danepowell/openhaptics
void DisplayInfo(void)
{
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_LIGHTING);

    glPushMatrix();
    glLoadIdentity();

	// switch to 2d orthographic mMode for drawing text
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	gluOrtho2D(0, mWindW, mWindH, 0);
	glMatrixMode(GL_MODELVIEW);
	
	glColor3f(1.0, 1.0, 1.0);

	int textRowDown = 0; // lines of text already drawn downwards from the top
	int textRowUp = 0; // lines of text already drawn upwards from the bottom

	if (mDrawInfo == drawInfo_All)
		DrawBitmapString(5, 20 + textRowDown * 15, GLUT_BITMAP_9_BY_15, "Surface Resolution: %d", mSurfaceParticles);

	if (mDrawInfo == drawInfo_All || mDrawInfo == drawInfo_FPS)
		DrawBitmapString(mWindW - 10 * 9, 20 + (textRowDown) * 15, GLUT_BITMAP_9_BY_15, "FPS: %4.1f", DetermineFPS());

	textRowDown++;
	
	if (mDrawInfo == drawInfo_All)
	{
		std::string stepLabel;
		
		if (mUseFixedTimeStep)
			DrawBitmapString(mWindW - 24 * 9, 20 + (textRowDown) * 15, GLUT_BITMAP_9_BY_15, "Fixed Step (sec): %1.3f" , mTimeStep);
		else
			DrawBitmapString(mWindW - 18 * 9, 20 + (textRowDown) * 15, GLUT_BITMAP_9_BY_15, "Step (sec): %1.3f" , mTimeStep);

		DrawBitmapString(5, mWindH - 10 - (textRowUp) * 15, GLUT_BITMAP_9_BY_15, "%s", mSurfaceConditionsName.c_str());

		std::string displayingList;
		if (mDrawSurface) displayingList += "surface ";
		if (mDrawNormals) displayingList += "normals ";
		if (mDrawSystem) displayingList += "system ";
		if (displayingList.length() == 0) displayingList = "(nothing)";
		displayingList.insert(0, "Displaying: ");
		DrawBitmapString(mWindW - displayingList.length() * 9, mWindH - 10 - (textRowUp++) * 15, GLUT_BITMAP_9_BY_15, "%s", displayingList.c_str());

		DrawBitmapString(5, mWindH - 10 - (textRowUp) * 15, GLUT_BITMAP_9_BY_15, "kd: %4.1f", mPS.GetSpringDampingConstant());
		DrawBitmapString(5 + 12 * 9, mWindH - 10 - (textRowUp++) * 15, GLUT_BITMAP_9_BY_15, "Gravity:%5.1f", mPS.gravity);
		
		DrawBitmapString(5, mWindH - 10 - (textRowUp) * 15, GLUT_BITMAP_9_BY_15, "ks: %4.1f", mPS.GetSpringConstant());
		DrawBitmapString(5 + 12 * 9, mWindH - 10 - (textRowUp) * 15, GLUT_BITMAP_9_BY_15, "Mass:   %5.1f", mSurface.GetMassProportion());
		DrawBitmapString(5 + 30 * 9, mWindH - 10 - (textRowUp) * 15, GLUT_BITMAP_9_BY_15, "Drag: %5.3f", mPS.drag);
	}

	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
	
	// turn depth and lighting back on for 3D rendering
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_LIGHTING);
}
コード例 #18
0
ファイル: Hero.cpp プロジェクト: kulgan/playn-greengrappler
void Hero::update()
{
	if (myIsDead)
		return;

	Entity::update();

	if (mSpawnPoint.x < -100 && mSpawnPoint.y < -100)
	{
		mSpawnPoint = getPosition();
	}

	if (mRopeState == RopeState_Dissapearing) {
		mRopeDissapearCounter++;
		if (mRopeDissapearCounter >= ROPE_DISSAPPEAR_TICKS) {
			mRopeState = RopeState_Retracted;
		}
	}

	float acceleration = mOnGround ? GROUND_ACCELERATION : AIR_ACCELERATION;
	bool airRunning = false;

	if (Input::isHeld(Button_Left)) {
		mVelocity.x -= acceleration;

		if (mRopeState == RopeState_Attached && !mOnGround) {
			mFacingDirection = Direction_Left;
			airRunning = true;
			mMovementState = MovementState_AirRun;
		}
	}

	if (Input::isHeld(Button_Right)) {
		mVelocity.x += acceleration;

		if (mRopeState == RopeState_Attached && !mOnGround) {
			mFacingDirection = Direction_Right;
			airRunning = true;
			mMovementState = MovementState_AirRun;
		}
	}

	if (Input::isPressed(Button_Jump)) {
		if (!mJumpPrepressed && mOnGround)
			Sound::playSample("data/sounds/jump.wav");
		mJumpPrepressed = true;
	}

	if (mOnGround && mJumpPrepressed) {
		mVelocity.y = -JUMP_VELOCITY;
		if (mRopeState != RopeState_Attached) {
			mJumpHeld = true;
		}
		mJumpPrepressed = false;
	}

	if (Input::isReleased(Button_Jump)) {
		if (mJumpHeld && mVelocity.y < 0) {
			mVelocity.y *= 0.5f;
		}

		mJumpHeld = false;
		mJumpPrepressed = false;
	}

	if (Input::isReleased(Button_Fire)) {
		detachHook();
	}

	if (mVelocity.y >= 0) {
		mJumpHeld = false;
	}

	if (!airRunning) {
		mMovementState = MovementState_Still;
	}

	if (mOnGround) {
		if (mVelocity.x > 0) {
			mFacingDirection = Direction_Right;
		} else if (mVelocity.x < 0) {
			mFacingDirection = Direction_Left;
		}

		if (abs(mVelocity.x) > GROUND_STOP_VELOCITY)
		{
			mMovementState = MovementState_Run;
		}
	}
	else if (!airRunning)
	{
		if (mVelocity.y > 0)
			mMovementState = MovementState_Jump;
		else
			mMovementState = MovementState_Fall;
	}

	if (mMovementState == MovementState_Still)
	{
		mVelocity.x = 0;
	}

	if (Input::isPressed(Button_Fire)) {
		Sound::playSample("data/sounds/rope.wav");
		mRopeState = RopeState_Moving;
		mRopePosition = mPosition;
		mRopeVelocity = float2::ZERO;

		if (Input::isHeld(Button_Left)) {
			mRopeVelocity.x -= 1;
		}

		if (Input::isHeld(Button_Right)) {
			mRopeVelocity.x += 1;
		}

		if (Input::isHeld(Button_Up)) {
			mRopeVelocity.y -= 1;
		}

		if (Input::isHeld(Button_Down)) {
			mRopeVelocity.y += 1;
		}

		if (floatIsZero(mRopeVelocity)) {
			mRopeVelocity.x = (mFacingDirection == Direction_Left ? -1 : 1);
		}

		mRopeVelocity = adjustRopeDirection(normalize(mVelocity + normalize(mRopeVelocity) * ROPE_SPEED)) * ROPE_SPEED;

		if (mRopeVelocity.x < 0) {
			mFacingDirection = Direction_Left;
		} else if (mRopeVelocity.x > 0) {
			mFacingDirection = Direction_Right;
		}
	}

	if (mRopeState == RopeState_Moving) {
		const int substeps = 25;
		for (int i = 0; i < substeps; i++) {
			mRopePosition += mRopeVelocity / (substeps * Time::TicksPerSecond);
			int tileX = (int)(mRopePosition.x / mRoom->getTileWidth());
			int tileY = (int)(mRopePosition.y / mRoom->getTileHeight());
			if (mRoom->isHookable(tileX, tileY)) {
				//Sound::stopSample("data/sounds/rope.wav");
				Sound::playSample("data/sounds/hook.wav");
				mRopeState = RopeState_Attached;
				mJumpHeld = false;

				ParticleSystem* particleSystem = new ParticleSystem(
					mAnimationHookParticle,
					2,
					30,
					10,
					1,
					50,
					10,
					-normalize(mRopeVelocity)*10,
					1.0);

				particleSystem->setPosition(mRopePosition);

				mRoom->addEntity(particleSystem);

				break;
			}

			if (length(mRopePosition-mPosition) > mRopeMaxLenghth)
			{
				detachHook();
				Sound::playSample("data/sounds/no_hook.wav");
				break;
			}

			if (mRoom->isCollidable(tileX, tileY)) {
				detachHook();
				Sound::playSample("data/sounds/no_hook.wav");
				break;
			}

			if (mRoom->damageDone((int)(mRopePosition.x), (int)(mRopePosition.y))) {
				detachHook();
				break;
			}

			mHookedEntity = mRoom->findHookableEntity(mRopePosition);
			if (mHookedEntity != 0) {
				Sound::playSample("data/sounds/hook.wav");
				mRopeState = RopeState_Attached;
				mJumpHeld = false;
				mHookedEntityOffset = mRopePosition - mHookedEntity->getPosition();
				mHookedEntityOffset.x = floor(mHookedEntityOffset.x);
				mHookedEntityOffset.y = floor(mHookedEntityOffset.y);
			}
		}
	}

	if (mRopeState == RopeState_Attached) {
		if (mHookedEntity != 0) {
			mRopePosition = mHookedEntity->getPosition() + mHookedEntityOffset;
		}

		float2 ropeToHero = mPosition - mRopePosition;
		if (lengthCompare(ropeToHero, ROPE_REST_LENGTH) > 0) {
			float2 ropeRestPoint = mRopePosition + normalize(ropeToHero) * ROPE_REST_LENGTH;
			float2 heroToRestPoint = ropeRestPoint - mPosition;
			float2 ropeAcceleration = heroToRestPoint * ROPE_SPRING_CONSTANT;
			if (lengthCompare(ropeAcceleration, ROPE_MAX_ACCELERATION) > 0) {
				ropeAcceleration = normalize(ropeAcceleration) * ROPE_MAX_ACCELERATION;
			}
			mVelocity += ropeAcceleration;
		}

		if (Input::isHeld(Button_Up)) {
			mVelocity.y -= acceleration;
		}

		if (Input::isHeld(Button_Down)) {
			mVelocity.y += acceleration;
		}

		int ropeTileX = (int)(mRopePosition.x / mRoom->getTileWidth());
		int ropeTileY = (int)(mRopePosition.y / mRoom->getTileWidth());
		if (mHookedEntity == 0 && !mRoom->isHookable(ropeTileX, ropeTileY)) {
			detachHook();
		}
	}

	unsigned int bumps = moveWithCollision();
	
	if ((bumps & (Direction_Left | Direction_Right)) != 0) {
		mVelocity.x = 0;
	}

	if ((bumps & (Direction_Up | Direction_Down)) != 0) {
		mVelocity.y = 0;
	}

	float gravity = mJumpHeld ? JUMP_GRAVITY : GRAVITY;
	mVelocity.y += gravity;
	bool ground = ((bumps & Direction_Down) != 0);
	if (ground && !mOnGround && mRopeState != RopeState_Attached)
	{
		Sound::playSample("data/sounds/land.wav");
	}
	mOnGround = ground;

	float drag = mOnGround ? GROUND_DRAG : AIR_DRAG;
	mVelocity *= drag;

	mFrame ++;
	
	if (mBlinkingTicksLeft)
	{
		mBlinkingTicksLeft --;
	}
}
コード例 #19
0
ファイル: ex1.cpp プロジェクト: rd3k/WaterSprinkler
void update(int t) {

	if (currentCamera == 0) {

		cameraAngle += (diffMouseDownX / 100.0);
		cameraDistance = (cameraDistance += (diffMouseDownY / 20.0)) < 10 ? 10 : cameraDistance;
		camera.set(
			cameraDistance * cos(cameraAngle * (M_PI / 180)),
			cameraElevation,
			cameraDistance * sin(cameraAngle * (M_PI / 180))
			);
		cameraLookAt = Vector3();
		cameraUp = Vector3(0, 1, 0);

	}
	else if (currentCamera == 1) {

		aboveCamera.y = (std::max(50.0, aboveCamera.y + (diffMouseDownY / 100.0)));

		aboveCameraLookAt = Vector3(0, aboveCamera.y - 100, aboveCamera.z);
		cameraLookAt = aboveCameraLookAt;
		camera.set(aboveCamera.x, aboveCamera.y, aboveCamera.z);
		cameraUp = aboveCameraUp;

	}
	else if (currentCamera == 2) {

		frontCamera.y = (frontCamera.y + (diffMouseDownY / 100.0));
		frontCamera.x = (frontCamera.x - (diffMouseDownX / 100.0));
		frontCamera.z = (cameraDistance);

		frontCameraLookAt = frontCamera.add(Vector3(0.0, 0.0, -1.0));
		cameraLookAt = frontCameraLookAt;

		camera.set(frontCamera.x, frontCamera.y, frontCamera.z);

		cameraUp = frontCameraUp;

	}
	else if (currentCamera == 3) {

		getFreeCameraLookAt();
		cameraLookAt = freeCameraLookAt;

		camera.set(freeCamera.x, freeCamera.y, freeCamera.z);

		freeCameraUp.x = sin(upAngle * (M_PI / 180));
		freeCameraUp.y = cos(upAngle * (M_PI / 180));

		cameraUp = freeCameraUp;

	}
	else if (currentCamera >= 4) {

		updateFlyBy();

		cameraLookAt = flyBySettings.lookAt;
		camera.set(
			flyBySettings.position.x,
			flyBySettings.position.y,
			flyBySettings.position.z
			);

		cameraUp = flyBySettings.up;

	}

	gravity.y = gravityIntensity;

	particleSystem.applyForce(gravity);

	for (int i = 0; i < 9; i++) {
		if (gravitationalForce[i].type != GRAVITATIONALFORCETYPE_NONE) {
			particleSystem.applyGravitationalForce(gravitationalForce[i]);
		}
	}

	if (cycleColours) {
		colourSwitch--;
		if (colourSwitch == 0) {
			colourSwitch = 10;
			Particle::startColour = emitColours[initialColour];
			currentColour = Particle::startColour;
			initialColour = (++initialColour) == colourCount ? 0 : initialColour;
		}
		else {
			Particle::startColour.r = linearEase(10 - colourSwitch, currentColour.r, emitColours[initialColour].r - currentColour.r, 10);
			Particle::startColour.g = linearEase(10 - colourSwitch, currentColour.g, emitColours[initialColour].g - currentColour.g, 10);
			Particle::startColour.b = linearEase(10 - colourSwitch, currentColour.b, emitColours[initialColour].b - currentColour.b, 10);
		}
	}

	particleSystem.update();

	// FPS monitoring
	frame++;
	elapsedTime = glutGet(GLUT_ELAPSED_TIME);
	if (elapsedTime - timebase > 1000) {
		fps = frame * 1000.0 / (elapsedTime - timebase);
		timebase = elapsedTime;
		frame = 0;
	}

	glutPostRedisplay();
	glutTimerFunc(30, update, 0);

}
コード例 #20
0
ファイル: robotarm.cpp プロジェクト: billytotochan/anime
int main()
{
    ModelerControl controls[NUMCONTROLS ];

	controls[BASE_ROTATION] = ModelerControl("base rotation (theta)", -180.0, 180.0, 0.1, 0.0 );
    controls[LOWER_TILT] = ModelerControl("lower arm tilt (phi)", 15.0, 95.0, 0.1, 55.0 );
    controls[UPPER_TILT] = ModelerControl("upper arm tilt (psi)", 0.0, 135.0, 0.1, 30.0 );
	controls[CLAW_ROTATION] = ModelerControl("claw rotation (cr)", -30.0, 180.0, 0.1, 0.0 );
    controls[BASE_LENGTH] = ModelerControl("base height (h1)", 0.5, 10.0, 0.1, 0.8 );
    controls[LOWER_LENGTH] = ModelerControl("lower arm length (h2)", 1, 10.0, 0.1, 3.0 );
	controls[UPPER_LENGTH] = ModelerControl("upper arm length (h3)", 1, 10.0, 0.1, 2.5);
	controls[PARTICLE_COUNT] = ModelerControl("particle count (pc)", 0.0, 5.0, 0.1, 5.0);
	controls[X_WIND] = ModelerControl("X_WIND", 0.0, 5.0, 0.1, 0.6);
	controls[Y_WIND] = ModelerControl("Y_WIND", 0.0, 5.0, 0.1, 0.0);
	controls[Z_WIND] = ModelerControl("Z_WIND", 0.0, 5.0, 0.1, 0.2);
	controls[WIND_MAGNITUDE] = ModelerControl("WIND_MAGNITUDE", 0.0, 10.0, 0.1, 2.0);
	controls[GRAVITY] = ModelerControl("GRAVITY", -10.0, 10.0, 1.0, 9.8);
    
    controls[XPOS] = ModelerControl("X Position", -5, 5, 0.1f, 0);
    controls[YPOS] = ModelerControl("Y Position", 0, 5, 0.1f, 0);
    controls[ZPOS] = ModelerControl("Z Position", -5, 5, 0.1f, 0);

    controls[XSCALE] = ModelerControl("X Scale", 0, 3, 0.1f, 1.0f);
    controls[YSCALE] = ModelerControl("Y Scale", 0, 3, 0.1f, 1.0f);
    controls[ZSCALE] = ModelerControl("Z Scale", 0, 3, 0.1f, 1.0f);

    controls[HEIGHT] = ModelerControl("Height", 1, 2.5, 0.1f, 1);
    controls[ROTATE] = ModelerControl("Rotate", -135, 135, 1, 0);

    controls[HEAD_SIZE] = ModelerControl("Head Size", 0.8, 2, 0.1f, 1);
    controls[HEAD_ROTATE] = ModelerControl("Head Rotate", -70, 70, 1, 0);
    controls[EAR_SIZE] = ModelerControl("Ear Size", 0, 2, 0.1f, 1);

    controls[UPPER_ARM_LENGTH] = ModelerControl("Upper Arm Length", 1, 5, 0.1f, 0.8);
    controls[LEFT_UPPER_ARM_ROTATE_X] = ModelerControl("Left Upper Arm Rotate X", 20, 120, 1.0f, 80);
    controls[LEFT_UPPER_ARM_ROTATE_Y] = ModelerControl("Left Upper Arm Rotate Y", -30, 90, 1.0f, 0);
    controls[RIGHT_UPPER_ARM_ROTATE_X] = ModelerControl("Right Upper Arm Rotate X", -90, 100, 1.0f, -40);
    controls[RIGHT_UPPER_ARM_ROTATE_Y] = ModelerControl("Right Upper Arm Rotate Y", -90, 30, 1.0f, 0);

    controls[LOWER_ARM_LENGTH] = ModelerControl("Lower Arm Length", 1, 5, 0.1f, 0.8);
    controls[LEFT_LOWER_ARM_ROTATE] = ModelerControl("Left Lower Arm Rotate", 20, 180, 1.0f, 80);
    controls[RIGHT_LOWER_ARM_ROTATE] = ModelerControl("Right Lower Arm Rotate", 20, 180, 1.0f, 180);
    controls[RIGHT_HAND_ANGLE] = ModelerControl("Right Hand Angle", 0, 70, 1, 0);
    controls[LEFT_HAND_ANGLE] = ModelerControl("Left Hand Angle", 0, 70, 1, 0);

    controls[LEG_LENGTH] = ModelerControl("Leg Length", 1, 5, 0.1f, 2);
    controls[LEFT_LEG_ROTATE_X] = ModelerControl("Left Leg Rotate X", 30, 150, 1.0f, 40);
    controls[LEFT_LEG_ROTATE_Y] = ModelerControl("Left Leg Rotate Y", -80, 90, 1.0f, 0);
    controls[RIGHT_LEG_ROTATE_X] = ModelerControl("Right Leg Rotate X", 30, 150, 1.0f, 140);
    controls[RIGHT_LEG_ROTATE_Y] = ModelerControl("Right Leg Rotate Y", -90, 80, 1.0f, 0);
    
    controls[TORUS_R] = ModelerControl("Torus R", 0, 10, 0.1f, 0.6);
    controls[TORUS_r] = ModelerControl("Torus r", 0, 10, 0.1f, 0.15);

    controls[FLOOR_SIZE] = ModelerControl("Floor Size", 0, 8, 0.1f, 5.0f);
    controls[FLOOR_DEPTH] = ModelerControl("Floor Depth", 0, 10, 1, 4);

    controls[DETAIL_LEVEL] = ModelerControl("Detail Level", 1, 5, 1, 3);


	// You should create a ParticleSystem object ps here and then
	// call ModelerApplication::Instance()->SetParticleSystem(ps)
	// to hook it up to the animator interface.

	ModelerApplication::Instance()->Init(&createRobotArm, controls, NUMCONTROLS);
	ParticleSystem *ps = new ParticleSystem();
	ModelerApplication::Instance()->SetParticleSystem(ps);
	Force* g = new Gravity((float)VAL(GRAVITY));
	//Force* g = new Gravity(9.8f);
	ps->addForce(g);
	Wind *wind = new Wind();
	wind->setDirection(Vec3f((float)-VAL(X_WIND) - 5.0f, (float)VAL(Y_WIND) - 5.0f, (float)VAL(Y_WIND) - 5.0f));
	//wind->setDirection(Vec3f(-0.4, 0, 0.2));
	wind->setMagnitube((float)VAL(WIND_MAGNITUDE));
	//wind->setMagnitube(6.0);
	ps->addForce(wind);
	

    return ModelerApplication::Instance()->Run();
}
コード例 #21
0
ファイル: ex1.cpp プロジェクト: rd3k/WaterSprinkler
void display () {

	if (wireframe) {
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	}

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	glEnable(GL_BLEND);
	glEnable(GL_DEPTH_TEST);

	// Clear the screen
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	enter3D();

	gluLookAt(camera.x, camera.y, camera.z,
			  cameraLookAt.x, cameraLookAt.y, cameraLookAt.z,
			  cameraUp.x, cameraUp.y, cameraUp.z);

	glPushMatrix();
	glScaled(1.0, -1.0, 1.0);

	if (showSky) {
		drawSky();
	}

	// Draw coordinate axis
	// glCallList(axisList);

	for (int i = 0; i < 9; i ++) {
		gravitationalForce[i].draw();
	}

	if (showGround) {
		drawGround();
	}

	if (showPipe) {
		glPushMatrix();
			drawSprinkler(emitterSpacing * emitterCount, sprinkerHeight, 100, 5.0, 40.0);
		glPopMatrix();
	}

	if (showMountains) {
		drawMoutains(3000, 0, 0);
		drawMoutains(4000, 180, -200);
		drawMoutains(5600, 45, -500);
	}

	if (showTrees) {
		drawTrees();
	}

	if (renderMode == PARTICLERENDERMODE_TEXTURESPRITE) {
		Texture::set("shine");
		glBlendFunc(GL_SRC_ALPHA, GL_ONE);
	}

	particleSystem.draw();

	if (renderMode == PARTICLERENDERMODE_TEXTURESPRITE) {
		Texture::done();
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}

	/*glPushMatrix();
	glColor3f(1.0, 1.0, 1.0);
	glTranslatef(0.0, -100.0, 0.0);
	glScalef(100.0, -100.0, 100.0);
	drawModel();
	glPopMatrix();*/

	if (wireframe) {
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	}

	glDisable(GL_DEPTH_TEST);
	enter2D();

	glColor4d(0.0, 0.0, 0.0, 1.0);
	sprintf(fpsText, "FPS:%4.2f", fps);
	drawText(GLUT_BITMAP_HELVETICA_18, windowWidth - 100, 20, fpsText);

	if (showHUD) {

		drawText(GLUT_BITMAP_HELVETICA_18, 10, 20, "Water sprinkler");

		sprintf(cameraText, "%4.2f %4.2f %4.2f", camera.x, camera.y, camera.z);
		drawText(GLUT_BITMAP_HELVETICA_12, 10, 60, cameraText);

		sprintf(particleText, "Particles: %llu", particleSystem.getParticleCount());
		drawText(GLUT_BITMAP_HELVETICA_12, 10, 100, particleText);

		if (menu) {

			// Current option
			glColor4d(0.2, 0.2, 0.2, 0.8);
			glRectd(10, windowHeight - 40, 120, windowHeight - 10);
			glColor4d(1.0, 1.0, 1.0, 1.0);
			drawText(GLUT_BITMAP_HELVETICA_12, 20, windowHeight - 20, options[currentOption]);

			// Current option value
			glColor4d(0.4, 0.4, 0.4, 0.8);
			glRectd(120, windowHeight - 40, 240, windowHeight - 10);
			glColor4d(1.0, 1.0, 1.0, 1.0);

			switch (currentOption) {
			case 0: sprintf(optionValue, "%4.2f", Particle::initialVelocity); break;
			case 1: sprintf(optionValue, "%d", initialColour); break;
			case 2: sprintf(optionValue, "%d", gravityIntensity); break;
			case 3: sprintf(optionValue, "%d", Particle::startLifeSpan); break;
			case 4: sprintf(optionValue, "%s", renderModes[renderMode]); break;
			case 5: sprintf(optionValue, "%d", emitterCount); break;
			case 6: sprintf(optionValue, "%d", emitterSpacing); break;
			case 7: sprintf(optionValue, "%s", cameras[currentCamera]); break;
			case 8: sprintf(optionValue, "%4.2f", Particle::airResistance); break;
			case 9: sprintf(optionValue, "%s", cycleColours ? "On" : "Off"); break;
			case 10: sprintf(optionValue, "%d", emitFrequency); break;
			case 11: sprintf(optionValue, "%4.2f", ParticleEmitter::emitSpread); break;
			case 12: sprintf(optionValue, "%d", ParticleSystem::perEmit); break;
			case 13: sprintf(optionValue, "%s", ParticleEmitter::show ? "Yes" : "No"); break;
			case 14: sprintf(optionValue, "%s", wireframe ? "Yes" : "No"); break;
			case 15: sprintf(optionValue, "%s", showMountains ? "On" : "Off"); break;
			case 16: sprintf(optionValue, "%s", showTrees ? "On" : "Off"); break;
			case 17: sprintf(optionValue, "%s", showSky ? "On" : "Off"); break;
			case 18: sprintf(optionValue, "%s", showGround ? "On" : "Off"); break;
			case 19: sprintf(optionValue, "%s", demos[demo]->name.c_str()); break;
			case 20: sprintf(optionValue, "%1.1f", Particle::bounce); break;
			case 21: sprintf(optionValue, "%s", skyTexture ? "On" : "Off"); break;
			case 22: sprintf(optionValue, "%s", grassTexture ? "On" : "Off"); break;
			case 23: sprintf(optionValue, "%s", showPipe ? "On" : "Off"); break;
			case 24: sprintf(optionValue, "%s", ParticleEmitter::randomness ? "On" : "Off"); break;
			case 25: sprintf(optionValue, "%s", Tree::drawLeaves ? "On" : "Off"); break;
			default: sprintf(optionValue, "%s", ""); break;
			}

			drawText(GLUT_BITMAP_HELVETICA_12, 130, windowHeight - 20, optionValue);

		}
		else {
			glColor4d(1.0, 1.0, 1.0, 1.0);
			drawText(GLUT_BITMAP_HELVETICA_12, 20, windowHeight - 20, "Press m to toggle menu");
		}

		for (int i = 1; i < 10; i++) {
			if (selectedGravitationalForce == i - 1) {
				glColor4d(1.0, 0.4, 0.4, 0.8);
			}
			else {
				glColor4d(0.4, 0.4, 1.0, 0.2);
			}
			glRectd(200 + ((i - 1) * 50), 10, 230 + ((i - 1) * 50), 40);
			glColor4d(0.0, 0.0, 0.0, 1.0);
			sprintf(n, "%d", i);
			drawText(GLUT_BITMAP_HELVETICA_18, 210 + ((i - 1) * 50), 30, n);
		}

	}

	if (currentCamera == 3) {
		glBegin(GL_LINES);
			glColor3d(0.8, 0.8, 0.8);
			glVertex2d((windowWidth / 2) - 30, windowHeight / 2);
			glVertex2d((windowWidth / 2) + 30, windowHeight / 2);
			glVertex2d(windowWidth / 2, (windowHeight / 2) - 30);
			glVertex2d(windowWidth / 2, (windowHeight / 2) + 30);
		glEnd();
	}

	glPopMatrix();

	glutSwapBuffers();
	glutPostRedisplay();
}
コード例 #22
0
// We are going to override (is that the right word?) the draw()
// method of ModelerView to draw out MyModel
void MyModel::draw()
{
	// This call takes care of a lot of the nasty projection 
	// matrix stuff.  Unless you want to fudge directly with the 
	// projection matrix, don't bother with this ...

	ModelerView::draw();


	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	ChooseCostume(VAL(COSTUME));

	
		LocateBody(VAL(XPOS), VAL(YPOS), VAL(ZPOS), VAL(ROTATE));
		RotateHead(0, VAL(NECK) + 180, 0);
		int SType = VAL(SLASH_TYPE);
		switch (SType){
		case VERTICAL:
			RotateExcalibur(0.0, 90.0, 2*LOWER_ARM_SLASH*VAL(SLASH) < 40.0 ? 2*LOWER_ARM_SLASH*VAL(SLASH) : 40.0, "yzx");
			RotateRightUpperArm(1.5*VAL(SLASH), 0.0, 0.0);
			RotateRightLowerArm(LOWER_ARM_SLASH*VAL(SLASH), 0.0, 2*LOWER_ARM_SLASH*VAL(SLASH) < 40.0 ? -2*LOWER_ARM_SLASH*VAL(SLASH) : -40.0, "zxy");
			RotateLeftUpperArm(1.5*VAL(SLASH), 0.0, 0.0);
			RotateLeftLowerArm(LOWER_ARM_SLASH*VAL(SLASH), 0.0, 2*LOWER_ARM_SLASH*VAL(SLASH) < 40.0 ? 2*LOWER_ARM_SLASH*VAL(SLASH) : 40.0, "zxy");
			break;
		case STAND:
			RotateExcalibur(VAL(SLASH)>75?-VAL(SLASH)*2+25:-VAL(SLASH)*125.0/75.0, 0.0,VAL(SLASH) < 40.0 ? VAL(SLASH) : 40.0 , "xyz");
			RotateRightUpperArm(1.1*VAL(SLASH), 0.0, 0.0);
			RotateRightLowerArm(0.6*VAL(SLASH), 0.0, VAL(SLASH) < 40.0 ? -VAL(SLASH) : -40.0, "zxy");
			RotateLeftUpperArm(1.1*VAL(SLASH), 0.0, 0.0);
			RotateLeftLowerArm(0.6*VAL(SLASH), 0.0, VAL(SLASH) < 40.0 ? VAL(SLASH) : 40.0, "zxy");
			break;
		case SKEW:
			if (VAL(SLASH) < 45.0){
				RotateExcalibur(0.0, 0.0, 70.0 * VAL(SLASH) / 45.0, "xyz");
				RotateRightUpperArm(90.0*VAL(SLASH) / 45.0, -30.0 * VAL(SLASH) / 45.0, 0.0, "xyz");
				RotateRightLowerArm(110.0*VAL(SLASH) / 45.0, 30.0*VAL(SLASH) / 45.0, 0.0, "xyz");
				RotateLeftUpperArm(90.0*VAL(SLASH) / 45.0, -45.0*VAL(SLASH) / 45.0, 0.0, "xyz");
				RotateLeftLowerArm(65.0*VAL(SLASH) / 45.0, -15.0*VAL(SLASH) / 45.0, 0.0, "xyz");
			}
			else{
				RotateExcalibur(0.0, 90.0*(VAL(SLASH) - 45.0) / 45.0, 70.0 *(1 - (VAL(SLASH) - 45.0) / 45.0), "xyz");
				RotateRightUpperArm(90.0 - 30.0*(VAL(SLASH) - 45.0) / 45.0, -30.0 + 55.0 * (VAL(SLASH) - 45.0) / 45.0, 0.0, "xyz");
				RotateRightLowerArm(110.0 - 110.0*(VAL(SLASH) - 45.0) / 45.0, 30.0 - 30.0*(VAL(SLASH) - 45.0) / 45.0, 0.0, "xyz");
				RotateLeftUpperArm(90.0 - 40.0*(VAL(SLASH) - 45.0) / 45.0, -45.0 + 30.0*(VAL(SLASH) - 45.0) / 45.0, 0.0, "xyz");
				RotateLeftLowerArm(65.0 - 50.0*(VAL(SLASH) - 45.0) / 45.0, -15.0 + 15.0*(VAL(SLASH) - 45.0) / 45.0, 10.0*(VAL(SLASH) - 45.0) / 45.0, "xyz");
				break;
			}
		case SINGLE:
			if (VAL(SLASH) < 45.0){
				RotateExcalibur(0.0, 0.0, 70.0 * VAL(SLASH) / 45.0, "xyz");
				RotateRightUpperArm(90.0*VAL(SLASH) / 45.0, -30.0 * VAL(SLASH) / 45.0, 0.0, "xyz");
				RotateRightLowerArm(110.0*VAL(SLASH) / 45.0, 30.0*VAL(SLASH) / 45.0, 0.0, "xyz");
			}
			else{
				RotateExcalibur(0.0, -90.0*(VAL(SLASH) - 45.0) / 45.0, 70.0 *(1 - (VAL(SLASH) - 45.0) / 45.0), "xyz");
				RotateRightUpperArm(90.0, -30.0 + 75.0 * (VAL(SLASH) - 45.0) / 45.0, 0.0, "xyz");
				RotateRightLowerArm(110.0 - 110.0*(VAL(SLASH) - 45.0) / 45.0, 30.0 + 60.0*(VAL(SLASH) - 45.0) / 45.0, 0.0, "xyz");
			}
				break;
		}
		
		
	treeRoot->RootRender();
	
	if (valid()){
		ParticleSystem *ps = ModelerApplication::Instance()->GetParticleSystem();
		if (ps != NULL) {
			ps->computeForcesAndUpdateParticles(t);
			ps->drawParticles(t);
		}
	}

	endDraw();
}
コード例 #23
0
void displayFunc1() {

	  // Clear Color and Depth Buffers
	  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	  // Reset transformations
	  glLoadIdentity();
	  // Set the camera

	  if(camera==1){
	  gluLookAt(	0.0f, 0.3f, 2.0f,
			0.0f, -.5f,  0.0f,
			0.0f, 1.0f,  0.0f);
	  }
	  else if(camera == 2){
	  gluLookAt(	0.0f, -.7f, 2.0f,
			0.0f, -.7f,  0.0f,
			0.0f, 1.0f,  0.0f);
	  }
	  // new settings just to see obj file. can change later.
	  else if(camera == 3){
	  gluLookAt(	0.0f, 2.3f, 1.5f,
			0.0f, -.5f,  0.0f,
			0.0f, 1.0f,  0.0f);
	  }


	  glRotatef(angle, 0.0f, 1.0f, 0.0f);
	  glColor4f(1.0, 1.0, 1.0, 1.0);
	  glBegin(GL_TRIANGLES);
	  glVertex3f( -1.0f, -1.0f, -1.0f);
	  glVertex3f( 1.0f, -1.0f, -1.0);
	  glVertex3f( 1.0f, -1.0f, 1.0);
	  glEnd();

	  glBegin(GL_TRIANGLES);
	  glVertex3f( 1.0f, -1.0f, 1.0f);
	  glVertex3f( -1.0f, -1.0f, 1.0);
	  glVertex3f( -1.0f, -1.0f, -1.0);
	  glEnd();

	  angle+=0.3f;

	  if (bBoxScene) {
	    boxScene();
	  }
	  else if (bxScene) {
	    xScene();
	  }
	  else if (bzScene) {
	    zScene();
	  }
	  else if (bNoBound) {
	    noBound();
	  }
	  glClearDepth(1);
	  /*glEnable(GL_DEPTH_TEST);
	  glEnable(GL_LIGHTING);
	  glEnable(GL_COLOR_MATERIAL);

	  GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
	  GLfloat mat_shininess[] = { 50.0 };
	  GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
	  glClearColor (0.0, 0.0, 0.0, 0.0);
	  glShadeModel (GL_SMOOTH);

	  glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
	  glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
	  glLightfv(GL_LIGHT0, GL_POSITION, light_position);


	  glEnable(GL_LIGHT0);*/

	  glEnable(GL_DEPTH_TEST);
	  glEnable(GL_LIGHTING);
	  glEnable(GL_COLOR_MATERIAL);
	    glEnable(GL_LIGHT0);
	  float lightPos0[4] = { 0, 0, 5, 1 };
	  float dif0[4] = { .6, .6, .6, 1 };
	  float amb0[4] = { .1, .1, .1, 1 };
	  float spec0[4] = { .6, .6, .6, 1 };
	  float shine0[1] = {1};
	  glLightfv(GL_LIGHT0, GL_POSITION, lightPos0);
	  glLightfv(GL_LIGHT0, GL_AMBIENT, amb0);
	  glLightfv(GL_LIGHT0, GL_DIFFUSE, dif0);
	  glLightfv(GL_LIGHT0, GL_SPECULAR, spec0);
	  glLightfv(GL_LIGHT0, GL_SHININESS, shine0);
	  glEnable(GL_LIGHT1);
	  float lightPos1[4] = {0, 2, -5, 1};
	  glLightfv(GL_LIGHT1, GL_POSITION, lightPos1);


	  mesh.updateColors();
	  vector<float> triangles, normals;
	  mesh.marchingCubes(triangles, normals);

	  glBegin(GL_TRIANGLES);
	  glColor4f(0.1, 0.3, 0.8, 0.7);
	  for (int j = 0; j < (int) triangles.size(); j+=3) {
		glNormal3f(normals[j], normals[j+1], normals[j+2]);
		glVertex3f(triangles[j], triangles[j+1], triangles[j+2]);
	  }
	  glEnd();

	  if (currentTime < totalTime) {
	    pSystem.update(dt);
	    currentTime += dt;
	  } else {
	    exit(1);
	  }
	  //glDisable(GL_LIGHTING);
	  glFlush();
	  if(record) {
	    recorder.RecordFrame();
	  }
	  glutSwapBuffers();
}
コード例 #24
0
ファイル: ParticleFactory.cpp プロジェクト: brucelane/f2_Orbs
void ParticleFactory::perform(const double elapsedSeconds, const Vec2f origin, const Listener& list, ParticleSystem & ps)
{
	double offsetSeconds = elapsedSeconds + d_adjustSeconds - d_offsetTime;
	if (offsetSeconds < 0)
		ci::app::console() << "waiting for song to start..." << std::endl;

	if (offsetSeconds >= 30 && offsetSeconds < 45)
	{
		while (ps.mParticles.size() < 3)
		{
			Particle* particle = new ParticleG(origin, list);
			ps.addParticle(particle);
		}
	}
	if (offsetSeconds >= 45 && offsetSeconds < 75)
	{
		Particle* particle = new ParticleC(origin, list);
		ps.addParticle(particle);
	}
	if (offsetSeconds >= 75 && offsetSeconds < 105)
	{
		Particle* particle = new ParticleB(origin, list);
		ps.addParticle(particle);
	}
	if (offsetSeconds >= 105 && offsetSeconds < 135)
	{
		Particle* particle = new ParticleL(origin, list);
		ps.addParticle(particle);
	}
	if (offsetSeconds >= 135 && offsetSeconds < 150)
	{
		Particle* particle = new ParticleI(origin, list);
		ps.addParticle(particle);
	}
	if (offsetSeconds >= 135 && offsetSeconds < 165)
	{
		for (int i = 0; i < (int)(list.getVolume()*10.f); ++i)
		{
			Particle* particle = new ParticleD(origin, list);
			ps.addParticle(particle);
		}
		for (int i = 0; i < 3; ++i)
		{
			Particle* particle = new ParticleA(origin, list);
			particle->mOrientation = ps.mOrientation;
			ps.addParticle(particle);
		}
	}
	if (offsetSeconds >= 165 && offsetSeconds < 195)
	{
		for (int i = 0; i < 4; ++i)
		{
			Particle* particle = new ParticleH(origin, list);
			ps.addParticle(particle);
		}
	}
	if (offsetSeconds >= 195 && offsetSeconds < 210)
	{
		for (int i = 0; i < 4; ++i)
		{
			Particle* particle = new ParticleF(origin, list);
			particle->mOrientation = ps.mOrientation;
			ps.addParticle(particle);
		}
		Particle* particle = new ParticleE(origin, list);
		particle->mOrientation = ps.mOrientation;
		ps.addParticle(particle);
	}
	if (offsetSeconds >= 210 && offsetSeconds < 225)
	{
		Particle* particle = new ParticleJ(origin, list);
		ps.addParticle(particle);
	}
	if (offsetSeconds >= 225 && offsetSeconds < 255)
	{
		Particle* particle = new ParticleN(origin, list);
		ps.addParticle(particle);
	}
	if (offsetSeconds >= 255 )
	{
		Particle* particle = new ParticleK(origin, list);
		ps.addParticle(particle);
	}

}
コード例 #25
0
/* Display is updated/rendered here. */
void displayFunc() {

  // Clear Color and Depth Buffers
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  // Reset transformations
  glLoadIdentity();
  // Set the camera
  
  if(camera==1){
  gluLookAt(	0.0f, 0.3f, 2.0f,
		0.0f, -.5f,  0.0f,
		0.0f, 1.0f,  0.0f);
  }
  else if(camera == 2){
  gluLookAt(	0.0f, -.7f, 2.0f,
		0.0f, -.7f,  0.0f,
		0.0f, 1.0f,  0.0f);
  }
  // new settings just to see obj file. can change later.
  else if(camera == 3){
  gluLookAt(	0.0f, 2.3f, 1.5f,
		0.0f, -.5f,  0.0f,
		0.0f, 1.0f,  0.0f);
  }


  glRotatef(angle, 0.0f, 1.0f, 0.0f);
  glColor4f(1.0, 1.0, 1.0, 1.0);
  glBegin(GL_TRIANGLES);
  glVertex3f( -1.0f, -1.0f, -1.0f);
  glVertex3f( 1.0f, -1.0f, -1.0);
  glVertex3f( 1.0f, -1.0f, 1.0);
  glEnd();

  glBegin(GL_TRIANGLES);
  glVertex3f( 1.0f, -1.0f, 1.0f);
  glVertex3f( -1.0f, -1.0f, 1.0);
  glVertex3f( -1.0f, -1.0f, -1.0);
  glEnd();

  angle+=0.3f;

  if (bBoxScene) {
    boxScene();
  }
  else if (bxScene) {
    xScene();
  }
  else if (bzScene) {
    zScene();
  }
  else if (bNoBound) {
    noBound();
  }
  glClearDepth(1);
  /*glEnable(GL_DEPTH_TEST);
  glEnable(GL_LIGHTING);
  glEnable(GL_COLOR_MATERIAL);

  GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
  GLfloat mat_shininess[] = { 50.0 };
  GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
  glClearColor (0.0, 0.0, 0.0, 0.0);
  glShadeModel (GL_SMOOTH);

  glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
  glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
  glLightfv(GL_LIGHT0, GL_POSITION, light_position);


  glEnable(GL_LIGHT0);*/

  glEnable(GL_DEPTH_TEST);
  glEnable(GL_LIGHTING);
  glEnable(GL_COLOR_MATERIAL);
    glEnable(GL_LIGHT0);
  float lightPos0[4] = { 0, 0, 5, 1 };
  float dif0[4] = { .6, .6, .6, 1 };
  float amb0[4] = { .1, .1, .1, 1 };
  float spec0[4] = { .6, .6, .6, 1 };
  float shine0[1] = {1};
  glLightfv(GL_LIGHT0, GL_POSITION, lightPos0);
  glLightfv(GL_LIGHT0, GL_AMBIENT, amb0);
  glLightfv(GL_LIGHT0, GL_DIFFUSE, dif0);
  glLightfv(GL_LIGHT0, GL_SPECULAR, spec0);
  glLightfv(GL_LIGHT0, GL_SHININESS, shine0);
  glEnable(GL_LIGHT1);
  float lightPos1[4] = {0, 2, -5, 1};
  glLightfv(GL_LIGHT1, GL_POSITION, lightPos1);


  glBegin(GL_POINTS);
  //glColor4f(0.0, 0.2, 1.0, 1.0);
  Particle* p;
  unsigned int i = 0;
  for (i = 0; i < pSystem.getParticles().size()/2; i++) {
    p = pSystem.getParticle(i);
	glColor4f(p->getColor().getX(),p->getColor().getY(),p->getColor().getZ(), 1.0);
    glVertex3f(p->getPosition().getX(), p->getPosition().getY(), p->getPosition().getZ());
  }
  glEnd();
  glBegin(GL_POINTS);
  //glColor4f(0.2, 0.7, 0.0, 1.0);
  for (; i < pSystem.getParticles().size(); i++) {
    p = pSystem.getParticle(i);
	glColor4f(p->getColor().getX(),p->getColor().getY(),p->getColor().getZ(), 1.0);
    glVertex3f(p->getPosition().getX(), p->getPosition().getY(), p->getPosition().getZ());
  }
  glEnd();
  if (currentTime < totalTime) {
    pSystem.update(dt);
    currentTime += dt;
  } else {
    exit(1);
  }
  //glDisable(GL_LIGHTING);
  glFlush();
  if(record) {
    recorder.RecordFrame();
  }
  glutSwapBuffers();
}
コード例 #26
0
//-----------------------------------------------------------------------------
//!!!!!!! def non impair
void CParalyse::Create(int adef, float arayon, float ahcapuchon, float ahauteur, Vec3f * aePos, int aduration)
{
	if(adef < 3)
		return;

	key = -1;
	pos = *aePos;
	currduration = colduration = 0;
	duration = aduration;
	prisminterpcol = 0.f;
	r = arayon;

	SetColPrismDep(128.f, 128.f, 128.f);
	SetColPrismEnd(100.f, 100.f, 128.f);

	prismnbpt = 1 + (adef << 1);
	prismnbface = adef + (adef << 1);
	prismd3d = new TexturedVertex[prismnbpt];
	prismvertex = new Vec3f[prismnbpt];
	prismind = new unsigned short [prismnbface*3];

	for(int i = 0; i < 100; i++) {
		tabprism[i].vertex = new Vec3f[prismnbpt];
	}

	tex_prism = TextureContainer::Load("graph/obj3d/textures/(fx)_paralyze");
	tex_p	  = TextureContainer::Load("graph/particles/missile");
	tex_p1	  = TextureContainer::Load("graph/obj3d/textures/(fx)_tsu_blueting");
	tex_p2	  = TextureContainer::Load("graph/obj3d/textures/(fx)_tsu_bluepouf");

	CreatePrismTriangleList(arayon, ahcapuchon, ahauteur, adef);
	CreateLittlePrismTriangleList();

	if(lLightId >= 0) {
		int id = lLightId;
		DynLight[id].exist = 1;
		DynLight[id].intensity = 1.4f + 4.f * rnd();
		DynLight[id].fallend = r * 3.f;
		DynLight[id].fallstart = r * 3.f * .75f;
		DynLight[id].rgb.r = (prismrd * 2.f) / 255.f;
		DynLight[id].rgb.g = (prismgd * 2.f) / 255.f;
		DynLight[id].rgb.b = (prismbd * 2.f) / 255.f;
		DynLight[id].pos.x = pos.x;
		DynLight[id].pos.y = pos.y - ahcapuchon * .5f;
		DynLight[id].pos.z = pos.z;
	}

	// système de partoches pour la poussière
	ParticleSystem * pPS = new ParticleSystem();
	ParticleParams cp;
	memset(&cp, 0, sizeof(cp));
	cp.iNbMax = 200;
	cp.fLife = 500; //2000
	cp.fLifeRandom = 900;
	cp.p3Pos.x = 20;
	cp.p3Pos.y = 80;
	cp.p3Pos.z = 20;
	cp.p3Direction.x = 0;
	cp.p3Direction.y = -10;
	cp.p3Direction.z = 0;
	cp.fAngle = radians(360);
	cp.fSpeed = 10;
	cp.fSpeedRandom = 10;
	cp.p3Gravity.x = 0;
	cp.p3Gravity.y = 10;
	cp.p3Gravity.z = 0;
	cp.fFlash = 0;
	cp.fRotation = 0;

	cp.fStartSize = 0;
	cp.fStartSizeRandom = 1; 
	cp.fStartColor[0] = 20;
	cp.fStartColor[1] = 20;
	cp.fStartColor[2] = 20;
	cp.fStartColor[3] = 50;
	cp.fStartColorRandom[0] = 0;
	cp.fStartColorRandom[1] = 0;
	cp.fStartColorRandom[2] = 0;
	cp.fStartColorRandom[3] = 50;

	cp.fEndSize = 1; 
	cp.fEndSizeRandom = 4;
	cp.fEndColor[0] = 20;
	cp.fEndColor[1] = 20;
	cp.fEndColor[2] = 20;
	cp.fEndColor[3] = 10;
	cp.fEndColorRandom[0] = 0;
	cp.fEndColorRandom[1] = 0;
	cp.fEndColorRandom[2] = 0;
	cp.fEndColorRandom[3] = 0;

	cp.iBlendMode = 5;

	pPS->SetParams(cp);
	pPS->ulParticleSpawn = 0;
	pPS->SetTexture("graph/particles/lil_greypouf", 0, 200);

	Vec3f ep;
	ep.x = aePos->x;
	ep.y = aePos->y - 80;
	ep.z = aePos->z;
	pPS->SetPos(ep);
	pPS->Update(0);
	pPS->iParticleNbMax = 0;

	if (pParticleManager)
	{
		pParticleManager->AddSystem(pPS);
	} else {
		// TODO memory leak (pPS)?
	}

	// système de partoches pour la poussière au sol
	pPS = new ParticleSystem();
	
	cp.iNbMax = 20;
	cp.fLife = 1000; //2000
	cp.fLifeRandom = 2000;
	cp.p3Pos.x = 20;
	cp.p3Pos.y = 5;
	cp.p3Pos.z = 20;
	cp.p3Direction.x = 0;
	cp.p3Direction.y = -10;
	cp.p3Direction.z = 0;
	cp.fAngle = radians(144);
	cp.fSpeed = 10;
	cp.fSpeedRandom = 10;
	cp.p3Gravity.x = 0;
	cp.p3Gravity.y = -4;
	cp.p3Gravity.z = 0;
	cp.fFlash = 0;
	cp.fRotation = 0;

	cp.fStartSize = 2;
	cp.fStartSizeRandom = 2; 
	cp.fStartColor[0] = 25;
	cp.fStartColor[1] = 25;
	cp.fStartColor[2] = 25;
	cp.fStartColor[3] = 0;
	cp.fStartColorRandom[0] = 25;
	cp.fStartColorRandom[1] = 25;
	cp.fStartColorRandom[2] = 25;
	cp.fStartColorRandom[3] = 25;
	cp.bStartLock = true;

	cp.fEndSize = 5;
	cp.fEndSizeRandom = 10;
	cp.fEndColor[0] = 7;
	cp.fEndColor[1] = 7;
	cp.fEndColor[2] = 7;
	cp.fEndColor[3] = 0;
	cp.fEndColorRandom[0] = 27;
	cp.fEndColorRandom[1] = 0;
	cp.fEndColorRandom[2] = 0;
	cp.fEndColorRandom[3] = 0;
	cp.bEndLock = true;
	cp.iBlendMode = 5;

	pPS->SetParams(cp);
	pPS->ulParticleSpawn = 0;
	pPS->SetTexture("graph/particles/lil_greypouf", 0, 200);

	ep.x = aePos->x;
	ep.y = aePos->y - 10;
	ep.z = aePos->z;
	pPS->SetPos(ep);
	pPS->Update(0);
	pPS->iParticleNbMax = 0;

	if(pParticleManager) {
		pParticleManager->AddSystem(pPS);
	} else {
		// TODO memory leak (pPS)?
	}
}
コード例 #27
0
void keyboard(unsigned char key, int x, int y) {
  Particle p1;
  switch(key) {
    case ' ': // allow spacebar to end the program
      exit(0);
      break;
    case 'b':
      maxX = 1;
      maxY = 0;
      maxZ = 1;
      bBoxScene = false;
      bxScene = false;
      bzScene = false;
      bNoBound = true;
      pSystem.setBoundaries(-maxX, -1, -maxZ, maxX, maxY, maxZ);
      break;
    case 'p':
      p1 = Water();
      p1.setPosition(Point3D(0,.1,0));
      pSystem.addParticle(p1);
      break;
	case 'o':
		for(float i = 0.; i < 5; i++){
			for(float j = 0.; j < 5; j++){
				for(float k = 0.; k < 5; k++){
					p1 = Mucus();
					p1.setPosition(Point3D(i/50,j/50-.2,k/50));
					pSystem.addParticle(p1);
				}
			}
		}
      break;
	  	case 'w':
		for(float i = 0.; i < 5; i++){
			for(float j = 0.; j < 5; j++){
				for(float k = 0.; k < 5; k++){
					p1 = Water();
					p1.setPosition(Point3D(i/50,j/50-.2,k/50));
					pSystem.addParticle(p1);
				}
			}
		}
      break;
    case 'x': // opens up x portion of boundary
      bBoxScene = false;
      bxScene = true;
      bzScene = false;
      bNoBound = false;
      pSystem.setBoundaries(-1, -1, -.1, .1, 0, .1);
      break;
    case 'z': // open up z portion of the boundary
      bBoxScene = false;
      bxScene = false;
      bzScene = true;
      bNoBound = false;
      pSystem.setBoundaries(-.1, -1, -.2, .1, 0, .1);
      break;
	case 'c': // change camera
		camera++;
		if (camera > numcameras)
			camera = 1;
		break;
    default:
      break;
  }
  glutPostRedisplay();
}
コード例 #28
0
ファイル: scene.cpp プロジェクト: RafiKueng/TankGame
void Scene::updateScene()
{
	if ( _firstUpdate )
    {
        _firstUpdate = false;
		_timer.start();
		return;
    }

	float timeSinceLastUpdate = _timer.getMilliseconds()/1000;
	_secondsPlayed += timeSinceLastUpdate;
	_updateTime = timeSinceLastUpdate;
	_landscape.setTimeSinceLastUpdate(timeSinceLastUpdate);
	_timer.start();

	if (_nrKills >= getNrKillsToWin())
	{
		reset(true);
		return;
	}
	else if (_nrDeaths >= getNrDeathsToLose())
	{
		reset(false);
		return;
	}

    /**
    // save old configuration of enemies and playertank
    // (this will be used for the collision handling below)
    */
    Point *enemies_pos_old = new Point[getNrEnemies()];
    double *enemies_angle_old = new double[getNrEnemies()];
    Point player_pos_old = _playerTank.getPosition();
    double player_angle_old = _playerTank.getAngle();
    for(int i = 0; i < getNrEnemies(); i++)
    {
        enemies_pos_old[i] = _enemies[i].getPosition();
        enemies_angle_old[i] = _enemies[i].getAngle();
    }

	// let enemies choose their next action
	for (int i = 0; i < getNrEnemies(); i++)
	{
		_enemies[i].updateAction(&_landscape, _playerTank.getPosition());
	}

    /**
    // Update
    */
	// update tanks
	_playerTank.update(timeSinceLastUpdate);
	for (int i = 0; i < getNrEnemies(); i++)
	{
		_enemies[i].update(timeSinceLastUpdate);
		//_enemies[i].setSpeed(3.0);
	}
	// update bullets
    for ( BulletVector::iterator bulletIter = _bullets.begin();
         bulletIter != _bullets.end(); bulletIter++)
    {
        Bullet &bullet = *bulletIter;
        bullet.update(timeSinceLastUpdate, _xSlices, _zSlices, _planeX, _planeZ);
    }
	// check player tank if it is dead
	if(_playerTank.getState() == TANK_DYING)
	{
		ParticleSystem p;
        p.setPosition(Point(_playerTank.getPosition().x, _playerTank.getPosition().y + 1.0, _playerTank.getPosition().z));
        p.setVelRange(10.0);
        p.setLifetime(3.0);
        p.setRGB(0.5, 0.2, 0.0);
        _psystems.push_back(p);
        _playerTank.setState(TANK_DEAD);

		_nrDeaths++;
		_playerTank.reset();
	}
    // check enemies if they are dead
	for (int i = 0; i < getNrEnemies(); i++)
	{
		if(_enemies[i].getState() == TANK_DYING)
		{
		    ParticleSystem p;
            p.setPosition(Point(_enemies[i].getPosition().x, _enemies[i].getPosition().y + 1.0, _enemies[i].getPosition().z));
            p.setVelRange(10.0);
            p.setLifetime(3.0);
            p.setRGB(0.5, 0.2, 0.0);
            _psystems.push_back(p);
            _enemies[i].setState(TANK_DEAD);

			_nrKills++;
			_enemies[i].reset();
		}
	}
	//update particle systems
    //psystem.setPosition(Point(_playerTank.getPosition().x, _playerTank.getPosition().y + 1.0, _playerTank.getPosition().z));
	for (unsigned int i = 0; i < _psystems.size(); i++)
		_psystems[i].update(timeSinceLastUpdate);

    /**
    // Deletion and Death animation
    */
    // bullets
    for(unsigned int i = 0; i < _bullets.size(); i++)
    {
        if(_bullets[i].getState() == BULLET_DELETE)
        {
            ParticleSystem p;
            p.setPosition(Point(_bullets[i].getPosition().x, _bullets[i].getPosition().y + 0.2, _bullets[i].getPosition().z));
            p.setVelRange(5.0);
            p.setLifetime(3.0);
            p.setPeriod(5.0);
            p.setRGB(0.1, 0.1, 0.1);
            if(_bullets[i].getType() == BULLET_MG)
                p.setNParticles(3);
            _psystems.push_back(p);
            _bullets.erase(_bullets.begin()+i);
        }
    }
    // particle systems
    for(unsigned int i = 0; i < _psystems.size(); i++)
    {
        if(_psystems[i].getState() == PSYSTEM_DEAD)
        {
            _psystems.erase(_psystems.begin()+i);
        }
    }

    /**
    // Collision Check
    */
    collisionCheck(enemies_pos_old, enemies_angle_old, player_pos_old, player_angle_old);

    /**
    // Cleanup
    */
    delete [] enemies_pos_old;
    delete [] enemies_angle_old;
}
コード例 #29
0
ParticleSystemDrawable::ParticleSystemDrawable(const ParticleSystem& particle_system)
  : Drawable(Vector2f()),
    m_particle_system(particle_system)
{
  set_render_mask(particle_system.get_layer());
}
コード例 #30
0
ファイル: scene.cpp プロジェクト: RafiKueng/TankGame
void Scene::collisionCheck(Point *enemies_pos_old, double *enemies_angle_old,
                            Point player_pos_old, double player_angle_old )
{
    // playertank - enemy
    CollisionModel *cm1 = _playerTank.getCollisionModel();
    IntVector v1 = _playerTank.getFields();
    for(int i = 0; i < getNrEnemies(); i++)
    {
        // coarse check
        IntVector v2 = _enemies[i].getFields();
        if(!fieldsCollide(v1, v2))
        {
            continue;
        }

        // fine check
        CollisionModel *cm2 = _enemies[i].getCollisionModel();
        if(cm1->bCollision(cm2))
        {
            // collision sound
            Sound::playCollision(_enemies[i].getPosition());

            // recover old configurations
            _playerTank.setPosition(player_pos_old);
            _playerTank.setAngle(player_angle_old);
            _enemies[i].setPosition(enemies_pos_old[i]);
            _enemies[i].setAngle(enemies_angle_old[i]);
            _playerTank.updateCollisionModel();
            _enemies[i].updateCollisionModel();
            // swap velocities
            float temp = _playerTank.getSpeed();
            _playerTank.setSpeed(-_enemies[i].getSpeed());
            _enemies[i].setSpeed(-temp);
            // do a little bit of deleceration due to collisional friction
            _playerTank.setSpeed(_playerTank.getSpeed()*COLLISION_DECELERATION_COEFF);
            _playerTank.setAngularSpeed(_playerTank.getAngularSpeed()*COLLISION_DECELERATION_COEFF);
            _enemies[i].setSpeed(_enemies[i].getSpeed()*COLLISION_DECELERATION_COEFF);
            _enemies[i].setAngularSpeed(_enemies[i].getAngularSpeed()*COLLISION_DECELERATION_COEFF);
            // do check of full list again, due to possible collision cascade
            //i = 0;
        }
    }

    // enemy - enemy
    for(int i = 0; i < getNrEnemies(); i++)
    {
        // coarse check
        CollisionModel *cm1 = _enemies[i].getCollisionModel();
        IntVector v1 = _enemies[i].getFields();
        for(int j = i+1; j < getNrEnemies(); j++)
        {
            IntVector v2 = _enemies[j].getFields();
            if(!fieldsCollide(v1, v2))
            {
                continue;
            }

            // fine check
            CollisionModel *cm2 = _enemies[j].getCollisionModel();
            if(cm1->bCollision(cm2))
            {
                // collision sound
                Sound::playCollision(_enemies[i].getPosition());
                Sound::playCollision(_enemies[j].getPosition());

                // recover old configurations
                _enemies[i].setPosition(enemies_pos_old[i]);
                _enemies[i].setAngle(enemies_angle_old[i]);
                _enemies[j].setPosition(enemies_pos_old[j]);
                _enemies[j].setAngle(enemies_angle_old[j]);
                _enemies[i].updateCollisionModel();
                _enemies[j].updateCollisionModel();
                // swap velocities
                float temp = _enemies[i].getSpeed();
                _enemies[i].setSpeed(-_enemies[j].getSpeed());
                _enemies[j].setSpeed(-temp);
                // do a little bit of deleceration due to collisional friction
                _enemies[i].setSpeed(_enemies[i].getSpeed()*COLLISION_DECELERATION_COEFF);
                _enemies[i].setAngularSpeed(_enemies[i].getAngularSpeed()*COLLISION_DECELERATION_COEFF);
                _enemies[j].setSpeed(_enemies[j].getSpeed()*COLLISION_DECELERATION_COEFF);
                _enemies[j].setAngularSpeed(_enemies[j].getAngularSpeed()*COLLISION_DECELERATION_COEFF);
                // do check of full list again, due to possible collision cascade
                //i = 0;
            }
        }
    }

    // playertank - bullet
    v1 = _playerTank.getFields();
    for(unsigned int i = 0; i < _bullets.size(); i++)
    {
		if (_bullets[i].getState() == BULLET_DELETE)
			continue;

        // coarse check
        IntVector v2 = _bullets[i].getFields();
        if(!fieldsCollide(v1, v2))
        {
            continue;
        }

        // fine check
        CollisionModel *cm2 = _bullets[i].getCollisionModel();
        if(cm1->bCollision(cm2))
        {
			// play explosion sound
			if (_bullets[i].getType() == BULLET_GRENADE)
				Sound::playGrenade(_playerTank.getPosition());
			else if (_bullets[i].getType() == BULLET_MG)
				Sound::playProjectile(_playerTank.getPosition());
            // deal damage to playertank
            int damage = GRENADE_DAMAGE;
            if(_bullets[i].getType() == BULLET_MG)
                damage = MG_DAMAGE;
            _playerTank.setHealth(_playerTank.getHealth() - damage);
            // delete the bullet
            _bullets[i].setState(BULLET_DELETE);
			// generate particle system
            ParticleSystem p;
            p.setPosition(Point(_playerTank.getPosition().x, _playerTank.getPosition().y + 1.0, _playerTank.getPosition().z));
            p.setVelRange(10.0);
            p.setLifetime(3.0);
            p.setRGB(0.07, 0.1, 0.07);
            p.setNParticles(10);
            _psystems.push_back(p);
        }
    }

    // enemy - bullet
    for(int i = 0; i < getNrEnemies(); i++)
    {
        CollisionModel *cm1 = _enemies[i].getCollisionModel();
        v1 = _enemies[i].getFields();
        for(unsigned int j = 0; j < _bullets.size(); j++)
        {
			if (_bullets[j].getState() == BULLET_DELETE)
				continue;

            // coarse check
            IntVector v2 = _bullets[j].getFields();
            if(!fieldsCollide(v1, v2))
            {
                continue;
            }

            // fine check
            CollisionModel *cm2 = _bullets[j].getCollisionModel();
            if(cm1->bCollision(cm2))
            {
				// play explosion sound
				if (_bullets[j].getType() == BULLET_GRENADE)
					Sound::playGrenade(_enemies[i].getPosition());
				else if (_bullets[j].getType() == BULLET_MG)
					Sound::playProjectile(_enemies[i].getPosition());
                // deal damage to enemy
                int damage = GRENADE_DAMAGE;
                if(_bullets[j].getType() == BULLET_MG)
                    damage = MG_DAMAGE;
                _enemies[i].setHealth(_enemies[i].getHealth() - damage);
                // delete the bullet
                _bullets[j].setState(BULLET_DELETE);
                // generate particle system
                ParticleSystem p;
                p.setPosition(Point(_enemies[i].getPosition().x, _enemies[i].getPosition().y + 1.0, _enemies[i].getPosition().z));
                p.setVelRange(10.0);
                p.setLifetime(3.0);
                p.setRGB(0.1, 0.05, 0.05);
                p.setNParticles(10);
                _psystems.push_back(p);
            }
        }
    }

    // building - playertank
    v1 = _playerTank.getFields();
    IntVector coarse_collisions = fieldsCollideWithBuilding(v1);
    if(coarse_collisions.size() != 0)           // coarse check
    {
        if(RectCollidesWithFields(_playerTank.getCollisionModel(), coarse_collisions)) // fine check
        {
            // play a collision sound
            Sound::playCollision(_playerTank.getPosition());
            // recover old configuration
            _playerTank.setPosition(player_pos_old);
            _playerTank.setAngle(player_angle_old);
            _playerTank.updateCollisionModel();
            // reflect velocity
            _playerTank.setSpeed(-_playerTank.getSpeed());
            // do a little bit of deleceration due to collisional friction
            _playerTank.setSpeed(_playerTank.getSpeed()*COLLISION_DECELERATION_COEFF);
            _playerTank.setAngularSpeed(_playerTank.getAngularSpeed()*COLLISION_DECELERATION_COEFF);
        }

    }

    // building - bullet
    for(unsigned int i = 0; i < _bullets.size(); i++)
    {
        // coarse check
        v1 = _bullets[i].getFields();
        IntVector coarse_collisions = fieldsCollideWithBuilding(v1);
        //fine check
        if(coarse_collisions.size() != 0)
        {
            if(RectCollidesWithFields(_bullets[i].getCollisionModel(), coarse_collisions)) // fine check
            {
				// play explosion sound
				if (_bullets[i].getType() == BULLET_GRENADE)
					Sound::playGrenade(_bullets[i].getPosition());
				else if (_bullets[i].getType() == BULLET_MG)
					Sound::playProjectile(_bullets[i].getPosition());
				// delete bullet
                _bullets[i].setState(BULLET_DELETE);
            }
        }
    }

     // building - enemy
    for(int i = 0; i < getNrEnemies(); i++)
    {
        // coarse check
        v1 = _enemies[i].getFields();
        IntVector coarse_collisions = fieldsCollideWithBuilding(v1);
        //fine check
        if(coarse_collisions.size() != 0)
        {
            if(RectCollidesWithFields(_enemies[i].getCollisionModel(), coarse_collisions)) // fine check
            {
                // play a collision sound
                Sound::playCollision(_enemies[i].getPosition());
                // recover old configuration
                _enemies[i].setPosition(enemies_pos_old[i]);
                _enemies[i].setAngle(enemies_angle_old[i]);
                _enemies[i].updateCollisionModel();
				// reflect velocity
				_enemies[i].setSpeed(-_enemies[i].getSpeed());
                // do a little bit of deleceration due to collisional friction
                _enemies[i].setSpeed(_enemies[i].getSpeed()*COLLISION_DECELERATION_COEFF);
                _enemies[i].setAngularSpeed(_enemies[i].getAngularSpeed()*COLLISION_DECELERATION_COEFF);
            }
        }
    }

    // powerup - playertank
    std::vector<PowerUp*> powerups = _landscape.getPowerupVector();
    float x = _playerTank.getPosition().x;
    float z = _playerTank.getPosition().z;
    int tank_x_idx = int(floor(x));
    int tank_z_idx = int(floor(z));
    for(unsigned int i = 0; i < powerups.size(); i++)
    {
        int *loc = powerups[i]->getLocation();
        int pu_x_idx = loc[0] - FIELD_SIZE/2.0;
        int pu_z_idx = loc[1] - FIELD_SIZE/2.0;
        if(tank_x_idx == pu_x_idx && tank_z_idx == pu_z_idx)
        {
            if( powerups[i]->getType() == POWERUP_GRENADE)
            {
                _playerTank.enableGrenadeLauncher();
            }
            else
				_playerTank.setHealth(_playerTank.getHealth() + POWERUP_HEALTH_BONUS);

            /** TODO: uncomment this function when it is fixed */
            _landscape.powerupPickedUp(loc);
        }
    }

    // enemies - playertank
    for(int i = 0; i < getNrEnemies(); i++)
    {
        float x = _enemies[i].getPosition().x;
        float z = _enemies[i].getPosition().z;
        int enemy_x_idx = int(floor(x));
        int enemy_z_idx = int(floor(z));
        for(unsigned int j = 0; j < powerups.size(); j++)
        {
            int *loc = powerups[j]->getLocation();
            int pu_x_idx = loc[0] - FIELD_SIZE/2.0;
            int pu_z_idx = loc[1] - FIELD_SIZE/2.0;
            if(enemy_x_idx == pu_x_idx && enemy_z_idx == pu_z_idx)
            {
                if( powerups[j]->getType() == POWERUP_GRENADE)
                {
                    _enemies[i].enableGrenadeLauncher();
                }
                else
                    _enemies[i].setHealth(_enemies[i].getHealth() + POWERUP_HEALTH_BONUS);

                /** TODO: uncomment this function when it is fixed */
                //_landscape.powerupPickedUp(loc);
            }
        }
    }

}