コード例 #1
0
cell AMX_NATIVE_CALL Natives::CreateDynamicPolygon(AMX *amx, cell *params)
{
	CHECK_PARAMS(7, "CreateDynamicPolygon");
	if (core->getData()->getGlobalMaxItems(STREAMER_TYPE_AREA) == core->getData()->areas.size())
	{
		return 0;
	}
	if (static_cast<int>(params[4] >= 2 && static_cast<int>(params[4]) % 2))
	{
		Utility::logError("CreateDynamicPolygon: Number of points must be divisible by two");
		return 0;
	}
	int areaID = Item::Area::identifier.get();
	Item::SharedArea area(new Item::Area);
	area->amx = amx;
	area->areaID = areaID;
	area->type = STREAMER_AREA_TYPE_POLYGON;
	Utility::convertArrayToPolygon(amx, params[1], params[4], boost::get<Polygon2D>(area->position));
	area->height = Eigen::Vector2f(amx_ctof(params[2]), amx_ctof(params[3]));
	Box2D box = boost::geometry::return_envelope<Box2D>(boost::get<Polygon2D>(area->position));
	area->size = static_cast<float>(boost::geometry::comparable_distance(box.min_corner(), box.max_corner()));
	Utility::addToContainer(area->worlds, static_cast<int>(params[5]));
	Utility::addToContainer(area->interiors, static_cast<int>(params[6]));
	Utility::addToContainer(area->players, static_cast<int>(params[7]));
	core->getGrid()->addArea(area);
	core->getData()->areas.insert(std::make_pair(areaID, area));
	return static_cast<cell>(areaID);
}
コード例 #2
0
string QuadtreeNode::toString() {
	ostringstream stream;

	Box2D *rect;

	int size = 0;

	if ( !objectVector || (size = (int)objectVector->size()) > 0 ) {
		stream << "";

		stream << "Obj.: ";

		for (int i=0; i < size; i++) {
			rect = (Box2D *)objectVector->at(i);
			stream << rect->toString();

			if ( i < size - 1 )
				stream << ", ";
		}
	} else {
		stream << "Empty";
	}

	return stream.str();
}
コード例 #3
0
void LocalMultiBlockInfo2D::computePeriodicOverlaps (
    SparseBlockStructure2D const& sparseBlock, plint blockId )
{
    Box2D intersection; // Temporary variable.
    std::vector<plint> neighbors; // Temporary variable.
    SmartBulk2D bulk(sparseBlock, envelopeWidth, blockId);

    for (plint dx=-1; dx<=+1; dx+=1) {
        for (plint dy=-1; dy<=+1; dy+=1) {
            if (dx!=0 || dy!=0) {
                // The new block is shifted by the length of the full multi block in each space
                //   direction. Consequently, overlaps between the original multi block and the
                //   shifted new block are identified as periodic overlaps.
                plint shiftX = dx*sparseBlock.getBoundingBox().getNx();
                plint shiftY = dy*sparseBlock.getBoundingBox().getNy();
                Box2D shiftedBulk(bulk.getBulk().shift(shiftX,shiftY));
                Box2D shiftedEnvelope(bulk.computeEnvelope().shift(shiftX,shiftY));
                // Speed optimization: perform following checks only if the shifted
                //   domain touches the bounding box.
                Box2D dummyIntersection;
                if (intersect(shiftedEnvelope, sparseBlock.getBoundingBox(), dummyIntersection)) {
                    neighbors.clear();
                    sparseBlock.findNeighbors(shiftedBulk, envelopeWidth, neighbors);
                    // Check overlap with each existing block in the neighborhood, including with the newly added one.
                    for (pluint iNeighbor=0; iNeighbor<neighbors.size(); ++iNeighbor) {
                        plint neighborId = neighbors[iNeighbor];
                        SmartBulk2D neighborBulk(sparseBlock, envelopeWidth, neighborId);
                        // Does the envelope of the shifted new block overlap with the bulk of a previous
                        //   block? If yes, add an overlap, in which the previous block has the "original
                        //   position", and the new block has the "overlap position".
                        if (intersect(neighborBulk.getBulk(), shiftedEnvelope, intersection)) {
                            PeriodicOverlap2D overlap (
                                Overlap2D(neighborId, blockId, intersection, shiftX, shiftY),
                                dx, dy );
                            periodicOverlaps.push_back(overlap);
                            periodicOverlapWithRemoteData.push_back(overlap);
                        }
                        // Does the bulk of the shifted new block overlap with the envelope of a previous
                        //   block? If yes, add an overlap, in which the new block has the "original position",
                        //   and the previous block has the "overlap position".
                        //   If we are in the situation in which the newly added block is periodic with itself,
                        //   this step must be skipped, because otherwise the overlap is counted twice.
                        if (!(neighborId==blockId) &&
                                intersect(shiftedBulk, neighborBulk.computeEnvelope(), intersection))
                        {
                            intersection = intersection.shift(-shiftX,-shiftY);
                            periodicOverlaps.push_back (
                                PeriodicOverlap2D (
                                    Overlap2D(blockId, neighborId, intersection, -shiftX, -shiftY),
                                    -dx, -dy ) );
                        }
                    }
                }
            }
        }
    }
}
コード例 #4
0
void saveFull( MultiBlock2D& multiBlock, FileName fName, IndexOrdering::OrderingT ordering )
{
    global::profiler().start("io");
    SparseBlockStructure2D blockStructure(multiBlock.getBoundingBox());
    Box2D bbox = multiBlock.getBoundingBox();
    if (ordering==IndexOrdering::forward) {
        plint nBlocks = std::min(bbox.getNx(), (plint)global::mpi().getSize());
        std::vector<std::pair<plint,plint> > ranges;
        util::linearRepartition(bbox.x0, bbox.x1, nBlocks, ranges);
        for (pluint iRange=0; iRange<ranges.size(); ++iRange) {
            blockStructure.addBlock (
                    Box2D( ranges[iRange].first, ranges[iRange].second,
                           bbox.y0, bbox.y1 ),
                    iRange );
        }
    }
    else if (ordering==IndexOrdering::backward) {
        plint nBlocks = std::min(bbox.getNy(), (plint)global::mpi().getSize());
        std::vector<std::pair<plint,plint> > ranges;
        util::linearRepartition(bbox.y0, bbox.y1, nBlocks, ranges);
        for (pluint iRange=0; iRange<ranges.size(); ++iRange) {
            blockStructure.addBlock (
                    Box2D( bbox.x0, bbox.x1, ranges[iRange].first, ranges[iRange].second ),
                    iRange );
        }
    }
    else {
        // Sparse ordering not defined.
        PLB_ASSERT( false );
    }
    plint envelopeWidth=1;
    MultiBlockManagement2D adjacentMultiBlockManagement (
            blockStructure, new OneToOneThreadAttribution, envelopeWidth );
    MultiBlock2D* multiAdjacentBlock = multiBlock.clone(adjacentMultiBlockManagement);
    
    std::vector<plint> offset;
    std::vector<plint> myBlockIds;
    std::vector<std::vector<char> > data;

    bool dynamicContent = false;
    dumpData(*multiAdjacentBlock, dynamicContent, offset, myBlockIds, data);
    if (ordering==IndexOrdering::backward && myBlockIds.size()==1) {
        PLB_ASSERT( data.size()==1 );
        Box2D domain;
        blockStructure.getBulk(myBlockIds[0], domain);
        plint sizeOfCell = multiAdjacentBlock->sizeOfCell();
        PLB_ASSERT( domain.nCells()*sizeOfCell == (plint)data[0].size() );
        transposeToBackward( sizeOfCell, domain, data[0] );
    }

    plint totalSize = offset[offset.size()-1];
    writeOneBlockXmlSpec(*multiAdjacentBlock, fName, totalSize, ordering);
    writeRawData(fName, myBlockIds, offset, data);
    delete multiAdjacentBlock;
    global::profiler().stop("io");
}
コード例 #5
0
Box2D<qint32> GeoReference::coord2Pixel(const Box2D<double> &box) const
{
    if ( !box.isValid()) {
        ERROR2(ERR_INVALID_PROPERTY_FOR_2,"size", "box");
        return  Box2D<qint32>();
    }
    Pixel p1 = coord2Pixel(box.min_corner());
    Pixel p2 = coord2Pixel(box.max_corner());
    return Box2D<qint32>(p1,p2);
}
コード例 #6
0
Box2D<double> GeoReference::pixel2Coord(const Box2D<qint32> &box) const
{
    if ( !box.isValid()) {
        ERROR2(ERR_INVALID_PROPERTY_FOR_2,"size", "box");
        return Box2D<double>();
    }
    Coordinate c1 = pixel2Coord(box.min_corner());
    Coordinate c2 = pixel2Coord(box.max_corner());
    return Box2D<double>(c1,c2);
}
コード例 #7
0
ファイル: MCnucl.cpp プロジェクト: chunshen1987/superMC
void MCnucl::addDensity(Nucleus* nucl, double** dens)
{
    vector<Particle*> participant = nucl->getParticipants();
    for(unsigned int ipart=0; ipart<participant.size(); ipart++) 
    {
        Particle* part = participant[ipart];
        Box2D partBox = part->getBoundingBox();
      double x = part->getX();
      double y = part->getY();
      int x_idx_left = (int)((partBox.getXL() - Xmin)/dx);
      int x_idx_right = (int)((partBox.getXR() - Xmin)/dx);
      int y_idx_left = (int)((partBox.getYL() - Ymin)/dy);
      int y_idx_right = (int)((partBox.getYR() - Ymin)/dy);
      if(x_idx_left < 0 || y_idx_left < 0 || x_idx_left > Maxx || y_idx_left > Maxy)
      {
        cerr << "Wounded nucleon extends out of grid bounds " << "("<< part->getX() << "," << part->getY() << ")" << endl;
      }
      x_idx_left = max(0, x_idx_left);
      x_idx_right = min(Maxx, x_idx_right);
      y_idx_left = max(0, y_idx_left);
      y_idx_right = min(Maxy, y_idx_right);


      for(int ir = x_idx_left; ir < x_idx_right; ir++)
      {
         double xg = Xmin + ir*dx;
         for(int jr = y_idx_left; jr < y_idx_right; jr++)
         {
             double yg = Ymin + jr*dy;
             double dc = (x-xg)*(x-xg) + (y-yg)*(y-yg);
             if (shape_of_entropy==1) // "Checker" nucleons:
             {
               if(dc>dsq) 
                   continue;

               double areai = 10.0/siginNN;
               dens[ir][jr] += areai*participant[ipart]->getFluctfactor();
             }
             else if (shape_of_entropy>=2 && shape_of_entropy<=9) // Gaussian nucleons:
             {
               double density;
               if (shape_of_entropy == 3)
               {
                  density = participant[ipart]->getFluctuatedDensity(xg,yg);
               }
               else
               {
                  density = participant[ipart]->getSmoothDensity(xg,yg);
               }
               dens[ir][jr] += density;
             }
         }
      }
    }
}
コード例 #8
0
bool Geometric2DCollection::Collides(const Box2D& box) const
{
  for(size_t i=0;i<aabbs.size();i++)
    if(box.intersects(aabbs[i])) return true;
  for(size_t i=0;i<boxes.size();i++) 
    if(box.intersects(boxes[i])) return true;
  for(size_t i=0;i<circles.size();i++)
    if(box.intersects(circles[i])) return true;
  for(size_t i=0;i<triangles.size();i++)
    if(box.intersects(triangles[i])) return true;
  return false;
}
コード例 #9
0
bool Geometric2DCollection::Collides(const Geometric2DCollection& geom,int obstacle) const
{
  for(size_t i=0;i<geom.aabbs.size();i++) {
    Box2D box; box.set(geom.aabbs[i]);
    if(Collides(box,obstacle)) return true;
  }
  for(size_t i=0;i<geom.boxes.size();i++)
    if(Collides(geom.boxes[i],obstacle)) return true;
  for(size_t i=0;i<geom.circles.size();i++)
    if(Collides(geom.circles[i],obstacle)) return true;
  for(size_t i=0;i<geom.triangles.size();i++)
    if(Collides(geom.triangles[i],obstacle)) return true;
  return false;
}
コード例 #10
0
bool Geometric2DCollection::Collides(const Triangle2D& tri) const
{
  for(size_t i=0;i<aabbs.size();i++) {
    Box2D box; box.set(aabbs[i]);
    if(box.intersects(tri)) return true;
  }
  for(size_t i=0;i<boxes.size();i++)
    if(boxes[i].intersects(tri)) return true;
  for(size_t i=0;i<circles.size();i++)
    if(tri.closestPoint(circles[i].center).distanceSquared(circles[i].center) < Sqr(circles[i].radius)) return true;
  for(size_t i=0;i<triangles.size();i++)
    if(tri.intersects(triangles[i])) return true;
  return false;
}
コード例 #11
0
bool GridCoverageGenerator::setSize(const Box2D<qint32>& box, const Box2D<double> bounds) {
    Size szOut(box.width(),box.height());

    if ( szOut != size()) {
        CornersGeoReference *grf = new CornersGeoReference();
        grf->setName("subset_" + name());
        grf->setCoordinateSystem(coordinateSystem());
        grf->setEnvelope(bounds);
        IGeoReference georef;
        georef.set(static_cast<GeoReference *>(grf));
        georef->compute(szOut.toQSize());
        setGeoreference(georef);
    }
    return true;
}
コード例 #12
0
void LocalMultiBlockInfo2D::computeAllPeriodicOverlaps (
    SparseBlockStructure2D const& sparseBlock )
{
    for (pluint iBlock=0; iBlock<myBlocks.size(); ++iBlock) {
        plint blockId = myBlocks[iBlock];
        Box2D bulk;
        sparseBlock.getBulk(blockId, bulk);
        // Speed optimization: execute the test for periodicity
        //   only for bulk-domains which touch the bounding box.
        if (!contained (
                    bulk.enlarge(1), sparseBlock.getBoundingBox() ) )
        {
            computePeriodicOverlaps(sparseBlock, blockId);
        }
    }
}
コード例 #13
0
void transposeToBackward(plint sizeOfCell, Box2D const& domain, std::vector<char>& data) {
    plint nx = domain.getNx();
    plint ny = domain.getNy();
    std::vector<char> transp(data.size());

    for (plint iX=0; iX<nx; ++iX) {
        for (plint iY=0; iY<ny; ++iY) {
            plint iForward = sizeOfCell*(iY + ny*iX);
            plint iBackward = sizeOfCell*(iX + nx*iY);
            for (plint iByte=0; iByte<sizeOfCell; ++iByte) {
                transp[iBackward+iByte] = data[iForward+iByte];
            }
        }
    }
    transp.swap(data);
}
コード例 #14
0
bool Geometric2DCSpace::ObstacleOverlap(const Box2D& box) const
{
  AABB2D bb;
  box.getAABB(bb);
  if(!domain.contains(bb)) return true;
  return Geometric2DCollection::Collides(box);
}
コード例 #15
0
bool Geometric2DCollection::Collides(const Box2D& box,int obstacle) const
{
  Type type=ObstacleType(obstacle);
  int index = ObstacleIndex(obstacle);
  switch(type) {
  case AABB:
    return box.intersects(aabbs[index]);
  case Triangle:
    return box.intersects(triangles[index]);
  case Box:
    return box.intersects(boxes[index]);
  case Circle:
    return box.intersects(circles[index]);
  }
  abort();
  return false;
}
コード例 #16
0
ファイル: LocationView.cpp プロジェクト: jjhoyt/gengis
void LocationView::RenderLabel()
{
	if(!GetLabelBindToChart() && m_label->IsVisible() && !App::Inst().GetMouseDragging())
	{
		// get screen coordinates for location
		Point3D winPos = App::Inst().GetMapController()->ProjectToScreen(GetPosition());

		Box2D bb = m_label->GetBoundingBox();

		float size = m_size * App::Inst().GetResolutionFactor();

		// compensate for perspective projection
		float angle = sin(App::Inst().GetViewport()->GetCamera()->GetPitch()*DEG_TO_RAD);
		float perspectiveSize = size * angle;
		float perspectiveTextHeight = bb.Height()*angle;

		// calculate screen position of label
		uint offset = 2 * App::Inst().GetResolutionFactor();

		if(m_label->GetLabelPosition() == _T("Right"))
			m_label->SetScreenPosition(Point3D(winPos.x+size+offset, winPos.y-bb.Height()/3, LABEL_LAYER));
		else if(m_label->GetLabelPosition() == _T("Left"))
			m_label->SetScreenPosition(Point3D(winPos.x-bb.Width()-size-offset, winPos.y-bb.Height()/3, LABEL_LAYER));
		else if(m_label->GetLabelPosition() == _T("Top"))
			m_label->SetScreenPosition(Point3D(winPos.x-bb.Width()/2, winPos.y+perspectiveSize+offset, LABEL_LAYER));
		else if(m_label->GetLabelPosition() == _T("Bottom"))
			m_label->SetScreenPosition(Point3D(winPos.x-bb.Width()/2, winPos.y-perspectiveTextHeight-perspectiveSize, LABEL_LAYER));

		m_label->Render();
	}
}
コード例 #17
0
ファイル: parallelizer2D.cpp プロジェクト: Longlonc/palabos
plint Parallelizer2D::computeCost(std::vector<std::vector<Box2D> > const& originalBlocks, Box2D box){
    plint totalCost = 0;
    plint numLevels = originalBlocks.size();
    
    for (plint iLevel=(plint)originalBlocks.size()-1; iLevel>=0; --iLevel){
        // convert the box to the current level
        Box2D levelBox = global::getDefaultMultiScaleManager().scaleBox(box,iLevel-(numLevels-1));
        for (pluint iComp=0; iComp<originalBlocks[iLevel].size(); ++iComp){
            Box2D currentBox;
            if (intersect(originalBlocks[iLevel][iComp], levelBox, currentBox)){
                plint volume = currentBox.getNx()*currentBox.getNy();
                totalCost += (plint) util::twoToThePower(iLevel) * volume;
            }
        }
    }
    
    return totalCost;
}
コード例 #18
0
ファイル: grid.cpp プロジェクト: BigETI/samp-streamer-plugin
CellID Grid::getCellID(const Eigen::Vector2f &position, bool insert)
{
    static Box2D box;
    box.min_corner()[0] = std::floor((position[0] / cellSize)) * cellSize;
    box.min_corner()[1] = std::floor((position[1] / cellSize)) * cellSize;
    box.max_corner()[0] = box.min_corner()[0] + cellSize;
    box.max_corner()[1] = box.min_corner()[1] + cellSize;
    Eigen::Vector2f centroid = boost::geometry::return_centroid<Eigen::Vector2f>(box);
    CellID cellID = std::make_pair(static_cast<int>(centroid[0]), static_cast<int>(centroid[1]));
    if (insert)
    {
        boost::unordered_map<CellID, SharedCell>::iterator c = cells.find(cellID);
        if (c == cells.end())
        {
            SharedCell cell(new Cell(cellID));
            cells[cellID] = cell;
        }
    }
    return cellID;
}
コード例 #19
0
ファイル: MCnucl.cpp プロジェクト: chunshen1987/superMC
Box2D MCnucl::getHotSpots(vector<Box2D> & hotSpots)
{
    hotSpots.clear();
    
    vector<Particle*> participants = proj->getParticipants();
    for(int i = 0; i < participants.size(); i++)
        hotSpots.push_back(participants[i]->getBoundingBox());
    
    participants = targ->getParticipants();
    for(int i = 0; i < participants.size(); i++)
        hotSpots.push_back(participants[i]->getBoundingBox());
    
    for(int i = 0; i < binaryCollision.size(); i++)
        hotSpots.push_back(binaryCollision[i]->getBoundingBox());
    
    Box2D hotSpot = hotSpots[0];
    
    for(int i = 1; i < hotSpots.size(); i++)
        hotSpot.overUnion(hotSpots[i]);
    return hotSpot;
}
コード例 #20
0
bool Geometric2DCollection::Collides(const Triangle2D& t,int obstacle) const
{
  Type type=ObstacleType(obstacle);
  int index = ObstacleIndex(obstacle);
  switch(type) {
  case AABB:
    {
      Box2D box; box.set(aabbs[index]);
      return box.intersects(t);
    }
  case Triangle:
    return triangles[index].intersects(t);
  case Box:
    return boxes[index].intersects(t);
  case Circle:
    {
      return (t.closestPoint(circles[index].center).distanceSquared(circles[index].center) < Sqr(circles[index].radius));
    }
  }
  abort();
  return false;
}
コード例 #21
0
ファイル: QtSDL.cpp プロジェクト: brunoweig/quadtreeThread
/*
 * Gera n objetos aleatórios
 */
