StatusCode DelphesSaveGenJets::saveOutput(Delphes& delphes, const fcc::MCParticleCollection& mcParticles) { // Create the collections auto colGenJets = m_genJets.createAndPut(); auto colJetsFlavor = m_jetFlavorTags.createAndPut(); auto ascColJetsToFlavor = m_jetFlavorAssociations.createAndPut(); auto ascColGenJetsToMC = m_mcAssociations.createAndPut(); const TObjArray* delphesColl = delphes.ImportArray(m_delphesArrayName.c_str()); if (delphesColl == nullptr) { warning() << "Delphes collection " << m_delphesArrayName << " not present. Skipping it." << endmsg; return StatusCode::SUCCESS; } for(int j = 0; j < delphesColl->GetEntries(); ++j) { auto cand = static_cast<Candidate *>(delphesColl->At(j)); // Jet info auto jet = colGenJets->create(); auto bareJet = fcc::BareJet(); bareJet.Area = -1; bareJet.P4.Px = cand->Momentum.Px(); bareJet.P4.Py = cand->Momentum.Py(); bareJet.P4.Pz = cand->Momentum.Pz(); bareJet.P4.Mass = cand->Mass; jet.Core(bareJet); // Flavor-tag info auto flavorTag = colJetsFlavor->create(); auto relationToFlavor = ascColJetsToFlavor->create(); flavorTag.Value(cand->Flavor); relationToFlavor.Jet(jet); relationToFlavor.Tag(flavorTag); // Debug: print FCC-EDM jets info if (msgLevel() <= MSG::DEBUG) { double energy = sqrt(jet.Core().P4.Px*jet.Core().P4.Px + jet.Core().P4.Py*jet.Core().P4.Py + jet.Core().P4.Pz*jet.Core().P4.Pz + jet.Core().P4.Mass*jet.Core().P4.Mass); debug() << "Gen Jet: " << " Id: " << std::setw(3) << j+1 << " Flavor: " << std::setw(3) << relationToFlavor.Tag().Value() << std::scientific << " Px: " << std::setprecision(2) << std::setw(9) << jet.Core().P4.Px << " Py: " << std::setprecision(2) << std::setw(9) << jet.Core().P4.Py << " Pz: " << std::setprecision(2) << std::setw(9) << jet.Core().P4.Pz << " E: " << std::setprecision(2) << std::setw(9) << energy << " M: " << std::setprecision(2) << std::setw(9) << jet.Core().P4.Mass << std::fixed << std::endl; } // Reference to MC - Delphes holds references to all objects related to the Jet object, // several relations might exist -> find "recursively" in a tree history the MC particle. // Add index to the reference index field to avoid double counting std::set<int> idRefMCPart; // Avoid double counting when referencingh MC particles // Recursive procedure stops after the relation found is the one to MC particle and not to // a particle object. If particle not related to MC particle (<0 value) findJetPartMC(cand, mcParticles.size(), idRefMCPart); // Debug: print variable double totSimE = 0; for (auto id : idRefMCPart) { auto relationToMC = ascColGenJetsToMC->create(); relationToMC.Jet(jet); relationToMC.Particle(mcParticles.at(id)); // Debug: print FCC-EDM jet relation info if (msgLevel() <= MSG::DEBUG) { double recE = sqrt(relationToMC.Jet().Core().P4.Px*relationToMC.Jet().Core().P4.Px + relationToMC.Jet().Core().P4.Py*relationToMC.Jet().Core().P4.Py + relationToMC.Jet().Core().P4.Pz*relationToMC.Jet().Core().P4.Pz + relationToMC.Jet().Core().P4.Mass*relationToMC.Jet().Core().P4.Mass); double simE = sqrt(relationToMC.Particle().Core().P4.Px*relationToMC.Particle().Core().P4.Px + relationToMC.Particle().Core().P4.Py*relationToMC.Particle().Core().P4.Py + relationToMC.Particle().Core().P4.Pz*relationToMC.Particle().Core().P4.Pz + relationToMC.Particle().Core().P4.Mass*relationToMC.Particle().Core().P4.Mass); totSimE += simE; debug() << " RefId: " << std::setw(3) << id+1 << " Rel E: " << std::setprecision(2) << std::scientific << std::setw(9) << simE << " " << std::setw(9) << totSimE << " <-> " << std::setw(9) << recE << std::fixed << std::endl; } // Debug } // Debug: print end-line if (msgLevel() <= MSG::DEBUG) debug() << endmsg; } // For - jets return StatusCode::SUCCESS; }
Particle::Particle() { Particle( ofVec2f( ofGetWidth()/2, ofGetHeight()/2 ) ); }
Cloth::Cloth( const Vec3& _origin_pos, int _num_particles_width, int _num_particles_height, double _step_x, double _step_y, double _smoothThreshold, double _heightThreshold, int rigidness, double time_step) : constraint_iterations(rigidness) , time_step(time_step) , smoothThreshold(_smoothThreshold) , heightThreshold(_heightThreshold) , num_particles_width(_num_particles_width) , num_particles_height(_num_particles_height) , origin_pos(_origin_pos) , step_x(_step_x) , step_y(_step_y) { particles.resize(num_particles_width*num_particles_height); //I am essentially using this vector as an array with room for num_particles_width*num_particles_height particles double time_step2 = time_step*time_step; // creating particles in a grid for (int i = 0; i < num_particles_width; i++) { for (int j = 0; j < num_particles_height; j++) { Vec3 pos( origin_pos.x + i * step_x, origin_pos.y, origin_pos.z + j * step_y); particles[j*num_particles_width + i] = Particle(pos, time_step2); // insert particle in column i at j'th row particles[j*num_particles_width + i].pos_x = i; particles[j*num_particles_width + i].pos_y = j; } } // Connecting immediate neighbor particles with constraints (distance 1 and sqrt(2) in the grid) for (int x = 0; x<num_particles_width; x++) { for (int y = 0; y<num_particles_height; y++) { if (x < num_particles_width - 1) { addConstraint(&getParticle(x, y), &getParticle(x + 1, y)); } if (y < num_particles_height - 1) { addConstraint(&getParticle(x, y), &getParticle(x, y + 1)); } if (x < num_particles_width - 1 && y < num_particles_height - 1) { addConstraint(&getParticle(x, y), &getParticle(x + 1, y + 1)); addConstraint(&getParticle(x + 1, y), &getParticle(x, y + 1)); } } } // Connecting secondary neighbors with constraints (distance 2 and sqrt(4) in the grid) for (int x = 0; x < num_particles_width; x++) { for (int y = 0; y < num_particles_height; y++) { if (x < num_particles_width - 2) { addConstraint(&getParticle(x, y), &getParticle(x + 2, y)); } if (y < num_particles_height - 2) { addConstraint(&getParticle(x, y), &getParticle(x, y + 2)); } if (x < num_particles_width - 2 && y < num_particles_height - 2) { addConstraint(&getParticle(x, y), &getParticle(x + 2, y + 2)); addConstraint(&getParticle(x + 2, y), &getParticle(x, y + 2)); } } } }
void SimulationParameters::initialiseEnvironment( bool &o_rbdCollsionEnabled, ngl::Vector &o_boundaryPosition, ngl::Vector &o_boundaryDimension, ngl::Real &o_boundaryRestitutionCoefficientForFluid, std::vector<Particle> &o_rbdSphereList, ngl::Real &o_rbdSphereRestitutionCoefficient, ngl::Colour &o_boundaryColour ) { /*----Load Settings from XML File----------------------------------------------*/ pugi::xml_document doc; doc.load_file(s_settingsDocumentPath.c_str()); //temporary variable std::vector<ngl::Real> tmp; pugi::xpath_node_set node = doc.select_nodes("/Settings/Environment"); /*--- Reading Boundry Parameters-------------------------------------------*/ tmp = getFloatVectorFromString(node.first().node().select_single_node("Boundary").node().attribute("position").value(), 3); o_boundaryPosition.set(tmp[0], tmp[1], tmp[2]); tmp = getFloatVectorFromString(node.first().node().select_single_node("Boundary").node().attribute("dimension").value(), 3); o_boundaryDimension.set(tmp[0], tmp[1], tmp[2]); o_boundaryRestitutionCoefficientForFluid = node.first().node().select_single_node("Boundary").node().attribute("restitutionForFluid").as_float(); tmp = getFloatVectorFromString(node.first().node().select_single_node("Boundary").node().attribute("colour").value(), 3); o_boundaryColour.set(tmp[0],tmp[1],tmp[2],1.0); /*--- Read CollisionParameters-------------------------------------------------------------------*/ node = doc.select_nodes("/Settings/Environment/Obstacles"); o_rbdCollsionEnabled = node.first().node().attribute("enabled").as_bool(); o_rbdSphereRestitutionCoefficient = node.first().node().attribute("restitution").as_float(); /*---- Creating and Storing Rigid Body Sphere -----------------------------------------*/ node = node.first().node().select_nodes("Sphere"); for (pugi::xpath_node_set::const_iterator it = node.begin(); it != node.end(); ++it) { //get details for an obstacle pugi::xpath_node node1 = *it; //get parameters active parameter tmp = getFloatVectorFromString(node1.node().attribute("position").value(), 3); ngl::Vector position(tmp[0], tmp[1], tmp[2]); ngl::Vector velocity(0,0,0); ngl::Real collisionRadius = node1.node().attribute("collisionRadius").as_float(); ngl::Real drawRadius = node1.node().attribute("drawRadius").as_float(); tmp = getFloatVectorFromString(node1.node().attribute("colour").value(), 3); ngl::Colour colour(tmp[0], tmp[1], tmp[2]); /*---Create and Add Spheres to RBDSphere List----------------------------------------------------*/ Particle p = Particle (SimulationParameters::s_nextRBDSphereId--,0,position,colour,collisionRadius,drawRadius,velocity); o_rbdSphereList.push_back(p); } }
// Main int main() { // Create main window sf::RenderWindow app(sf::VideoMode(800, 600), "AntTweakBar simple example using SFML"); app.PreserveOpenGLStates(true); // Particules std::list<Particle> particles; std::list<Particle>::iterator p; float birthCount = 0; float birthRate = 20; // number of particles generated per second float maxAge = 3.0f; // particles life time float speedDir[3] = {0, 1, 0}; // initial particles speed direction float speedNorm = 7.0f; // initial particles speed amplitude float size = 0.1f; // particles size float color[3] = {0.8f, 0.6f, 0}; // particles color float bgColor[3] = {0, 0.6f, 0.6f}; // background color // Initialize AntTweakBar TwInit(TW_OPENGL, NULL); // Tell the window size to AntTweakBar TwWindowSize(app.GetWidth(), app.GetHeight()); // Create a tweak bar TwBar *bar = TwNewBar("Particles"); TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with SFML and OpenGL.' "); // Message added to the help bar. // Change bar position int barPos[2] = {16, 240}; TwSetParam(bar, NULL, "position", TW_PARAM_INT32, 2, &barPos); // Add 'birthRate' to 'bar': this is a modifiable variable of type TW_TYPE_FLOAT in range [0.1, 100]. Its shortcuts are [+] and [-]. TwAddVarRW(bar, "Birth rate", TW_TYPE_FLOAT, &birthRate, " min=0.1 max=100 step=0.1 keyIncr='+' keyDecr='-' "); // Add 'speedNorm' to 'bar': this is a modifiable variable of type TW_TYPE_FLOAT in range [0.1, 10]. Its shortcuts are [s] and [S]. TwAddVarRW(bar, "Speed", TW_TYPE_FLOAT, &speedNorm, " min=0.1 max=10 step=0.1 keyIncr='s' keyDecr='S' "); // Add 'speedDir' to 'bar': this is a modifiable variable of type TW_TYPE_DIR3F. Just displaying the arrow widget TwAddVarRW(bar, "Direction", TW_TYPE_DIR3F, &speedDir, " opened=true showval=false "); // Add 'color' to 'bar': this is a modifiable variable of type TW_TYPE_COLOR3F. Switched to HLS TwAddVarRW(bar, "Color", TW_TYPE_COLOR3F, &color, " colorMode=hls opened=true "); // Add 'bgColor' to 'bar': this is a modifiable variable of type TW_TYPE_COLOR3F. Switched to HLS TwAddVarRW(bar, "Background color", TW_TYPE_COLOR3F, &bgColor, " colorMode=hls opened=true "); // Initialize OpenGL states glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90.f, (float)app.GetWidth()/app.GetHeight(), 0.1f, 100.f); glMatrixMode(GL_MODELVIEW); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_NORMALIZE); glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); // Init time sf::Clock clock; float time = clock.GetElapsedTime(); // Main loop while (app.IsOpened()) { // Process events sf::Event event; while (app.GetEvent(event)) { // Send event to AntTweakBar int handled = TwEventSFML(&event, 1, 6); // Assume SFML version 1.6 here // If event has not been handled by AntTweakBar, process it if( !handled ) { // Close or Escape if (event.Type == sf::Event::Closed || (event.Type == sf::Event::KeyPressed && event.Key.Code == sf::Key::Escape)) app.Close(); // Resize if (event.Type == sf::Event::Resized) { glViewport(0, 0, event.Size.Width, event.Size.Height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90.f, (float)event.Size.Width/event.Size.Height, 1.f, 500.f); glMatrixMode(GL_MODELVIEW); // TwWindowSize has been called by TwEventSFML, // so it is not necessary to call it again here. } } } if (!app.IsOpened()) continue; // Update time float dt = clock.GetElapsedTime() - time; time += dt; // Update particles p = particles.begin(); while (p != particles.end()) { p->Update(dt); if (p->Age >= maxAge) p = particles.erase(p); // Die! else ++p; } // Generate new particles birthCount += dt * birthRate; while (birthCount >= 1.0f) { particles.push_back(Particle(size, speedDir, speedNorm, color)); birthCount--; } // Clear depth buffer glClearColor(bgColor[0], bgColor[1], bgColor[2], 1); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // Draw particles for (p = particles.begin(); p != particles.end(); ++p) { glColor4fv(p->Color); glLoadIdentity(); glTranslatef(0.0f, -1.0f, -3.0f); // Camera position glTranslatef(p->Position[0], p->Position[1], p->Position[2]); glScalef(p->Size, p->Size, p->Size); glRotatef(p->RotationAngle, p->RotationAxis[0], p->RotationAxis[1], p->RotationAxis[2]); // Draw a cube glBegin(GL_QUADS); glNormal3f(0,0,-1); glVertex3f(0,0,0); glVertex3f(0,1,0); glVertex3f(1,1,0); glVertex3f(1,0,0); // front face glNormal3f(0,0,+1); glVertex3f(0,0,1); glVertex3f(1,0,1); glVertex3f(1,1,1); glVertex3f(0,1,1); // back face glNormal3f(-1,0,0); glVertex3f(0,0,0); glVertex3f(0,0,1); glVertex3f(0,1,1); glVertex3f(0,1,0); // left face glNormal3f(+1,0,0); glVertex3f(1,0,0); glVertex3f(1,1,0); glVertex3f(1,1,1); glVertex3f(1,0,1); // right face glNormal3f(0,-1,0); glVertex3f(0,0,0); glVertex3f(1,0,0); glVertex3f(1,0,1); glVertex3f(0,0,1); // bottom face glNormal3f(0,+1,0); glVertex3f(0,1,0); glVertex3f(0,1,1); glVertex3f(1,1,1); glVertex3f(1,1,0); // top face glEnd(); } TwDraw(); // Finally, display the rendered frame on screen app.Display(); } // Un-initialize AntTweakBar TwTerminate(); return EXIT_SUCCESS; }
TEST(Serializer, HostBufferOfParticle) { test< HostBuffer<Particle> >( std::vector<Particle>{ Particle({0,0,0,0}, {1,1,1,1}), Particle({3,3,3,3}, {5,5,5,5}) }, [] (Particle& a, Particle& b) { return a.r.x == b.r.x; } ); }
//! create EventArray of known particles matching a specific PDG name // and runID. EventArray* createParticles(const std::string& inputFile, const size_t knownNumber, const std::string& particle, const double /*mass*/, const std::string& runId) { // Create a filereader and check its validity FileReader counter(inputFile); if (!counter.isValid()) { std::cerr << "[createParticles:error] " << inputFile << " is not valid" << std::endl; return 0; } EventArray* pEA = createEventArray(knownNumber); std::string particleName, dataID; int eventId(0); int pdgCode(0); int currentParticle(0); double px(0.0), py(0.0), pz(0.0); while (counter.nextLine()) { // Valid lines should begin with an integer, continue without error // to skip header eventId = counter.getFieldAsInt(1); if (counter.inputFailed()) continue; particleName = counter.getFieldAsString(2); if (counter.inputFailed()) { std::cerr << "[countParticles:error] Field 2 of " << inputFile << " is not a string" << std::endl; destroyEventArray(pEA); return pEA; } dataID = counter.getFieldAsString(6); if (counter.inputFailed()) { std::cerr << "[countParticles:error] Field 6 of " << inputFile << " is not a string" << std::endl; destroyEventArray(pEA); return pEA; } if (dataID == runId) { if (particleName == particle) { px = counter.getFieldAsDouble(3); if (counter.inputFailed()) { std::cerr << "[createParticles:error] Field 3 of " << inputFile << " is not a double" << std::endl; destroyEventArray(pEA); return pEA; } py = counter.getFieldAsDouble(4); if (counter.inputFailed()) { std::cerr << "[countParticles:error] Field 4 of " << inputFile << " is not a double" << std::endl; destroyEventArray(pEA); return pEA; } pz = counter.getFieldAsDouble(5); if (counter.inputFailed()) { std::cerr << "[countParticles:error] Field 5 of " << inputFile << " is not a double" << std::endl; destroyEventArray(pEA); return pEA; } // Input is all o.k. for this line, so add the entry to the // EventArray pdgCode = getPDGCode(particle); (pEA->ids)[currentParticle] = eventId; (pEA->particles)[currentParticle] = Particle(pdgCode, px, py, pz); ++currentParticle; } } } return pEA; }
//-------------------------------------------------------------- void testApp::update(){ ofBackground(0,0,0); bool bNewFrame = false; if(useLiveVideo) { vidGrabber.grabFrame(); bNewFrame = vidGrabber.isFrameNew(); if(rewind) { vidPlayer.setFrame(0); rewind = false; } if(paused) { vidPlayer.setPaused(paused); paused = false; } if(play) { vidPlayer.setPaused(false); vidPlayer.play(); paused = false; } } else { // vidPlayer.idleMovie(); // bNewFrame = vidPlayer.isFrameNew(); } if (bNewFrame){ if(useLiveVideo) { colorImg.setFromPixels(vidGrabber.getPixels(), vidGrabber.getWidth(), vidGrabber.getHeight()); } else { // colorImg.setFromPixels(vidPlayer.getPixels(), vidPlayer.getWidth(), vidPlayer.getHeight()); } bigGrayImage = colorImg; grayImage.scaleIntoMe(bigGrayImage); mouths.update(&grayImage); // take the abs value of the difference between background and incoming and then threshold: grayDiff.absDiff(grayBg, grayImage); grayDiff.threshold(threshold); // find contours which are between the size of 20 pixels and 1/3 the w*h pixels. // also, find holes is set to true so we will get interior contours as well.... contourFinder.findContours(grayDiff, 20, (340*240)/3, 10, true); // find holes float pitch = 0; float filter = 0; for(int i = 0; i < mouths.size(); i++) { pitch = mouths[i]->getPitch(); filter = mouths[i]->getFilter(); zg.sendFloat("volume"+ofToString(i), mouths[i]->isOpen()?1:0); if(mouths[i]->isOpen()) { zg.sendFloat("pitch"+ofToString(i), pitch); zg.sendFloat("filter"+ofToString(i), filter); zg.sendFloat("pan"+ofToString(i), mouths[i]->getPan()); } } for(int i = 0; i < mouths.size(); i++) { if(mouths[i]->isOpen() && ofRandom(0, 1)>0.5) { //mouthJustOpened()) { printf("Just opened\n"); particles.push_back(Particle(mouths[i]->getPos(), mouths[i]->getFilter())); } } } for(int i = 0; i < particles.size(); i++) { if(particles[i].isAlive()) { particles[i].update(); } else { particles.erase(particles.begin()+i); i--; } } }
//-------------------------------------------------------------- void testApp::addParticle(float x, float y){ float xPos = (x+0.5) * 10.0; float yPos = (y+0.5) * 10.0; particles.push_back(Particle(ofVec2f(xPos, yPos))); }
const Particle Group::getParticle(size_t index) const { SPK_ASSERT(index < particleData.nbParticles,"Group::getParticle(size_t) - Particle index is out of bounds : " << index); return Particle(const_cast<Group&>(*this),index); }
void ParticlePool::engineExhaust(int id, float radius, short selectEngines) { int numParticles; const Position *source = currentNode->getEntityPosition(id); if (selectEngines & 0x1) { numParticles = randInt(10,15); for (int i = 0; i < numParticles; i++) { float randAngle = randFloat((M_PI) - (M_PI/9), (M_PI) + M_PI/9); float spawnX = source->getX() - (radius + randFloat(3.0, 7.0)) * -cos(source->getR() + M_PI); float spawnY = source->getY() - (radius + randFloat(3.0, 7.0)) * (/*0-*/sin(source->getR() + M_PI)); float speed = randFloat(75.0, 200.0); float spawnVelX = speed * cos(source->getR() + randAngle) + source->getX_vel(); float spawnVelY = speed * (-sin(source->getR() + randAngle)) + source->getY_vel(); Position spawnPos = Position(spawnX, spawnY); spawnPos.setX_vel(spawnVelX); spawnPos.setY_vel(spawnVelY); Particle p = Particle(255, randInt(64, 215), 0, 255, randFloat(0.1, 0.3), spawnPos, particleFadeSpeed*4); add(p); } } if (selectEngines & 0x2) { numParticles = randInt(5,8); for (int i = 0; i < numParticles; i++) { float randAngle = randFloat((M_PI) - (M_PI/9), (M_PI) + M_PI/9); float spawnX = source->getX() - (radius + randFloat(3.0, 7.0) + 6.0) * cos(source->getR() + M_PI + M_PI/5.5); float spawnY = source->getY() - (radius + randFloat(3.0, 7.0) + 6.0) * (-sin(source->getR() + M_PI + M_PI/5.5)); float speed = randFloat(75.0, 200.0); float spawnVelX = speed * -cos(source->getR() + randAngle) + source->getX_vel(); float spawnVelY = speed * (sin(source->getR() + randAngle)) + source->getY_vel(); Position spawnPos = Position(spawnX, spawnY); spawnPos.setX_vel(spawnVelX); spawnPos.setY_vel(spawnVelY); Particle p = Particle(255, randInt(64, 215), 0, 255, randFloat(0.1, 0.3), spawnPos, particleFadeSpeed*8); add(p); } for (int i = 0; i < numParticles; i++) { float randAngle = randFloat((M_PI) - (M_PI/9), (M_PI) + M_PI/9); float spawnX = source->getX() - (radius + randFloat(3.0, 7.0) + 6.0) * cos(source->getR() + M_PI - M_PI/5.5); float spawnY = source->getY() - (radius + randFloat(3.0, 7.0) + 6.0) * (-sin(source->getR() + M_PI - M_PI/5.5)); float speed = randFloat(75.0, 200.0); float spawnVelX = speed * -cos(source->getR() + randAngle) + source->getX_vel(); float spawnVelY = speed * (sin(source->getR() + randAngle)) + source->getY_vel(); Position spawnPos = Position(spawnX, spawnY); spawnPos.setX_vel(spawnVelX); spawnPos.setY_vel(spawnVelY); Particle p = Particle(255, randInt(64, 215), 0, 255, randFloat(0.1, 0.3), spawnPos, particleFadeSpeed*8); add(p); } } if (selectEngines & 0x4) { numParticles = randInt(5,8); for (int i = 0; i < numParticles; i++) { float randAngle = randFloat((M_PI) - (M_PI/9), (M_PI) + M_PI/9); float spawnX = source->getX() - (radius + randFloat(3.0, 7.0) + 20.0) * -cos(source->getR() + M_PI + M_PI/3); float spawnY = source->getY() - (radius + randFloat(3.0, 7.0) + 20.0) * (sin(source->getR() + M_PI + M_PI/3)); float speed = randFloat(75.0, 200.0); float spawnVelX = speed * cos(source->getR() + randAngle + M_PI/2.5) + source->getX_vel(); float spawnVelY = speed * (-sin(source->getR() + randAngle + M_PI/2.5)) + source->getY_vel(); Position spawnPos = Position(spawnX, spawnY); spawnPos.setX_vel(spawnVelX); spawnPos.setY_vel(spawnVelY); Particle p = Particle(255, randInt(64, 215), 0, 255, randFloat(0.1, 0.3), spawnPos, particleFadeSpeed*8); add(p); } for (int i = 0; i < numParticles; i++) { float randAngle = randFloat((M_PI) - (M_PI/9), (M_PI) + M_PI/9); float spawnX = source->getX() - (radius + randFloat(3.0, 7.0) + 8.0) * cos(source->getR() + M_PI - M_PI/5.5); float spawnY = source->getY() - (radius + randFloat(3.0, 7.0) + 8.0) * (-sin(source->getR() + M_PI - M_PI/5.5)); float speed = randFloat(75.0, 200.0); float spawnVelX = speed * -cos(source->getR() + randAngle - M_PI/2.5) + source->getX_vel(); float spawnVelY = speed * (sin(source->getR() + randAngle - M_PI/2.5)) + source->getY_vel(); Position spawnPos = Position(spawnX, spawnY); spawnPos.setX_vel(spawnVelX); spawnPos.setY_vel(spawnVelY); Particle p = Particle(255, randInt(64, 215), 0, 255, randFloat(0.1, 0.3), spawnPos, particleFadeSpeed*8); add(p); } } if (selectEngines & 0x8) { numParticles = randInt(5,8); for (int i = 0; i < numParticles; i++) { float randAngle = randFloat((M_PI) - (M_PI/9), (M_PI) + M_PI/9); float spawnX = source->getX() - (radius + randFloat(3.0, 7.0) + 20.0) * -cos(source->getR() + M_PI - M_PI/3); float spawnY = source->getY() - (radius + randFloat(3.0, 7.0) + 20.0) * (sin(source->getR() + M_PI - M_PI/3)); float speed = randFloat(75.0, 200.0); float spawnVelX = speed * cos(source->getR() + randAngle - M_PI/2.5) + source->getX_vel(); float spawnVelY = speed * (-sin(source->getR() + randAngle - M_PI/2.5)) + source->getY_vel(); Position spawnPos = Position(spawnX, spawnY); spawnPos.setX_vel(spawnVelX); spawnPos.setY_vel(spawnVelY); Particle p = Particle(255, randInt(64, 215), 0, 255, randFloat(0.1, 0.3), spawnPos, particleFadeSpeed*8); add(p); } for (int i = 0; i < numParticles; i++) { float randAngle = randFloat((M_PI) - (M_PI/9), (M_PI) + M_PI/9); float spawnX = source->getX() - (radius + randFloat(3.0, 7.0) + 8.0) * cos(source->getR() + M_PI + M_PI/5.5); float spawnY = source->getY() - (radius + randFloat(3.0, 7.0) + 8.0) * (-sin(source->getR() + M_PI + M_PI/5.5)); float speed = randFloat(75.0, 200.0); float spawnVelX = speed * -cos(source->getR() + randAngle + M_PI/2.5) + source->getX_vel(); float spawnVelY = speed * (sin(source->getR() + randAngle + M_PI/2.5)) + source->getY_vel(); Position spawnPos = Position(spawnX, spawnY); spawnPos.setX_vel(spawnVelX); spawnPos.setY_vel(spawnVelY); Particle p = Particle(255, randInt(64, 215), 0, 255, randFloat(0.1, 0.3), spawnPos, particleFadeSpeed*8); add(p); } } }
void SwappedSystem::update (const Particle *particle1, const Particle *particle2, const Wavefunction<amplitude_t>::Amplitude &phialpha1, const Wavefunction<amplitude_t>::Amplitude &phialpha2) { // this function should be called *after* the phialpha's have been updated assert(current_state == READY); current_state = UPDATE_IN_PROGRESS; const PositionArguments &r1 = phialpha1.get_positions(); const PositionArguments &r2 = phialpha2.get_positions(); #ifndef NDEBUG assert(r1.get_N_species() == r2.get_N_species()); for (unsigned int i = 0; i < r1.get_N_species(); ++i) assert(r1.get_N_filled(i) == r2.get_N_filled(i)); #endif assert(!particle1 || r1.particle_is_valid(*particle1)); assert(!particle2 || r2.particle_is_valid(*particle2)); const Lattice &lattice = phialpha1.get_lattice(); // these will be will be >= 0 if the particle was in the subsystem before, // -1 if the particle was not in the subsystem before, and -2 if the // particle isn't even being moved. int pairing_index1 = (!particle1) ? -2 : vector_find(copy1_subsystem_indices[particle1->species], particle1->index); int pairing_index2 = (!particle2) ? -2 : vector_find(copy2_subsystem_indices[particle2->species], particle2->index); const bool particle1_now_in_subsystem = (particle1 && subsystem->position_is_within(r1[*particle1], lattice)); const bool particle2_now_in_subsystem = (particle2 && subsystem->position_is_within(r2[*particle2], lattice)); const int delta1 = (particle1_now_in_subsystem ? 1 : 0) + (pairing_index1 >= 0 ? -1 : 0); #ifndef NDEBUG const int delta2 = (particle2_now_in_subsystem ? 1 : 0) + (pairing_index2 >= 0 ? -1 : 0); #endif assert(particle1 || delta1 == 0); assert(particle2 || delta2 == 0); assert(delta1 == delta2); const int delta = delta1; assert(delta == 0 || (particle1 && particle2 && particle1->species == particle2->species)); assert(delta == 0 || particle1_now_in_subsystem == particle2_now_in_subsystem); // to ensure only a single update is necessary to the phibeta's, we require // that a particle only be moved in one copy if the particle number is not // changing assert(delta != 0 || !(particle1 && particle2)); // remember a few things in case we need to cancel recent_delta = delta; if (particle1) recent_particle1 = *particle1; if (particle2) recent_particle2 = *particle2; if (delta == -1) { // if a particle of the same type leaves each subsystem simultaneously, // we need to use some special logic in case we have to re-pair the // remaining particles in the subsystem. (re-pair in the sense of what // gets swapped with what) // these repeat some logic in the "if" statement, but are a useful // sanity check nonetheless (for now) assert(pairing_index1 >= 0 && pairing_index2 >= 0); assert(!particle1_now_in_subsystem); assert(!particle2_now_in_subsystem); const unsigned int species = particle1->species; std::vector<unsigned int> &c1_s = copy1_subsystem_indices[species]; std::vector<unsigned int> &c2_s = copy2_subsystem_indices[species]; if (pairing_index1 != pairing_index2) { // in order to re-pair the particles left behind, we move the pair // that is leaving the subsystem to the max_pairing_index, and move // the pair that is staying behind to the min_pairing_index. phibeta1->swap_particles(c1_s[pairing_index1], c1_s[pairing_index2], species); phibeta2->swap_particles(c2_s[pairing_index1], c2_s[pairing_index2], species); if (pairing_index1 < pairing_index2) std::swap(c1_s[pairing_index1], c1_s[pairing_index2]); else std::swap(c2_s[pairing_index1], c2_s[pairing_index2]); } // update the phibeta's const unsigned int max_pairing_index = std::max(pairing_index1, pairing_index2); assert(!phibeta1_dirty && !phibeta2_dirty); { Move move; move.push_back(SingleParticleMove(Particle(c1_s[max_pairing_index], species), r1[*particle1])); phibeta1->perform_move(move); } { Move move; move.push_back(SingleParticleMove(Particle(c2_s[max_pairing_index], species), r2[*particle2])); phibeta2->perform_move(move); } phibeta1_dirty = true; phibeta2_dirty = true; // remove the empty pair in the subsystem indices (yes, these steps // make sense whether we had to re-pair or not) c1_s[max_pairing_index] = c1_s[c1_s.size() - 1]; c1_s.pop_back(); c2_s[max_pairing_index] = c2_s[c2_s.size() - 1]; c2_s.pop_back(); } else { assert(delta == 0 || delta == 1); // either both particles moved within their respective subsystems // (if they moved at all), or both entered the subsystem and paired // with each other immediately // update the subsystem indices if necessary if (delta == 1) { std::vector<unsigned int> &c1_s = copy1_subsystem_indices[particle1->species]; std::vector<unsigned int> &c2_s = copy2_subsystem_indices[particle2->species]; c1_s.push_back(particle1->index); pairing_index1 = c1_s.size() - 1; c2_s.push_back(particle2->index); pairing_index2 = c2_s.size() - 1; } assert(subsystem_particle_counts_match()); // update the phibeta's if (particle1) { std::unique_ptr<Wavefunction<amplitude_t>::Amplitude> &phibeta = particle1_now_in_subsystem ? phibeta2 : phibeta1; bool &phibeta_dirty = particle1_now_in_subsystem ? phibeta2_dirty : phibeta1_dirty; const Particle phibeta_particle = particle1_now_in_subsystem ? Particle(copy2_subsystem_indices[particle1->species][pairing_index1], particle1->species) : *particle1; assert(!phibeta_dirty); Move move; move.push_back(SingleParticleMove(phibeta_particle, r1[*particle1])); phibeta->perform_move(move); phibeta_dirty = true; } if (particle2) { std::unique_ptr<Wavefunction<amplitude_t>::Amplitude> &phibeta = particle2_now_in_subsystem ? phibeta1 : phibeta2; bool &phibeta_dirty = particle2_now_in_subsystem ? phibeta1_dirty : phibeta2_dirty; const Particle phibeta_particle = particle2_now_in_subsystem ? Particle(copy1_subsystem_indices[particle2->species][pairing_index2], particle2->species) : *particle2; // the only time both particles will move here is when delta == 1, // in which case this phibeta and the phibeta above will be // different, so we know that phibeta_dirty will never be true // here. assert(!phibeta_dirty); Move move; move.push_back(SingleParticleMove(phibeta_particle, r2[*particle2])); phibeta->perform_move(move); phibeta_dirty = true; } } }
void JelloMesh::InitJelloMesh() { m_vsprings.clear(); if (m_width < 0.01 || m_height < 0.01 || m_depth < 0.01) return; if (m_cols < 1 || m_rows < 1 || m_stacks < 1) return; // Init particles float wcellsize = m_width / m_cols; float hcellsize = m_height / m_rows; float dcellsize = m_depth / m_stacks; for (int i = 0; i < m_rows+1; i++) { for (int j = 0; j < m_cols+1; j++) { for (int k = 0; k < m_stacks+1; k++) { float x = -m_width*0.5f + wcellsize*i; float y = 0.5 + hcellsize*j; float z = -m_depth*0.5f + dcellsize*k; m_vparticles[i][j][k] = Particle(GetIndex(i,j,k), vec3(x, y, z)); } } } // Setup structural springs ParticleGrid& g = m_vparticles; for (int i = 0; i < m_rows+1; i++) { for (int j = 0; j < m_cols+1; j++) { for (int k = 0; k < m_stacks+1; k++) { if (j < m_cols) AddStructuralSpring(GetParticle(g,i,j,k), GetParticle(g,i,j+1,k)); if (i < m_rows) AddStructuralSpring(GetParticle(g,i,j,k), GetParticle(g,i+1,j,k)); if (k < m_stacks) AddStructuralSpring(GetParticle(g,i,j,k), GetParticle(g,i,j,k+1)); } } } // AddShearSpring(Particle& p1, Particle& p2); for (int i = 0; i < m_rows+1; i++) { for (int j = 0; j < m_cols+1; j++) { for (int k = 0; k < m_stacks; k++) { if(j < m_cols) AddShearSpring(GetParticle(g,i,j,k), GetParticle(g,i,j+1,k+1)); if(j > 0) AddShearSpring(GetParticle(g,i,j,k), GetParticle(g,i,j-1,k+1)); } } } for (int j = 0; j < m_cols+1; j++) { for (int i = 0; i < m_rows+1; i++) { for (int k = 0; k < m_stacks; k++) { if(i < m_rows) AddShearSpring(GetParticle(g,i,j,k), GetParticle(g,i+1,j,k+1)); if(i > 0) AddShearSpring(GetParticle(g,i,j,k), GetParticle(g,i-1,j,k+1)); } } } for (int k = 0; k < m_stacks+1; k++) { for (int i = 0; i < m_rows+1; i++) { for (int j = 0; j < m_cols; j++) { if(i < m_rows) AddShearSpring(GetParticle(g,i,j,k), GetParticle(g,i+1,j+1,k)); if(i > 0) AddShearSpring(GetParticle(g,i,j,k), GetParticle(g,i-1,j+1,k)); } } } // AddBendSpring(Particle& p1, Particle& p2); for (int i = 0; i < m_rows+1; i++) { for (int j = 0; j < m_cols+1; j++) { for (int k = 0; k < m_stacks+1; k++) { if (j < m_cols-1) AddBendSpring(GetParticle(g,i,j,k), GetParticle(g,i,j+2,k)); if (i < m_rows-1) AddBendSpring(GetParticle(g,i,j,k), GetParticle(g,i+2,j,k)); if (k < m_stacks-1) AddBendSpring(GetParticle(g,i,j,k), GetParticle(g,i,j,k+2)); } } } for (int i = 0; i < m_rows+1; i++) { for (int j = 0; j < m_cols+1; j++) { for (int k = 0; k < m_stacks+1; k++) { if (j < m_cols-2) AddBendSpring(GetParticle(g,i,j,k), GetParticle(g,i,j+3,k)); if (i < m_rows-2) AddBendSpring(GetParticle(g,i,j,k), GetParticle(g,i+3,j,k)); if (k < m_stacks-2) AddBendSpring(GetParticle(g,i,j,k), GetParticle(g,i,j,k+3)); } } } for (int i = 0; i < m_rows+1; i++) // cube diagonal { for (int j = 0; j < m_cols+1; j++) { for (int k = 0; k < m_stacks+1; k++) { if (i < m_rows && j < m_cols && k < m_stacks) AddBendSpring(GetParticle(g,i,j,k), GetParticle(g,i+1,j+1,k+1)); if (i < m_rows && j < m_cols && k > 0) AddBendSpring(GetParticle(g,i,j,k), GetParticle(g,i+1,j+1,k-1)); if (i > 0 && j < m_cols && k > 0) AddBendSpring(GetParticle(g,i,j,k), GetParticle(g,i-1,j+1,k-1)); if (i > 0 && j < m_cols && k < m_stacks) AddBendSpring(GetParticle(g,i,j,k), GetParticle(g,i-1,j+1,k+1)); } } } // Init mesh geometry m_mesh.clear(); m_mesh.push_back(FaceMesh(*this,XLEFT)); m_mesh.push_back(FaceMesh(*this,XRIGHT)); m_mesh.push_back(FaceMesh(*this,YTOP)); m_mesh.push_back(FaceMesh(*this,YBOTTOM)); m_mesh.push_back(FaceMesh(*this,ZFRONT)); m_mesh.push_back(FaceMesh(*this,ZBACK)); }
void testApp::addParticle(float x, float y) { float xPos = ( x + 0.5f ) * 4.0f; float yPos = ( y + 0.5f ) * 4.0f; particleList.push_back( Particle( ofVec2f( xPos, yPos ) ) ); }
Particle Particle::createParticle() { // Generate particle (the constructor of particle(position) creates random particle return Particle(_position, _belief * 0.9, _map); }
//-------------------------------------------------------------- void testApp::setup() { //Set the background to black ofBackground( 0 , 0 , 0 ) ; //load our image inside bin/data image.loadImage ( "images/text.png" ) ; //if the app performs slowly raise this number sampling = 1 ; curImageIndex = 0 ; //Retrieve the pixels from the loaded image unsigned char * pixels = image.getPixels() ; //store width and height for optimization and clarity int w = image.width ; int h = image.height ; //offsets to center the particle son screen int xOffset = (ofGetWidth() - w ) /2 ; int yOffset = (ofGetHeight() - h ) /2 ; numParticles= 0 ; r = ofRandom ( 45 , 255 ) ; g = ofRandom ( 45 , 255 ) ; b = ofRandom ( 45 , 255 ) ; ofVec3f origin = ofVec3f( ofGetWidth() /2 , ofGetHeight() /2 , 0 ) ; //Loop through all the rows for ( int x = 0 ; x < w ; x+=sampling ) { //Loop through all the columns for ( int y = 0 ; y < h ; y+=sampling ) { //Pixels are stored as unsigned char ( 0 <-> 255 ) as RGB //If our image had transparency it would be 4 for RGBA int index = ( y * w + x ) * 4 ; ofColor color ; if ( pixels[index+3] > 0 ) { color.r = r ; //pixels[index+0] ; //red pixel color.g = g ; //pixels[index+1] ; //blue pixel color.b = b ; //pixels[index+2] ; //green pixel ofVec3f spawnPoint = ofPoint ( x + xOffset , y + yOffset , ofRandom ( -50, 50 ) ) ; // spawnPoint.z = ; //origin.distance ( spawnPoint ) * 200.0f ; particles.push_back( Particle ( spawnPoint , color ) ) ; numParticles++ ; } } } ofSetFrameRate( 30 ) ; // numParticles = ( image.width * image.height ) / sampling ; //Set spring and sink values cursorMode = 0 ; forceRadius = 45 ; friction = 0.85 ; springFactor = 0.12 ; springEnabled = true ; //setup openGL ofSetFrameRate(30) ; ofBackground(0, 0, 0); //ofSetBackgroundAuto(false); ofSetVerticalSync(true); nImages = DIR.listDir("images/"); images = new ofImage[nImages]; //you can now iterate through the files as you like for(int i = 0; i < nImages; i++) { images[i].loadImage(DIR.getPath(i)); } fadeFbo.allocate( ofGetWidth() , ofGetHeight() ) ; fadeFbo.begin() ; ofClear(0, 0, 0, 1); fadeFbo.end() ; fadeAlpha = 2 ; }
SampleMaterial::SampleMaterial(std::string name) : MaterialGL(name,"SampleMaterial") { modelViewProjMatrix = vp->uniforms()->getGPUmat4("CPU_modelViewProjMatrix"); modelViewMatrix = vp->uniforms()->getGPUmat4("CPU_modelViewMatrix"); //viewMatrix = vp->uniforms()->getGPUmat4("viewMatrix"); CamPos = vp->uniforms()->getGPUvec3("CamPos"); glEnable(GL_BLEND); //additive blending glBlendFunc(GL_SRC_ALPHA, GL_ONE); //transparency //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //premiere texture texture = new GPUTexture2D("C:/Users/Thomas/Desktop/GoblimNouvelleversion/Goblim-Win32-core.git/SampleProject/Objets/Textures/flame_transparent.png"); sampler = fp->uniforms()->getGPUsampler("sampler"); sampler->Set(0); texture2 = new GPUTexture2D("C:/Users/Thomas/Desktop/GoblimNouvelleversion/Goblim-Win32-core.git/SampleProject/Objets/Textures/smoke1.png"); sampler2 = fp->uniforms()->getGPUsampler("sampler2"); sampler2->Set(1); texture3 = new GPUTexture2D("C:/Users/Thomas/Desktop/GoblimNouvelleversion/Goblim-Win32-core.git/SampleProject/Objets/Textures/sparkTransparent.png"); sampler3 = fp->uniforms()->getGPUsampler("sampler3"); sampler3->Set(2); //textureArray = new GPUTexture2DArray("textureArray", 1024, 1024, 2, GL_RGBA, GL_RGBA, GL_FLOAT); /*textureArray = new GPUTexture2DArray("textureArray"); textureArray->create(2048, 2048, 3); //textureArray->addLayer("C:/Users/Thomas/Desktop/GoblimNouvelleversion/Goblim-Win32-core.git/SampleProject/Objets/Textures/flame_transparent.png", 0, true); textureArray->addLayer("C:/Users/Thomas/Desktop/GoblimNouvelleversion/Goblim-Win32-core.git/SampleProject/Objets/Textures/flame_transparent.png", 0); samplerArray = fp->uniforms()->getGPUsampler("samplerArray"); samplerArray->Set(1);*/ GPUdureeVieMax = fp->uniforms()->getGPUfloat("lifetimeMax"); GPUdureeVieMax->Set(dureeVieMax); height = fp->uniforms()->getGPUint("height"); height->Set(rowParticleAtlas); width = fp->uniforms()->getGPUint("width"); width->Set(columnParticleAtlas); /*color = fp->uniforms()->getGPUvec3("color"); color->Set(glm::vec3(0.6, 0.0, 0.0)); time = vp->uniforms()->getGPUfloat("temps"); translationVector = vp->uniforms()->getGPUvec3("translationVector"); translationVector->Set(glm::vec3(0.0f, 0.1f, 0.0f));*/ //initialisation du tableau de particules tabParticles = new Particle[maxParticles]; for (int i = 0; i < maxParticles; i++){ float x = minPos + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (maxPos - minPos))); float z = minPos + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (maxPos - minPos))); float angle = minAngle + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (maxAngle - minAngle))); float speed = minSpeed + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (maxSpeed - minSpeed))); float dureeVie = minLife + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (maxLife - minLife))); Particle p = Particle(glm::vec3(x,0.0,z), dureeVie, angle, speed); tabParticles[i] = p; } }
probability_t BaseSwapPossibleWalk::compute_probability_ratio_of_random_transition (RandomNumberGenerator &rng) { BOOST_ASSERT(!transition_in_progress); transition_in_progress = true; const Lattice &lattice = phialpha1->get_lattice(); const Subsystem &subsystem = swapped_system->get_subsystem(); // decide which (zero-indexed) copy of the system to base this move around. // We call the chosen copy "copy A." const unsigned int copy_A = rng.random_small_uint(2); const PositionArguments &r_A = (copy_A == 0) ? phialpha1->get_positions() : phialpha2->get_positions(); const PositionArguments &r_B = (copy_A == 0) ? phialpha2->get_positions() : phialpha1->get_positions(); // first choose a random move in copy A chosen_particle_A = choose_random_particle(r_A, rng); const unsigned int particle_A_destination = plan_particle_move_to_nearby_empty_site(chosen_particle_A, r_A, lattice, rng); if (r_A[chosen_particle_A] == particle_A_destination) { autoreject_in_progress = true; return 0; } // If the particle we are moving in copy A is not going to change its // subsystem status, then we go ahead and make that move. If, however, the // particle we are moving in copy A changes its subsystem status (i.e., // enters or leaves the subsystem), then we must also choose a move in copy // B that does likewise, and take into account the transition probability // ratio so that the simulation maintains balance. unsigned int particle_B_destination = -1; // uninitialized real_t transition_ratio(1); const int copy_A_subsystem_particle_change = calculate_subsystem_particle_change(swapped_system->get_subsystem(), r_A[chosen_particle_A], particle_A_destination, lattice); const unsigned int species = chosen_particle_A.species; if (copy_A_subsystem_particle_change != 0) { const bool candidate_particle_B_subsystem_status = (copy_A_subsystem_particle_change == -1); // determine reverse/forward transition attempt probability ratios const unsigned int N_sites = r_A.get_N_sites(); const unsigned int N_filled = r_A.get_N_filled(species); const unsigned int N_within_subsystem = swapped_system->get_N_subsystem(species); const unsigned int N_outside_subsystem = N_filled - N_within_subsystem; const unsigned int N_vacant_within_subsystem = N_subsystem_sites - N_within_subsystem; const unsigned int N_vacant_outside_subsystem = (N_sites - N_filled) - N_vacant_within_subsystem; unsigned int forward_particle_possibilities, forward_vacant_possibilities, reverse_particle_possibilities, reverse_vacant_possibilities; if (copy_A_subsystem_particle_change == 1) { forward_particle_possibilities = N_outside_subsystem; forward_vacant_possibilities = N_vacant_within_subsystem; reverse_particle_possibilities = N_within_subsystem + 1; reverse_vacant_possibilities = N_vacant_outside_subsystem + 1; } else { BOOST_ASSERT(copy_A_subsystem_particle_change == -1); forward_particle_possibilities = N_within_subsystem; forward_vacant_possibilities = N_vacant_outside_subsystem; reverse_particle_possibilities = N_outside_subsystem + 1; reverse_vacant_possibilities = N_vacant_within_subsystem + 1; } if (forward_particle_possibilities == 0 || forward_vacant_possibilities == 0) { autoreject_in_progress = true; return 0; } transition_ratio = real_t(forward_particle_possibilities * forward_vacant_possibilities) / real_t(reverse_particle_possibilities * reverse_vacant_possibilities); // choose a particle from B with the same subsystem status as the // particle we are moving in A std::vector<unsigned int> candidate_particle_B_array; candidate_particle_B_array.reserve(forward_particle_possibilities); for (unsigned int i = 0; i < N_filled; ++i) { if (subsystem.position_is_within(r_B[Particle(i, species)], lattice) == candidate_particle_B_subsystem_status) candidate_particle_B_array.push_back(i); } BOOST_ASSERT(forward_particle_possibilities == candidate_particle_B_array.size()); chosen_particle_B = Particle(candidate_particle_B_array[rng.random_small_uint(candidate_particle_B_array.size())], species); // choose a destination such that the particle in copy B will change its // subsystem status const bool destination_B_in_subsystem = !candidate_particle_B_subsystem_status; std::vector<unsigned int> candidate_destination_B_array; candidate_destination_B_array.reserve(forward_vacant_possibilities); for (unsigned int i = 0; i < N_sites; ++i) { if (!r_B.is_occupied(i, species) && subsystem.position_is_within(i, lattice) == destination_B_in_subsystem) candidate_destination_B_array.push_back(i); } BOOST_ASSERT(forward_vacant_possibilities == candidate_destination_B_array.size()); particle_B_destination = candidate_destination_B_array[rng.random_small_uint(candidate_destination_B_array.size())]; } // translate from "copy A or B" language back to "copy 1 or 2" const Particle * const chosen_particle_B_ptr = (copy_A_subsystem_particle_change != 0) ? &chosen_particle_B : 0; chosen_particle1 = (copy_A == 0) ? &chosen_particle_A : chosen_particle_B_ptr; chosen_particle2 = (copy_A == 0) ? chosen_particle_B_ptr : &chosen_particle_A; // move particles, determining phialpha probability ratios amplitude_t phialpha1_ratio(1), phialpha2_ratio(1); if (chosen_particle1) { const Big<amplitude_t> old_phialpha1_psi(phialpha1->psi()); if (!phialpha1.unique()) // copy-on-write phialpha1 = phialpha1->clone(); Move move; move.push_back(SingleParticleMove(*chosen_particle1, (copy_A == 0) ? particle_A_destination : particle_B_destination)); phialpha1->perform_move(move); phialpha1_ratio = phialpha1->psi().ratio(old_phialpha1_psi); } if (chosen_particle2) { const Big<amplitude_t> old_phialpha2_psi(phialpha2->psi()); if (!phialpha2.unique()) // copy-on-write phialpha2 = phialpha2->clone(); Move move; move.push_back(SingleParticleMove(*chosen_particle2, (copy_A == 0) ? particle_B_destination : particle_A_destination)); phialpha2->perform_move(move); phialpha2_ratio = phialpha2->psi().ratio(old_phialpha2_psi); } amplitude_t phibeta1_ratio(0), phibeta2_ratio(0); if (update_swapped_system_before_accepting) { // remember old phibeta's const Big<amplitude_t> old_phibeta1_psi(swapped_system->get_phibeta1().psi()); const Big<amplitude_t> old_phibeta2_psi(swapped_system->get_phibeta2().psi()); // implement copy-on-write if (!swapped_system.unique()) swapped_system = boost::make_shared<SwappedSystem>(*swapped_system); // update phibeta's swapped_system->update(chosen_particle1, chosen_particle2, *phialpha1, *phialpha2); // determine probability ratios phibeta1_ratio = swapped_system->get_phibeta1().psi().ratio(old_phibeta1_psi); phibeta2_ratio = swapped_system->get_phibeta2().psi().ratio(old_phibeta2_psi); } // return a probability return transition_ratio * probability_ratio(phialpha1_ratio, phialpha2_ratio, phibeta1_ratio, phibeta2_ratio); }
/** * Create or load a particle system and simulate a number of time steps. */ int main(int argc, char *argv[]) { // Create particles and springs. particles.reserve(dimx * dimy * dimz); for (size_t z = 0; z < dimz; ++z) { for (size_t y = 0; y < dimy; ++y) { for (size_t x = 0; x < dimx; ++x) { Length3D p; p[0] = (x / float(dimx > 1 ? dimx - 1 : 1) - 0.5) * m - 1 * m;// - 6 * m; p[1] = (y / float(dimy > 1 ? dimy - 1 : 1) - 0.5) * 0.005 * m - 1.7 * m;// + 5 * m; p[2] = (z / float(dimz > 1 ? dimz - 1 : 1) - 0.5) * m; particles.push_back(Particle(mass, p, Velocity3D())); // create connections to all existing neighbors std::vector<size_t> other_xs, other_ys, other_zs; if (z > 0) other_zs.push_back(z - 1); if (y > 0) other_ys.push_back(y - 1); if (x > 0) other_xs.push_back(x - 1); other_zs.push_back(z); other_ys.push_back(y); other_xs.push_back(x); if (z + 1 < dimz) other_zs.push_back(z + 1); if (y + 1 < dimy) other_ys.push_back(y + 1); if (x + 1 < dimx) other_xs.push_back(x + 1); for (std::vector<size_t>::const_iterator oz = other_zs.begin(); oz != other_zs.end(); ++oz) { for (std::vector<size_t>::const_iterator oy = other_ys.begin(); oy != other_ys.end(); ++oy) { for (std::vector<size_t>::const_iterator ox = other_xs.begin(); ox != other_xs.end(); ++ox) { size_t idx = *oz * dimy * dimx + *oy * dimx + *ox; if (idx < particles.size() - 1) { springs.push_back(Spring(particles[idx], particles.back(), stiffness, springDamping, shrinkage)); } } } } } } } // Create obstacles. /*Number3D plane_normal; plane_normal[0] = 0.5; plane_normal[1] = 1.0; plane_normal[2] = 0.0; obstacles.push_back(new Plane(plane_normal / norm(plane_normal), -1.0 * m, bounciness, friction)); plane_normal[0] = 0.0; plane_normal[1] = 1.0; plane_normal[2] = 0.0; obstacles.push_back(new Plane(plane_normal / norm(plane_normal), -1.5 * m, bounciness, friction)); plane_normal[0] = -1.0; plane_normal[1] = 0.0; plane_normal[2] = 0.0; obstacles.push_back(new Plane(plane_normal / norm(plane_normal), -5.0 * m, bounciness, friction)); */ Number3D table_normal; table_normal[0] = 0.0; table_normal[1] = 1.0; table_normal[2] = 0.0; Length table_radius = 0.35 * m; Length3D table_origin; table_origin[0] = -1.0 * m; table_origin[1] = -2.0 * m; table_origin[2] = 0.0 * m; obstacles.push_back(new Table(table_origin, table_normal, table_radius, bounciness, friction)); table_origin[0] = -1.15 * m; table_origin[1] = -1.9 * m; obstacles.push_back(new Table(table_origin, table_normal, table_radius, bounciness, friction)); table_origin[0] = -0.85 * m; table_origin[1] = -2.1 * m; obstacles.push_back(new Table(table_origin, table_normal, table_radius, bounciness, friction)); // Create a particle system. particle_system = new MassSpringSystem(particles, springs, obstacles, particleDamping); // Create a solver. solver = new RungeKuttaSolver(particle_system); quadObj = gluNewQuadric(); glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowPosition(0, 0); glutInitWindowSize(windowWidth, windowHeight); glutCreateWindow("Particle System"); glutIdleFunc(idle); glutDisplayFunc(display); glutReshapeFunc(reshape); glutMouseFunc(mouse); glutMotionFunc(motion); glutKeyboardFunc(keyboard); glEnable(GL_DEPTH_TEST); glutMainLoop(); return 0; }
vector<Particle> Lightcone::getSegment(Snapshot& snap, double rMax, double rMin) { printf("Generating segment (rMax, rMin) (%.0f, %.0f) . . . \n", rMax, rMin); vector<Particle> inSegment; // First find the observer collision box // Define the 8 points that enclose the lightcone in rotated reference frame vector<Particle> points; double d = rMax * tan(mOpening); // // correction to d // if (d > rMax) { // d = rMax; // } double dp = rMin * sin(mOpening); double rp = rMin * cos(mOpening); //printf("d:d':r' (%.0f:%.0f:%.0f)\n", d, dp, rp); points.push_back(Particle(-d, -d, rMax)); points.push_back(Particle(-d, d, rMax)); points.push_back(Particle(d, -d, rMax)); points.push_back(Particle(d, d, rMax)); points.push_back(Particle(-dp, -dp, rp)); points.push_back(Particle(-dp, dp, rp)); points.push_back(Particle(dp, -dp, rp)); points.push_back(Particle(dp, dp, rp)); reverseRotation(points); shiftPointsByObserver(points, true); Box obsBox = makeBoxFromParticles(points); // Full sky map if (mOpening > M_PI / 2) { obsBox = Box(mObserver.x - rMax, mObserver.y - rMax, mObserver.z - rMax, 2 * rMax); } printf( "Original Observer box at [%.2f, %.2f, %.2f] with size [%.2f, %.2f, %.2f], ", obsBox.x, obsBox.y, obsBox.z, obsBox.w, obsBox.h, obsBox.d); // Calculate the offset range need in each direction int xOffMin, xOffMax, yOffMin, yOffMax, zOffMin, zOffMax; xOffMin = (obsBox.x / BOX_WIDTH) - 1; xOffMax = ((obsBox.x + obsBox.w) / BOX_WIDTH) + 1; // printf("x Offset (Min:Max)(%d:%d) \n", xOffMin, xOffMax); yOffMin = (obsBox.y / BOX_WIDTH) - 1; yOffMax = ((obsBox.y + obsBox.h) / BOX_WIDTH) + 1; // printf("y Offset (Min:Max)(%d:%d) \n", yOffMin, yOffMax); zOffMin = (obsBox.z / BOX_WIDTH) - 1; zOffMax = ((obsBox.z + obsBox.d) / BOX_WIDTH) + 1; // printf("z Offset (Min:Max)(%d:%d) \n", zOffMin, zOffMax); // Create snapshot boxes from offset and test if they collide with segment vector<Particle> validOffsets; for (int i = xOffMin; i <= xOffMax; i++) { for (int j = yOffMin; j <= yOffMax; j++) { for (int k = zOffMin; k <= zOffMax; k++) { // Create the box Box virtualSnap = Box(i * BOX_WIDTH, j * BOX_WIDTH, k * BOX_WIDTH, BOX_WIDTH); if (collide(obsBox, virtualSnap)) { validOffsets.push_back(Particle(i, j, k)); } } } } printf("%lu boxes are required.\n", validOffsets.size()); // Check lightcone inSegment = snap.getCone(rMax, rMin, mTheta, mPhi, mOpening, mObserver, validOffsets); if (inSegment.size() == 0) { printf("[Error] Segment returns 0 particles!\n"); } printf(" Segment Size: %lu\n", inSegment.size()); return inSegment; }
//Keyboard handler function void kbd(unsigned char key, int x, int y) { y = 500 - y; if(key == 'q' || key == 27) { exit(0); } if(key == 's') { flip1 = true; } if(key == 'a') { flip2 = true; } if(key == 's' && key == 'a') { flip1 = true; flip2 = true; } if (key == '1') { for (int count = 0; count < game.ActiveObjects.size(); count++) { if (game.ActiveObjects.at(count).hit == true) { game.ActiveObjects.at(count).objectType = 1; } } printf("Cube selected\n"); } if (key == '2') { for (int count = 0; count < game.ActiveObjects.size(); count++) { if (game.ActiveObjects.at(count).hit == true) { game.ActiveObjects.at(count).objectType = 2; } } printf("Sphere selected\n"); } if (key == '3') { for (int count = 0; count < game.ActiveObjects.size(); count++) { if (game.ActiveObjects.at(count).hit == true) { game.ActiveObjects.at(count).objectType = 3; } } printf("Ring selected\n"); } if (key == '8') { cameraParticlePosition = true; printf("Pinball Perspective\n"); } if (key == '9') { cameraParticlePosition = false; printf("Regular Perspective\n"); } if (key == 'x') { for (int count = 0; count < game.ActiveObjects.size(); count++) { if (game.ActiveObjects.at(count).hit == true) { game.ActiveObjects.at(count).objectTranslateX(0.1); } } } if (key == 'X') { for (int count = 0; count < game.ActiveObjects.size(); count++) { if (game.ActiveObjects.at(count).hit == true) { game.ActiveObjects.at(count).objectTranslateX(-0.1); } } } if (key == 'y') { for (int count = 0; count < game.ActiveObjects.size(); count++) { if (game.ActiveObjects.at(count).hit == true) { game.ActiveObjects.at(count).objectTranslateY(0.1); } } } if (key == 'Y') { for (int count = 0; count < game.ActiveObjects.size(); count++) { if (game.ActiveObjects.at(count).hit == true) { game.ActiveObjects.at(count).objectTranslateY(-0.1); } } } if (key == 'z') { for (int count = 0; count < game.ActiveObjects.size(); count++) { if (game.ActiveObjects.at(count).hit == true) { game.ActiveObjects.at(count).objectTranslateZ(0.1); } } } if (key == 'Z') { for (int count = 0; count < game.ActiveObjects.size(); count++) { if (game.ActiveObjects.at(count).hit == true) { game.ActiveObjects.at(count).objectTranslateZ(-0.1); } } } if (key == ' ') { //check to see if on, is so turn off and vice versa if (startStop == true) { startStop = false; printf("stoped animation\n"); } else if (startStop == false) { startStop = true; printf("started animation\n"); } } if (key == 'r') { //check to see if on, is so turn off and vice versa game.ball = Particle(); game.points = Points(); gameOver = false; printf("Restart\n"); } if (key == 'l') { if(lightswitch == true) { lightswitch = false; glEnable(GL_LIGHTING); printf("Light Enabled\n"); } else { lightswitch = true; glDisable(GL_LIGHTING); printf("Light Disabled\n"); } } }
void System::Problem_generate_geometry(const int param) { const double dt_max = 1.0/128.0; scheduler = Scheduler(dt_max); t_end = 5.0 + 1.0/65536; dt_restart = 1.0/64; dt_snap = 1.0/16; dt_restart = std::max(dt_restart, dt_max); dt_snap = std::max(dt_snap, dt_max); int Npnts_glb = 2e5; #if 1 Npnts_glb = 2e6; #endif #if 0 Npnts_glb = 2e7; #endif const int Npnts = Npnts_glb/numElements; ptcl_list.clear(); ptcl_list.reserve(Npnts); Rand48 rnd; rnd.srand(123 + 123*thisIndex); { const real pow = 3.0/2.0; int pc = 0; const real Rmax = global_domain_size.abs(); const real eps = BND_RADIUS1; assert(pow > 1.0); const real r0 = eps/std::sqrt(pow - 1.0); const real n3rmax = r0*r0/std::pow(r0*r0 + eps*eps, pow); while (pc < Npnts) { bool pick = false; real r = eps; while (!pick) { r = Rmax*drand48(); const real n3 = 1.0/std::pow(r*r + eps*eps, pow); const real n3r = r*r*n3; pick = (n3rmax*drand48() < n3r); } #if 0 real theta = 0; pick = false; while (!pick) { theta = drand48()*M_PI; const real sigma = (M_PI/2.0) * 0.075; const real f= 0.05; const real p = (f + (1.0 - f)*exp(-sqr(theta - M_PI/2.0)/2/sqr(sigma)))*sin(theta); pick = (drand48() < p); } #else const real theta = acos(1.0 - 2.0*drand48()); #endif const real phi = 2*M_PI*drand48(); const vec3 pos(r*sin(theta)*cos(phi), r*sin(theta)*sin(phi), r*cos(theta)); if (pos.x < global_domain.get_rmin().x) continue; if (pos.x > global_domain.get_rmax().x) continue; if (pos.y < global_domain.get_rmin().y) continue; if (pos.y > global_domain.get_rmax().y) continue; if (pos.z < global_domain.get_rmin().z) continue; if (pos.z > global_domain.get_rmax().z) continue; ptcl_list.push_back(Particle(ptcl_list.size(), thisIndex, pos)); pc++; } } local_n = ptcl_list.size(); generateGeometry_nRelax = 5; }
//-------------------------------------------------------------- void ParticleController::addParticle ( ofVec2f pos ) { mParticles.push_back ( Particle ( pos ) ); }
void Particle::reset(){ *this = Particle(); }
void SpringSystem::add_particle(vec3 position, vec3 velocity, float mass, bool locked) { particles.push_back( Particle(position, velocity, mass, locked,nrParticules) ); nrParticules++; }
Particle Particle::operator-(Vector v) { return Particle(Point(*this) - v,step,ttl,type,polygonIndex); }
int data[] = { 5, 2, 3, 6, 7, 4, 0, 1 }; std::vector<int> vector(data, data + 8); boost::compute::sort(vector.begin(), vector.end(), queue); CHECK_RANGE_EQUAL(int, 8, vector, (0, 1, 2, 3, 4, 5, 6, 7)); } BOOST_AUTO_TEST_CASE(sort_custom_struct) { // function to compare particles by their x-coordinate BOOST_COMPUTE_FUNCTION(bool, sort_by_x, (Particle a, Particle b), { return a.x < b.x; }); std::vector<Particle> particles; particles.push_back(Particle(0.1f, 0.f)); particles.push_back(Particle(-0.4f, 0.f)); particles.push_back(Particle(10.0f, 0.f)); particles.push_back(Particle(0.001f, 0.f)); boost::compute::vector<Particle> vector(4, context); boost::compute::copy(particles.begin(), particles.end(), vector.begin(), queue); BOOST_CHECK_EQUAL(vector.size(), size_t(4)); BOOST_CHECK( boost::compute::is_sorted(vector.begin(), vector.end(), sort_by_x, queue) == false ); boost::compute::sort(vector.begin(), vector.end(), sort_by_x, queue); BOOST_CHECK( boost::compute::is_sorted(vector.begin(), vector.end(),
Particle ParticleEmitter::makeParticle(float frameTimePassed, float deltaTime, vec3f position) { (void) frameTimePassed; (void) deltaTime; (void) position; return Particle(); }
//#define TEST_COUNTER //-------------------------------------------------------------- void testApp::setup(){ #ifdef TEST_COUNTER ofSetLogLevel(OF_LOG_SILENT); cout << "Start test Count 10000" << endl; cout << "--------------------------------------------------------------" << endl; for(int i = 0 ; i < 10000 ; i++) { stateMachine.getSharedData().load(); cout << "Count = "<< stateMachine.getSharedData().counter <<endl; stateMachine.getSharedData().counter+=1; stateMachine.getSharedData().save(); } cout << "End test Count 10000" << endl; cout << "--------------------------------------------------------------" << endl; std::exit(0); #endif ofEnableSmoothing(); ofEnableAlphaBlending(); ofSetVerticalSync(true); glDisable(GL_DEPTH_TEST); ofxXmlSettings xml = stateMachine.getSharedData().xml; if(xml.loadFile(settingFileName)) { if(xml.pushTag("DATA")) { stateMachine.getSharedData().bDebug = xml.getValue("DEBUG", true); float width = xml.getValue("WIDTH", 1280); float height = xml.getValue("HEIGHT", 720); sndPlayer.loadSound(xml.getValue("SOUND_PATH", "sounds/Zone 5 - Door Creak, scream and witchly laugh.wav")); sndPlayer.setLoop(true); sndPlayer.play(); stateMachine.getSharedData(). wRatio = width/1920; stateMachine.getSharedData(). hRatio = height/1080; ofSetFullscreen(xml.getValue("FULLSCREEN", 0)); ofSetWindowShape(width, height); stateMachine.getSharedData().path_to_save = xml.getValue("CAPTURE_PATH", "./captures"); stateMachine.getSharedData().filesXml.loadFile(stateMachine.getSharedData().path_to_save+"/files.xml"); if(!stateMachine.getSharedData().filesXml.pushTag("XML")) { stateMachine.getSharedData().filesXml.addTag("XML"); stateMachine.getSharedData().filesXml.pushTag("XML"); } stateMachine.getSharedData().numDigi = xml.getValue("DIGI", 5); stateMachine.getSharedData().font.loadFont(xml.getValue("FONT_PATH", "fonts/LunacyMore.ttf"),xml.getValue("FONT_SIZE", 128)); ofDirectory dir; if(dir.listDir(stateMachine.getSharedData().path_to_save)<1) { dir.createDirectory(stateMachine.getSharedData().path_to_save); } xml.popTag(); } } else { ofLog(OF_LOG_ERROR,"Faile to load "+ settingFileName); } // // setup shared data ofxControlPanel::setBackgroundColor(simpleColor(30, 30, 60, 100)); ofxControlPanel::setTextColor(simpleColor(240, 50, 50, 255)); stateMachine.getSharedData().panel.setup(ofGetWidth(),ofGetHeight()); stateMachine.getSharedData().panel.loadFont("MONACO.TTF", 8); stateMachine.getSharedData().panel.addPanel("General", 4,false); ofxControlPanel::setBackgroundColor(simpleColor(60, 30, 30, 100)); stateMachine.getSharedData().panel.addPanel("FaceTracking", 5, false); ofxControlPanel::setBackgroundColor(simpleColor(60, 30, 30, 100)); stateMachine.getSharedData().panel.addPanel("FaceTracking0", 4, false); ofxControlPanel::setBackgroundColor(simpleColor(60, 30, 30, 100)); stateMachine.getSharedData().panel.addPanel("FaceTracking1", 4, false); ofxControlPanel::setBackgroundColor(simpleColor(70, 70, 30, 100)); stateMachine.getSharedData().panel.addPanel("FaceMapEdit", 4, false); ofxControlPanel::setBackgroundColor(simpleColor(30, 30, 30, 100)); //some dummy vars we will update to show the variable lister object appFrameRate = ofGetFrameRate(); stateMachine.getSharedData().panel.setWhichPanel("General"); stateMachine.getSharedData().panel.setWhichColumn(0); stateMachine.getSharedData().panel.addChartPlotter("some chart", guiStatVarPointer("app fps", &appFrameRate, GUI_VAR_FLOAT, true, 2), 200, 50, 200, 5, 80); vector<string> loglevel; loglevel.push_back("OF_LOG_VERBOSE"); loglevel.push_back("OF_LOG_NOTICE"); loglevel.push_back("OF_LOG_WARNING"); loglevel.push_back("OF_LOG_ERROR"); loglevel.push_back("OF_LOG_FATAL_ERROR"); loglevel.push_back("OF_LOG_SILENT"); stateMachine.getSharedData().panel.addTextDropDown("LogLevel","LogLevel", 0, loglevel); // initialise state machine stateMachine.addState(new IndexState()); stateMachine.addState(new SelectPlayerState()); stateMachine.addState(new CaptureState()); stateMachine.addState(new EditState()); stateMachine.addState(new EndState()); stateMachine.addState(new LicenseState()); stateMachine.changeState(xml.getValue("DATA:INIT_STATE", "IndexState")); stateMachine.getSharedData().panel.loadSettings("settings.xml"); stateMachine.getSharedData().panel.hide(); // if(!stateMachine.getSharedData().bDebug) // { //// stateMachine.getSharedData().panel.unregisterKeyboardEvent(); // } stateMachine.getSharedData().numPlayer = 1; for(int i = 0 ; i < NUM_SEQ ;i++) { image[i].loadSequence("images/bat/bat_", "png", 0, 154, 5); image[i].setFrameRate(60); } int num = 3000; stateMachine.getSharedData().p.assign(num, Particle()); resetParticles(); }
void system::set_geometry(const bool init) { const double dt_max = 1.0/512; scheduler = Scheduler(dt_max); int np; float lx, ly, lz; FILE *fin = NULL; if (myproc == 0) { float wp; fin = fopen(fin_data, "r"); int ival; size_t nread; nread = fread(&ival, sizeof(int), 1, fin); assert(ival == 2*sizeof(int)); nread = fread(&np, sizeof(int), 1, fin); nread = fread(&wp, sizeof(float), 1, fin); nread = fread(&ival, sizeof(int), 1, fin); assert(ival == 2*sizeof(int)); nread = fread(&ival, sizeof(int), 1, fin); assert(ival == 3*sizeof(float)); nread = fread(&lx, sizeof(float), 1, fin); nread = fread(&ly, sizeof(float), 1, fin); nread = fread(&lz, sizeof(float), 1, fin); nread = fread(&ival, sizeof(int), 1, fin); assert(ival == 3*sizeof(float)); fprintf(stderr, " np= %d wp= %g \n",np, wp); fprintf(stderr, " lx= %g ly= %g lz= %g \n", lx, ly, lz); } MPI_Bcast(&lx, 1, MPI_FLOAT, 0, MPI_COMM_WORLD); MPI_Bcast(&ly, 1, MPI_FLOAT, 0, MPI_COMM_WORLD); MPI_Bcast(&lz, 1, MPI_FLOAT, 0, MPI_COMM_WORLD); t_end = 0.2; n_restart = 2; dt_restart = dt_max; dt_dump = 0.01; di_log = 100; global_n = local_n = 0; // eulerian = true; const vec3 rmin(0.0); const vec3 rmax(lx, ly, lz); global_domain = boundary(rmin, rmax); global_domain_size = global_domain.hsize() * 2.0; const vec3 Len3 = global_domain.hsize() * 2.0; pfloat<0>::set_scale(Len3.x); pfloat<1>::set_scale(Len3.y); pfloat<2>::set_scale(Len3.z); if (myproc == 0) { ptcl.resize(np); const int nx = (int)std::pow(np, 1.0/3.0); const dvec3 dr = dvec3(Len3.x/nx, Len3.y/nx, Len3.z/nx); const real rmax = dr.abs() * 1.0; fprintf(stderr, "dr= %g %g %g \n", dr.x, dr.y, dr.z); local_n = ptcl.size(); global_n = local_n; { std::vector<float> x(local_n), y(local_n), z(local_n); size_t nread; int ival; nread = fread(&ival, sizeof(int), 1, fin); assert(ival == local_n*(int)sizeof(float)); nread = fread(&x[0], sizeof(float), local_n, fin); assert((int)nread == local_n); nread = fread(&ival, sizeof(int), 1, fin); assert(ival == local_n*(int)sizeof(float)); nread = fread(&ival, sizeof(int), 1, fin); assert(ival == local_n*(int)sizeof(float)); nread = fread(&y[0], sizeof(float), local_n, fin); assert((int)nread == local_n); nread = fread(&ival, sizeof(int), 1, fin); assert(ival == local_n*(int)sizeof(float)); nread = fread(&ival, sizeof(int), 1, fin); assert(ival == local_n*(int)sizeof(float)); nread = fread(&z[0], sizeof(float), local_n, fin); assert((int)nread == local_n); nread = fread(&ival, sizeof(int), 1, fin); assert(ival == local_n*(int)sizeof(float)); for (int i = 0; i < local_n; i++) { const dvec3 vel(0.0, 0.0, 0.0); ptcl[i] = Particle(x[i], y[i], z[i], vel.x, vel.y, vel.z, i); ptcl[i].rmax = rmax; ptcl[i].unset_derefine(); } } U.resize(local_n); const int var_list[7] = { Fluid::VELX, Fluid::VELY, Fluid::VELZ, Fluid::DENS, Fluid::BX, Fluid::BY, Fluid::BZ}; std::vector<float> data(local_n); for (int var = 0; var < 7; var++) { fprintf(stderr, " reading vat %d out of %d \n", var+1, 7); int ival; size_t nread; nread = fread(&ival, sizeof(int), 1, fin); assert(ival == local_n*(int)sizeof(float)); nread = fread(&data[0], sizeof(float), local_n, fin); assert((int)nread == local_n); nread = fread(&ival, sizeof(int), 1, fin); assert(ival == local_n*(int)sizeof(float)); for (int i = 0; i < local_n; i++) U[i][var_list[var]] = data[i]; } for (int i = 0; i < local_n; i++) { assert(U[i][Fluid::DENS] > 0.0); U[i][Fluid::ETHM] = cs2 * U[i][Fluid::DENS]; } fclose(fin); fprintf(stderr, " *** proc= %d : local_n= %d global_n= %d \n", myproc, local_n, global_n); } // myproc == 0 MPI_Bcast(&global_n, 1, MPI_INT, 0, MPI_COMM_WORLD); fprintf(stderr, " proc= %d distrubite \n", myproc); MPI_Barrier(MPI_COMM_WORLD); Distribute::int3 nt(1, 1, 1); switch(nproc) { case 1: break; case 2: nt.x = 2; nt.y = 1; nt.z = 1; break; case 4: nt.x = 2; nt.y = 2; nt.z = 1; break; case 6: nt.x = 3; nt.y = 2; nt.z = 1; break; case 8: nt.x = 2; nt.y = 2; nt.z = 2; break; case 16: nt.x = 4; nt.y = 2; nt.z = 2; break; case 32: nt.x = 4; nt.y = 4; nt.z = 2; break; case 64: nt.x = 4; nt.y = 4; nt.z = 4; break; case 128: nt.x = 8; nt.y = 4; nt.z = 4; break; case 256: nt.x = 8; nt.y = 8; nt.z = 4; break; case 512: nt.x = 8; nt.y = 8; nt.z = 8; break; default: assert(false); } const Distribute::int3 nt_glb(nt); const pBoundary pglobal_domain(pfloat3(0.0), pfloat3(Len3)); distribute_glb.set(nproc, nt, pglobal_domain); for (int k = 0; k < 5; k++) distribute_data(true, false); const int nloc_reserve = (int)(2.0*global_n/nproc); fit_reserve_vec(ptcl, nloc_reserve); fit_reserve_vec(ptcl_ppos, nloc_reserve); fit_reserve_vec(U, nloc_reserve); fit_reserve_vec(dU, nloc_reserve); fit_reserve_vec(Wgrad, nloc_reserve); fit_reserve_vec(gradPsi, nloc_reserve); fit_reserve_vec(cells, nloc_reserve); MPI_Barrier(MPI_COMM_WORLD); fprintf(stderr, " *** proc= %d : local_n= %d global_n= %d \n", myproc, local_n, global_n); fprintf(stderr, " proc= %d building_mesh \n", myproc); MPI_Barrier(MPI_COMM_WORLD); const double t10 = mytimer::get_wtime(); clear_mesh(); int nattempt = build_mesh(true); double dt10 = mytimer::get_wtime() - t10; double volume_loc = 0.0; { std::vector<TREAL> v(local_n); for (int i = 0; i < local_n; i++) v[i] = cells[i].Volume; std::sort(v.begin(), v.end()); // sort volumes from low to high, to avoid roundoff errors for (int i = 0; i < local_n; i++) volume_loc += v[i]; } double dt10max; MPI_Allreduce(&dt10, &dt10max, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD); double volume_glob = 0.0; int nattempt_max, nattempt_min; MPI_Allreduce(&volume_loc, &volume_glob, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(&nattempt, &nattempt_max, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD); MPI_Allreduce(&nattempt, &nattempt_min, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD); const double volume_exact = global_domain_size.x*global_domain_size.y*global_domain_size.z; if (myproc == 0) { fprintf(stderr, "first call build_mesh:[ %g sec :: %g cells/s/proc/thread ]\n", dt10max, global_n/nproc/dt10max); fprintf(stderr, " computed_volume= %g exact_volume= %g diff= %g [ %g ] nattempt= %d %d \n", volume_glob, volume_exact, volume_glob - volume_exact, (volume_glob - volume_exact)/volume_exact, nattempt_min, nattempt_max); } exchange_ptcl(); }