Exemple #1
0
void Cinema::keyPressed(int key){
        switch(key){
            case ' ':{
//                dbIndex = ofRandom(strdb.size());
                loadLaterIndex = ofRandom(strdb[dbIndex].size());
                loadMovie(app->parameterMap[selectedPlayer], dbIndex, loadLaterIndex, true);
            }break;
            case '&':
                app->parameterMap[selectedPlayer] = 0;break;
            case 233:
                app->parameterMap[selectedPlayer] = 1;break;
            case 'n':
                {
                    randomPosition(ofRandom(0,1));
                    app->deltaMap[user5] = 1;
                        stillFbo->begin(); //capture transition fbo
                        fbo.draw(0,0);
                        stillFbo->end();
                }
                break;
            case 4352: randomPosition(ofRandom(0,1));
                break;
            default:;
                
        }
    };
Exemple #2
0
void Cinema::randomScene(string tag){
        string path = players[app->parameterMap[selectedPlayer]]->getMoviePath();
        float pos, pos2;
        if(playerScenes[path].size()>0){
            vector<int> indexes;
            for(int i=0;i<playerScenesMovements[path].size();i++)
                if(!playerScenesMovements[path][i].compare(tag))
                    indexes.push_back(playerScenes[path][i]);
            if(indexes.size()==0){
                randomPosition(ofRandom(1));
                return;
            }
            
            int sx = (int) (ofRandom(1) * indexes.size());
            pos = indexes[sx];
            for(int i=0;i<playerScenes[path].size();i++)
                if(pos==playerScenes[path][i])
                    pos2 = i<playerScenes[path].size()-1 ? playerScenes[path][i+1] : players[app->parameterMap[selectedPlayer]]->getTotalNumFrames()-1;
            players[app->parameterMap[selectedPlayer]]->setFrame(pos);
            app->parameterMap[loopLength] = pos2-pos;
            app->parameterMap[loopStart] = pos;
        }else{
            players[app->parameterMap[selectedPlayer]]->setPosition(ofRandom(1));
        }
    }
Exemple #3
0
	void TankWarWorld::createTrees(float time){
		Tree *t;
		Ogre::Vector3 randomPosition(Ogre::Math::RangeRandom(-1500,1500), 0, Ogre::Math::RangeRandom(-1500,1500));
		if(treeFactory->treeList.size() < 10){
			t = treeFactory->generateTree(randomPosition, Ogre::Matrix3::IDENTITY);
			geometryList.push_back(t->getEntity());
		}
		
	}
Exemple #4
0
	void TankWarWorld::addBonusItems(float time){
		if(itemFactory->itemList.size() < 25){
			//srand(time);
			Ogre::Vector3 randomPosition(Ogre::Math::RangeRandom(-1500,1500), 10, Ogre::Math::RangeRandom(-1500,1500));
			int r = rand()%3;
			if(r == 0) itemFactory->generateItem(randomPosition, time, ITEM_MACHINE_GUN);	 
			else if(r == 1) itemFactory->generateItem(randomPosition, time, ITEM_HEALTH);	 
			else if(r == 2) itemFactory->generateItem(randomPosition, time, ITEM_LAND_MINE);	 

		}
	}
