Exemple #1
0
bool Region::validate(const Region& reg, const char* name)
{
    bool result = true;
    const_iterator cur = reg.begin();
    const_iterator const tail = reg.end();
    const_iterator prev = cur++;
    Rect b(*prev);
    while (cur != tail) {
        b.left   = b.left   < cur->left   ? b.left   : cur->left;
        b.top    = b.top    < cur->top    ? b.top    : cur->top;
        b.right  = b.right  > cur->right  ? b.right  : cur->right;
        b.bottom = b.bottom > cur->bottom ? b.bottom : cur->bottom;
        if (cur->top == prev->top) {
            if (cur->bottom != prev->bottom) {
                LOGE("%s: invalid span %p", name, cur);
                result = false;
            } else if (cur->left < prev->right) {
                LOGE("%s: spans overlap horizontally prev=%p, cur=%p",
                        name, prev, cur);
                result = false;
            }
        } else if (cur->top < prev->bottom) {
            LOGE("%s: spans overlap vertically prev=%p, cur=%p",
                    name, prev, cur);
            result = false;
        }
        prev = cur;
        cur++;
    }
    if (b != reg.getBounds()) {
        result = false;
        LOGE("%s: invalid bounds [%d,%d,%d,%d] vs. [%d,%d,%d,%d]", name,
                b.left, b.top, b.right, b.bottom,
                reg.getBounds().left, reg.getBounds().top, 
                reg.getBounds().right, reg.getBounds().bottom);
    }
    if (result == false) {
        reg.dump(name);
    }
    return result;
}
Exemple #2
0
TEST(Region, Iterators)
{
  Region a;
  a.createUnion(a, Region(Rect(0, 0, 32, 64)));
  a.createUnion(a, Region(Rect(0, 0, 64, 32)));
  int c = 0;
  for (Region::iterator it=a.begin(), end=a.end(); it!=end; ++it) {
    ++c;
  }
  EXPECT_EQ(2, c);

  c = 0;
  for (Region::const_iterator it=a.begin(), end=a.end(); it!=end; ++it) {
    ++c;
  }
  EXPECT_EQ(2, c);
}
void
Palette::processCursor(SpaceCursor* c, int downdragup) {
	Region* r = RegionForSid(c->sid);
	c->region = r;
	if ( r ) {
		if ( r->isButton() ) {
			switch (downdragup) {
			case CURSOR_DOWN: r->buttonDown(); break;
			case CURSOR_UP: r->buttonUp(); break;
			}
		} else {
			switch (downdragup) {
			case CURSOR_DOWN: r->cursorDown(c); break;
			case CURSOR_DRAG: r->cursorDrag(c); break;
			case CURSOR_UP: r->cursorUp(c); break;
			}
		}
	} else {
		NosuchErrorOutput("Palette::processCursor Unable to find region (A) for sid=%d/%s",c->sid,c->source.c_str());
	}
}
void DrawingAreaProxyImpl::paint(BackingStore::PlatformGraphicsContext context, const IntRect& rect, Region& unpaintedRegion)
{
    unpaintedRegion = rect;

    if (isInAcceleratedCompositingMode())
        return;

    ASSERT(m_currentBackingStoreStateID <= m_nextBackingStoreStateID);
    if (m_currentBackingStoreStateID < m_nextBackingStoreStateID) {
        // Tell the web process to do a full backing store update now, in case we previously told
        // it about our next state but didn't request an immediate update.
        sendUpdateBackingStoreState(RespondImmediately);

        if (m_isWaitingForDidUpdateBackingStoreState) {
            // Wait for a DidUpdateBackingStoreState message that contains the new bits before we paint
            // what's currently in the backing store.
            waitForAndDispatchDidUpdateBackingStoreState();
        }

        // Dispatching DidUpdateBackingStoreState (either beneath sendUpdateBackingStoreState or
        // beneath waitForAndDispatchDidUpdateBackingStoreState) could destroy our backing store or
        // change the compositing mode.
        if (!m_backingStore || isInAcceleratedCompositingMode())
            return;
    } else {
        ASSERT(!m_isWaitingForDidUpdateBackingStoreState);
        if (!m_backingStore) {
            // The view has asked us to paint before the web process has painted anything. There's
            // nothing we can do.
            return;
        }
    }

    m_backingStore->paint(context, rect);
    unpaintedRegion.subtract(IntRect(IntPoint(), m_backingStore->size()));

    discardBackingStoreSoon();
}
Exemple #5
0
//recursively identify a contiguous region of the same color, or any color
//contiguous here means all blocks are connected by an edge
void Region::identifyRegion(Region& region, Coord orig, unsigned char color)
{
    if (orig.x >= nextris::options::get_options().game.width || orig.y >= nextris::options::get_options().game.height ||
            orig.x < 0 || orig.y < 0) //edge!
        return;
    if (region.grid[orig.x][orig.y] == NULL) //no block
        return;
    if (region.grid[orig.x][orig.y]->getColor() != color && color != 255) //wrong color
        return;

    cdebug << "Entering Region::identifyRegion()\n";

    //prevent duplicate adds
    for (unsigned int i = 0; i < region.blocks.size(); ++i)
        if (region.blocks[i]->isAt(orig) )
            return;
        else if (region.blocks[i] == region.grid[orig.x][orig.y])
            return;

    //add this block
    cdebug << "Adding " << orig.x << "," << orig.y << "\n";
    if (region.grid[orig.x][orig.y] == NULL)
        cdebug << "BUT IT'S NULL!!1????\n";
    region.addBlock(region.grid[orig.x][orig.y]);

    //recurse for neighbors
    Coord c1 = {orig.x, orig.y + 1},
          c2 = {orig.x, orig.y - 1},
          c3 = {orig.x - 1, orig.y},
          c4 = {orig.x + 1, orig.y};

    identifyRegion(region, c1, color);
    identifyRegion(region, c2, color);
    identifyRegion(region, c3, color);
    identifyRegion(region, c4, color);

    cdebug << "Exiting Region::identifyRegion()\n";
}
Exemple #6
0
void RenderEngine::fillRegionWithColor(const Region& region, uint32_t height,
                                       float red, float green, float blue, float alpha) {
    size_t c;
    Rect const* r = region.getArray(&c);
    Mesh mesh(Mesh::TRIANGLES, c*6, 2);
    Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
    for (size_t i=0 ; i<c ; i++, r++) {
        position[i*6 + 0].x = r->left;
        position[i*6 + 0].y = height - r->top;
        position[i*6 + 1].x = r->left;
        position[i*6 + 1].y = height - r->bottom;
        position[i*6 + 2].x = r->right;
        position[i*6 + 2].y = height - r->bottom;
        position[i*6 + 3].x = r->left;
        position[i*6 + 3].y = height - r->top;
        position[i*6 + 4].x = r->right;
        position[i*6 + 4].y = height - r->bottom;
        position[i*6 + 5].x = r->right;
        position[i*6 + 5].y = height - r->top;
    }
    setupFillWithColor(red, green, blue, alpha);
    drawMesh(mesh);
}
Exemple #7
0
void
Network::link(const std::string& srcRegionName, const std::string& destRegionName, 
              const std::string& linkType, const std::string& linkParams, 
              const std::string& srcOutputName, const std::string& destInputName)
{
  
  // Find the regions
  if (! regions_.contains(srcRegionName))
    NTA_THROW << "Network::link -- source region '" << srcRegionName << "' does not exist";
  Region* srcRegion = regions_.getByName(srcRegionName);
  
  if (! regions_.contains(destRegionName))
    NTA_THROW << "Network::link -- dest region '" << destRegionName << "' does not exist";
  Region* destRegion = regions_.getByName(destRegionName);

  // Find the inputs/outputs
  const Spec* srcSpec = srcRegion->getSpec();
  std::string outputName = srcOutputName;
  if (outputName == "")
    outputName = srcSpec->getDefaultOutputName();
  
  Output* srcOutput = srcRegion->getOutput(outputName);
  if (srcOutput == NULL)
    NTA_THROW << "Network::link -- output " << outputName 
              << " does not exist on region " << srcRegionName;


  const Spec *destSpec = destRegion->getSpec();
  std::string inputName;
  if (destInputName == "")
    inputName = destSpec->getDefaultInputName();
  else
    inputName = destInputName;

  Input* destInput = destRegion->getInput(inputName);
  if (destInput == NULL)
  {
    NTA_THROW << "Network::link -- input '" << inputName 
              << " does not exist on region " << destRegionName;
  }

  // Create the link itself
  destInput->addLink(linkType, linkParams, srcOutput);

}
void createRegions(struct rt_wdb* wdbp)
{
    struct wmember tophead;
    BU_LIST_INIT(&tophead.l);

    for (std::map<std::string, Region*>::iterator it = regionTable.begin();
	it != regionTable.end();
	++it) {
	Region* regionp = it->second;

	std::cout << regionp->getDescription() << std::endl;

	if ((regionp->getMaterial() != 0) && (regionp->nonEmpty()))
	    regionp->push(wdbp, &tophead);
	else
	    std::cout << "Empty region: " << regionp->getCompNr() << (regionp->referred() ? " (referred)" : " (unreferred)") << std::endl;
    }

    mk_lfcomb(wdbp, "g_all", &tophead, 0);

    mk_freemembers(&tophead.l);
}
Exemple #9
0
void Layer::unlockPageFlip(
        const Transform& planeTransform, Region& outDirtyRegion)
{
    ATRACE_CALL();

    Region postedRegion(mPostedDirtyRegion);
    if (!postedRegion.isEmpty()) {
        mPostedDirtyRegion.clear();
        if (!visibleRegionScreen.isEmpty()) {
            // The dirty region is given in the layer's coordinate space
            // transform the dirty region by the surface's transformation
            // and the global transformation.
            const Layer::State& s(drawingState());
            const Transform tr(planeTransform * s.transform);
            postedRegion = tr.transform(postedRegion);

            // At this point, the dirty region is in screen space.
            // Make sure it's constrained by the visible region (which
            // is in screen space as well).
            postedRegion.andSelf(visibleRegionScreen);
            outDirtyRegion.orSelf(postedRegion);
        }
    }
}
Exemple #10
0
Node::PtrList RegionsBuilder::MakeSelectedRegionsByCountry(Region const & country,
                                                           Regions const & allRegions)
{
  std::vector<LevelRegion> regionsInCountry{{PlaceLevel::Country, country}};
  for (auto const & region : allRegions)
  {
    if (country.ContainsRect(region))
      regionsInCountry.emplace_back(GetLevel(region), region);
  }

  auto const comp = [](LevelRegion const & l, LevelRegion const & r) {
    auto const lArea = l.GetArea();
    auto const rArea = r.GetArea();
    return lArea != rArea ? lArea > rArea : l.GetRank() < r.GetRank();
  };
  std::sort(std::begin(regionsInCountry), std::end(regionsInCountry), comp);

  Node::PtrList nodes;
  nodes.reserve(regionsInCountry.size());
  for (auto && region : regionsInCountry)
    nodes.emplace_back(std::make_shared<Node>(std::move(region)));

  return nodes;
}
Exemple #11
0
TEST(Region, Equal)
{
  Region a;
  a = Rect(2, 3, 4, 5);
  EXPECT_EQ(Rect(2, 3, 4, 5), a.bounds());
  EXPECT_EQ(Rect(2, 3, 4, 5), a[0]);
  EXPECT_FALSE(a.isEmpty());

  a = Rect(6, 7, 8, 9);
  EXPECT_EQ(Rect(6, 7, 8, 9), a.bounds());
  EXPECT_EQ(Rect(6, 7, 8, 9), a[0]);

  Region b;
  b = a;
  EXPECT_EQ(Rect(6, 7, 8, 9), b[0]);

  b = Rect(0, 0, 0, 0);
  EXPECT_TRUE(b.isEmpty());
}
void Image::remove(Region& reg)
{
	int minX, minY, maxX, maxY;

	minX = reg.OffsetX();
	minY = reg.OffsetY();

	maxX = width < minX + reg.Width() ? width : minX + reg.Width();
	maxY = height < minY + reg.Height() ? height : minY + reg.Height();

	int i, j;

	for (j = minY; j < maxY; j++)
	{
		for (i = minX; i < maxX; i++)
		{
			if (reg(i - minX, j - minY) == 255)
			{
				this->operator ()(i, j) = 0;
			}
		}
	}

}
Exemple #13
0
void FixEfield::post_force(int vflag)
{
  double **f = atom->f;
  double *q = atom->q;
  int *mask = atom->mask;
  imageint *image = atom->image;
  int nlocal = atom->nlocal;

  // reallocate efield array if necessary

  if (varflag == ATOM && nlocal > maxatom) {
    maxatom = atom->nmax;
    memory->destroy(efield);
    memory->create(efield,maxatom,4,"efield:efield");
  }

  // update region if necessary

  Region *region = NULL;
  if (iregion >= 0) {
    region = domain->regions[iregion];
    region->prematch();
  }

  // fsum[0] = "potential energy" for added force
  // fsum[123] = extra force added to atoms

  fsum[0] = fsum[1] = fsum[2] = fsum[3] = 0.0;
  force_flag = 0;

  double **x = atom->x;
  double fx,fy,fz;

  // constant efield

  if (varflag == CONSTANT) {
    double unwrap[3];

    // charge interactions
    // force = qE, potential energy = F dot x in unwrapped coords

    if (qflag) {
      for (int i = 0; i < nlocal; i++)
        if (mask[i] & groupbit) {
          if (region && !region->match(x[i][0],x[i][1],x[i][2])) continue;
          fx = q[i]*ex;
          fy = q[i]*ey;
          fz = q[i]*ez;
          f[i][0] += fx;
          f[i][1] += fy;
          f[i][2] += fz;

          domain->unmap(x[i],image[i],unwrap);
          fsum[0] -= fx*unwrap[0]+fy*unwrap[1]+fz*unwrap[2];
          fsum[1] += fx;
          fsum[2] += fy;
          fsum[3] += fz;
        }
    }

    // dipole interactions
    // no force, torque = mu cross E, potential energy = -mu dot E

    if (muflag) {
      double **mu = atom->mu;
      double **t = atom->torque;
      double tx,ty,tz;
      for (int i = 0; i < nlocal; i++)
        if (mask[i] & groupbit) {
          if (region && !region->match(x[i][0],x[i][1],x[i][2])) continue;
          tx = ez*mu[i][1] - ey*mu[i][2];
          ty = ex*mu[i][2] - ez*mu[i][0];
          tz = ey*mu[i][0] - ex*mu[i][1];
          t[i][0] += tx;
          t[i][1] += ty;
          t[i][2] += tz;
          fsum[0] -= mu[i][0]*ex + mu[i][1]*ey + mu[i][2]*ez;
        }
    }

  // variable efield, wrap with clear/add
  // potential energy = evar if defined, else 0.0

  } else {

    modify->clearstep_compute();

    if (xstyle == EQUAL) ex = qe2f * input->variable->compute_equal(xvar);
    else if (xstyle == ATOM)
      input->variable->compute_atom(xvar,igroup,&efield[0][0],4,0);
    if (ystyle == EQUAL) ey = qe2f * input->variable->compute_equal(yvar);
    else if (ystyle == ATOM)
      input->variable->compute_atom(yvar,igroup,&efield[0][1],4,0);
    if (zstyle == EQUAL) ez = qe2f * input->variable->compute_equal(zvar);
    else if (zstyle == ATOM)
      input->variable->compute_atom(zvar,igroup,&efield[0][2],4,0);
    if (estyle == ATOM)
      input->variable->compute_atom(evar,igroup,&efield[0][3],4,0);

    modify->addstep_compute(update->ntimestep + 1);

    // charge interactions
    // force = qE

    if (qflag) {
      for (int i = 0; i < nlocal; i++)
        if (mask[i] & groupbit) {
          if (region && !region->match(x[i][0],x[i][1],x[i][2])) continue;
          if (xstyle == ATOM) fx = qe2f * q[i]*efield[i][0];
          else fx = q[i]*ex;
          f[i][0] += fx;
          fsum[1] += fx;
          if (ystyle == ATOM) fy = qe2f * q[i]*efield[i][1];
          else fy = q[i]*ey;
          f[i][1] += fy;
          fsum[2] += fy;
          if (zstyle == ATOM) fz = qe2f * q[i]*efield[i][2];
          else fz = q[i]*ez;
          f[i][2] += fz;
          fsum[3] += fz;
          if (estyle == ATOM) fsum[0] += efield[0][3];
        }
    }

    // dipole interactions
    // no force, torque = mu cross E

    if (muflag) {
      double **mu = atom->mu;
      double **t = atom->torque;
      double tx,ty,tz;
      for (int i = 0; i < nlocal; i++)
        if (mask[i] & groupbit) {
          if (region && !region->match(x[i][0],x[i][1],x[i][2])) continue;
          tx = ez*mu[i][1] - ey*mu[i][2];
          ty = ex*mu[i][2] - ez*mu[i][0];
          tz = ey*mu[i][0] - ex*mu[i][1];
          t[i][0] += tx;
          t[i][1] += ty;
          t[i][2] += tz;
        }
    }
  }
}
Exemple #14
0
void StepRegion(Region &Reg, double TimeStp, double &MinTimeStp, double &PresDeriv) {
    Reg.StepRegion(TimeStp, MinTimeStp, PresDeriv);
};
Exemple #15
0
void PreClc(Region &Reg) {
    Reg.ClcMass();
};
Exemple #16
0
void main(int argc, char *argv[]) {
    argc--;
    cout << " uil_my - version\n";
    cout << " Coreleft " << Coreleft() << "\n";
    //   char tmp[50];
    if((argc < 2) || (GetCmd("/h", argc, argv) != NULL)) {
        cout
            << "usage:\n"
            << argv[0] << "  in_lmethod  output_file\n"
            << "      /h - display help\n"
            << "      /dN - set dimension N\n"
            << "      /s - Skip vacuum for better show\n"
            << "      /oT - output in T times more frequently when something happens on the bound\n"
            << "      /eN - Skip calculation of sound N times ( 10 by default )\n"
            <<
#ifndef InternalPointsUrs
            "  current version - no internal points \n";
#else
            "  current version - with internal points \n";
#endif
        exit(1);
    }

    my_file = new fstream(argv[2], ios::out);


    int FstIter = 0;
    double TimeStp, EndTime, CurTime = 0, TimeWrite, PresDerivCoef;
    Region *Reg = GetRegion(
        argv[1], *my_file, FstIter, CurTime, TimeStp, TimeWrite, PresDerivCoef, EndTime);
    //	my_file->close();};/*

    double CoefUp = 1, NumSkipS = 10;
    char *tmp;
    if((tmp = GetCmd("/e", argc, argv)) != NULL)
        NumSkipS = atoi(tmp);
    if((tmp = GetCmd("/o", argc, argv)) != NULL)
        CoefUp = min(atof(tmp), 1);
    if((tmp = GetCmd("/s", argc, argv)) != NULL)
        Reg->RegionShow = 1;
    int d = 1;
    if((tmp = GetCmd("/d", argc, argv)) != NULL)
        d = atoi(tmp);
    //cout<<d<<"\n";

    Reg->SetBodySkipS(NumSkipS);

    Reg->SetWorkDim(d);
    Reg->ClcMass();
    int x = 1;

    double CurStp, OldTimeWrite, NewTimeWrite, PresDeriv = 1, OldStp = 1e5;
    int BreakSignal = 0;
    Time_struct Time;
    double CurStpSum = 0;
    int CurStpNum = 1;
    cout << " Before clc Coreleft " << Coreleft() << "\n";
    while((!(CurTime >= EndTime)) && (!BreakSignal)) {
        OldTimeWrite = CurTime;
        NewTimeWrite =
            min(OldTimeWrite + TimeWrite / (1 + PresDeriv * PresDerivCoef), EndTime);
        //cout<<" Before While NewTime "<<NewTimeWrite<<"\n";
        while((!(CurTime >= NewTimeWrite)) && (!BreakSignal)) {
            NewTimeWrite =
                min(OldTimeWrite + TimeWrite / (1 + PresDeriv * PresDerivCoef), EndTime);
            if(x < 100) {
                x++;
                CurStp = 0.5 * log10(x) * TimeStp;
            } else
                CurStp = TimeStp;
            if(CurStp + CurTime > NewTimeWrite)
                CurStp = NewTimeWrite - CurTime;
            if(CurStp < MathZer)
                break;
            if(CurStp > OldStp)
                CurStp = OldStp * (CoefUp * log(CurStp / OldStp) + 1);
            OldStp = CurStp;
            CurStpSum += CurStp;
            CurStpNum++;

            CurTime += CurStp;
            StepRegion(*Reg, CurStp, TimeStp, PresDeriv);
        }
        OutHead(*my_file, *Reg, CurTime, TimeStp, TimeWrite, PresDerivCoef, EndTime);
        cout << " Write !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1\n";
        cout << " CurStp " << CurStpSum / CurStpNum << " CurTime " << CurTime << "\n";
        CurStpNum = 1;
        CurStpSum = 0;
#ifdef WCPP
        if(_kbhit()) {
            BreakSignal = _getch();
            if(BreakSignal == ESC)
                break;
        }
#else
        while((BreakSignal = bioskey(1)) != 0)
            if(BreakSignal == ESC)
                break;
            else {
                cout << " " << BreakSignal;
                bioskey(0);
            }
#endif
    }
    cout << Time << "\n"
         << " Coreleft " << Coreleft() << "\n";
    Reg->DeleteRegion();
    my_file->close();
    cout << " Coreleft " << Coreleft() << "\n";
};
void LayerBase::drawTopAndBottom(const Region& clip ,uint32_t fbHeight ,uint8_t eType ) const
{
				struct TexCoords {
							GLfloat u;
							GLfloat v;
							};			 
				TexCoords texCoords[4];
				GLfloat mVerticesCopy1[4][2];
				GLfloat mVerticesCopy[4][2]; 
				mVerticesCopy1[0][0] = mVertices[0][0]; 
				mVerticesCopy1[0][1] = mVertices[0][1]; 
				mVerticesCopy1[1][0] = mVertices[1][0]; 
				mVerticesCopy1[1][1] = mVertices[1][1]; 
				mVerticesCopy1[2][0] = mVertices[2][0]; 
				mVerticesCopy1[2][1] = mVertices[2][1]; 
				mVerticesCopy1[3][0] = mVertices[3][0]; 
				mVerticesCopy1[3][1] = mVertices[3][1]; 	
				for (size_t i=0 ; i<4 ; i++){
					mVerticesCopy1[i][1] /= 2;						
				}
				mVerticesCopy[0][0] = mVerticesCopy1[0][0] ; 
				mVerticesCopy[0][1] = mVerticesCopy1[0][1]+(fbHeight/2); 
				mVerticesCopy[1][0] = mVerticesCopy1[1][0] ; 
				mVerticesCopy[1][1] = mVerticesCopy1[1][1]+(fbHeight/2); 
				mVerticesCopy[2][0] = mVerticesCopy1[2][0] ; 
				mVerticesCopy[2][1] = mVerticesCopy1[2][1]+(fbHeight/2); 
				mVerticesCopy[3][0] = mVerticesCopy1[3][0]; 
				mVerticesCopy[3][1] = mVerticesCopy1[3][1]+(fbHeight/2);
						//3d surface
				
				if(ISurfaceComposer::eLayerTopAndBottom == eType)
				{
					//draw 3D buttom to  FB buttom
							
					texCoords[0].u = 0; 
					texCoords[0].v = 0.5; 
					texCoords[1].u = 0; 
					texCoords[1].v = 0;
					texCoords[2].u = 1;
					texCoords[2].v = 0;
					texCoords[3].u = 1;
					texCoords[3].v = 0.5;
					glEnableClientState(GL_TEXTURE_COORD_ARRAY);			
					glVertexPointer(2, GL_FLOAT, 0, mVerticesCopy1);
					glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
					Region::const_iterator it = clip.begin();
					Region::const_iterator const end = clip.end();			
					while (it != end) {
						const Rect& r = *it++;		
						const GLint sy = fbHeight - (r.top + r.height());			
						glScissor(r.left, sy/2, r.width(), r.height()/2);			
						glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 
					}
				
					texCoords[0].u = 0; 
					texCoords[0].v = 1; 
					texCoords[1].u = 0; 
					texCoords[1].v = 0.5;
					texCoords[2].u = 1;
					texCoords[2].v = 0.5;
					texCoords[3].u = 1;
					texCoords[3].v = 1;
					glEnableClientState(GL_TEXTURE_COORD_ARRAY);
					//glVertexPointer(2, GL_FLOAT, 0, mVertices);
					glVertexPointer(2, GL_FLOAT, 0, mVerticesCopy);
					glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
					Region::const_iterator itCopy1 = clip.begin();	  
					Region::const_iterator const endCopy1 = clip.end();   
					while (itCopy1!= endCopy1) {   
						const Rect& rCopy1 = *itCopy1++;	
						const GLint syCopy1 = fbHeight - (rCopy1.top + rCopy1.height());  
						glScissor(rCopy1.left, syCopy1/2 + (fbHeight/2), rCopy1.width(), rCopy1.height()/2); 
						glDrawArrays(GL_TRIANGLE_FAN, 0, 4);			
					}		
							
				}
				else{
						//draw 2D surface to buttom 	
						 
					texCoords[0].u = 0;
					texCoords[0].v = 1;
					texCoords[1].u = 0;
					texCoords[1].v = 0;
					texCoords[2].u = 1;
					texCoords[2].v = 0;
					texCoords[3].u = 1;
					texCoords[3].v = 1; 	
					glEnableClientState(GL_TEXTURE_COORD_ARRAY);
					glVertexPointer(2, GL_FLOAT, 0, mVerticesCopy1);
					glTexCoordPointer(2, GL_FLOAT, 0, texCoords);		
					Region::const_iterator it = clip.begin();
					Region::const_iterator const end = clip.end();
					while (it != end) {
						const Rect& r = *it++;		
						const GLint sy = fbHeight - (r.top + r.height());
						glScissor(r.left, sy/2, r.width(), r.height()/2);
									
						glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 
					}
						//draw 2D surface to top				
					glVertexPointer(2, GL_FLOAT, 0, mVerticesCopy); 	
					glTexCoordPointer(2, GL_FLOAT, 0, texCoords);		
					Region::const_iterator itCopy = clip.begin();	 
					Region::const_iterator const endCopy = clip.end();	 
					while (itCopy!= endCopy) {	 
						const Rect& rCopy = *itCopy++;	  
						const GLint syCopy = fbHeight - (rCopy.top + rCopy.height());
						glScissor(rCopy.left, syCopy/2 + (fbHeight/2), rCopy.width(), rCopy.height()/2);
						glDrawArrays(GL_TRIANGLE_FAN, 0, 4);			
					}
				}

}
void LayerBase::drawSideBySide(const Region& clip ,uint32_t hw_w_half ,uint32_t fbHeight ,uint8_t eType ) const
{
	struct TexCoords {
							GLfloat u;
							GLfloat v;
							};			 
	TexCoords texCoords[4];

	GLfloat mVerticesCopy1[4][2];
	GLfloat mVerticesCopy[4][2]; 
	mVerticesCopy1[0][0] = mVertices[0][0]; 
	mVerticesCopy1[0][1] = mVertices[0][1]; 
	mVerticesCopy1[1][0] = mVertices[1][0]; 
	mVerticesCopy1[1][1] = mVertices[1][1]; 
	mVerticesCopy1[2][0] = mVertices[2][0]; 
	mVerticesCopy1[2][1] = mVertices[2][1]; 
	mVerticesCopy1[3][0] = mVertices[3][0]; 
	mVerticesCopy1[3][1] = mVertices[3][1]; 	
	for (size_t i=0 ; i<4 ; i++){
		mVerticesCopy1[i][0] /= 2;						
	}
	mVerticesCopy[0][0] = mVerticesCopy1[0][0] + hw_w_half; 
	mVerticesCopy[0][1] = mVerticesCopy1[0][1]; 
	mVerticesCopy[1][0] = mVerticesCopy1[1][0] + hw_w_half; 
	mVerticesCopy[1][1] = mVerticesCopy1[1][1]; 
	mVerticesCopy[2][0] = mVerticesCopy1[2][0] + hw_w_half; 
	mVerticesCopy[2][1] = mVerticesCopy1[2][1]; 
	mVerticesCopy[3][0] = mVerticesCopy1[3][0] + hw_w_half; 
	mVerticesCopy[3][1] = mVerticesCopy1[3][1];
					//3d surface
	LOGD("-------550-----Draw--in 3d surface --- mDrawingState.flags = %d", int(mDrawingState.flags));
	if((ISurfaceComposer::eLayerSideBySide == eType))
	{
					//draw 3D full to whole FB
						
		texCoords[0].u = 0; 
		texCoords[0].v = 1; 
		texCoords[1].u = 0; 
		texCoords[1].v = 0;
		texCoords[2].u = 0.5;
		texCoords[2].v = 0;
		texCoords[3].u = 0.5;
		texCoords[3].v = 1;
		glEnableClientState(GL_TEXTURE_COORD_ARRAY);			
		glVertexPointer(2, GL_FLOAT, 0, mVerticesCopy1);
		glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
		Region::const_iterator it = clip.begin();
		Region::const_iterator const end = clip.end();			
		while (it != end) {
			const Rect& r = *it++;		
			const GLint sy = fbHeight - (r.top + r.height());			
			glScissor(r.left/2, sy, r.width()/2, r.height());			
			glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 
		}
			
		texCoords[0].u = 0.5;	
		texCoords[0].v = 1; 
		texCoords[1].u = 0.5;	
		texCoords[1].v = 0;
		texCoords[2].u = 1;
		texCoords[2].v = 0;
		texCoords[3].u = 1;
		texCoords[3].v = 1;
		glEnableClientState(GL_TEXTURE_COORD_ARRAY);
				//glVertexPointer(2, GL_FLOAT, 0, mVertices);
		glVertexPointer(2, GL_FLOAT, 0, mVerticesCopy);
		glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
		Region::const_iterator itCopy1 = clip.begin();	  
		Region::const_iterator const endCopy1 = clip.end();   
		while (itCopy1!= endCopy1) {   
			const Rect& rCopy1 = *itCopy1++;	
			const GLint syCopy1 = fbHeight - (rCopy1.top + rCopy1.height());  
			glScissor(rCopy1.left/2+hw_w_half, syCopy1, rCopy1.width()/2, rCopy1.height()); 
			glDrawArrays(GL_TRIANGLE_FAN, 0, 4);			
		}		
						
	}
	else{
					//draw 2D surface to left		
					 
				texCoords[0].u = 0;
				texCoords[0].v = 1;
				texCoords[1].u = 0;
				texCoords[1].v = 0;
				texCoords[2].u = 1;
				texCoords[2].v = 0;
				texCoords[3].u = 1;
				texCoords[3].v = 1; 	
				glEnableClientState(GL_TEXTURE_COORD_ARRAY);
				glVertexPointer(2, GL_FLOAT, 0, mVerticesCopy1);
				glTexCoordPointer(2, GL_FLOAT, 0, texCoords);		
				Region::const_iterator it = clip.begin();
				Region::const_iterator const end = clip.end();
				while (it != end) {
					const Rect& r = *it++;		
					const GLint sy = fbHeight - (r.top + r.height());			
					glScissor(r.left/2, sy, r.width()/2, r.height());			
					glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 
				}
					//draw 2D surface to right				
				glVertexPointer(2, GL_FLOAT, 0, mVerticesCopy); 	
				glTexCoordPointer(2, GL_FLOAT, 0, texCoords);		
				Region::const_iterator itCopy = clip.begin();	 
				Region::const_iterator const endCopy = clip.end();	 
				while (itCopy!= endCopy) {	 
					const Rect& rCopy = *itCopy++;	  
					const GLint syCopy = fbHeight - (rCopy.top + rCopy.height());  
					glScissor(rCopy.left/2+hw_w_half, syCopy, rCopy.width()/2, rCopy.height()); 
					glDrawArrays(GL_TRIANGLE_FAN, 0, 4);			
				}
			}
}
double ComputeReduceRegion::compute_one(int m, int flag)
{
  int i;

  Region *region = domain->regions[iregion];
  region->prematch();

  // invoke the appropriate attribute,compute,fix,variable
  // compute scalar quantity by summing over atom scalars
  // only include atoms in group

  index = -1;
  double **x = atom->x;
  int *mask = atom->mask;
  int nlocal = atom->nlocal;

  int n = value2index[m];
  int j = argindex[m];

  double one;
  if (mode == SUM) one = 0.0;
  else if (mode == MINN) one = BIG;
  else if (mode == MAXX) one = -BIG;
  else if (mode == AVE) one = 0.0;

  if (which[m] == X) {
    if (flag < 0) {
      for (i = 0; i < nlocal; i++)
        if (mask[i] & groupbit && region->match(x[i][0],x[i][1],x[i][2]))
          combine(one,x[i][j],i);
    } else one = x[flag][j];
  } else if (which[m] == V) {
    double **v = atom->v;
    if (flag < 0) {
      for (i = 0; i < nlocal; i++)
        if (mask[i] & groupbit && region->match(x[i][0],x[i][1],x[i][2]))
          combine(one,v[i][j],i);
    } else one = v[flag][j];
  } else if (which[m] == F) {
    double **f = atom->f;
    if (flag < 0) {
      for (i = 0; i < nlocal; i++)
        if (mask[i] & groupbit && region->match(x[i][0],x[i][1],x[i][2]))
          combine(one,f[i][j],i);
    } else one = f[flag][j];

  // invoke compute if not previously invoked

  } else if (which[m] == COMPUTE) {
    Compute *compute = modify->compute[n];

    if (flavor[m] == PERATOM) {
      if (!(compute->invoked_flag & INVOKED_PERATOM)) {
        compute->compute_peratom();
        compute->invoked_flag |= INVOKED_PERATOM;
      }

      if (j == 0) {
        double *compute_vector = compute->vector_atom;
        int n = nlocal;
        if (flag < 0) {
          for (i = 0; i < n; i++)
            if (mask[i] & groupbit && region->match(x[i][0],x[i][1],x[i][2]))
              combine(one,compute_vector[i],i);
        } else one = compute_vector[flag];
      } else {
        double **compute_array = compute->array_atom;
        int n = nlocal;
        int jm1 = j - 1;
        if (flag < 0) {
          for (i = 0; i < n; i++)
            if (mask[i] & groupbit && region->match(x[i][0],x[i][1],x[i][2]))
              combine(one,compute_array[i][jm1],i);
        } else one = compute_array[flag][jm1];
      }

    } else if (flavor[m] == LOCAL) {
      if (!(compute->invoked_flag & INVOKED_LOCAL)) {
        compute->compute_local();
        compute->invoked_flag |= INVOKED_LOCAL;
      }

      if (j == 0) {
        double *compute_vector = compute->vector_local;
        int n = compute->size_local_rows;
        if (flag < 0)
          for (i = 0; i < n; i++)
            combine(one,compute_vector[i],i);
        else one = compute_vector[flag];
      } else {
        double **compute_array = compute->array_local;
        int n = compute->size_local_rows;
        int jm1 = j - 1;
        if (flag < 0)
          for (i = 0; i < n; i++)
            combine(one,compute_array[i][jm1],i);
        else one = compute_array[flag][jm1];
      }
    }

  // check if fix frequency is a match

  } else if (which[m] == FIX) {
    if (update->ntimestep % modify->fix[n]->peratom_freq)
      error->all(FLERR,"Fix used in compute reduce not computed at "
                 "compatible time");
    Fix *fix = modify->fix[n];

    if (flavor[m] == PERATOM) {
      if (j == 0) {
        double *fix_vector = fix->vector_atom;
        int n = nlocal;
        if (flag < 0) {
          for (i = 0; i < n; i++)
            if (mask[i] & groupbit && region->match(x[i][0],x[i][1],x[i][2]))
              combine(one,fix_vector[i],i);
        } else one = fix_vector[flag];
      } else {
        double **fix_array = fix->array_atom;
        int jm1 = j - 1;
        if (flag < 0) {
          for (i = 0; i < nlocal; i++)
            if (mask[i] & groupbit && region->match(x[i][0],x[i][1],x[i][2]))
              combine(one,fix_array[i][jm1],i);
        } else one = fix_array[flag][jm1];
      }

    } else if (flavor[m] == LOCAL) {
      if (j == 0) {
        double *fix_vector = fix->vector_local;
        int n = fix->size_local_rows;
        if (flag < 0)
          for (i = 0; i < n; i++)
            combine(one,fix_vector[i],i);
        else one = fix_vector[flag];
      } else {
        double **fix_array = fix->array_local;
        int n = fix->size_local_rows;
        int jm1 = j - 1;
        if (flag < 0)
          for (i = 0; i < n; i++)
            combine(one,fix_array[i][jm1],i);
        else one = fix_array[flag][jm1];
      }
    }

  // evaluate atom-style variable

  } else if (which[m] == VARIABLE) {
    if (nlocal > maxatom) {
      maxatom = atom->nmax;
      memory->destroy(varatom);
      memory->create(varatom,maxatom,"reduce/region:varatom");
    }

    input->variable->compute_atom(n,igroup,varatom,1,0);
    if (flag < 0) {
      for (i = 0; i < nlocal; i++)
        if (mask[i] & groupbit && region->match(x[i][0],x[i][1],x[i][2]))
          combine(one,varatom[i],i);
    } else one = varatom[flag];
  }

  return one;
}
Exemple #20
0
void ToolLoopManager::calculateDirtyArea(const Points& points)
{
  // Save the current dirty area if it's needed
  Region prevDirtyArea;
  if (m_toolLoop->getTracePolicy() == TracePolicy::Last)
    prevDirtyArea = m_dirtyArea;

  // Start with a fresh dirty area
  m_dirtyArea.clear();

  if (points.size() > 0) {
    Point minpt, maxpt;
    calculateMinMax(points, minpt, maxpt);

    // Expand the dirty-area with the pen width
    Rect r1, r2;
    m_toolLoop->getPointShape()->getModifiedArea(m_toolLoop, minpt.x, minpt.y, r1);
    m_toolLoop->getPointShape()->getModifiedArea(m_toolLoop, maxpt.x, maxpt.y, r2);

    m_dirtyArea.createUnion(m_dirtyArea, Region(r1.createUnion(r2)));
  }

  // Apply offset mode
  Point offset(m_toolLoop->getOffset());
  m_dirtyArea.offset(-offset);

  // Merge new dirty area with the previous one (for tools like line
  // or rectangle it's needed to redraw the previous position and
  // the new one)
  if (m_toolLoop->getTracePolicy() == TracePolicy::Last)
    m_dirtyArea.createUnion(m_dirtyArea, prevDirtyArea);

  // Apply tiled mode
  TiledMode tiledMode = m_toolLoop->getTiledMode();
  if (tiledMode != TiledMode::NONE) {
    int w = m_toolLoop->sprite()->width();
    int h = m_toolLoop->sprite()->height();
    Region sprite_area(Rect(0, 0, w, h));
    Region outside;
    outside.createSubtraction(m_dirtyArea, sprite_area);

    switch (tiledMode) {
      case TiledMode::X_AXIS:
        outside.createIntersection(outside, Region(Rect(-w*10000, 0, w*20000, h)));
        break;
      case TiledMode::Y_AXIS:
        outside.createIntersection(outside, Region(Rect(0, -h*10000, w, h*20000)));
        break;
    }

    Rect outsideBounds = outside.bounds();
    if (outsideBounds.x < 0) outside.offset(w * (1+((-outsideBounds.x) / w)), 0);
    if (outsideBounds.y < 0) outside.offset(0, h * (1+((-outsideBounds.y) / h)));
    int x1 = outside.bounds().x;

    while (true) {
      Region in_sprite;
      in_sprite.createIntersection(outside, sprite_area);
      outside.createSubtraction(outside, in_sprite);
      m_dirtyArea.createUnion(m_dirtyArea, in_sprite);

      outsideBounds = outside.bounds();
      if (outsideBounds.isEmpty())
        break;
      else if (outsideBounds.x+outsideBounds.w > w)
        outside.offset(-w, 0);
      else if (outsideBounds.y+outsideBounds.h > h)
        outside.offset(x1-outsideBounds.x, -h);
      else
        break;
    }
  }
}
Exemple #21
0
BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
  BasicBlock *Exit = NULL;

  while (true) {
    // Get largest region that starts at BB.
    Region *R = getRegionFor(BB);
    while (R && R->getParent() && R->getParent()->getEntry() == BB)
      R = R->getParent();

    // Get the single exit of BB.
    if (R && R->getEntry() == BB)
      Exit = R->getExit();
    else if (++succ_begin(BB) == succ_end(BB))
      Exit = *succ_begin(BB);
    else // No single exit exists.
      return Exit;

    // Get largest region that starts at Exit.
    Region *ExitR = getRegionFor(Exit);
    while (ExitR && ExitR->getParent()
           && ExitR->getParent()->getEntry() == Exit)
      ExitR = ExitR->getParent();

    for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
         ++PI)
      if (!R->contains(*PI) && !ExitR->contains(*PI))
        break;

    // This stops infinite cycles.
    if (DT->dominates(Exit, BB))
      break;

    BB = Exit;
  }

  return Exit;
}
Exemple #22
0
double getZoom(Region a,Region b,int it)
{
  long double zoomRatio = pow(  (long double)b.getLength() / (long double)a.getLength() , (long double) 1/(it-1)   );
  return (double)zoomRatio;
}
Exemple #23
0
status_t TextureManager::loadTexture(Texture* texture,
        const Region& dirty, const GGLSurface& t)
{
    if (texture->name == -1UL) {
        status_t err = initTexture(texture);
        LOGE_IF(err, "loadTexture failed in initTexture (%s)", strerror(err));
        return err;
    }

    if (texture->target != Texture::TEXTURE_2D)
        return INVALID_OPERATION;

    glBindTexture(GL_TEXTURE_2D, texture->name);

    /*
     * In OpenGL ES we can't specify a stride with glTexImage2D (however,
     * GL_UNPACK_ALIGNMENT is a limited form of stride).
     * So if the stride here isn't representable with GL_UNPACK_ALIGNMENT, we
     * need to do something reasonable (here creating a bigger texture).
     *
     * extra pixels = (((stride - width) * pixelsize) / GL_UNPACK_ALIGNMENT);
     *
     * This situation doesn't happen often, but some h/w have a limitation
     * for their framebuffer (eg: must be multiple of 8 pixels), and
     * we need to take that into account when using these buffers as
     * textures.
     *
     * This should never be a problem with POT textures
     */

    int unpack = __builtin_ctz(t.stride * bytesPerPixel(t.format));
    unpack = 1 << ((unpack > 3) ? 3 : unpack);
    glPixelStorei(GL_UNPACK_ALIGNMENT, unpack);

    /*
     * round to POT if needed
     */
    if (!mGLExtensions.haveNpot()) {
        texture->NPOTAdjust = true;
    }

    if (texture->NPOTAdjust) {
        // find the smallest power-of-two that will accommodate our surface
        texture->potWidth  = 1 << (31 - clz(t.width));
        texture->potHeight = 1 << (31 - clz(t.height));
        if (texture->potWidth  < t.width)  texture->potWidth  <<= 1;
        if (texture->potHeight < t.height) texture->potHeight <<= 1;
        texture->wScale = float(t.width)  / texture->potWidth;
        texture->hScale = float(t.height) / texture->potHeight;
    } else {
        texture->potWidth  = t.width;
        texture->potHeight = t.height;
    }

    Rect bounds(dirty.bounds());
    GLvoid* data = 0;
    if (texture->width != t.width || texture->height != t.height) {
        texture->width  = t.width;
        texture->height = t.height;

        // texture size changed, we need to create a new one
        bounds.set(Rect(t.width, t.height));
        if (t.width  == texture->potWidth &&
            t.height == texture->potHeight) {
            // we can do it one pass
            data = t.data;
        }

        if (t.format == HAL_PIXEL_FORMAT_RGB_565) {
            glTexImage2D(GL_TEXTURE_2D, 0,
                    GL_RGB, texture->potWidth, texture->potHeight, 0,
                    GL_RGB, GL_UNSIGNED_SHORT_5_6_5, data);
        } else if (t.format == HAL_PIXEL_FORMAT_RGBA_4444) {
            glTexImage2D(GL_TEXTURE_2D, 0,
                    GL_RGBA, texture->potWidth, texture->potHeight, 0,
                    GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, data);
        } else if (t.format == HAL_PIXEL_FORMAT_RGBA_8888 ||
                   t.format == HAL_PIXEL_FORMAT_RGBX_8888) {
            glTexImage2D(GL_TEXTURE_2D, 0,
                    GL_RGBA, texture->potWidth, texture->potHeight, 0,
                    GL_RGBA, GL_UNSIGNED_BYTE, data);
        } else if (isSupportedYuvFormat(t.format)) {
            // just show the Y plane of YUV buffers
            glTexImage2D(GL_TEXTURE_2D, 0,
                    GL_LUMINANCE, texture->potWidth, texture->potHeight, 0,
                    GL_LUMINANCE, GL_UNSIGNED_BYTE, data);
        } else {
            // oops, we don't handle this format!
            LOGE("texture=%d, using format %d, which is not "
                 "supported by the GL", texture->name, t.format);
        }
    }
    if (!data) {
        if (t.format == HAL_PIXEL_FORMAT_RGB_565) {
            glTexSubImage2D(GL_TEXTURE_2D, 0,
                    0, bounds.top, t.width, bounds.height(),
                    GL_RGB, GL_UNSIGNED_SHORT_5_6_5,
                    t.data + bounds.top*t.stride*2);
        } else if (t.format == HAL_PIXEL_FORMAT_RGBA_4444) {
            glTexSubImage2D(GL_TEXTURE_2D, 0,
                    0, bounds.top, t.width, bounds.height(),
                    GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4,
                    t.data + bounds.top*t.stride*2);
        } else if (t.format == HAL_PIXEL_FORMAT_RGBA_8888 ||
                   t.format == HAL_PIXEL_FORMAT_RGBX_8888) {
            glTexSubImage2D(GL_TEXTURE_2D, 0,
                    0, bounds.top, t.width, bounds.height(),
                    GL_RGBA, GL_UNSIGNED_BYTE,
                    t.data + bounds.top*t.stride*4);
        } else if (isSupportedYuvFormat(t.format)) {
            // just show the Y plane of YUV buffers
            glTexSubImage2D(GL_TEXTURE_2D, 0,
                    0, bounds.top, t.width, bounds.height(),
                    GL_LUMINANCE, GL_UNSIGNED_BYTE,
                    t.data + bounds.top*t.stride);
        }
    }
    return NO_ERROR;
}
Exemple #24
0
void RegionGenerator::copyStmt(ScopStmt &Stmt, ValueMapT &GlobalMap,
                               LoopToScevMapT &LTS) {
  assert(Stmt.isRegionStmt() &&
         "Only region statements can be copied by the block generator");

  // Forget all old mappings.
  BlockMap.clear();
  RegionMaps.clear();
  IncompletePHINodeMap.clear();

  // The region represented by the statement.
  Region *R = Stmt.getRegion();

  // Create a dedicated entry for the region where we can reload all demoted
  // inputs.
  BasicBlock *EntryBB = R->getEntry();
  BasicBlock *EntryBBCopy =
      SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
  EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
  Builder.SetInsertPoint(EntryBBCopy->begin());

  for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
    if (!R->contains(*PI))
      BlockMap[*PI] = EntryBBCopy;

  // Iterate over all blocks in the region in a breadth-first search.
  std::deque<BasicBlock *> Blocks;
  SmallPtrSet<BasicBlock *, 8> SeenBlocks;
  Blocks.push_back(EntryBB);
  SeenBlocks.insert(EntryBB);

  while (!Blocks.empty()) {
    BasicBlock *BB = Blocks.front();
    Blocks.pop_front();

    // First split the block and update dominance information.
    BasicBlock *BBCopy = splitBB(BB);
    BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);

    // In order to remap PHI nodes we store also basic block mappings.
    BlockMap[BB] = BBCopy;

    // Get the mapping for this block and initialize it with the mapping
    // available at its immediate dominator (in the new region).
    ValueMapT &RegionMap = RegionMaps[BBCopy];
    RegionMap = RegionMaps[BBCopyIDom];

    // Copy the block with the BlockGenerator.
    copyBB(Stmt, BB, BBCopy, RegionMap, GlobalMap, LTS);

    // In order to remap PHI nodes we store also basic block mappings.
    BlockMap[BB] = BBCopy;

    // Add values to incomplete PHI nodes waiting for this block to be copied.
    for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
      addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB,
                      GlobalMap, LTS);
    IncompletePHINodeMap[BB].clear();

    // And continue with new successors inside the region.
    for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
      if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
        Blocks.push_back(*SI);
  }

  // Now create a new dedicated region exit block and add it to the region map.
  BasicBlock *ExitBBCopy =
      SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
  ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
  BlockMap[R->getExit()] = ExitBBCopy;

  repairDominance(R->getExit(), ExitBBCopy);

  // As the block generator doesn't handle control flow we need to add the
  // region control flow by hand after all blocks have been copied.
  for (BasicBlock *BB : SeenBlocks) {

    BranchInst *BI = cast<BranchInst>(BB->getTerminator());

    BasicBlock *BBCopy = BlockMap[BB];
    Instruction *BICopy = BBCopy->getTerminator();

    ValueMapT &RegionMap = RegionMaps[BBCopy];
    RegionMap.insert(BlockMap.begin(), BlockMap.end());

    Builder.SetInsertPoint(BBCopy);
    copyInstScalar(Stmt, BI, RegionMap, GlobalMap, LTS);
    BICopy->eraseFromParent();
  }

  // Add counting PHI nodes to all loops in the region that can be used as
  // replacement for SCEVs refering to the old loop.
  for (BasicBlock *BB : SeenBlocks) {
    Loop *L = LI.getLoopFor(BB);
    if (L == nullptr || L->getHeader() != BB)
      continue;

    BasicBlock *BBCopy = BlockMap[BB];
    Value *NullVal = Builder.getInt32(0);
    PHINode *LoopPHI =
        PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
    Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
        LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
    LoopPHI->insertBefore(BBCopy->begin());
    LoopPHIInc->insertBefore(BBCopy->getTerminator());

    for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
      if (!R->contains(PredBB))
        continue;
      if (L->contains(PredBB))
        LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
      else
        LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
    }

    for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
      if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
        LoopPHI->addIncoming(NullVal, PredBBCopy);

    LTS[L] = SE.getUnknown(LoopPHI);
  }

  // Add all mappings from the region to the global map so outside uses will use
  // the copied instructions.
  for (auto &BBMap : RegionMaps)
    GlobalMap.insert(BBMap.second.begin(), BBMap.second.end());

  // Reset the old insert point for the build.
  Builder.SetInsertPoint(ExitBBCopy->begin());
}
void FixEHEX::update_scalingmask() {
  int m;
  int lid;
  bool stat;
  int nsites;

  // prematch region

  Region *region = NULL;
  if (iregion >= 0) {
    region = domain->regions[iregion];
    region->prematch();
  }

  // only rescale molecules whose center of mass if fully contained in the region

  if (cluster) {

    // loop over all clusters

    for (int i=0; i < fshake->nlist; i++) {

      // cluster id

      m    = fshake->list[i];

      // check if the centre of mass of the cluster is inside the region
      // if region == NULL, just check the group information of all sites

      if      (fshake->shake_flag[m] == 1)      nsites = 3;
      else if (fshake->shake_flag[m] == 2)      nsites = 2;
      else if (fshake->shake_flag[m] == 3)      nsites = 3;
      else if (fshake->shake_flag[m] == 4)      nsites = 4;
      else                                      nsites = 0;

      if (nsites == 0) {
        error->all(FLERR,"Internal error: shake_flag[m] has to be between 1 and 4 for m in nlist");
      }

      stat = check_cluster(fshake->shake_atom[m], nsites, region);

      for (int l=0; l < nsites; l++)  {
        lid = atom->map(fshake->shake_atom[m][l]);
        scalingmask[lid] = stat;
      }
    }

    // check atoms that do not belong to any cluster

    for (int i=0; i<atom->nlocal; i++)  {
      if (fshake->shake_flag[i] == 0)
        scalingmask[i] = rescale_atom(i,region);
    }

  }

  // no clusters, just individual sites (e.g. monatomic system or flexible molecules)

  else {
    for (int i=0; i<atom->nlocal; i++)
      scalingmask[i] =  rescale_atom(i,region);
  }

}
void TextureMapperLayer::paintUsingOverlapRegions(const TextureMapperPaintOptions& options)
{
    Region overlapRegion;
    Region nonOverlapRegion;
    computeOverlapRegions(overlapRegion, nonOverlapRegion, ResolveSelfOverlapAlways);
    if (overlapRegion.isEmpty()) {
        paintSelfAndChildrenWithReplica(options);
        return;
    }

    // Having both overlap and non-overlap regions carries some overhead. Avoid it if the overlap area
    // is big anyway.
    if (overlapRegion.bounds().size().area() > nonOverlapRegion.bounds().size().area()) {
        overlapRegion.unite(nonOverlapRegion);
        nonOverlapRegion = Region();
    }

    nonOverlapRegion.translate(options.offset);
    Vector<IntRect> rects = nonOverlapRegion.rects();

    for (auto& rect : rects) {
        if (!rect.intersects(options.textureMapper->clipBounds()))
            continue;

        options.textureMapper->beginClip(TransformationMatrix(), rect);
        paintSelfAndChildrenWithReplica(options);
        options.textureMapper->endClip();
    }

    rects = overlapRegion.rects();
    static const size_t OverlapRegionConsolidationThreshold = 4;
    if (nonOverlapRegion.isEmpty() && rects.size() > OverlapRegionConsolidationThreshold) {
        rects.clear();
        rects.append(overlapRegion.bounds());
    }

    IntSize maxTextureSize = options.textureMapper->maxTextureSize();
    IntRect adjustedClipBounds(options.textureMapper->clipBounds());
    adjustedClipBounds.move(-options.offset);
    for (auto& rect : rects) {
        for (int x = rect.x(); x < rect.maxX(); x += maxTextureSize.width()) {
            for (int y = rect.y(); y < rect.maxY(); y += maxTextureSize.height()) {
                IntRect tileRect(IntPoint(x, y), maxTextureSize);
                tileRect.intersect(rect);
                if (!tileRect.intersects(adjustedClipBounds))
                    continue;

                paintWithIntermediateSurface(options, tileRect);
            }
        }
    }
}
bool ScopDetection::isValidCFG(BasicBlock &BB,
                               DetectionContext &Context) const {
  Region &RefRegion = Context.CurRegion;
  TerminatorInst *TI = BB.getTerminator();

  // Return instructions are only valid if the region is the top level region.
  if (isa<ReturnInst>(TI) && !RefRegion.getExit() && TI->getNumOperands() == 0)
    return true;

  BranchInst *Br = dyn_cast<BranchInst>(TI);

  if (!Br)
    return invalid<ReportNonBranchTerminator>(Context, /*Assert=*/true, &BB);

  if (Br->isUnconditional())
    return true;

  Value *Condition = Br->getCondition();

  // UndefValue is not allowed as condition.
  if (isa<UndefValue>(Condition))
    return invalid<ReportUndefCond>(Context, /*Assert=*/true, &BB);

  // Only Constant and ICmpInst are allowed as condition.
  if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition)))
    return invalid<ReportInvalidCond>(Context, /*Assert=*/true, &BB);

  // Allow perfectly nested conditions.
  assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");

  if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
    // Unsigned comparisons are not allowed. They trigger overflow problems
    // in the code generation.
    //
    // TODO: This is not sufficient and just hides bugs. However it does pretty
    // well.
    if (ICmp->isUnsigned())
      return false;

    // Are both operands of the ICmp affine?
    if (isa<UndefValue>(ICmp->getOperand(0)) ||
        isa<UndefValue>(ICmp->getOperand(1)))
      return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB);

    Loop *L = LI->getLoopFor(ICmp->getParent());
    const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
    const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);

    if (!isAffineExpr(&Context.CurRegion, LHS, *SE) ||
        !isAffineExpr(&Context.CurRegion, RHS, *SE))
      return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS,
                                         RHS);
  }

  // Allow loop exit conditions.
  Loop *L = LI->getLoopFor(&BB);
  if (L && L->getExitingBlock() == &BB)
    return true;

  // Allow perfectly nested conditions.
  Region *R = RI->getRegionFor(&BB);
  if (R->getEntry() != &BB)
    return invalid<ReportCondition>(Context, /*Assert=*/true, &BB);

  return true;
}
bool BindingManager::isCellRegionValid(const QString& regionName) const
{
    const Region region(regionName, d->map);
    return (region.isValid() && region.isContiguous() && region.firstSheet());
}
Exemple #29
0
void RegionGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
                                           ValueMapT &BBMap,
                                           ValueMapT &GlobalMap) {
  const Region &R = Stmt.getParent()->getRegion();

  Region *StmtR = Stmt.getRegion();
  assert(StmtR && "Block statements need to use the generateScalarStores() "
                  "function in the BlockGenerator");

  BasicBlock *ExitBB = StmtR->getExit();

  // For region statements three kinds of scalar stores exists:
  //  (1) A definition used by a non-phi instruction outside the region.
  //  (2) A phi-instruction in the region entry.
  //  (3) A write to a phi instruction in the region exit.
  // The last case is the tricky one since we do not know anymore which
  // predecessor of the exit needs to store the operand value that doesn't
  // have a definition in the region. Therefore, we have to check in each
  // block in the region if we should store the value or not.

  // Iterate over all accesses in the given statement.
  for (MemoryAccess *MA : Stmt) {

    // Skip non-scalar and read accesses.
    if (!MA->isScalar() || MA->isRead())
      continue;

    Instruction *ScalarBase = cast<Instruction>(MA->getBaseAddr());
    Instruction *ScalarInst = MA->getAccessInstruction();
    PHINode *ScalarBasePHI = dyn_cast<PHINode>(ScalarBase);

    Value *ScalarValue = nullptr;
    AllocaInst *ScalarAddr = nullptr;

    if (!ScalarBasePHI) {
      // Case (1)
      ScalarAddr = getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
      ScalarValue = ScalarInst;
    } else if (ScalarBasePHI->getParent() != ExitBB) {
      // Case (2)
      assert(ScalarBasePHI->getParent() == StmtR->getEntry() &&
             "Bad PHI self write in non-affine region");
      assert(ScalarBase == ScalarInst &&
             "Bad PHI self write in non-affine region");
      ScalarAddr = getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
      ScalarValue = ScalarInst;
    } else {
      int PHIIdx = ScalarBasePHI->getBasicBlockIndex(BB);
      // Skip accesses we will not handle in this basic block but in another one
      // in the statement region.
      if (PHIIdx < 0)
        continue;

      // Case (3)
      ScalarAddr = getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops");
      ScalarValue = ScalarBasePHI->getIncomingValue(PHIIdx);
    }

    ScalarValue =
        getNewScalarValue(ScalarValue, R, ScalarMap, BBMap, GlobalMap);
    Builder.CreateStore(ScalarValue, ScalarAddr);
  }
}
Exemple #30
0
void makeRegionFile(Region a,Region b,int it,string filename)
{
  if (it == 0)
    return ;
  if (it == 1)
  {
    makeRegionFile(a,filename);
    return ;
  }
  if (it == 2)
  {
    fstream fin;
    fin.open(filename.c_str(),ios::out);
    
    fin << it << endl;   
    fin << a.getLeftUpCorner() << " ";
    fin << a.getRightLowerCorner() << endl;
    fin << b.getLeftUpCorner() << " ";
    fin << b.getRightLowerCorner() << endl;
    
    fin.close();
    return ;
  }

  // we find the zooming ratio
  long double zoomRatio = pow(  (long double)b.getLength() / (long double)a.getLength() , (long double) 1/(it-1)   );

  int iterRegion; // iterations needed to change the regions center from 'a' to 'b' 
  if (   (long double)b.getLength() / (long double)a.getLength() < (long double)RegionMoveMaximumConstant    )
  { // we calculate the iterRegion needed
    Region aux = a;
    iterRegion = 0;
    while (   (long double)aux.getLength() / (long double)a.getLength() > (long double)RegionMoveMaximumConstant    )
    { 
//cout << "current length: " << aux.getLength() << endl;
      iterRegion ++;
      aux = aux.zoomOn( zoomRatio );
    }
  }
  else
  { // it is close
    iterRegion = it-1;
  }

  // we find Moving Ratio
  complex <double> moveRatio = (b.getCenter() - a.getCenter()) / complex<double>(iterRegion,0);

  // open file 
  fstream fin;
  fin.open(filename.c_str(),ios::out);

  // print first iteration
  fin << it << endl;
  fin << a.getLeftUpCorner() << " ";
  fin << a.getRightLowerCorner() << endl;

  // we iterate
  Region curr = a;  
  for(int i=1 ; i < it-1 ; i++)
  {
    curr = curr.zoomOn(zoomRatio);
    if (i <= iterRegion)
      curr = curr.translationBy(moveRatio);
    else
      curr.setCenter(b.getCenter());

    fin << curr.getLeftUpCorner() << " ";
    fin << curr.getRightLowerCorner() << endl;
  }

  // print last iteration
  fin << b.getLeftUpCorner() << " ";
  fin << b.getRightLowerCorner() << endl;

  fin.close();
}