void QtSDL::generateObjects(int n) {
	int x, y, size;
	bool horizontal;
	bool vertical;
	int speed;

	objects->clear();

	Box2D limits = getRoot()->getArea();

	for (int i=0; i < n; i++) {
		x = randomNumber(limits.getLeftSide() + 5, limits.getRightSide() - 5);
		y = randomNumber(limits.getTopSide() + 5, limits.getBottomSide() - 5);

		size = randomNumber(2, 6);
		horizontal = randomBool();
		vertical = randomBool();
		speed = randomNumber(1, 2);

		objects->push_back(new RectangleSDL(Color::Blue, x, y, size, horizontal, vertical, speed));
	}
}
コード例 #22
0
void RectangleSDL::draw(Box2D & area, Color::enColor color, SDL_Surface *screen) {
	GLfloat c = 0.5;

	glBegin(GL_LINE_LOOP);
		glColor3f(c, c, c);

		glVertex2i(area.getLeftSide(), area.getTopSide());

		glVertex2i(area.getRightSide(), area.getTopSide());

		glVertex2i(area.getRightSide(), area.getBottomSide());

		glVertex2i(area.getLeftSide(), area.getBottomSide());
	glEnd();

	/*
	SDL_Color c = Color::getColor(color);

	boxRGBA(screen, area.getLeftSide(), area.getTopSide(), area.getRightSide(), area.getBottomSide(), c.r, c. g, c. b, 255);
	*/
}
コード例 #23
0
void initializeQuadrant(QuadTree* quadtree, const Box2D& quadrantBounds, unsigned int depth, unsigned int index, unsigned int offset, unsigned int levelWidth)
{
    unsigned int i = offset + index;

    // FIXME: checking boundaries
    if (i >= quadtree->maxQuadrants)
    {
        throw std::exception("max. quadrants overflow");
    }

    Quadrant& quadrant = quadtree->quadrants[i];
    quadrant.depth = depth;
    quadrant.bounds = quadrantBounds;

    if (depth == quadtree->maxDepth - 1) // leaf
    {
        quadrant.edges = quadtree->numQuadrantEdges++;
        return;
    }

    unsigned int baseIndex = (index * 4);
    unsigned int newOffset = offset + levelWidth;
    unsigned int newLevelWidth = levelWidth * 4;
    unsigned int newDepth = depth + 1;
    vml_vec2 subQuadrantSize = quadrantBounds.getExtents() / 2.0f;

    for (unsigned int y = 0, i = 0; y < 2; y++)
    {
        float subQuadrantY = quadrantBounds.min.y + ((float)y * subQuadrantSize.y);

        for (unsigned int x = 0; x < 2; x++, i++)
        {
            initializeQuadrant(quadtree, Box2D(quadrantBounds.min.x + ((float)x * subQuadrantSize.x), subQuadrantY, subQuadrantSize.x, subQuadrantSize.y), newDepth, baseIndex + i, newOffset, newLevelWidth);
        }
    }
}
コード例 #24
0
bool CoverageConnector::storeMetaData(IlwisObject *obj, IlwisTypes type, const DataDefinition& datadef)
{
    bool ok = Ilwis3Connector::storeMetaData(obj, type);
    if ( !ok)
        return false;

    Coverage *coverage = static_cast<Coverage *>(obj);

    const ICoordinateSystem csy = coverage->coordinateSystem();
    if (!csy.isValid())
        return ERROR2(ERR_NO_INITIALIZED_2, "CoordinateSystem", coverage->name());

    QString localName = Resource::toLocalFile(csy->source().url(),true);
    if ( localName == sUNDEF) {
        localName = CoordinateSystemConnector::createCsyFromCode(csy->code());
    }
    if ( localName == sUNDEF) {
        return ERROR2(ERR_NO_INITIALIZED_2, "CoordinateSystem", coverage->name());
    }
    _odf->setKeyValue("BaseMap","CoordSystem", localName);
    Box2D<double> bounds = coverage->envelope();
    if(!bounds.isValid())
        return ERROR2(ERR_NO_INITIALIZED_2, "Bounds", coverage->name());

    _odf->setKeyValue("BaseMap","CoordBounds",QString("%1 %2 %3 %4").
                      arg(bounds.min_corner().x(),10,'f').
                      arg(bounds.min_corner().y(),10,'f').
                      arg(bounds.max_corner().x(),10,'f').
                      arg(bounds.max_corner().y(),10,'f'));

    const IDomain dom = datadef.domain();
    if (!dom.isValid())
        return ERROR2(ERR_NO_INITIALIZED_2, "Domain", coverage->name());

    calcStatics(obj,NumericStatistics::pBASIC);
    if ( dom->ilwisType() == itNUMERICDOMAIN) {

        quint16 digits = coverage->statistics().significantDigits();
        qint32 delta = coverage->statistics()[NumericStatistics::pDELTA];
        if ( delta >= 0 && delta < 256 && digits == 0){
            if ( delta >= 0 && delta < 256 && digits == 0){
                if ( datadef.domain()->code() == "boolean"){
                    QString domInfo = QString("bool.dom;Byte;bool;0;;");
                    _odf->setKeyValue("BaseMap","DomainInfo",domInfo);
                    _odf->setKeyValue("BaseMap","Range","0:1:offset=-1");
                    _odf->setKeyValue("BaseMap","Domain","bool.dom");
                }
                else{
                    QString domInfo = QString("Image.dom;Byte;image;0;;");
                    _odf->setKeyValue("BaseMap","DomainInfo",domInfo);
                    _odf->setKeyValue("BaseMap","Range","0:255:offset=0");
                    _odf->setKeyValue("BaseMap","MinMax","0:255");
                    _odf->setKeyValue("BaseMap","Domain","Image.dom");
                }
            }
        }
        else {
            const NumericStatistics& stats = coverage->statistics();
            int digits = stats.significantDigits();
            RawConverter conv(stats[NumericStatistics::pMIN], stats[NumericStatistics::pMAX],pow(10, - digits));
            QString rangeString = QString("%1:%2:%3:offset=%4").arg(stats[NumericStatistics::pMIN]).arg(stats[NumericStatistics::pMAX]).arg(conv.scale()).arg(conv.offset());
            _odf->setKeyValue("BaseMap","Range",rangeString);
            _odf->setKeyValue("BaseMap","Domain","value.dom");

            _odf->setKeyValue("BaseMap","MinMax",QString("%1:%2").arg(stats[NumericStatistics::pMIN]).arg(stats[NumericStatistics::pMAX]));
            QString domInfo = QString("value.dom;Long;value;0;-9999999.9:9999999.9:0.1:offset=0");
            _odf->setKeyValue("BaseMap","DomainInfo",domInfo);
        }
    } if ( dom->ilwisType() == itITEMDOMAIN) {
        QString source = Resource::toLocalFile(dom->source().url(), true);
        if ( dom->valueType() == itTHEMATICITEM && coverage->ilwisType() == itRASTER) {
            IThematicDomain themdom = dom.get<ThematicDomain>();
            if ( themdom.isValid()) {
                QString domInfo = QString("%1;Byte;class;%2;;").arg(source).arg(themdom->count());
                _odf->setKeyValue("BaseMap","DomainInfo",domInfo);
                _odf->setKeyValue("BaseMap","Domain",source);
            }
        } else if(dom->valueType() == itINDEXEDITEM) {
            QString domName = _odf->fileinfo().fileName();
            QString domInfo = QString("%1;Long;UniqueID;0;;").arg(domName);
            _odf->setKeyValue("BaseMap","DomainInfo",domInfo);
            _odf->setKeyValue("BaseMap","Domain",domName);
        } else if ( dom->valueType() == itNAMEDITEM) {
            INamedIdDomain iddom = dom.get<NamedIdDomain>();
            QString domName = _odf->fileinfo().fileName();
            int index;
            if ( (index=domName.lastIndexOf("."))!= -1)             {
                domName = domName.left(index);
            }
            QString domInfo = QString("%1;;Int;id;%2;;").arg(domName).arg(iddom->count());
            _odf->setKeyValue("BaseMap","DomainInfo",domInfo);
            _odf->setKeyValue("BaseMap","Domain",domName);
            iddom->connectTo(QUrl(),"domain","ilwis3", IlwisObject::cmOUTPUT);
            iddom->store(Ilwis::IlwisObject::smMETADATA | Ilwis::IlwisObject::smBINARYDATA);
        }
    }

    ITable attTable = coverage->attributeTable();
    if ( attTable.isValid()) {
        QScopedPointer<TableConnector> conn(createTableConnector(attTable, coverage, type));
        conn->storeMetaData(attTable.ptr());
    }
    return true;
}
コード例 #25
0
void MultiGridManagement2D::coarsen(plint fineLevel, Box2D coarseDomain){
    // The coarsest multi-block, at level 0, cannot be further coarsened.
    PLB_PRECONDITION( fineLevel>=1 && fineLevel<(plint)bulks.size() );
    plint coarseLevel = fineLevel-1;

    // First, trim the domain coarseDomain in case it exceeds the extent of the
    //   multi-block, and determine whether coarseDomain touches one of the boundaries
    //   of the multi-block. This information is needed, because the coarse domain
    //   fully replaces the fine domain on boundaries of the multi-block, and there
    //   is therefore no need to create a coarse-fine coupling.
    bool touchLeft=false, touchRight=false, touchBottom=false, touchTop=false;
    trimDomain(coarseLevel, coarseDomain, touchLeft, touchRight, touchBottom, touchTop);

    // Convert the coarse domain to fine units.
    Box2D fineDomain(coarseDomain.multiply(2));
    // The reduced fine domain is the one which is going to be excluded from
    //   the original fine lattice.
    Box2D intermediateFineDomain(fineDomain.enlarge(-1));
    // The extended coarse domain it the one which is going to be added
    //   to the original coarse lattice.
    Box2D extendedCoarseDomain(coarseDomain.enlarge(1));
    
    // If the domain in question touches a boundary of the multi-block,
    //   both the reduced fine domain and the extended coarse domain are
    //   identified with the boundary location.
    if (touchLeft) {
        intermediateFineDomain.x0 -= 1;
        extendedCoarseDomain.x0   += 1;
    }
    if (touchRight) {
        intermediateFineDomain.x1 += 1;
        extendedCoarseDomain.x1   -= 1;
    }
    if (touchBottom) {
        intermediateFineDomain.y0 -= 1;
        extendedCoarseDomain.y0   += 1;
    }
    if (touchTop) {
        intermediateFineDomain.y1 += 1;
        extendedCoarseDomain.y1   -= 1;
    }

    // Extract reduced fine domain from the original fine multi-block.
    std::vector<Box2D> exceptedBlocks;
    for (pluint iBlock=0; iBlock<bulks[fineLevel].size(); ++iBlock) {
        except(bulks[fineLevel][iBlock], intermediateFineDomain, exceptedBlocks);
    }
    exceptedBlocks.swap(bulks[fineLevel]);

    // Add extended coarse domain to the original coarse multi-block.
    bulks[coarseLevel].push_back(extendedCoarseDomain);
    
    // Define coupling interfaces for all four sides of the refined domain, unless they
    //   touch a boundary of the multi-block.
    if (!touchLeft) {
        coarseGridInterfaces[coarseLevel].push_back( Box2D( extendedCoarseDomain.x0, extendedCoarseDomain.x0,
                                                            extendedCoarseDomain.y0, extendedCoarseDomain.y1 ) );
        fineGridInterfaces[fineLevel].push_back( Box2D( coarseDomain.x0, coarseDomain.x0, 
                                                        coarseDomain.y0, coarseDomain.y1 ) );
                                                        
        // it is a left border in the coarse case
        coarseInterfaceOrientations[coarseLevel].push_back(Array<plint,2>(0,-1));
        // it is an right border in the fine case
        fineInterfaceOrientations[fineLevel].push_back(Array<plint,2>(0,1));
    }
    if (!touchRight) {
        coarseGridInterfaces[coarseLevel].push_back( Box2D( extendedCoarseDomain.x1, extendedCoarseDomain.x1,
                                                            extendedCoarseDomain.y0, extendedCoarseDomain.y1 ) );
        fineGridInterfaces[fineLevel].push_back( Box2D( coarseDomain.x1, coarseDomain.x1, 
                                                        coarseDomain.y0, coarseDomain.y1 ) );
                                                        
        // it is a right border in the coarse case
        coarseInterfaceOrientations[coarseLevel].push_back(Array<plint,2>(0,1));
        // it is a left border in the fine case
        fineInterfaceOrientations[fineLevel].push_back(Array<plint,2>(0,-1));
    }
    if (!touchBottom) {
        coarseGridInterfaces[coarseLevel].push_back( Box2D( extendedCoarseDomain.x0, extendedCoarseDomain.x1,
                                                            extendedCoarseDomain.y0, extendedCoarseDomain.y0 ) );
        fineGridInterfaces[fineLevel].push_back( Box2D( coarseDomain.x0, coarseDomain.x1, 
                                                        coarseDomain.y0, coarseDomain.y0 ) );
                                                        
        // it is a bottom border in the coarse case
        coarseInterfaceOrientations[coarseLevel].push_back(Array<plint,2>(1,-1)); //TODO check this!!!
        // it is a top border in the fine case
        fineInterfaceOrientations[fineLevel].push_back(Array<plint,2>(1,1));        
    }
    if (!touchTop) {
        coarseGridInterfaces[coarseLevel].push_back( Box2D( extendedCoarseDomain.x0, extendedCoarseDomain.x1,
                                                            extendedCoarseDomain.y1, extendedCoarseDomain.y1 ) );
        fineGridInterfaces[fineLevel].push_back( Box2D( coarseDomain.x0, coarseDomain.x1, 
                                                        coarseDomain.y1, coarseDomain.y1 ) );
                                                        
        // it is a top border in the coarse case
        coarseInterfaceOrientations[coarseLevel].push_back(Array<plint,2>(1,1));
        // it is an bottom border in the fine case
        fineInterfaceOrientations[fineLevel].push_back(Array<plint,2>(1,-1));
    }
}
コード例 #26
0
void writeXmlSpec( MultiBlock2D& multiBlock, FileName fName,
                   std::vector<plint> const& offset, bool dynamicContent )
{
    fName.defaultExt("plb");
    MultiBlockManagement2D const& management = multiBlock.getMultiBlockManagement();
    std::map<plint,Box2D> const& bulks = management.getSparseBlockStructure().getBulks();
    PLB_ASSERT( offset.empty() || bulks.size()==offset.size() );
    std::vector<std::string> typeInfo = multiBlock.getTypeInfo();
    std::string blockName = multiBlock.getBlockName();
    PLB_ASSERT( !typeInfo.empty() );

    XMLwriter xml;
    XMLwriter& xmlMultiBlock = xml["Block2D"];
    xmlMultiBlock["General"]["Family"].setString(blockName);
    xmlMultiBlock["General"]["Datatype"].setString(typeInfo[0]);
    if (typeInfo.size()>1) {
        xmlMultiBlock["General"]["Descriptor"].setString(typeInfo[1]);
    }
    xmlMultiBlock["General"]["cellDim"].set(multiBlock.getCellDim());
    xmlMultiBlock["General"]["dynamicContent"].set(dynamicContent);
    xmlMultiBlock["General"]["globalId"].set(multiBlock.getId());

    Array<plint,4> boundingBox = multiBlock.getBoundingBox().to_plbArray();
    xmlMultiBlock["Structure"]["BoundingBox"].set<plint,4>(boundingBox);
    xmlMultiBlock["Structure"]["EnvelopeWidth"].set(management.getEnvelopeWidth());
    xmlMultiBlock["Structure"]["GridLevel"].set(management.getRefinementLevel());
    xmlMultiBlock["Structure"]["NumComponents"].set(bulks.size());

    xmlMultiBlock["Data"]["File"].setString(FileName(fName).setExt("dat"));

    XMLwriter& xmlBulks = xmlMultiBlock["Data"]["Component"];
    std::map<plint,Box2D>::const_iterator it = bulks.begin();
    plint iComp=0;
    for(; it != bulks.end(); ++it) {
        Box2D bulk = it->second;
        xmlBulks[iComp].set<plint,4>(bulk.to_plbArray());
        ++iComp;
    }
    if (!offset.empty()) {
        xmlMultiBlock["Data"]["Offsets"].set(offset);
    }

    // The following prints a unique list of dynamics-id pairs for all dynamics
    //   classes used in the multi-block. This is necessary, because dynamics
    //   classes may be ordered differently from one compilation to the other,
    //   or from one compiler to the other.
    //
    // Given that the dynamics classes are unique, they can be indexed by their
    //   name (which is not the case of the data processors below).
    std::map<std::string,int> dynamicsDict;
    multiBlock.getDynamicsDict(multiBlock.getBoundingBox(), dynamicsDict);
    if (!dynamicsDict.empty()) {
        XMLwriter& xmlDynamicsDict = xmlMultiBlock["Data"]["DynamicsDict"];
        for( std::map<std::string,int>::const_iterator it = dynamicsDict.begin();
             it != dynamicsDict.end(); ++it )
        {
            xmlDynamicsDict[it->first].set(it->second);
        }
    }

    // This is the only section in which actual content is stored outside the
    //   binary blob: the serialization of the data processors. This
    //   serialization was chosen to be in ASCII, because it takes little space
    //   and can be somewhat complicated.
    //
    // It is important that the processors are indexed by a continuous index
    //   "iProcessor". They cannot be indexed by the class name ("Name") or static
    //   id ("id") because several instances of the same class may occur.
    XMLwriter& xmlProcessors = xmlMultiBlock["Data"]["Processor"];
    std::vector<MultiBlock2D::ProcessorStorage2D> const& processors = multiBlock.getStoredProcessors();
    for (plint iProcessor=0; iProcessor<(plint)processors.size(); ++iProcessor) {
        int id = processors[iProcessor].getGenerator().getStaticId();
        if (id>=0) {
            Box2D domain;
            std::string data;
            processors[iProcessor].getGenerator().serialize(domain, data);
            xmlProcessors[iProcessor]["Name"].set(meta::processorRegistration2D().getName(id));
            xmlProcessors[iProcessor]["Domain"].set<plint,4>(domain.to_plbArray());
            xmlProcessors[iProcessor]["Data"].setString(data);
            xmlProcessors[iProcessor]["Level"].set(processors[iProcessor].getLevel());
            xmlProcessors[iProcessor]["Blocks"].set(processors[iProcessor].getMultiBlockIds());
        }
    }
    xml.print(FileName(fName).defaultPath(global::directories().getOutputDir()));
}
コード例 #27
0
void MultiGridManagement2D::refineMultiGrid(plint coarseLevel, Box2D coarseDomain){
        
    // The finest multi-block, at level bulks.size()-1, cannot be further refined.
    PLB_PRECONDITION( coarseLevel>=0 && coarseLevel< (plint)bulks.size()-1 );
    plint fineLevel = coarseLevel+1;
    
    // First, trim the domain coarseDomain in case it exceeds the extent of the
    //   multi-block, and determine whether coarseDomain touches one of the boundaries
    //   of the multi-block. This information is needed, because the coarse domain
    //   fully replaces the fine domain on boundaries of the multi-block, and there
    //   is therefore no need to create a coarse-fine coupling.
    bool touchLeft=false, touchRight=false, touchBottom=false, touchTop=false;
    trimDomain(coarseLevel, coarseDomain, touchLeft, touchRight, touchBottom, touchTop);

    // The reduced coarse domain is the one which is going to be excluded from
    //   the original coarse lattice.
    Box2D reducedCoarseDomain(coarseDomain.enlarge(-1));
    // The extended coarse domain it the one which is going to be added
    //   to the original fine lattice.
    Box2D extendedCoarseDomain(coarseDomain.enlarge(overlapWidth));
    
    // If the domain in question touches a boundary of the multi-block,
    //   both the reduced and the extended coarse domain are
    //   identified with the boundary location.
    if (touchLeft) {
        reducedCoarseDomain.x0    -= 1;
        extendedCoarseDomain.x0   += overlapWidth;
    }
    if (touchRight) {
        reducedCoarseDomain.x1    += 1;
        extendedCoarseDomain.x1   -= overlapWidth;
    }
    if (touchBottom) {
        reducedCoarseDomain.y0    -= 1;
        extendedCoarseDomain.y0   += overlapWidth;
    }
    if (touchTop) {
        reducedCoarseDomain.y1    += 1;
        extendedCoarseDomain.y1   -= overlapWidth;
    }

    
    // Do not do anything to the coarse domain
    
    
    // Convert the extended coarse domain to fine units,
    //   and add to the original fine multi-block.
    Box2D extendedFineDomain(extendedCoarseDomain.multiply(2));
    bulks[fineLevel].push_back(extendedFineDomain);

    // Define coupling interfaces for all four sides of the coarsened domain, unless they
    //   touch a boundary of the multi-block.
    if (!touchLeft) {

        // it is a right border in the coarse case
        coarseInterfaceOrientations[coarseLevel].push_back(Array<plint,2>(0,1));
        fineGridInterfaces[fineLevel].push_back( Box2D( extendedCoarseDomain.x0, extendedCoarseDomain.x0, 
                                                        extendedCoarseDomain.y0, extendedCoarseDomain.y1 ) );
        // it is a left border in the fine case
        fineInterfaceOrientations[fineLevel].push_back(Array<plint,2>(0,-1));
    }
    if (!touchRight) {

        // it is a left border in the coarse case
        coarseInterfaceOrientations[coarseLevel].push_back(Array<plint,2>(0,-1));
        fineGridInterfaces[fineLevel].push_back( Box2D( extendedCoarseDomain.x1, extendedCoarseDomain.x1, 
                                                        extendedCoarseDomain.y0, extendedCoarseDomain.y1 ) );
        // it is a right border in the fine case
        fineInterfaceOrientations[fineLevel].push_back(Array<plint,2>(0,1));
    }
    if (!touchBottom) {
        
        fineGridInterfaces[fineLevel].push_back( Box2D( extendedCoarseDomain.x0, extendedCoarseDomain.x1, 
                                                        extendedCoarseDomain.y0, extendedCoarseDomain.y0 ) );
        // it is an upper border in the coarse case
        coarseInterfaceOrientations[coarseLevel].push_back(Array<plint,2>(1,1));
        // it is a lower border in the fine case
        fineInterfaceOrientations[fineLevel].push_back(Array<plint,2>(1,-1));
    }
    if (!touchTop) {
        
        // it is a lower border in the coarse case
        coarseInterfaceOrientations[coarseLevel].push_back(Array<plint,2>(1,-1));
        fineGridInterfaces[fineLevel].push_back( Box2D( extendedCoarseDomain.x0, extendedCoarseDomain.x1, 
                                                        extendedCoarseDomain.y1, extendedCoarseDomain.y1 ) );
        // it is an upper border in the fine case
        fineInterfaceOrientations[fineLevel].push_back(Array<plint,2>(1,1));
    }
    
    coarseGridInterfaces[coarseLevel].push_back(coarseDomain);
}
コード例 #28
0
ファイル: segment2d.cpp プロジェクト: MinorKeyGames/Eldritch
bool Segment2D::Intersects( const Box2D& Box, CollisionInfo2D* const pInfo /*= NULL*/ ) const
{
	if( Box.Contains( m_Start ) )
	{
		if( pInfo )
		{
			pInfo->m_Collision = true;
			pInfo->m_EHitNormal = CollisionInfo2D::EHN_None;
			pInfo->m_HitNormal = Vector2();
			pInfo->m_HitT = 0.0f;
			pInfo->m_Intersection = m_Start;
		}

		return true;
	}

	float MinT = 0.0f;
	float MaxT = FLT_MAX;
	CollisionInfo2D::EHitNormal EnumHitNormal = CollisionInfo2D::EHN_None;
	Vector2 HitNormal;
	Vector2 Offset = m_End - m_Start;

	if( Abs( Offset.x ) < SMALLER_EPSILON )
	{
		if( m_Start.x < Box.m_Min.x || m_Start.x > Box.m_Max.x )
		{
			return false;
		}
	}
	else
	{
		float InvOffsetX = 1.0f / Offset.x;
		float T1 = ( Box.m_Min.x - m_Start.x ) * InvOffsetX;
		float T2 = ( Box.m_Max.x - m_Start.x ) * InvOffsetX;
		if( T1 > T2 )
		{
			Swap( T1, T2 );
		}
		MinT = Max( MinT, T1 );
		MaxT = Min( MaxT, T2 );
		if( MinT > MaxT )
		{
			return false;
		}

		if( MinT == T1 )
		{
			EnumHitNormal = ( Offset.x > 0.0f ) ? CollisionInfo2D::EHN_Left : CollisionInfo2D::EHN_Right;
			HitNormal.x = Sign( Offset.x );
		}
	}

	if( Abs( Offset.y ) < SMALLER_EPSILON )
	{
		if( m_Start.y < Box.m_Min.y || m_Start.y > Box.m_Max.y )
		{
			return false;
		}
	}
	else
	{
		float InvOffsetY = 1.0f / Offset.y;
		float T1 = ( Box.m_Min.y - m_Start.y ) * InvOffsetY;
		float T2 = ( Box.m_Max.y - m_Start.y ) * InvOffsetY;
		if( T1 > T2 )
		{
			Swap( T1, T2 );
		}
		MinT = Max( MinT, T1 );
		MaxT = Min( MaxT, T2 );
		if( MinT > MaxT )
		{
			return false;
		}

		if( MinT == T1 )
		{
			EnumHitNormal = ( Offset.y > 0.0f ) ? CollisionInfo2D::EHN_Up : CollisionInfo2D::EHN_Down;
			HitNormal.y = Sign( Offset.y );
		}
	}

	if( MinT > 1.0f )
	{
		return false;
	}

	ASSERT( EnumHitNormal != CollisionInfo2D::EHN_None );

	if( pInfo )
	{
		pInfo->m_Collision = true;
		pInfo->m_EHitNormal = EnumHitNormal;
		pInfo->m_HitNormal = HitNormal;
		pInfo->m_HitT = MinT;
		pInfo->m_Intersection = m_Start + Offset * MinT;
	}

	return true;
}
コード例 #29
0
ファイル: Box2D.cpp プロジェクト: Cryptoh/server
Box2D::Box2D(const CFrame& frame, Box2D& b) {
    for (int i = 0; i < 4; ++i) {
        m_corner[i] = frame.pointToWorldSpace(Vector3(b.corner(i), 0)).xy();
    }
    computeAxes();
}
コード例 #30
0
ファイル: MCnucl.cpp プロジェクト: chunshen1987/superMC
// --- find participants from proj/target and the number of binary coll. ---
int MCnucl::getBinaryCollision()
{
  bool missingNucleus = false;
  
  // Handling for the intrinsic nucleus case
  if(proj->getAtomic() == 0)
  {
      vector<Particle*> nucl2 = targ->getNucleons();
      missingNucleus = true;
      for(int i = 0; i < (int)nucl2.size(); i++){
          selectFluctFactors(nucl2[i]);
          nucl2[i]->addCollidingParticle(nucl2[i]);
          targ->markWounded(nucl2[i]);
      }
  }
  else if(targ->getAtomic() == 0)
  {
      vector<Particle*> nucl1 = proj->getNucleons();
      missingNucleus = true;
      for(int i = 0; i < (int)nucl1.size(); i++){
          selectFluctFactors(nucl1[i]);
          nucl1[i]->addCollidingParticle(nucl1[i]);
          proj->markWounded(nucl1[i]);
      }
  }
  else
  {
      vector<Particle*> projNucleons = proj->getNucleons();
      vector<Particle*> targNucleons = targ->getNucleons();
      
      int startingIndex = 0;
      for(int iproj = 0; iproj < projNucleons.size(); iproj++)
      {
          Particle* projPart = projNucleons[iproj];
          Box2D projBox = projPart->getBoundingBox();
          Box2D targBox;
          
          // Skip the left most nucleons for each proj nucleon.
          while(startingIndex < targNucleons.size())
          {
              targBox = targNucleons[startingIndex]->getBoundingBox();
              if(targBox.getXR() >= projBox.getXL())
                  break;
              startingIndex++;
          }
          
          // Actually test a collision for the next ones,
          // until they get too far away.
          int i = startingIndex;
          while(i < targNucleons.size()
                && projBox.getXR() >= targBox.getXL() )
          {
              Particle* targPart = targNucleons[i];
              targBox = targPart->getBoundingBox();
              
              if(projBox.getYL() <= targBox.getYR())
              {
                  if(projBox.getYR() >= targBox.getYL())
                  {
                      // Now we know the boxes do overlap in x and y.
                      if(hit(projPart,targPart))
                      {
                          selectFluctFactors(projPart);
                          selectFluctFactors(targPart);
                          projPart->addCollidingParticle(targPart);
                          targPart->addCollidingParticle(projPart);
                          proj->markWounded(projPart);
                          targ->markWounded(targPart);
                      }
                  }
              }
              i++;
          }
          
          // Continue loop over projBoxes
      }
      
      // Exit hit detection
  }

  createBinaryCollisions();
  Npart1=proj->getNpart();
  Npart2=targ->getNpart();
  
  Npart1 /= overSample;
  Npart2 /= overSample;
  
  if(missingNucleus)
    return 1;
  else
    return binaryCollision.size();
}