void ObjectsMenager::CreateRandomModelMatrix(unsigned int minSize,unsigned int maxSize,int minPosition,int maxPosition,Object &obj)
{
	boost::random::uniform_int_distribution<> randomSize(minSize,maxSize);
	boost::random::uniform_int_distribution<> randomPosition(minPosition,maxPosition);
	boost::random::uniform_int_distribution<> randomRotation(-360,360);
	float s = randomSize(rng);
	glm::vec3 scale(s,s,s);

	float x = randomPosition(rng);
	float y = randomPosition(rng);
	float z = randomPosition(rng);
	glm::vec3 position(x,y,z);

	float rotateX=randomRotation(rng);
	float rotateY=randomRotation(rng);
	float rotateZ=randomRotation(rng);
	glm::mat4 rotationMatrix=glm::eulerAngleYXZ(rotateY,rotateX,rotateZ);

	obj.SetModelMatrix(position,rotationMatrix,scale);
}
Exemple #6
0
bool createBoxShape( int shapeIndex )
{
	//#ifdef _DEBUG
	//static bool b = true;
	//
	//if ( b )
	//{
	//	g_pConvexShapes[ shapeIndex ] = new BoxShape( SimdVector3( 1, 1, 1 ) );

	//	g_pConvexShapes[ shapeIndex ]->SetMargin( 0.05 );

	//	g_convexShapesTransform[ shapeIndex ].setIdentity();

	//	SimdMatrix3x3 basis(  0.99365157, 0.024418538, -0.10981932,
	//						 -0.025452739, 0.99964380, -0.0080251107,
	//						  0.10958424, 0.010769366, 0.99391919 );

	//	g_convexShapesTransform[ shapeIndex ].setOrigin( SimdVector3( 4.4916530, -19.059078, -0.22695254 ) );
	//	g_convexShapesTransform[ shapeIndex ].setBasis( basis );

	//	b = false;
	//}
	//else
	//{
	//	g_pConvexShapes[ shapeIndex ] = new BoxShape( SimdVector3( 25, 10, 25 ) );

	//	g_pConvexShapes[ shapeIndex ]->SetMargin( 0.05 );

	//	//SimdMatrix3x3 basis( 0.658257, 0.675022, -0.333709,
	//	//					-0.333120, 0.658556, 0.675023,
	//	//					 0.675314, -0.333120, 0.658256 );

	//	g_convexShapesTransform[ shapeIndex ].setIdentity();

	//	g_convexShapesTransform[ shapeIndex ].setOrigin( SimdVector3( 0, -30, 0/*0.326090, -0.667531, 0.214331*/ ) );
	//	//g_convexShapesTransform[ shapeIndex ].setBasis( basis );
	//}
	//#endif

	g_pConvexShapes[ shapeIndex ] = new BoxShape( SimdVector3( 1, 1, 1 ) );

	g_pConvexShapes[ shapeIndex ]->SetMargin( 1e-1 );

	g_convexShapesTransform[ shapeIndex ].setIdentity();

	g_convexShapesTransform[ shapeIndex ].setOrigin( randomPosition( g_sceneVolumeMin, g_sceneVolumeMax ) );

	return true;
}
Exemple #7
0
/* Creates an individual randomly positioned ball */
QGLSceneNode *ModelBall::createNode(QGLMaterial *material) {
    const float defaultSize = 1.0;
    const float positionX = -1.5;
    const float positionY = 40.0;
    const float randomPositionScale = 1000.0;
    QGLBuilder builder;
    QGLSceneNode *node;
    builder.newNode();
    builder << QGLSphere(defaultSize);
    node = builder.finalizedSceneNode();
    node->setMaterial(material);
    node->setEffect(QGL::LitMaterial);
    QGraphicsTranslation3D *trans = new QGraphicsTranslation3D();
    node->addTransform(trans);
    QGraphicsTranslation3D *transStart = new QGraphicsTranslation3D();
    QVector3D *randomStart = new QVector3D(positionX +
                                           randomPosition()/randomPositionScale,
                                           positionY +
                                           randomPosition()/randomPositionScale,
                                           randomPosition()/randomPositionScale);
    transStart->setTranslate(*randomStart);
    node->addTransform(transStart);
    return node;
}
Exemple #8
0
void PSO::Swarm::randomizeInf(int maxTries) {
  int cnt(0);
  double f(-INFINITY);
  for (int j = 0; j < swarmSize; ++j) {
    if (swarm[j]->value == -INFINITY) {
      cerr << "f(" << j << ") = Inf. Randomizing position..." << flush;
      cnt = 0;
      f = -INFINITY;
      while (cnt++ <= maxTries) {
        randomPosition(j);
        f = evaluateParticle(j);
        if (f > -INFINITY) break;
      }
      cerr << " new pos = " << *swarm[j] << endl;
    }
  }
}
Exemple #9
0
bool createSphereShape( int shapeIndex )
{
	g_pConvexShapes[ shapeIndex ] = new SphereShape( g_sphereRadius );

	g_pConvexShapes[ shapeIndex ]->SetMargin( 1e-1 );

	g_convexShapesTransform[ shapeIndex ].setIdentity();
	g_convexShapesTransform[ shapeIndex ].setOrigin( randomPosition( g_sceneVolumeMin, g_sceneVolumeMax ) );

	//#ifdef _DEBUG
	//static bool b = true;
	//if ( b )
	//{
	//	g_convexShapesTransform[ shapeIndex ].setOrigin( SimdVector3( 0.001, 0, 0 ) );
	//	b = false;
	//}
	//else
	//{
	//	g_convexShapesTransform[ shapeIndex ].setOrigin( SimdVector3( 0, 0, 0 ) );
	//}
	//#endif

	return true;
}
Exemple #10
0
void NoiseGen::mainLoop()
{
    bool quit = false;
    bool refresh = true;
    //int cursor = 0;
    //bool viewcontrol = false;
//    int viewcontrolunits = 12; // how many units moved when in view control
    bool mapDrag = false;
    sf::Vector2i mapDragOffset;


    //debug
    //std::cout << "SCREEN :" << IMAGE_SIZE*IMAGE_SCALE+RIGHT_MARGIN_WIDTH << "," << IMAGE_SIZE*IMAGE_SCALE+BOTTOM_MARGIN_HEIGHT << std::endl;

   while(!quit)
    {

        sf::Event event;

        screen->clear();

        //check for right mouse button release if dragging
        if(mapDrag && !sf::Mouse::isButtonPressed(sf::Mouse::Right))
        {
            mapDrag = false;
            xpos = xpos - (sf::Mouse::getPosition(*screen).x - mapDragOffset.x);
            ypos = ypos - (sf::Mouse::getPosition(*screen).y - mapDragOffset.y);

            refresh = true;
        }
        else if(mapDrag) refresh = true;

        //create, populate, and display map image
        if(refresh)
        {
            if(sf::Mouse::isButtonPressed(sf::Mouse::Right) && mapDrag)
            {
                int x_off = sf::Mouse::getPosition(*screen).x - mapDragOffset.x;
                int y_off = sf::Mouse::getPosition(*screen).y - mapDragOffset.y;

                createMapImage(xpos - x_off, ypos - y_off);

            }
            else createMapImage(xpos, ypos);
            refresh = false;
        }

        //DRAW OBJECTS
        drawMap();
        drawSliders();
        drawButtons();
        drawCoordinates( sf::Vector2i(IMAGE_SCALE*IMAGE_SIZE + 12, 300));

        //debug draw mouse coordinates
        /*
        std::stringstream mpos;
        mpos << "(" << sf::Mouse::getPosition(*screen).x << "," << sf::Mouse::getPosition(*screen).y << ")";
        sf::Text mposTXT(mpos.str(), font, 12);
        mposTXT.setColor(sf::Color(200,0,0));
        screen->draw(mposTXT);
        */

        //handle input
        while(screen->pollEvent(event))
        {
            //if resize event happened
            if(event.type == sf::Event::Resized)
            {
                screen->setSize( sf::Vector2u(IMAGE_SCALE*IMAGE_SIZE + RIGHT_MARGIN_WIDTH, IMAGE_SCALE*IMAGE_SIZE + BOTTOM_MARGIN_HEIGHT));
                continue;
            }

            //pass event to sliders
            if(updateSliders(&event)) refresh = true;


            //WINDOW CLOSE EVENT
            if(event.type == sf::Event::Closed) quit = true;

            // MOUSE EVENTS
            if(event.type == sf::Event::MouseButtonPressed)
            {
                //LEFT MOUSE BUTTON
                if(event.mouseButton.button == sf::Mouse::Left)
                {
                    for(int i = 0; i < int(buttons.size()); i++)
                    {
                        if(buttons[i]->mouseIn())
                        {
                            switch(i)
                            {
                            case 0:
                                N_MODE = SIMPLEX;
                                break;
                            case 1:
                                N_MODE = PERLIN;
                                break;
                            case 2:
                                if(terrainmode) terrainmode = false;
                                else terrainmode = true;
                                break;
                            case 3:
                                exportToTXT();
                                break;
                            case 4:
                                exportToIMAGE();
                                break;
                            case 5:
                                randomPosition();
                                break;
                            case 6:
                                /*
                                defaultSettings();
                                updateSliders(NULL);
                                refresh = true;
                                */
                                reloadDefaultSettings();
                                break;
                            default:
                                break;
                            }

                            refresh = true;

                        }
                    }

                }
                else if(event.mouseButton.button == sf::Mouse::Right)
                {
                    sf::Vector2i m_pos = sf::Mouse::getPosition(*screen);

                    if(m_pos.x >= 0 && m_pos.x <= mapTexture->getSize().x && m_pos.y >= 0 && m_pos.y <= mapTexture->getSize().y)
                    {
                        mapDrag = true;
                        mapDragOffset = m_pos;
                        refresh = true;
                    }

                }

            }

            // KEYBOARD EVENTS
            if(event.type == sf::Event::KeyPressed)
            {
                //escape to quit
                if(event.key.code == sf::Keyboard::Escape)
                {
                    quit = true;
                }
                else if(event.key.code == sf::Keyboard::Q)
                {
                    /*
                    defaultSettings();
                    std::cout << "loaded default settings\n";
                    initTerrainSlider(); // memory leak?
                    std::cout << "initialized terrain slider\n";
                    updateSliders(NULL);
                    std::cout << "updated sliders\n";
                    */
                    reloadDefaultSettings();
                    refresh = true;
                }
                else if(event.key.code == sf::Keyboard::F1)
                {
                    segment newseg;
                    newseg.value = 254;
                    newseg.red = rand()%256;
                    newseg.green = rand()%256;
                    newseg.blue = rand()%256;

                    terSlider->addSegment(&newseg);
                }
                else if(event.key.code == sf::Keyboard::F5)
                {
                    xpos = 10;
                    ypos = 10;
                    refresh = true;
                }
                else if(event.key.code == sf::Keyboard::W) {ypos = ypos - IMAGE_SIZE/2; refresh = true;}
                else if(event.key.code == sf::Keyboard::S) {ypos = ypos + IMAGE_SIZE/2; refresh = true;}
                else if(event.key.code == sf::Keyboard::A) {xpos = xpos - IMAGE_SIZE/2; refresh = true;}
                else if(event.key.code == sf::Keyboard::D) {xpos = xpos + IMAGE_SIZE/2; refresh = true;}


            }
        }

        //draw screen
        screen->display();


    }

    //save settings after mainloop quit
    saveSettings();
}
Exemple #11
0
void RandomInlet::run(){
	DemField* dem=static_cast<DemField*>(field.get());
	if(!generator) throw std::runtime_error("RandomInlet.generator==None!");
	if(materials.empty()) throw std::runtime_error("RandomInlet.materials is empty!");
	if(collideExisting){
		if(!collider){
		for(const auto& e: scene->engines){ collider=dynamic_pointer_cast<Collider>(e); if(collider) break; }
		if(!collider) throw std::runtime_error("RandomInlet: no Collider found within engines (needed for collisions detection with already existing particles; if you don't need that, set collideExisting=False.)");
		}
		if(dynamic_pointer_cast<InsertionSortCollider>(collider)) static_pointer_cast<InsertionSortCollider>(collider)->forceInitSort=true;
	}
	if(isnan(massRate)) throw std::runtime_error("RandomInlet.massRate must be given (is "+to_string(massRate)+"); if you want to generate as many particles as possible, say massRate=0.");
	if(massRate<=0 && maxAttempts==0) throw std::runtime_error("RandomInlet.massFlowRate<=0 (no massFlowRate prescribed), but RandomInlet.maxAttempts==0. (unlimited number of attempts); this would cause infinite loop.");
	if(maxAttempts<0){
		std::runtime_error("RandomInlet.maxAttempts must be non-negative. Negative value, leading to meaking engine dead, is achieved by setting atMaxAttempts=RandomInlet.maxAttDead now.");
	}
	spheresOnly=generator->isSpheresOnly();
	padDist=generator->padDist();
	if(isnan(padDist) || padDist<0) throw std::runtime_error(generator->pyStr()+".padDist(): returned invalid value "+to_string(padDist));

	// as if some time has already elapsed at the very start
	// otherwise mass flow rate is too big since one particle during Δt exceeds it easily
	// equivalent to not running the first time, but without time waste
	if(stepPrev==-1 && stepPeriod>0) stepPrev=-stepPeriod; 
	long nSteps=scene->step-stepPrev;
	// to be attained in this step;
	stepGoalMass+=massRate*scene->dt*nSteps; // stepLast==-1 if never run, which is OK
	vector<AlignedBox3r> genBoxes; // of particles created in this step
	vector<shared_ptr<Particle>> generated;
	Real stepMass=0.;

	SpherePack spheres;
	//
	if(spheresOnly){
		spheres.pack.reserve(dem->particles->size()*1.2); // something extra for generated particles
		// HACK!!!
		bool isBox=dynamic_cast<BoxInlet*>(this);
		AlignedBox3r box;
		if(isBox){ box=this->cast<BoxInlet>().box; }
		for(const auto& p: *dem->particles){
			if(p->shape->isA<Sphere>() && (!isBox || box.contains(p->shape->nodes[0]->pos))) spheres.pack.push_back(SpherePack::Sph(p->shape->nodes[0]->pos,p->shape->cast<Sphere>().radius));
		}
	}

	while(true){
		// finished forever
		if(everythingDone()) return;

		// finished in this step
		if(massRate>0 && mass>=stepGoalMass) break;

		shared_ptr<Material> mat;
		Vector3r pos=Vector3r::Zero();
		Real diam;
		vector<ParticleGenerator::ParticleAndBox> pee;
		int attempt=-1;
		while(true){
			attempt++;
			/***** too many tries, give up ******/
			if(attempt>=maxAttempts){
				generator->revokeLast(); // last particle could not be placed
				if(massRate<=0){
					LOG_DEBUG("maxAttempts="<<maxAttempts<<" reached; since massRate is not positive, we're done in this step");
					goto stepDone;
				}
				switch(atMaxAttempts){
					case MAXATT_ERROR: throw std::runtime_error("RandomInlet.maxAttempts reached ("+lexical_cast<string>(maxAttempts)+")"); break;
					case MAXATT_DEAD:{
						LOG_INFO("maxAttempts="<<maxAttempts<<" reached, making myself dead.");
						this->dead=true;
						return;
					}
					case MAXATT_WARN: LOG_WARN("maxAttempts "<<maxAttempts<<" reached before required mass amount was generated; continuing, since maxAttemptsError==False"); break;
					case MAXATT_SILENT: break;
					default: throw std::invalid_argument("Invalid value of RandomInlet.atMaxAttempts="+to_string(atMaxAttempts)+".");
				}
			}
			/***** each maxAttempts/attPerPar, try a new particles *****/	
			if((attempt%(maxAttempts/attemptPar))==0){
				LOG_DEBUG("attempt "<<attempt<<": trying with a new particle.");
				if(attempt>0) generator->revokeLast(); // if not at the beginning, revoke the last particle

				// random choice of material with equal probability
				if(materials.size()==1) mat=materials[0];
				else{ 
					size_t i=max(size_t(materials.size()*Mathr::UnitRandom()),materials.size()-1);;
					mat=materials[i];
				}
				// generate a new particle
				std::tie(diam,pee)=(*generator)(mat,scene->time);
				assert(!pee.empty());
				LOG_TRACE("Placing "<<pee.size()<<"-sized particle; first component is a "<<pee[0].par->getClassName()<<", extents from "<<pee[0].extents.min().transpose()<<" to "<<pee[0].extents.max().transpose());
			}

			pos=randomPosition(diam,padDist); // overridden in child classes
			LOG_TRACE("Trying pos="<<pos.transpose());
			for(const auto& pe: pee){
				// make translated copy
				AlignedBox3r peBox(pe.extents); peBox.translate(pos); 
				// box is not entirely within the factory shape
				if(!validateBox(peBox)){ LOG_TRACE("validateBox failed."); goto tryAgain; }

				const shared_ptr<woo::Sphere>& peSphere=dynamic_pointer_cast<woo::Sphere>(pe.par->shape);

				if(spheresOnly){
					if(!peSphere) throw std::runtime_error("RandomInlet.spheresOnly: is true, but a nonspherical particle ("+pe.par->shape->pyStr()+") was returned by the generator.");
					Real r=peSphere->radius;
					Vector3r subPos=peSphere->nodes[0]->pos;
					for(const auto& s: spheres.pack){
						// check dist && don't collide with another sphere from this clump
						// (abuses the *num* counter for clumpId)
						if((s.c-(pos+subPos)).squaredNorm()<pow(s.r+r,2)){
							LOG_TRACE("Collision with a particle in SpherePack (a particle generated in this step).");
							goto tryAgain;
						}
					}
					// don't add to spheres until all particles will have been checked for overlaps (below)
				} else {
					// see intersection with existing particles
					bool overlap=false;
					if(collideExisting){
						vector<Particle::id_t> ids=collider->probeAabb(peBox.min(),peBox.max());
						for(const auto& id: ids){
							LOG_TRACE("Collider reports intersection with #"<<id);
							if(id>(Particle::id_t)dem->particles->size() || !(*dem->particles)[id]) continue;
							const shared_ptr<Shape>& sh2((*dem->particles)[id]->shape);
							// no spheres, or they are too close
							if(!peSphere || !sh2->isA<woo::Sphere>() || 1.1*(pos-sh2->nodes[0]->pos).squaredNorm()<pow(peSphere->radius+sh2->cast<Sphere>().radius,2)) goto tryAgain;
						}
					}

					// intersection with particles generated by ourselves in this step
					for(size_t i=0; i<genBoxes.size(); i++){
						overlap=(genBoxes[i].squaredExteriorDistance(peBox)==0.);
						if(overlap){
							const auto& genSh(generated[i]->shape);
							// for spheres, try to compute whether they really touch
							if(!peSphere || !genSh->isA<Sphere>() || (pos-genSh->nodes[0]->pos).squaredNorm()<pow(peSphere->radius+genSh->cast<Sphere>().radius,2)){
								LOG_TRACE("Collision with "<<i<<"-th particle generated in this step.");
								goto tryAgain;
							}
						}
					}
				}
			}
			LOG_DEBUG("No collision (attempt "<<attempt<<"), particle will be created :-) ");
			if(spheresOnly){
				// num will be the same for all spheres within this clump (abuse the *num* counter)
				for(const auto& pe: pee){
					Vector3r subPos=pe.par->shape->nodes[0]->pos;
					Real r=pe.par->shape->cast<Sphere>().radius;
					spheres.pack.push_back(SpherePack::Sph((pos+subPos),r,/*clumpId*/(pee.size()==1?-1:num)));
				}
			}
			break;
			tryAgain: ; // try to position the same particle again
		}

		// particle was generated successfully and we have place for it
		for(const auto& pe: pee){
			genBoxes.push_back(AlignedBox3r(pe.extents).translate(pos));
			generated.push_back(pe.par);
		}

		num+=1;

		#ifdef WOO_OPENGL			
			Real color_=isnan(color)?Mathr::UnitRandom():color;
		#endif
		if(pee.size()>1){ // clump was generated
			//LOG_WARN("Clumps not yet tested properly.");
			vector<shared_ptr<Node>> nn;
			for(auto& pe: pee){
				auto& p=pe.par;
				p->mask=mask;
				#ifdef WOO_OPENGL
					assert(p->shape);
					if(color_>=0) p->shape->color=color_; // otherwise keep generator-assigned color
				#endif
				if(p->shape->nodes.size()!=1) LOG_WARN("Adding suspicious clump containing particle with more than one node (please check, this is perhaps not tested");
				for(const auto& n: p->shape->nodes){
					nn.push_back(n);
					n->pos+=pos;
				}
				dem->particles->insert(p);
			}
			shared_ptr<Node> clump=ClumpData::makeClump(nn,/*no central node pre-given*/shared_ptr<Node>(),/*intersection*/false);
			auto& dyn=clump->getData<DemData>();
			if(shooter) (*shooter)(clump);
			if(scene->trackEnergy) scene->energy->add(-DemData::getEk_any(clump,true,true,scene),"kinInlet",kinEnergyIx,EnergyTracker::ZeroDontCreate);
			if(dyn.angVel!=Vector3r::Zero()){
				throw std::runtime_error("pkg/dem/RandomInlet.cpp: generated particle has non-zero angular velocity; angular momentum should be computed so that rotation integration is correct, but it was not yet implemented.");
				// TODO: compute initial angular momentum, since we will (very likely) use the aspherical integrator
			}
			ClumpData::applyToMembers(clump,/*reset*/false); // apply velocity
			#ifdef WOO_OPENGL
				boost::mutex::scoped_lock lock(dem->nodesMutex);
			#endif
			dyn.linIx=dem->nodes.size();
			dem->nodes.push_back(clump);

			mass+=clump->getData<DemData>().mass;
			stepMass+=clump->getData<DemData>().mass;
		} else {
			auto& p=pee[0].par;
			p->mask=mask;
			assert(p->shape);
			#ifdef WOO_OPENGL
				if(color_>=0) p->shape->color=color_;
			#endif
			assert(p->shape->nodes.size()==1); // if this fails, enable the block below
			const auto& node0=p->shape->nodes[0];
			assert(node0->pos==Vector3r::Zero());
			node0->pos+=pos;
			auto& dyn=node0->getData<DemData>();
			if(shooter) (*shooter)(node0);
			if(scene->trackEnergy) scene->energy->add(-DemData::getEk_any(node0,true,true,scene),"kinInlet",kinEnergyIx,EnergyTracker::ZeroDontCreate);
			mass+=dyn.mass;
			stepMass+=dyn.mass;
			assert(node0->hasData<DemData>());
			dem->particles->insert(p);
			#ifdef WOO_OPENGL
				boost::mutex::scoped_lock lock(dem->nodesMutex);
			#endif
			dyn.linIx=dem->nodes.size();
			dem->nodes.push_back(node0);
			// handle multi-nodal particle (unused now)
			#if 0
				// TODO: track energy of the shooter
				// in case the particle is multinodal, apply the same to all nodes
				if(shooter) shooter(p.shape->nodes[0]);
				const Vector3r& vel(p->shape->nodes[0]->getData<DemData>().vel); const Vector3r& angVel(p->shape->nodes[0]->getData<DemData>().angVel);
				for(const auto& n: p.shape->nodes){
					auto& dyn=n->getData<DemData>();
					dyn.vel=vel; dyn.angVel=angVel;
					mass+=dyn.mass;

					n->linIx=dem->nodes.size();
					dem->nodes.push_back(n);
				}
			#endif
		}
	};

	stepDone:
	setCurrRate(stepMass/(nSteps*scene->dt));
}
Exemple #12
0
	void TankFactory::autoGenerate(int rank, TANK_TYPE type){
		Ogre::Vector3 randomPosition(Ogre::Math::RangeRandom(-1500,1500), 0, Ogre::Math::RangeRandom(-1500,1500));
	
		generateTank(randomPosition, rank, type);
	}
Snake::Snake(byte length, byte turnChance) {
    xyz startPos = randomPosition();
    init(length, turnChance, startPos, randomValidDirection(startPos));
}
Exemple #14
0
void Cinema::update(){
        if (app->deltaMap[switchImg]) {
            app->deltaMap[switchImg] = app->parameterMap[switchImg] = 0;
            randomPosition(ofRandom(0,1));
        }
        
        if(triggerPlayLater){
            for(int i=0;i<players.size();i++)
                if(players[i]!=0 && !players[i]->isPlaying() && playerIntensities[i]!=0)
                    players[i]->play();
            triggerPlayLater= false;
        }
        
        app->parameterMap[circleRotation] = app->parameterMap[circleRotation] + (app->deltaMap[circleRotation]-app->parameterMap[circleRotation])*0.6;
        app->parameterMap[circleDist] = app->parameterMap[circleDist] + (app->deltaMap[circleDist]-app->parameterMap[circleDist])*0.6;
        
        
        //        if(syncToTempo){
        //            int index = 0;
        //            int sceneIndex = 0;
        //            double posToFrame = players[0]->getTotalNumFrames();
        //            loopStart = playerScenes[strdb[index][sceneIndex]] * posToFrame;
        //            loopLength = (playerScenes[index][sceneIndex+1]-playerScenes[index][sceneIndex]) * posToFrame;
        //            if(ofGetFrameNum()>3)
        //                players[0]->setSpeed(app->bpm*60*ofGetFrameRate()/(float)(4*loopLength));
        //        }
        
        videoMutex.lock();
        
        if(app->deltaMap[loopLength]>0){
            int p = players[app->parameterMap[selectedPlayer]]->getCurrentFrame()-app->parameterMap[loopStart];
            if(p>app->deltaMap[loopLength]-1 || p<-app->deltaMap[loopLength]){
                if(app->deltaMap[loopMode]==1){
                    int sens = p>app->parameterMap[loopLength]-1 ? -1 : 1;
                    if(app->parameterMap[movieSpeed] != abs(app->parameterMap[movieSpeed])*sens){
                        app->parameterMap[movieSpeed] = abs(app->parameterMap[movieSpeed])*sens;
                    }
                }else{
                    int frame = max(0.0f, app->deltaMap[loopStart]);
                    players[app->parameterMap[selectedPlayer]]->setFrame(frame);
                }
                
            }
        }
        
        for(int i=0;i<playerIntensities.size();i++)
            if(playerIntensities[i]>0){
                if(app->parameterMap[movieSpeed]!=players[i]->getSpeed())
                    players[i]->setSpeed(app->parameterMap[movieSpeed]);
                if(app->savingGif){ // frame by frame
                    players[i]->setPaused(true);
                    if(players[i]->getPosition() < 1)
                        players[i]->nextFrame();
                    else
                        players[i]->setPosition(0);
                    players[i]->update();
                }else{
                    players[i]->setPaused(false);
                    players[i]->update();
                }
            }
        
        
        
        videoMutex.unlock();
    }