Example #1
0
 std::list<Pingu*>::size_type size ()  { return pingus.size (); }
Example #2
0
void getBankerInChargingDB() {

    float countOfBanker = 0;
    float countOfNeutralBanker = 0;
    float countOfNagtiveBanker = 0;
    float countOfPositiveBanker = 0;

    std::list<std::string> fileNames;
    getAllDatabase(fileNames, "dbs");
    fileNames.sort();
    std::list<std::string> listOfDBs;
    std::list<std::string>::iterator itrOfDBNames = fileNames.begin();
    TurnOverDiscover* pTurnOverDiscover = NULL;
    for (int i = 0; i < fileNames.size(); i++) {
      pTurnOverDiscover = new TurnOverDiscover(*itrOfDBNames, "FilterResult20W");
/*
      if (pTurnOverDiscover->isTodayBankerInCharge(DAY_OF_TARGET)) {
          if (pTurnOverDiscover->isTodayNeutralBankerInCharge(DAY_OF_TARGET)) {
              //printf("Is Positive:%s\n", itrOfDBNames->c_str());
              countOfNeutralBanker += 1;
          }
          if (pTurnOverDiscover->isTodayNagtiveBankerInCharge(DAY_OF_TARGET)) {
              //printf("Is Nagtive:%s\n", itrOfDBNames->c_str());
              countOfNagtiveBanker += 1;
          }
          if (pTurnOverDiscover->isTodayPositiveBankerInCharge(DAY_OF_TARGET)) {
              //printf("Is Positive:%s\n", itrOfDBNames->c_str());
              std::vector<double> bankerTurnOvers;
              pTurnOverDiscover->getBankerTurnOvers(bankerTurnOvers);
              //printf("BankerTurnOvers, Buy:%lf, Sale:%lf\n", bankerTurnOvers[0], bankerTurnOvers[1]);
              PositiveDB tmpPositiveDB;
              tmpPositiveDB.Name = *itrOfDBNames;
              tmpPositiveDB.BankerBuyingTurnOver = bankerTurnOvers[0];
              tmpPositiveDB.BankerSalingTurnOver = bankerTurnOvers[1];
              tmpPositiveDB.RatioBS = bankerTurnOvers[0]/bankerTurnOvers[1];
              sPositiveDBs.push_back(tmpPositiveDB);
              countOfPositiveBanker += 1;
          }
          countOfBanker += 1;
      }
*/
      pTurnOverDiscover->updateBankerResultTable();
      //if (pTurnOverDiscover->isPreviousDaysSuckIn(20)) {
      //    printf("isDBBankedInDays for DB:%s\n", itrOfDBNames->c_str());
      //}

      //printf("updateBankerResultTable for DB:%s\n", itrOfDBNames->c_str());
      itrOfDBNames++;
      delete pTurnOverDiscover;
      pTurnOverDiscover = NULL;
    }

    //printf("BankerInCharge size:%lf ratio:%lf\n", countOfBanker, countOfBanker / fileNames.size());
    //printf("NeutralBanker  size:%lf ratio:%lf\n", countOfNeutralBanker ,countOfNeutralBanker / countOfBanker);
    //printf("NagtiveBanker  size:%lf ratio:%lf\n", countOfNagtiveBanker, countOfNagtiveBanker / countOfBanker);
    //printf("PositiveBanker size:%lf ratio:%lf\n", countOfPositiveBanker, countOfPositiveBanker / countOfBanker);

    sPositiveDBs.sort(LargeToSmall);
    std::list<PositiveDB>::iterator iterPositionDB = sPositiveDBs.begin();
    for (int i = 0; i < sPositiveDBs.size(); i++) {
        printf("PositiveBanker, name:%s, buying:%lf sale:%lf, ratio:%lf\n", iterPositionDB->Name.c_str(), iterPositionDB->BankerBuyingTurnOver, iterPositionDB->BankerSalingTurnOver, iterPositionDB->RatioBS);
        iterPositionDB++; 
    }
}
Example #3
0
static void OffsetWithLoops(const TPolyPolygon &pp, TPolyPolygon &pp_new, double inwards_value)
{
	Clipper c;

	bool inwards = (inwards_value > 0);
	bool reverse = false;
	double radius = -fabs(inwards_value);

	if(inwards)
	{
		// add a large square on the outside, to be removed later
		TPolygon p;
		p.push_back(DoubleAreaPoint(-10000.0, -10000.0).int_point());
		p.push_back(DoubleAreaPoint(-10000.0, 10000.0).int_point());
		p.push_back(DoubleAreaPoint(10000.0, 10000.0).int_point());
		p.push_back(DoubleAreaPoint(10000.0, -10000.0).int_point());
		c.AddPath(p, ptSubject, true);
	}
	else
	{
		reverse = true;
	}

	for(unsigned int i = 0; i < pp.size(); i++)
	{
		const TPolygon& p = pp[i];

		pts_for_AddVertex.clear();

		if(p.size() > 2)
		{
			if(reverse)
			{
				for(std::size_t j = p.size()-1; j > 1; j--)MakeLoop(p[j], p[j-1], p[j-2], radius);
				MakeLoop(p[1], p[0], p[p.size()-1], radius);
				MakeLoop(p[0], p[p.size()-1], p[p.size()-2], radius);
			}
			else
			{
				MakeLoop(p[p.size()-2], p[p.size()-1], p[0], radius);
				MakeLoop(p[p.size()-1], p[0], p[1], radius);
				for(unsigned int j = 2; j < p.size(); j++)MakeLoop(p[j-2], p[j-1], p[j], radius);
			}

			TPolygon loopy_polygon;
			loopy_polygon.reserve(pts_for_AddVertex.size());
			for(std::list<DoubleAreaPoint>::iterator It = pts_for_AddVertex.begin(); It != pts_for_AddVertex.end(); It++)
			{
				loopy_polygon.push_back(It->int_point());
			}
			c.AddPath(loopy_polygon, ptSubject, true);
			pts_for_AddVertex.clear();
		}
	}

	//c.ForceOrientation(false);
	c.Execute(ctUnion, pp_new, pftNonZero, pftNonZero);

	if(inwards)
	{
		// remove the large square
		if(pp_new.size() > 0)
		{
			pp_new.erase(pp_new.begin());
		}
	}
	else
	{
		// reverse all the resulting polygons
		TPolyPolygon copy = pp_new;
		pp_new.clear();
		pp_new.resize(copy.size());
		for(unsigned int i = 0; i < copy.size(); i++)
		{
			const TPolygon& p = copy[i];
			TPolygon p_new;
			p_new.resize(p.size());
			std::size_t size_minus_one = p.size() - 1;
			for(unsigned int j = 0; j < p.size(); j++)p_new[j] = p[size_minus_one - j];
			pp_new[i] = p_new;
		}
	}
}
void drop_on_map( const Character &c, item_drop_reason reason, const std::list<item> &items,
                  const tripoint &where )
{
    if( items.empty() ) {
        return;
    }
    const std::string ter_name = g->m.name( where );
    const bool can_move_there = g->m.passable( where );

    if( same_type( items ) ) {
        const item &it = items.front();
        const int dropcount = items.size() * it.count();
        const std::string it_name = it.tname( dropcount );

        switch( reason ) {
            case item_drop_reason::deliberate:
                if( can_move_there ) {
                    c.add_msg_player_or_npc(
                        ngettext( "You drop your %1$s on the %2$s.",
                                  "You drop your %1$s on the %2$s.", dropcount ),
                        ngettext( "<npcname> drops their %1$s on the %2$s.",
                                  "<npcname> drops their %1$s on the %2$s.", dropcount ),
                        it_name, ter_name
                    );
                } else {
                    c.add_msg_player_or_npc(
                        ngettext( "You put your %1$s in the %2$s.",
                                  "You put your %1$s in the %2$s.", dropcount ),
                        ngettext( "<npcname> puts their %1$s in the %2$s.",
                                  "<npcname> puts their %1$s in the %2$s.", dropcount ),
                        it_name, ter_name
                    );
                }
                break;
            case item_drop_reason::too_large:
                c.add_msg_if_player(
                    ngettext( "There's no room in your inventory for the %s, so you drop it.",
                              "There's no room in your inventory for the %s, so you drop them.", dropcount ),
                    it_name
                );
                break;
            case item_drop_reason::too_heavy:
                c.add_msg_if_player(
                    ngettext( "The %s is too heavy to carry, so you drop it.",
                              "The %s is too heavy to carry, so you drop them.", dropcount ),
                    it_name
                );
                break;
            case item_drop_reason::tumbling:
                c.add_msg_if_player(
                    m_bad,
                    ngettext( "Your %1$s tumbles to the %2$s.",
                              "Your %1$s tumble to the %2$s.", dropcount ),
                    it_name, ter_name
                );
                break;
        }
    } else {
        switch( reason ) {
            case item_drop_reason::deliberate:
                if( can_move_there ) {
                    c.add_msg_player_or_npc(
                        _( "You drop several items on the %s." ),
                        _( "<npcname> drops several items on the %s." ),
                        ter_name
                    );
                } else {
                    c.add_msg_player_or_npc(
                        _( "You put several items in the %s." ),
                        _( "<npcname> puts several items in the %s." ),
                        ter_name
                    );
                }
                break;
            case item_drop_reason::too_large:
            case item_drop_reason::too_heavy:
            case item_drop_reason::tumbling:
                c.add_msg_if_player( m_bad, _( "Some items tumble to the %s." ), ter_name );
                break;
        }
    }
    for( const auto &it : items ) {
        g->m.add_item_or_charges( where, it );
    }
}
Example #5
0
 static void exec(OutArcType& oarc, const std::list<T>& vec){
   serialize_iterator(oarc,vec.begin(),vec.end(), vec.size());
 }
Example #6
0
ASR_RETVAL fpathAStarRoute(MOVE_CONTROL *psMove, PATHJOB *psJob)
{
	ASR_RETVAL      retval = ASR_OK;

	bool            mustReverse = true;

	const PathCoord tileOrig(map_coord(psJob->origX), map_coord(psJob->origY));
	const PathCoord tileDest(map_coord(psJob->destX), map_coord(psJob->destY));

	PathCoord endCoord;  // Either nearest coord (mustReverse = true) or orig (mustReverse = false).

	std::list<PathfindContext>::iterator contextIterator = fpathContexts.begin();
	for (contextIterator = fpathContexts.begin(); contextIterator != fpathContexts.end(); ++contextIterator)
	{
		if (!contextIterator->matches(psJob->blockingMap, tileDest))
		{
			// This context is not for the same droid type and same destination.
			continue;
		}

		// We have tried going to tileDest before.

		if (contextIterator->map[tileOrig.x + tileOrig.y*mapWidth].iteration == contextIterator->iteration
		 && contextIterator->map[tileOrig.x + tileOrig.y*mapWidth].visited)
		{
			// Already know the path from orig to dest.
			endCoord = tileOrig;
		}
		else
		{
			// Need to find the path from orig to dest, continue previous exploration.
			fpathAStarReestimate(*contextIterator, tileOrig);
			endCoord = fpathAStarExplore(*contextIterator, tileOrig);
		}

		if (endCoord != tileOrig)
		{
			// orig turned out to be on a different island than what this context was used for, so can't use this context data after all.
			continue;
		}

		mustReverse = false;  // We have the path from the nearest reachable tile to dest, to orig.
		break;  // Found the path! Don't search more contexts.
	}

	if (contextIterator == fpathContexts.end())
	{
		// We did not find an appropriate context. Make one.

		if (fpathContexts.size() < 30)
		{
			fpathContexts.push_back(PathfindContext());
		}
		--contextIterator;

		// Init a new context, overwriting the oldest one if we are caching too many.
		// We will be searching from orig to dest, since we don't know where the nearest reachable tile to dest is.
		fpathInitContext(*contextIterator, psJob->blockingMap, tileOrig, tileOrig, tileDest);
		endCoord = fpathAStarExplore(*contextIterator, tileDest);
		contextIterator->nearestCoord = endCoord;
	}

	PathfindContext &context = *contextIterator;

	// return the nearest route if no actual route was found
	if (context.nearestCoord != tileDest)
	{
		retval = ASR_NEAREST;
	}

	// Get route, in reverse order.
	static std::vector<Vector2i> path;  // Declared static to save allocations.
	path.clear();

	PathCoord newP;
	for (PathCoord p = endCoord; p != context.tileS; p = newP)
	{
		ASSERT_OR_RETURN(ASR_FAILED, tileOnMap(p.x, p.y), "Assigned XY coordinates (%d, %d) not on map!", (int)p.x, (int)p.y);
		ASSERT_OR_RETURN(ASR_FAILED, path.size() < (unsigned)mapWidth*mapHeight, "Pathfinding got in a loop.");

		path.push_back(Vector2i(world_coord(p.x) + TILE_UNITS / 2, world_coord(p.y) + TILE_UNITS / 2));

		PathExploredTile &tile = context.map[p.x + p.y*mapWidth];
		newP = PathCoord(p.x - tile.dx, p.y - tile.dy);
		if (p == newP)
		{
			break;  // We stopped moving, because we reached the closest reachable tile to context.tileS. Give up now.
		}
	}
	if (path.empty())
	{
		// We are probably already in the destination tile. Go to the exact coordinates.
		path.push_back(Vector2i(psJob->destX, psJob->destY));
	}
	else if (retval == ASR_OK)
	{
		// Found exact path, so use exact coordinates for last point, no reason to lose precision
		Vector2i v(psJob->destX, psJob->destY);
		if (mustReverse)
		{
			path.front() = v;
		}
		else
		{
			path.back() = v;
		}
	}

	// TODO FIXME once we can change numPoints to something larger than uint16_t
	psMove->numPoints = std::min<int>(UINT16_MAX, path.size());

	// Allocate memory
	psMove->asPath = static_cast<Vector2i *>(malloc(sizeof(*psMove->asPath) * path.size()));
	ASSERT(psMove->asPath, "Out of memory");
	if (!psMove->asPath)
	{
		fpathHardTableReset();
		return ASR_FAILED;
	}

	// get the route in the correct order
	// If as I suspect this is to reverse the list, then it's my suspicion that
	// we could route from destination to source as opposed to source to
	// destination. We could then save the reversal. to risky to try now...Alex M
	//
	// The idea is impractical, because you can't guarentee that the target is
	// reachable. As I see it, this is the reason why psNearest got introduced.
	// -- Dennis L.
	//
	// If many droids are heading towards the same destination, then destination
	// to source would be faster if reusing the information in nodeArray. --Cyp
	if (mustReverse)
	{
		// Copy the list, in reverse.
		std::copy(path.rbegin(), path.rend(), psMove->asPath);

		if (!context.isBlocked(tileOrig.x, tileOrig.y))  // If blocked, searching from tileDest to tileOrig wouldn't find the tileOrig tile.
		{
			// Next time, search starting from nearest reachable tile to the destination.
			fpathInitContext(context, psJob->blockingMap, tileDest, context.nearestCoord, tileOrig);
		}
	}
	else
	{
		// Copy the list.
		std::copy(path.begin(), path.end(), psMove->asPath);
	}

	// Move context to beginning of last recently used list.
	if (contextIterator != fpathContexts.begin())  // Not sure whether or not the splice is a safe noop, if equal.
	{
		fpathContexts.splice(fpathContexts.begin(), fpathContexts, contextIterator);
	}

	psMove->destination = psMove->asPath[path.size() - 1];

	return retval;
}
Example #7
0
File: main.cpp Project: CCJY/coliru
void operator()( std::list<T> & v ) const
{
    simple::serialize<int>::write(v.size());
    std::for_each(v.begin(),v.end(),*this);
}
Example #8
0
	void abrirPista(int idPista){
		thread_pista[idPista] = -1;
		if(landList.size()>0) NotifyLandingPlanesThatHadRunWay(idPista, idPista);
		else if(takeoffList.size()>0)NotifyTakeOffPlanesThatHadRunWay(idPista, idPista);
	}
Example #9
0
	void alertaFuracao(bool al){
		_furacao = al;
		if(_furacao == false && takeoffList.size()>0){
			NotifyTakeOffPlanesThatHadRunWay(0,1);
		}
	}
Example #10
0
        void UpdateAI(const uint32 uiDiff)
        {
            if (!UpdateVictim())
                return;

            switch (m_uiStage)
            {
                case 0:
                    if (m_uiFreezeSlashTimer <= uiDiff)
                    {
                        DoCastVictim(SPELL_FREEZE_SLASH);
                        m_uiFreezeSlashTimer = 15*IN_MILLISECONDS;
                    } else m_uiFreezeSlashTimer -= uiDiff;

                    if (m_uiPenetratingColdTimer <= uiDiff)
                    {
                        me->CastCustomSpell(RAID_MODE(SPELL_PENETRATING_COLD_10_N, SPELL_PENETRATING_COLD_25_N, SPELL_PENETRATING_COLD_10_H, SPELL_PENETRATING_COLD_25_H) , SPELLVALUE_MAX_TARGETS, RAID_MODE(2, 5));
                        m_uiPenetratingColdTimer = 20*IN_MILLISECONDS;
                    } else m_uiPenetratingColdTimer -= uiDiff;

                    if (m_uiSummonNerubianTimer <= uiDiff && (IsHeroic() || !m_bReachedPhase3))
                    {
                        me->CastCustomSpell(SPELL_SUMMON_BURROWER, SPELLVALUE_MAX_TARGETS, RAID_MODE(1, 2, 2, 4));
                        m_uiSummonNerubianTimer = 45*IN_MILLISECONDS;
                    } else m_uiSummonNerubianTimer -= uiDiff;

                    if (IsHeroic() && m_uiNerubianShadowStrikeTimer <= uiDiff)
                    {
                        Summons.DoAction(NPC_BURROWER, ACTION_SHADOW_STRIKE);
                        m_uiNerubianShadowStrikeTimer = 30*IN_MILLISECONDS;
                    } else m_uiNerubianShadowStrikeTimer -= uiDiff;

                    if (m_uiSubmergeTimer <= uiDiff && !m_bReachedPhase3 && !me->HasAura(SPELL_BERSERK))
                    {
                        m_uiStage = 1;
                        m_uiSubmergeTimer = 60*IN_MILLISECONDS;
                    } else m_uiSubmergeTimer -= uiDiff;
                    break;
                case 1:
                    DoCast(me, SPELL_SUBMERGE_ANUBARAK);
                    DoCast(me, SPELL_CLEAR_ALL_DEBUFFS);
                    me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE);
                    DoScriptText(SAY_BURROWER, me);
                    m_uiScarabSummoned = 0;
                    m_uiSummonScarabTimer = 4*IN_MILLISECONDS;
                    m_uiStage = 2;
                    break;
                case 2:
                    if (m_uiPursuingSpikeTimer <= uiDiff)
                    {
                        DoCast(SPELL_SPIKE_CALL);
                        // Just to make sure it won't happen again in this phase
                        m_uiPursuingSpikeTimer = 90*IN_MILLISECONDS;
                    } else m_uiPursuingSpikeTimer -= uiDiff;

                    if (m_uiSummonScarabTimer <= uiDiff)
                    {
                        /* WORKAROUND
                         * - The correct implementation is more likely the comment below but it needs spell knowledge
                         */
                        std::list<uint64>::iterator i = m_vBurrowGUID.begin();
                        uint32 at = urand(0, m_vBurrowGUID.size()-1);
                        for (uint32 k = 0; k < at; k++)
                            ++i;
                        if (Creature* pBurrow = Unit::GetCreature(*me, *i))
                            pBurrow->CastSpell(pBurrow, 66340, false);
                        m_uiScarabSummoned++;
                        m_uiSummonScarabTimer = 4*IN_MILLISECONDS;
                        if (m_uiScarabSummoned == 4) m_uiSummonScarabTimer = RAID_MODE(4, 20)*IN_MILLISECONDS;

                        /*It seems that this spell have something more that needs to be taken into account
                        //Need more sniff info
                        DoCast(SPELL_SUMMON_BEATLES);
                        // Just to make sure it won't happen again in this phase
                        m_uiSummonScarabTimer = 90*IN_MILLISECONDS;*/
                    } else m_uiSummonScarabTimer -= uiDiff;

                    if (m_uiSubmergeTimer <= uiDiff)
                    {
                        m_uiStage = 3;
                        m_uiSubmergeTimer = 80*IN_MILLISECONDS;
                    } else m_uiSubmergeTimer -= uiDiff;
                    break;
                case 3:
                    m_uiStage = 0;
                    DoCast(SPELL_SPIKE_TELE);
                    if (Creature* pSpike = Unit::GetCreature(*me, m_uiSpikeGUID))
                        me->NearTeleportTo(pSpike->GetPositionX(), pSpike->GetPositionY(), pSpike->GetPositionZ(), pSpike->GetOrientation());
                    Summons.DespawnEntry(NPC_SPIKE);
                    me->RemoveAurasDueToSpell(SPELL_SUBMERGE_ANUBARAK);
                    me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE);
                    DoCast(me, SPELL_EMERGE_ANUBARAK);
                    me->GetMotionMaster()->MoveChase(me->getVictim());
                    m_uiSummonNerubianTimer = 10*IN_MILLISECONDS;
                    m_uiNerubianShadowStrikeTimer = 30*IN_MILLISECONDS;
                    m_uiSummonScarabTimer = 2*IN_MILLISECONDS;
                    break;
            }

            if (!IsHeroic())
            {
                if (m_uiSummonFrostSphereTimer <= uiDiff)
                {
                    uint8 startAt = urand(0, 5);
                    uint8 i = startAt;
                    do
                    {
                        if (Unit* pSphere = Unit::GetCreature(*me, m_aSphereGUID[i]))
                        {
                            if (!pSphere->HasAura(SPELL_FROST_SPHERE))
                            {
                                if (Creature* summon = me->SummonCreature(NPC_FROST_SPHERE, SphereSpawn[i]))
                                    m_aSphereGUID[i] = summon->GetGUID();
                                break;
                            }
                        }
                        i = (i+1)%6;
                    } while (i != startAt);
                    m_uiSummonFrostSphereTimer = urand(20, 30)*IN_MILLISECONDS;
                } else m_uiSummonFrostSphereTimer -= uiDiff;
            }

            if (HealthBelowPct(30) && m_uiStage == 0 && !m_bReachedPhase3)
            {
                m_bReachedPhase3 = true;
                DoCastAOE(RAID_MODE(SPELL_LEECHING_SWARM_10_N, SPELL_LEECHING_SWARM_25_N, SPELL_LEECHING_SWARM_10_H, SPELL_LEECHING_SWARM_25_H));
                DoScriptText(EMOTE_LEECHING_SWARM, me);
                DoScriptText(SAY_LEECHING_SWARM, me);
            }

            if (m_uiBerserkTimer <= uiDiff && !me->HasAura(SPELL_BERSERK))
            {
                DoCast(me, SPELL_BERSERK);
            } else m_uiBerserkTimer -= uiDiff;

            DoMeleeAttackIfReady();
        }
Example #11
0
void cElXMLTree::GenAccessor
     (
          bool         Recurs,
          cElXMLTree * anAnc,
          int aProf,
          FILE* aFile,
          std::list<cElXMLTree *> & aList,  // Empile les fils pour imbrication
          bool isH
     )
{
// std::cout  << "GA " << mValTag << "\n";

   const std::string & aPat = ValAttr("Nb");
   aList.push_back(this);
   
   if (Recurs && ((aProf==0) || (aPat=="1") || (aPat=="?")))
   {
      for
      (
          std::list<cElXMLTree *>::iterator itF=mFils.begin();
          itF != mFils.end();
          itF++
      )
      {
           if (TagFilsIsClass((*itF)->mValTag))
           {
              std::string aDefAccFils = "true";
              bool GenAccFils = ((*itF)->ValAttr("AccessorFils",aDefAccFils)=="true");
              if ( !  HasAttr("RefType"))
                  (*itF)->GenAccessor(GenAccFils,anAnc,aProf+1,aFile,aList,isH);
           }
      }
   }
   if (aProf==0) 
      return;

   fprintf(aFile,"\n");
   std::string aPortee =  isH ? "" : (anAnc->NameOfClass()+"::");
   for (int aK=0 ; aK<2; aK++) // aK : 1 Const - 0 Non Const
   {
        std::string aContsQual = (aK==0) ? "" : "const ";

 // if (aProf !=1) fprintf(aFileH," // %d ",aProf);
        if (isH) fprintf(aFile,"        ");
        fprintf
        (
                aFile,
                "%s%s & %s%s()%s",
                aContsQual.c_str(),
                NameImplemOfClass().c_str(),
                aPortee.c_str(),
                mValTag.c_str(),
                aContsQual.c_str()
         );
         
         if (isH)
         {
             fprintf(aFile,";\n");
         }
         else
         {
             fprintf(aFile,"\n");
             fprintf(aFile,"{\n"); 
             fprintf(aFile,"   return ");
             if (aProf ==1)
                 fprintf(aFile,"m%s",mValTag.c_str());
             else
             {
                std::list<cElXMLTree *>::iterator itT = aList.begin();
                itT++;
                int aK=0;
                int aL = (int) aList.size();
                while (itT != aList.end())
                {
                   if (aK!=0)  fprintf(aFile,".");
                   fprintf(aFile,"%s()",(*itT)->mValTag.c_str());
                   const std::string & aPatLoc = (*itT)->ValAttr("Nb");
                   if ((aK!= aL-2) && (aPatLoc == "?"))
                      fprintf(aFile,".Val()");
                   itT++;
                   aK++;
                }
             }
             fprintf(aFile,";\n");
             fprintf(aFile,"}\n\n");
         }
   }  
   aList.pop_back();
}
Example #12
0
void output_html_results(bool show_description, const std::string& tagname)
{
   std::stringstream os;
   if(result_list.size())
   {
      //
      // start by outputting the table header:
      //
      os << "<table border=\"1\" cellspacing=\"1\">\n";
      os << "<tr><td><strong>Expression</strong></td>";
      if(show_description)
         os << "<td><strong>Text</strong></td>";
#if defined(BOOST_HAS_GRETA)
      if(time_greta == true)
         os << "<td><strong>GRETA</strong></td>";
      if(time_safe_greta == true)
         os << "<td><strong>GRETA<BR>(non-recursive mode)</strong></td>";
#endif
      if(time_boost == true)
         os << "<td><strong>Boost</strong></td>";
      if(time_localised_boost == true)
         os << "<td><strong>Boost + C++ locale</strong></td>";
#if defined(BOOST_HAS_POSIX)
      if(time_posix == true)
         os << "<td><strong>POSIX</strong></td>";
#endif
#ifdef BOOST_HAS_PCRE
      if(time_pcre == true)
         os << "<td><strong>PCRE</strong></td>";
#endif
#ifdef BOOST_HAS_XPRESSIVE
      if(time_xpressive == true)
         os << "<td><strong>Dynamic Xpressive</strong></td>";
#endif
#ifndef BOOST_NO_CXX11_HDR_REGEX
      if(time_std == true)
         os << "<td><strong>std::regex</strong></td>";
#endif
      os << "</tr>\n";

      //
      // Now enumerate through all the test results:
      //
      std::list<results>::const_iterator first, last;
      first = result_list.begin();
      last = result_list.end();
      while(first != last)
      {
         os << "<tr><td><code>" << html_quote(first->expression) << "</code></td>";
         if(show_description)
            os << "<td>" << html_quote(first->description) << "</td>";
#if defined(BOOST_HAS_GRETA)
         if(time_greta == true)
         {
            print_result(os, first->greta_time, first->factor);
            if(first->greta_time > 0)
            {
               greta_total += first->greta_time / first->factor;
               ++greta_test_count;
            }
         }
         if(time_safe_greta == true)
         {
            print_result(os, first->safe_greta_time, first->factor);
            if(first->safe_greta_time > 0)
            {
               safe_greta_total += first->safe_greta_time / first->factor;
               ++safe_greta_test_count;
            }
         }
#endif
         if(time_boost == true)
         {
            print_result(os, first->boost_time, first->factor);
            if(first->boost_time > 0)
            {
               boost_total += first->boost_time / first->factor;
               ++boost_test_count;
            }
         }
         if(time_localised_boost == true)
         {
            print_result(os, first->localised_boost_time, first->factor);
            if(first->localised_boost_time > 0)
            {
               locale_boost_total += first->localised_boost_time / first->factor;
               ++locale_boost_test_count;
            }
         }
         if(time_posix == true)
         {
            print_result(os, first->posix_time, first->factor);
            if(first->posix_time > 0)
            {
               posix_total += first->posix_time / first->factor;
               ++posix_test_count;
            }
         }
#if defined(BOOST_HAS_PCRE)
         if(time_pcre == true)
         {
            print_result(os, first->pcre_time, first->factor);
            if(first->pcre_time > 0)
            {
               pcre_total += first->pcre_time / first->factor;
               ++pcre_test_count;
            }
         }
#endif
#if defined(BOOST_HAS_XPRESSIVE)
         if(time_xpressive == true)
         {
            print_result(os, first->xpressive_time, first->factor);
            if(first->xpressive_time > 0)
            {
               xpressive_total += first->xpressive_time / first->factor;
               ++xpressive_test_count;
            }
         }
#endif
#ifndef BOOST_NO_CXX11_HDR_REGEX
         if(time_std == true)
         {
            print_result(os, first->std_time, first->factor);
            if(first->std_time > 0)
            {
               std_total += first->std_time / first->factor;
               ++std_test_count;
            }
         }
#endif
         os << "</tr>\n";
         ++first;
      }
      os << "</table>\n";
      result_list.clear();
   }
   else
   {
      os << "<P><I>Results not available...</I></P>\n";
   }

   std::string result = os.str();

   std::string::size_type pos = html_contents.find(tagname);
   if(pos != std::string::npos)
   {
      html_contents.replace(pos, tagname.size(), result);
   }
}
bool ccContourExtractor::ExtractConcaveHull2D(	std::vector<Vertex2D>& points,
												std::list<Vertex2D*>& hullPoints,
												ContourType contourType,
												bool allowMultiPass,
												PointCoordinateType maxSquareEdgeLength/*=0*/,
												bool enableVisualDebugMode/*=false*/,
												double maxAngleDeg/*=0.0*/)
{
	//first compute the Convex hull
	if (!CCLib::PointProjectionTools::extractConvexHull2D(points,hullPoints))
		return false;

	//do we really need to compute the concave hull?
	if (hullPoints.size() < 2 || maxSquareEdgeLength < 0)
		return true;

	unsigned pointCount = static_cast<unsigned>(points.size());

	std::vector<HullPointFlags> pointFlags;
	try
	{
		pointFlags.resize(pointCount, POINT_NOT_USED);
	}
	catch(...)
	{
		//not enough memory
		return false;
	}

	double minCosAngle = maxAngleDeg <= 0 ? -1.0 : std::cos(maxAngleDeg * M_PI / 180.0);

	//hack: compute the theoretical 'minimal' edge length
	PointCoordinateType minSquareEdgeLength = 0;
	{
		CCVector2 minP, maxP;
		for (size_t i=0; i<pointCount; ++i)
		{
			const Vertex2D& P = points[i];
			if (i)
			{
				minP.x = std::min(P.x,minP.x);
				minP.y = std::min(P.y,minP.y);
				maxP.x = std::max(P.x,maxP.x);
				maxP.y = std::max(P.y,maxP.y);
			}
			else
			{
				minP = maxP = P;
			}
		}
		minSquareEdgeLength = (maxP - minP).norm2() / static_cast<PointCoordinateType>(1.0e7); //10^-7 of the max bounding rectangle side
		minSquareEdgeLength = std::min(minSquareEdgeLength, maxSquareEdgeLength / 10);

		//we remove very small edges
		for (VertexIterator itA = hullPoints.begin(); itA != hullPoints.end(); ++itA)
		{
			VertexIterator itB = itA; ++itB;
			if (itB == hullPoints.end())
				itB = hullPoints.begin();
			if ((**itB-**itA).norm2() < minSquareEdgeLength)
			{
				pointFlags[(*itB)->index] = POINT_FROZEN;
				hullPoints.erase(itB);
			}
		}

		if (contourType != FULL)
		{
			//we will now try to determine which part of the contour is the 'upper' one and which one is the 'lower' one

			//search for the min and max vertices
			VertexIterator itLeft = hullPoints.begin();
			VertexIterator itRight = hullPoints.begin();
			{
				for (VertexIterator it = hullPoints.begin(); it != hullPoints.end(); ++it)
				{
					if ((*it)->x < (*itLeft)->x || ((*it)->x == (*itLeft)->x && (*it)->y < (*itLeft)->y))
					{
						itLeft = it;
					}
					if ((*it)->x > (*itRight)->x || ((*it)->x == (*itRight)->x && (*it)->y < (*itRight)->y))
					{
						itRight = it;
					}
				}
			}
			assert(itLeft != itRight);
			//find the right way to go
			{
				VertexIterator itBefore = itLeft;
				if (itBefore == hullPoints.begin())
					itBefore = hullPoints.end(); --itBefore;
				VertexIterator itAfter = itLeft; ++itAfter;
				if (itAfter == hullPoints.end())
					itAfter = hullPoints.begin();

				bool forward = ((**itBefore - **itLeft).cross(**itAfter - **itLeft) < 0 && contourType == LOWER);
				if (!forward)
					std::swap(itLeft,itRight);
			}

			//copy the right part
			std::list<Vertex2D*> halfHullPoints;
			try
			{
				for (VertexIterator it = itLeft; ; ++it)
				{
					if (it == hullPoints.end())
						it = hullPoints.begin();
					halfHullPoints.push_back(*it);
					if (it == itRight)
						break;
				}
			}
			catch (const std::bad_alloc&)
			{
				//not enough memory
				return false;
			}
			//replace the input hull by the selected part
			hullPoints = halfHullPoints;
		}

		if (hullPoints.size() < 2)
		{
			//no more edges?!
			return false;
		}
	}


	//DEBUG MECHANISM
	ccContourExtractorDlg debugDialog;
	ccPointCloud* debugCloud = 0;
	ccPolyline* debugContour = 0;
	ccPointCloud* debugContourVertices = 0;
	if (enableVisualDebugMode)
	{
		debugDialog.init();
		debugDialog.setGeometry(50,50,800,600);
		debugDialog.show();

		//create point cloud with all (2D) input points
		{
			debugCloud = new ccPointCloud;
			debugCloud->reserve(pointCount);
			for (size_t i=0; i<pointCount; ++i)
			{
				const Vertex2D& P = points[i];
				debugCloud->addPoint(CCVector3(P.x,P.y,0));
			}
			debugCloud->setPointSize(3);
			debugDialog.addToDisplay(debugCloud,false); //the window will take care of deleting this entity!
		}

		//create polyline
		{
			debugContourVertices = new ccPointCloud;
			debugContour = new ccPolyline(debugContourVertices);
			debugContour->addChild(debugContourVertices);
			unsigned hullSize = static_cast<unsigned>(hullPoints.size());
			debugContour->reserve(hullSize);
			debugContourVertices->reserve(hullSize);
			unsigned index = 0;
			for (VertexIterator itA = hullPoints.begin(); itA != hullPoints.end(); ++itA, ++index)
			{
				const Vertex2D* P = *itA;
				debugContourVertices->addPoint(CCVector3(P->x,P->y,0));
				debugContour->addPointIndex(index/*(*itA)->index*/);
			}
			debugContour->setColor(ccColor::red);
			debugContourVertices->setEnabled(false);
			debugContour->setClosed(contourType == FULL);
			debugDialog.addToDisplay(debugContour,false); //the window will take care of deleting this entity!
		}

		//set zoom
		{
			ccBBox box = debugCloud->getOwnBB();
			debugDialog.zoomOn(box);
		}
		debugDialog.refresh();
	}

	//Warning: high STL containers usage ahead ;)
	unsigned step = 0;
	bool somethingHasChanged = true;
	while (somethingHasChanged)
	{
		try
		{
			somethingHasChanged = false;
			++step;

			//reset point flags
			//for (size_t i=0; i<pointCount; ++i)
			//{
			//	if (pointFlags[i] != POINT_FROZEN)
			//		pointFlags[i] = POINT_NOT_USED;
			//}

			//build the initial edge list & flag the convex hull points
			std::multiset<Edge> edges;
			//initial number of edges
			assert(hullPoints.size() >= 2);
			size_t initEdgeCount = hullPoints.size();
			if (contourType != FULL)
				--initEdgeCount;

			VertexIterator itB = hullPoints.begin();
			for (size_t i=0; i<initEdgeCount; ++i)
			{
				VertexIterator itA = itB; ++itB;
				if (itB == hullPoints.end())
					itB = hullPoints.begin();

				//we will only process the edges that are longer than the maximum specified length
				if ((**itB - **itA).norm2() > maxSquareEdgeLength)
				{
					unsigned nearestPointIndex = 0;
					PointCoordinateType minSquareDist = FindNearestCandidate(
						nearestPointIndex,
						itA,
						itB,
						points,
						pointFlags,
						minSquareEdgeLength,
						step > 1,
						minCosAngle);

					if (minSquareDist >= 0)
					{
						Edge e(itA, nearestPointIndex, minSquareDist);
						edges.insert(e);
					}
				}

				pointFlags[(*itA)->index] = POINT_USED;
			}

			//flag the last vertex as well for non closed contours!
			if (contourType != FULL)
				pointFlags[(*hullPoints.rbegin())->index] = POINT_USED;

			while (!edges.empty())
			{
				//current edge (AB)
				//this should be the edge with the nearest 'candidate'
				Edge e = *edges.begin();
				edges.erase(edges.begin());

				VertexIterator itA = e.itA;
				VertexIterator itB = itA; ++itB;
				if (itB == hullPoints.end())
				{
					assert(contourType == FULL);
					itB = hullPoints.begin();
				}

				//nearest point
				const Vertex2D& P = points[e.nearestPointIndex];
				assert(pointFlags[P.index] == POINT_NOT_USED); //we don't consider already used points!

				//create labels
				cc2DLabel* edgeLabel = 0;
				cc2DLabel* label = 0;
				if (enableVisualDebugMode && !debugDialog.isSkipped())
				{
					edgeLabel = new cc2DLabel("edge");
					unsigned indexA = 0;
					unsigned indexB = 0;
					for (size_t i=0; i<pointCount; ++i)
					{
						const Vertex2D& P = points[i];
						if (&P == *itA)
							indexA = static_cast<unsigned>(i);
						if (&P == *itB)
							indexB = static_cast<unsigned>(i);
					}
					edgeLabel->addPoint(debugCloud,indexA);
					edgeLabel->addPoint(debugCloud,indexB);
					edgeLabel->setVisible(true);
					edgeLabel->setDisplayedIn2D(false);
					debugDialog.addToDisplay(edgeLabel);
					debugDialog.refresh();

					label = new cc2DLabel("nearest point");
					label->addPoint(debugCloud,e.nearestPointIndex);
					label->setVisible(true);
					label->setSelected(true);
					debugDialog.addToDisplay(label);
					debugDialog.displayMessage(QString("nearest point found index #%1 (dist = %2)").arg(e.nearestPointIndex).arg(sqrt(e.nearestPointSquareDist)),true);
				}

				//check that we don't create too small edges!
				//CCVector2 AP = (P-**itA);
				//CCVector2 PB = (**itB-P);
				//PointCoordinateType squareLengthAP = (P-**itA).norm2();
				//PointCoordinateType squareLengthPB = (**itB-P).norm2();
				////at least one of the new segments must be smaller than the initial one!
				//assert( squareLengthAP < e.squareLength || squareLengthPB < e.squareLength );
				//if (squareLengthAP < minSquareEdgeLength || squareLengthPB < minSquareEdgeLength)
				//{
				//	pointFlags[P.index] = POINT_IGNORED;
				//	edges.push(e); //retest the edge!
				//	if (enableVisualDebugMode)
				//		debugDialog.displayMessage("nearest point is too close!",true);
				//}

				//last check: the new segments must not intersect with the actual hull!
				bool intersect = false;
				//if (false)
				{
					for (VertexIterator itJ = hullPoints.begin(), itI = itJ++; itI != hullPoints.end(); ++itI, ++itJ)
					{
						if (itJ == hullPoints.end())
						{
							if (contourType == FULL)
								itJ = hullPoints.begin();
							else
								break;
						}

						if (	((*itI)->index != (*itA)->index && (*itJ)->index != (*itA)->index && CCLib::PointProjectionTools::segmentIntersect(**itI,**itJ,**itA,P))
							||	((*itI)->index != (*itB)->index && (*itJ)->index != (*itB)->index && CCLib::PointProjectionTools::segmentIntersect(**itI,**itJ,P,**itB)) )
						{
							intersect = true;
							break;
						}
					}
				}
				if (!intersect)
				{
					//add point to concave hull
					VertexIterator itP = hullPoints.insert(itB == hullPoints.begin() ? hullPoints.end() : itB, &points[e.nearestPointIndex]);

					//we won't use P anymore!
					pointFlags[P.index] = POINT_USED;

					somethingHasChanged = true;

					if (enableVisualDebugMode && !debugDialog.isSkipped())
					{
						if (debugContour)
						{
							debugContourVertices->clear();
							unsigned hullSize = static_cast<unsigned>(hullPoints.size());
							debugContourVertices->reserve(hullSize);
							unsigned index = 0;
							for (VertexIterator it = hullPoints.begin(); it != hullPoints.end(); ++it, ++index)
							{
								const Vertex2D* P = *it;
								debugContourVertices->addPoint(CCVector3(P->x,P->y,0));
							}
							debugContour->reserve(hullSize);
							debugContour->addPointIndex(hullSize-1);
							debugDialog.refresh();
						}
						debugDialog.displayMessage("point has been added to contour",true);
					}

					//update all edges that were having 'P' as their nearest candidate as well
					if (!edges.empty())
					{
						std::vector<VertexIterator> removed;
						std::multiset<Edge>::const_iterator lastValidIt = edges.end();
						for (std::multiset<Edge>::const_iterator it = edges.begin(); it != edges.end(); ++it)
						{
							if ((*it).nearestPointIndex == e.nearestPointIndex)
							{
								//we'll have to put them back afterwards!
								removed.push_back((*it).itA);
							
								edges.erase(it);
								if (edges.empty())
									break;
								if (lastValidIt != edges.end())
									it = lastValidIt;
								else
									it = edges.begin();
							}
							else
							{
								lastValidIt = it;
							}
						}

						//update the removed edges info and put them back in the main list
						for (size_t i = 0; i < removed.size(); ++i)
						{
							VertexIterator itC = removed[i];
							VertexIterator itD = itC; ++itD;
							if (itD == hullPoints.end())
								itD = hullPoints.begin();
						
							unsigned nearestPointIndex = 0;
							PointCoordinateType minSquareDist = FindNearestCandidate(
								nearestPointIndex,
								itC,
								itD,
								points,
								pointFlags,
								minSquareEdgeLength,
								false,
								minCosAngle);

							if (minSquareDist >= 0)
							{
								Edge e(itC, nearestPointIndex, minSquareDist);
								edges.insert(e);
							}
						}
					}

					//we'll inspect the two new segments later (if necessary)
					if ((P-**itA).norm2() > maxSquareEdgeLength)
					{
						unsigned nearestPointIndex = 0;
						PointCoordinateType minSquareDist = FindNearestCandidate(
							nearestPointIndex,
							itA,
							itP,
							points,
							pointFlags,
							minSquareEdgeLength,
							false,
							minCosAngle);

						if (minSquareDist >= 0)
						{
							Edge e(itA,nearestPointIndex,minSquareDist);
							edges.insert(e);
						}
					}
					if ((**itB-P).norm2() > maxSquareEdgeLength)
					{
						unsigned nearestPointIndex = 0;
						PointCoordinateType minSquareDist = FindNearestCandidate(
							nearestPointIndex,
							itP,
							itB,
							points,
							pointFlags,
							minSquareEdgeLength,
							false,
							minCosAngle);

						if (minSquareDist >= 0)
						{
							Edge e(itP,nearestPointIndex,minSquareDist);
							edges.insert(e);
						}
					}
				}
				else
				{
					if (enableVisualDebugMode)
						debugDialog.displayMessage("[rejected] new edge would intersect the current contour!",true);
				}
			
				//remove labels
				if (label)
				{
					assert(enableVisualDebugMode);
					debugDialog.removFromDisplay(label);
					delete label;
					label = 0;
					//debugDialog.refresh();
				}

				if (edgeLabel)
				{
					assert(enableVisualDebugMode);
					debugDialog.removFromDisplay(edgeLabel);
					delete edgeLabel;
					edgeLabel = 0;
					//debugDialog.refresh();
				}
			}
		}
		catch (...)
		{
			//not enough memory
			return false;
		}

		if (!allowMultiPass)
			break;
	}

	return true;
}
Example #14
0
 /// Check if the memory block is empty.
 inline bool is_empty() const
 {
     return (free_subblocks_.size() == 1 &&
             free_subblocks_.front().first == 0 &&
             free_subblocks_.front().second == size_);
 }
Example #15
0
bool IGFrame::ManageSelection (const IGLibrary::SELECTIONPARAMS& selParams, const std::list<POINT>& lPts)
{
	// Request thread access
	if (!RequestAccess ())
		return false;
	CxImage *pCurrentLayer = GetWorkingLayer();
	if (!pCurrentLayer)
		return false;
	int nCurLayerId = (int)pCurrentLayer->GetId();
	int nCurLayerWidth = (int)pCurrentLayer->GetWidth();
	int nCurLayerHeight = (int)pCurrentLayer->GetHeight();
	_ASSERTE ((nCurLayerId >= 0) && L"Current layer is not identified");
	if (nCurLayerId < 0)
		return false;
	bool bRes = false;
	POINT ptTopLeft = {0, 0};
	POINT ptBottomRight = {-1, -1};
	IGSELECTIONENUM eSelectionType = selParams.eSelectionType;
	if (((eSelectionType & IGSELECTION_SQUARE) == IGSELECTION_SQUARE) ||
		((eSelectionType & IGSELECTION_LASSO) == IGSELECTION_LASSO))
	{
		if (lPts.size() > 0)
		{
			bool bAllEqual = true;
			for (list <POINT>::const_iterator itPt = lPts.cbegin(); itPt != lPts.cend(); ++itPt)
			{
				if (((*itPt).x != lPts.front().x) || ((*itPt).y != lPts.front().y))
					bAllEqual = false;
			}
			if (bAllEqual)
				eSelectionType = IGSELECTION_CLEAR;
		}
	}
	if ((eSelectionType & IGSELECTION_CLEAR) == IGSELECTION_CLEAR)
	{
		if ((eSelectionType & IGSELECTION_INVERT) == IGSELECTION_INVERT)
			bRes = pCurrentLayer->SelectionInvert();
		else
			bRes = pCurrentLayer->SelectionDelete();
	}
	else
	{
		if ((eSelectionType & IGSELECTION_REPLACE) == IGSELECTION_REPLACE)
			pCurrentLayer->SelectionClear();	
		BYTE level = ((eSelectionType & IGSELECTION_REMOVE) == IGSELECTION_REMOVE) ? 0 : 255;

		std::list<POINT> lConvertedPts (lPts); 
		// convert IG coordinates to Cx coordinates
		IGConvertible::FromIGtoCxCoords(lConvertedPts, pCurrentLayer->GetHeight());
	
		// apply selection
		if ((eSelectionType & IGSELECTION_SQUARE) == IGSELECTION_SQUARE)
		{
			if (lPts.size() != 2)
				return false;	
			// read rectangle coordinates
			ptTopLeft = lConvertedPts.front();
			ptBottomRight = lConvertedPts.back();
			int nPosX = ptTopLeft.x;
			int nPosY = ptBottomRight.y;
			RECT rcSel;
			rcSel.left = nPosX; rcSel.top = nPosY;
			nPosX = ptBottomRight.x;
			nPosY = ptTopLeft.y;
			rcSel.right = nPosX; rcSel.bottom = nPosY;
			// adjust rectangle orientation
			int nWidth = rcSel.right - rcSel.left;
			int nHeight = rcSel.top - rcSel.bottom;
			nWidth = (nWidth < 0) ? -1 * nWidth : nWidth;
			nHeight = (nHeight < 0) ? -1 * nHeight : nHeight;
			rcSel.left = (rcSel.left < rcSel.right) ? rcSel.left : rcSel.right;
			rcSel.bottom = (rcSel.bottom < rcSel.top) ? rcSel.bottom : rcSel.top;
			rcSel.right = rcSel.left + nWidth;
			rcSel.top = rcSel.bottom + nHeight;
			// test if rectangle is inside the frame
			if ((rcSel.right < 0) || (rcSel.left >= nCurLayerWidth)
				|| (rcSel.top < 0) || (rcSel.bottom >= nCurLayerHeight))
				return false;	// selection out of bounds
			// adjust bounds
			rcSel.left = (rcSel.left < 0) ? 0 : rcSel.left;
			rcSel.right = (rcSel.right >= nCurLayerWidth) ? nCurLayerWidth - 1 : rcSel.right;
			rcSel.bottom = (rcSel.bottom < 0) ? 0 : rcSel.bottom;
			rcSel.top = (rcSel.top >= nCurLayerHeight) ? nCurLayerHeight - 1 : rcSel.top;
			// add the selection
			bRes = pCurrentLayer->SelectionAddRect (rcSel, level);
		}
		else if ((eSelectionType & IGSELECTION_LASSO) == IGSELECTION_LASSO)
		{
			bRes = pCurrentLayer->SelectionAddPolygon (lConvertedPts, level);
		}
		else if ((eSelectionType & IGSELECTION_MAGIC) == IGSELECTION_MAGIC)
		{
			bRes = pCurrentLayer->SelectionAddMagic (lConvertedPts.front(), level, selParams.nTolerance);
		}
		else if ((eSelectionType & IGSELECTION_FACES) == IGSELECTION_FACES)
		{
			bRes = pCurrentLayer->SelectionAddFaces (level);
		}
		else if ((eSelectionType & IGSELECTION_EYES) == IGSELECTION_EYES)
		{
			bRes = pCurrentLayer->SelectionAddEyes (level);
		}
		else if ((eSelectionType & IGSELECTION_MOUTH) == IGSELECTION_MOUTH)
		{
			bRes = pCurrentLayer->SelectionAddMouth (level);
		}
		else if ((eSelectionType & IGSELECTION_NOZE) == IGSELECTION_NOZE)
		{
			bRes = pCurrentLayer->SelectionAddNoze (level);
		}
		else if ((eSelectionType & IGSELECTION_LPE) == IGSELECTION_LPE)
		{
			bRes = pCurrentLayer->SelectionAddLPE (lConvertedPts, level);
		}
		if (ptBottomRight.x < ptTopLeft.x)
		{
			int nSwap = ptTopLeft.x;
			ptTopLeft.x = ptBottomRight.x;
			ptBottomRight.x = nSwap;
		}
		if (ptBottomRight.y < ptTopLeft.y)
		{
			int nSwap = ptTopLeft.y;
			ptTopLeft.y = ptBottomRight.y;
			ptBottomRight.y = nSwap;
		}
		if (ptTopLeft.x < 0)
			ptTopLeft.x = 0;
		if (ptTopLeft.y < 0)
			ptTopLeft.y = 0;
		if (ptBottomRight.x >= nCurLayerWidth)
			ptBottomRight.x = nCurLayerWidth - 1;
		if (ptBottomRight.y >= nCurLayerHeight)
			ptBottomRight.y = nCurLayerHeight - 1;
	}
	if (!pCurrentLayer->SelectionIsValid())
		pCurrentLayer->SelectionDelete();
	AddNewStep (IGFRAMEHISTORY_STEP_SELECTION, L"Change selection", (int)&selParams, (int)&lPts);
	Redraw (true);
	return bRes;
}
Example #16
0
//Call the rejointMesh in RejointMeshes.cpp on the meshes that have distance with targetPoint greater than double distance
// use isExternJoin = true to joint the extern meshes, use isExternJoin = false to joint the internal meshes
std::list<MeshData> rejointMeshesInDistance(std::list<MeshData> &listMeshData, KDPoint targetPoint, double distance, double isExternJoin)
{
	std::list<MeshData> result;
	std::list<MeshData> meshesToJoin;
	double squaredDistance = distance * distance;
	PointCGAL exactTargetPoint(targetPoint.x(), targetPoint.y(), targetPoint.z());

	std::list<MeshData>::iterator meshDataInter;
	for(meshDataInter = listMeshData.begin(); meshDataInter != listMeshData.end(); ++meshDataInter)
	{
		bool meshIsOutOfDistance = true; //Algorithm 1
		//bool meshIsOutOfDistance = false; //Algorithm 2
		std::list<Triangle>::iterator triangleIter;
		for(triangleIter = meshDataInter->first.begin(); triangleIter != meshDataInter->first.end(); ++triangleIter)
		{
			Triangle t = *triangleIter;

			//Algorithm 1: This algorithm excludes from the join the meshes on the radius
			for (int i = 0; i < 3; ++i)
			{
				PointCGAL tv = t.vertex(i);

				//it could be used a logic XNOR but it is not so understable, so I use this condition
				if (isExternJoin)
				{
					if (CGAL::squared_distance(tv, exactTargetPoint) < squaredDistance)
					{
						meshIsOutOfDistance = false;
					}
				}
				else
				{
					if (CGAL::squared_distance(tv, exactTargetPoint) > squaredDistance)
					{
						meshIsOutOfDistance = false;
					}
				}
			}
			if (!meshIsOutOfDistance)
			{
				break;
			}


			/*
			//Algorithm 2: This algorithm includes from the join the meshes on the radius
			//Ideale per pezzi piccoli e dominio dei punti voronoi dentro il raggio,
			// sembra funzionare solo per isExternJoin, TODO: test
			for (int i = 0; i < 3; ++i)
			{
				PointCGAL tv = t.vertex(i);

				if (isExternJoin)
				{
					if (CGAL::squared_distance(tv, exactTargetPoint) > squaredDistance)
					{
						meshIsOutOfDistance = true;
					}
				}
				else
				{
					if (CGAL::squared_distance(tv, exactTargetPoint) < squaredDistance)
					{
						meshIsOutOfDistance = true;
					}
				}
			}
			if (meshIsOutOfDistance)
			{
				break;
			}
			*/

		}

		if (meshIsOutOfDistance)
		{
			meshesToJoin.push_back(*meshDataInter);
		}
		else
		{
			result.push_back(*meshDataInter);
		}
	}

	if (meshesToJoin.size() > 0)
	{
		MeshData rejointMeshes = simpleRejointMeshes(meshesToJoin);
		//MeshData rejointMeshes = rejointMeshes(meshesToJoin);
		result.push_back(rejointMeshes);
	}

	std::cout << "Executed rejointMeshesInDistance: not joined meshes: " << (listMeshData.size() - meshesToJoin.size()) << ", joined meshes: " << meshesToJoin.size() << std::endl;

	return result;

}
 void FilterTargets(std::list<WorldObject*>& targets)
 {
     targets.remove_if(Trinity::UnitAuraCheck(true, SPELL_SABER_LASH_IMMUNITY));
     if (targets.size() <= 1)
         FinishCast(SPELL_FAILED_DONT_REPORT);
 }
Example #18
0
bool FramePlay()
{
	if(play == 1)
	{
		if (level == 1)
		{
			ins = 7;
			beee = 2;
			hpp = 1;
		}
		else if (level == 2)
		{
			ins = 5;
			beee = 3;
			hpp = 1;
		}
		else if (level == 3)
		{
			ins = 3;
			beee = 5;
			hpp = 3;
		}
		else if (level == 4)
		{
			ins = 3;
			beee = 0;
			hpp = 3;
			bs = 1;
		}
		float delta = hge->Timer_GetDelta();
		//Insects
		if (Insects.size() < ins)
		{
			short Health = hge->Random_Int(50, 100);

			insects* Insect = new insects(hgeVector(hge->Random_Int(10, 800), 40), hgeVector(-hge->Random_Int(-4, 4), hge->Random_Int(1, 1)), g_tEColors[hge->Random_Int(0, 4)]);

			Insects.push_back(Insect);
		}

		for (auto i = Insects.begin(); i != Insects.end();)
		{
			if ((*i)->GetPosition().x < 0 || (*i)->GetPosition().y > 580 || (*i)->GetPosition().y < 20)
			{
				delete (*i);
				i = Insects.erase(i);
			}
			else
			{
				(*i)->Update(delta);
				i++;
			}
		}
		//Bee
		if (Bees.size() < beee)
		{
			short Health = hge->Random_Int(50, 100);
			bee* Bee = new bee(hgeVector(hge->Random_Int(10, 800), 40), hgeVector(-hge->Random_Int(-4, 4), hge->Random_Int(1, 1)), g_bee[hge->Random_Int(0, 1)]);
			Bees.push_back(Bee);
		}

		for (auto i = Bees.begin(); i != Bees.end();)
		{
			if ((*i)->GetPosition().x < 0 || (*i)->GetPosition().y > 580 || (*i)->GetPosition().y < 20)
			{
				delete (*i);
				i = Bees.erase(i);
			}
			else
			{
				(*i)->Update(delta);
				i++;
			}
		}
		//boss
		if (Bosses.size() < bs)
		{
			short Health = hge->Random_Int(50, 100);
			boss* Boss = new boss(hgeVector(hge->Random_Int(10, 800), 40), hgeVector(-hge->Random_Int(-4, 4), hge->Random_Int(1, 1)), g_boss[hge->Random_Int(0, 1)]);
			Bosses.push_back(Boss);
		}

		for (auto i = Bosses.begin(); i != Bosses.end();)
		{
			if ((*i)->GetPosition().x < 0 || (*i)->GetPosition().y > 580 || (*i)->GetPosition().y < 20)
			{
				delete (*i);
				i = Bosses.erase(i);
			}
			else
			{
				(*i)->Update(delta);
				i++;
			}
		}
		//Player
		Player1->Update(delta);

		//PB
		if (count != 0 && count % 5 == 0 && PB.size() < 2)
		{
			short Health = hge->Random_Int(50, 100);
			point_bonus* point_bon = new point_bonus(hgeVector(hge->Random_Int(10, 800), 40), hgeVector(-hge->Random_Int(-4, 4), hge->Random_Int(1, 1)), g_pb[hge->Random_Int(0, 1)]);
			PB.push_back(point_bon);
		}

		for (auto i = PB.begin(); i != PB.end();)
		{
			if ((*i)->GetPosition().x < 0 || (*i)->GetPosition().y > 580 || (*i)->GetPosition().y < 20)
			{
				i = PB.erase(i);
			}
			else
			{
				(*i)->Update(delta);
				i++;
			}
		}
		//HPB
		if (HPB.size() < 2 && hp < 3 && count != 0 && count % 5 == 0)
		{
			short Health = hge->Random_Int(50, 100);
			hp_bonus* hp_bon = new hp_bonus(hgeVector(hge->Random_Int(10, 800), 40), hgeVector(-hge->Random_Int(-4, 4), hge->Random_Int(1, 1)), g_hpb[hge->Random_Int(0, 1)]);
			HPB.push_back(hp_bon);
		}

		for (auto i = HPB.begin(); i != HPB.end();)
		{
			if ((*i)->GetPosition().x < 0 || (*i)->GetPosition().y > 580 || (*i)->GetPosition().y < 20)
			{
				i = HPB.erase(i);
			}
			else
			{
				(*i)->Update(delta);
				i++;
			}
		}
		//Insects vs Player
		for (auto i = Insects.begin(); i != Insects.end();)
		{
			if ((*i)->GetBoundingBox().Intersect(&Player1->GetBoundingBox()))
			{
				delete (*i);
				i = Insects.erase(i);
				count++;
			}
			else i++;
		}
		//BOSS vs Player
		for (auto i = Bosses.begin(); i != Bosses.end();)
		{
			if ((*i)->GetBoundingBox().Intersect(&Player1->GetBoundingBox()))
			{
				delete (*i);
				i = Bosses.erase(i);
				if (count>175 && count<185)
					hp=hp-2;
				else if(count>200)
				{
					count=count+200;
					MessageBox(NULL, "You're WIN!!!", "WIN", MB_OK);
					play = 0;
					gui->Enter();
				}
			}
			else i++;
		}
		//Bee vs Player
		for (auto i = Bees.begin(); i != Bees.end();)
		{
			if ((*i)->GetBoundingBox().Intersect(&Player1->GetBoundingBox()))
			{
				delete (*i);
				i = Bees.erase(i);
				hp = hp - hpp;
			}
			else i++;
		}
		if (hp == 0 || hp < 0 )
		{
			MessageBox(NULL, "GAME OVER! Your HP - 0", "Game Over", MB_OK);
			play = 0;
			gui->Enter();
			return true;
		}
		//PB vs PLayer
		for (auto i = PB.begin(); i != PB.end();)
		{
			if ((*i)->GetBoundingBox().Intersect(&Player1->GetBoundingBox()))
			{
				(*i)->Bonus();
				i = PB.erase(i);
			}
			else i++;
		}
		//HPB vs PLayer
		for (auto i = HPB.begin(); i != HPB.end();)
		{
			if ((*i)->GetBoundingBox().Intersect(&Player1->GetBoundingBox()))
			{
				if (hp<5)
					(*i)->Bonus();
				i = HPB.erase(i);

			}
			else i++;
		}
		if (count>50 && count<150)
		{
			lvl=2;
			level = 2;
		}
		if (count>150 && count<175)
		{
			level = 3;
			lvl=3;
		}
		if (count>175 && count<180)
		{
			level = 4;
			lvl=4;
		}
		if (count>180 && count<200)
		{
			lvl = 5;
			level = 4;
		}
		if (count>200)
		{
			lvl=6;
			level = 4;
		}
		if(hge->Input_GetKeyState(HGEK_ESCAPE))
		{
			play = 0;
			game_menu = 3;
			gui->Enter();
		}
	}
	return false;
}
Example #19
0
 void FilterTargets(std::list<WorldObject*>& targets)
 {
     targetCount = targets.size();
 }
Example #20
0
void __TriggerInterrupt(int type, PSPInterrupt intno, int subintr)
{
	if (interruptsEnabled || (type & PSP_INTR_ONLY_IF_ENABLED) == 0)
	{
		intrHandlers[intno]->queueUp(subintr);
		DEBUG_LOG(HLE, "Triggering subinterrupts for interrupt %i sub %i (%i in queue)", intno, subintr, (u32)pendingInterrupts.size());
		__TriggerRunInterrupts(type);
	}
}
Example #21
0
  CHECK_EQ(2, c.get_alternative_blocks_count());

  // Some blocks that were in main chain are in alt chain now
  BOOST_FOREACH(block b, alt_blocks)
  {
    CHECK_TEST_CONDITION(m_chain_1.end() != std::find(m_chain_1.begin(), m_chain_1.end(), b));
  }

  std::vector<currency::block> chain;
  map_hash2tx_t mtx;
  r = find_block_chain(events, chain, mtx, get_block_hash(blocks.back()));
  CHECK_TEST_CONDITION(r);
  CHECK_EQ(MK_COINS(8),  get_balance(m_recipient_account_1, chain, mtx));
  CHECK_EQ(MK_COINS(3),  get_balance(m_recipient_account_2, chain, mtx));
  CHECK_EQ(MK_COINS(14), get_balance(m_recipient_account_3, chain, mtx));
  CHECK_EQ(MK_COINS(16), get_balance(m_recipient_account_4, chain, mtx));

  std::list<transaction> tx_pool;
  r = c.get_pool_transactions(tx_pool);
  CHECK_TEST_CONDITION(r);
  CHECK_EQ(1, tx_pool.size());
  CHECK_TEST_CONDITION(!(tx_pool.front() == m_tx_pool.front()));

  std::vector<size_t> tx_outs;
  uint64_t transfered;
  lookup_acc_outs(m_recipient_account_2.get_keys(), tx_pool.front(), tx_outs, transfered);
  CHECK_EQ(MK_COINS(7), transfered);

  return true;
}
	unsigned int GetChildren(wxDataViewItemArray &out) const override {
		out.reserve(categories.size());
		for (auto const& category : categories)
			out.push_back(wxDataViewItem((void*)&category));
		return out.size();
	}
void put_into_vehicle( Character &c, item_drop_reason reason, const std::list<item> &items,
                       vehicle &veh, int part )
{
    if( items.empty() ) {
        return;
    }

    const tripoint where = veh.global_part_pos3( part );
    const std::string ter_name = g->m.name( where );
    int fallen_count = 0;
    int into_vehicle_count = 0;

    for( auto it : items ) { // cant use constant reference here because of the spill_contents()
        if( Pickup::handle_spillable_contents( c, it, g->m ) ) {
            continue;
        }
        if( veh.add_item( part, it ) ) {
            into_vehicle_count += it.count();
        } else {
            if( it.count_by_charges() ) {
                // Maybe we can add a few charges in the trunk and the rest on the ground.
                auto charges_added = veh.add_charges( part, it );
                it.mod_charges( -charges_added );
                into_vehicle_count += charges_added;
            }
            g->m.add_item_or_charges( where, it );
            fallen_count += it.count();
        }
    }

    const std::string part_name = veh.part_info( part ).name();

    if( same_type( items ) ) {
        const item &it = items.front();
        const int dropcount = items.size() * it.count();
        const std::string it_name = it.tname( dropcount );

        switch( reason ) {
            case item_drop_reason::deliberate:
                c.add_msg_player_or_npc(
                    ngettext( "You put your %1$s in the %2$s's %3$s.",
                              "You put your %1$s in the %2$s's %3$s.", dropcount ),
                    ngettext( "<npcname> puts their %1$s in the %2$s's %3$s.",
                              "<npcname> puts their %1$s in the %2$s's %3$s.", dropcount ),
                    it_name, veh.name, part_name
                );
                break;
            case item_drop_reason::too_large:
                c.add_msg_if_player(
                    ngettext(
                        "There's no room in your inventory for the %s, so you drop it into the %s's %s.",
                        "There's no room in your inventory for the %s, so you drop them into the %s's %s.",
                        dropcount ),
                    it_name, veh.name, part_name
                );
                break;
            case item_drop_reason::too_heavy:
                c.add_msg_if_player(
                    ngettext( "The %s is too heavy to carry, so you drop it into the %s's %s.",
                              "The %s are too heavy to carry, so you drop them into the %s's %s.", dropcount ),
                    it_name, veh.name, part_name
                );
                break;
            case item_drop_reason::tumbling:
                c.add_msg_if_player(
                    m_bad,
                    ngettext( "Your %s tumbles into the %s's %s.",
                              "Your %s tumble into the %s's %s.", dropcount ),
                    it_name, veh.name, part_name
                );
                break;
        }
    } else {
        switch( reason ) {
            case item_drop_reason::deliberate:
                c.add_msg_player_or_npc(
                    _( "You put several items in the %1$s's %2$s." ),
                    _( "<npcname> puts several items in the %1$s's %2$s." ),
                    veh.name, part_name
                );
                break;
            case item_drop_reason::too_large:
            case item_drop_reason::too_heavy:
            case item_drop_reason::tumbling:
                c.add_msg_if_player(
                    m_bad, _( "Some items tumble into the %1$s's %2$s." ),
                    veh.name, part_name
                );
                break;
        }
    }

    if( fallen_count > 0 ) {
        if( into_vehicle_count > 0 ) {
            c.add_msg_if_player(
                m_warning,
                ngettext( "The %s is full, so something fell to the %s.",
                          "The %s is full, so some items fell to the %s.", fallen_count ),
                part_name, ter_name
            );
        } else {
            c.add_msg_if_player(
                m_warning,
                ngettext( "The %s is full, so it fell to the %s.",
                          "The %s is full, so they fell to the %s.", fallen_count ),
                part_name, ter_name
            );
        }
    }
}
Example #24
0
    void
    modifVec(std::list<ElementRange> const& __r, eltType const& u,vectorType & UnVec,ExprType const& expr,
             size_type rowstart, int ComponentShiftFactor,
             mpl::int_<MESH_FACES> /**/ )
    {
        //using namespace Feel::vf;
        typedef typename eltType::functionspace_type::mesh_type mesh_type;
        typedef typename mesh_type::face_iterator face_iterator;
        typedef typename mesh_type::face_const_iterator face_const_iterator;

        typedef typename mesh_type::element_type geoelement_type;
        typedef typename geoelement_type::face_type face_type;
        // basis
        typedef typename eltType::functionspace_type::fe_type fe_type;

        typedef typename eltType::functionspace_type::dof_type dof_type;

        const size_type context = ExprType::context|vm::POINT;

        // geometric mapping context
        typedef typename mesh_type::gm_type gm_type;
        typedef boost::shared_ptr<gm_type> gm_ptrtype;
        typedef typename gm_type::template Context<context, geoelement_type> gmc_type;
        typedef boost::shared_ptr<gmc_type> gmc_ptrtype;
        typedef fusion::map<fusion::pair<vf::detail::gmc<0>, gmc_ptrtype> > map_gmc_type;

        typedef typename ExprType::template tensor<map_gmc_type> t_expr_type;

        if ( __r.size() == 0 ) return;
        auto __face_it =  __r.begin()->template get<1>();
        auto __face_en =  __r.begin()->template get<2>();
        //if ( __face_it == __face_en ) return;
        bool findAFace = false;
        for( auto lit = __r.begin(), len = __r.end(); lit != len; ++lit )
        {
            __face_it = lit->template get<1>();
            __face_en = lit->template get<2>();
            if ( __face_it != __face_en )
            {
                findAFace=true;
                break;
            }
        }
        if ( !findAFace ) return;

        // get the first face properly connected
        bool findAFaceToInit=false;
        for( auto lit = __r.begin(), len = __r.end(); lit != len; ++lit )
        {
            __face_it = lit->template get<1>();
            __face_en = lit->template get<2>();
            for( ; __face_it != __face_en; ++__face_it )
            {
                if ( boost::unwrap_ref(*__face_it).isConnectedTo0() )
                {
                    findAFaceToInit=true;
                    break;
                }
            }
            if ( findAFaceToInit ) break;
        }
        CHECK( findAFaceToInit ) << "not find a face to init\n";


        size_type nbFaceDof = invalid_size_type_value;
        if ( !fe_type::is_modal )
            nbFaceDof = ( face_type::numVertices * fe_type::nDofPerVertex +
                          face_type::numEdges * fe_type::nDofPerEdge +
                          face_type::numFaces * fe_type::nDofPerFace );
        else
            nbFaceDof = face_type::numVertices * fe_type::nDofPerVertex;



        //dof_type const* __dof = u.functionSpace()->dof().get();
        fe_type const* __fe = u.functionSpace()->fe().get();
        gm_ptrtype __gm( new gm_type );

        //
        // Precompute some data in the reference element for
        // geometric mapping and reference finite element
        //
        typedef typename geoelement_type::permutation_type permutation_type;
        typedef typename gm_type::precompute_ptrtype geopc_ptrtype;
        typedef typename gm_type::precompute_type geopc_type;
        std::vector<std::map<permutation_type, geopc_ptrtype> > __geopc( geoelement_type::numTopologicalFaces );
        for ( uint16_type __f = 0; __f < geoelement_type::numTopologicalFaces; ++__f )
        {
            permutation_type __p( permutation_type::IDENTITY );
            __geopc[__f][__p] = geopc_ptrtype(  new geopc_type( __gm, __fe->points( __f ) ) );
        }

        uint16_type __face_id = __face_it->pos_first();
        gmc_ptrtype __c( new gmc_type( __gm, __face_it->element(0), __geopc, __face_id ) );

        map_gmc_type mapgmc( fusion::make_pair<vf::detail::gmc<0> >( __c ) );
        t_expr_type LExpr( expr, mapgmc );

        std::vector<bool> dofdone( u.functionSpace()->dof()->nLocalDofWithGhost(), false );

        //face_const_iterator __face_it, __face_en;

        for( auto lit = __r.begin(), len = __r.end(); lit != len; ++lit )
        {
            __face_it = lit->template get<1>();
            __face_en = lit->template get<2>();
            for ( ; __face_it != __face_en; ++__face_it )
            {
                uint16_type __face_id = __face_it->pos_first();
                __c->update( __face_it->element(0), __face_id );
                map_gmc_type mapgmc( fusion::make_pair<vf::detail::gmc<0> >( __c ) );
                LExpr.update( mapgmc );

                for (uint c1=0;c1<eltType::nComponents1;c1++)
                    for (uint c2=0;c2<eltType::nComponents2;c2++)
                    {
                        for ( uint16_type l = 0; l < nbFaceDof; ++l )
                        {
                            size_type index = boost::get<0>(u.functionSpace()->dof()->faceLocalToGlobal( __face_it->id(), l, c1 ));
                            if ( dofdone[index] ) continue;
                            size_type thedof =  u.start() + ComponentShiftFactor*index;
                            double __value=LExpr.evalq( c1, c2, l );
                            //u( thedof ) =  __value;
                            UnVec->set(rowstart+thedof,__value);
                            dofdone[index] = true;
                        }
                    }
            }
        }
        //UnVec->close();
    } // modifVec
    // tokenizes the string.  Edges must NOT have []'s
    void Tokenize( const wxString &pkt )
    {
        wxString temp = pkt;
        wxString minStr, maxStr;
        unsigned long long cur; // temporary long long to hold the "current" packet
        wxString str[4]; // at most we allow 4 parts to the packet
        temp.Replace(_(":"), _(",")); // replace :'s with ,'s (they're both separators)
        temp.Replace(_(";"), _(",")); // replace ;'s with ,'s (they're both separators)
        // explode the string
        for( int i=0; i < 4; ++i ) {
            str[i] = temp.BeforeFirst(',');
            temp   = temp.AfterFirst(',');
        }

        // if there are 4 parts to the packet and not more than 4
        if( str[3].size() > 0 && temp.size() == 0 ) {
            // minimum
            if( str[1].size() > 0 ) {
                min = HexToDecimal<unsigned long long>(str[1]);
            } else {
                min = 0;
            }
            // maximum
            if( str[2].size() > 0 ) {
                max = HexToDecimal<unsigned long long>(str[2]);
            } else {
                max = 0;
            }
            // current
            if( str[0].size() > 0 ) {
                cur = HexToDecimal<unsigned long long>(str[0]);
            } else {
                cur = min;
            }
            // numNibbles
            numNibbles = str[2].size() > str[1].size() ? str[2].size() : str[1].size();
            numNibbles = str[0].size() > numNibbles ? str[0].size() : numNibbles;
            temp = str[3]; // we use temp later on to hold the expressions
        } else if( str[2].size() > 0 && temp.size() == 0 ) { // if there are 3 parts
            // minimum
            if( str[0].size() > 0 ) {
                min = HexToDecimal<unsigned long long>(str[0]);
            } else {
                min = 0;
            }
            // maximum
            if( str[1].size() > 0 ) {
                max = HexToDecimal<unsigned long long>(str[1]);
            } else {
                max = 0;
            }
            // current
            cur = min;
            // numNibbles
            numNibbles = str[1].size() > str[0].size() ? str[1].size() : str[0].size();
            temp = str[2]; // we use temp later on to hold the expressions
        } // else error
        numNibbles %= 16+1; // can't have more than 16 nibbles

        if( min > max ) // if start is greater than stop
        {
            std::swap(min,max);
        }
        // if cur is out of range
        if( !(cur >= min && cur <= max) ) {
            cur = min;
        }
        currentPkt = DecimalToHexL(cur);
        currentPkt = currentPkt.Mid(0,numNibbles);

        wxString val = _("");
        PartialPacketToken pktToken;
        for( size_t i=0, j=0; i < temp.size(); ++i )
        {
            bool foundToken = true;
            switch( static_cast<char>(temp[i]))
            {
            case '+':
                pktToken.type  = PARTIAL_PACKET_ADDITION;
                pktToken.value = _("+");
                break;
            case '-':
                pktToken.type  = PARTIAL_PACKET_SUBTRACTION;
                pktToken.value = _("-");
                break;
            case '*':
                pktToken.type  = PARTIAL_PACKET_MULTIPLICATION;
                pktToken.value = _("*");
                break;
            case '/':
                pktToken.type  = PARTIAL_PACKET_DIVISION;
                pktToken.value = _("/");
                break;
            case 'P': // case p should always follow this
            case 'p':
                pktToken.type  = PARTIAL_PACKET_PACKET;
                pktToken.value = _("p");
                break;
            default:
                foundToken = false;
            }

            // add token with a value
            if( !foundToken )
            {
                val += temp[i];
            }
            else
            {
                if( val.size() > 0 ) // append the partial packet value before the other token
                {
                    if( tokens.size() == 0 ) // if there was no expression token before this value, then default to addition
                        tokens.push_back( PartialPacketToken(PARTIAL_PACKET_ADDITION, _("+")) );
                    tokens.push_back( PartialPacketToken(PARTIAL_PACKET_VALUE, val) );
                    val.Clear();
                }

                if( tokens.back().type == PARTIAL_PACKET_ADDITION ||
                    tokens.back().type == PARTIAL_PACKET_SUBTRACTION ||
                    tokens.back().type == PARTIAL_PACKET_MULTIPLICATION ||
                    tokens.back().type == PARTIAL_PACKET_DIVISION )
                {
                    tokens.back() = pktToken; // only store last symbol
                }
                else
                    tokens.push_back(pktToken);
            }
        }
        if( val.size() > 0 )
        {
            if( tokens.size() == 0 ) // if there was no expression token before this value, then default to addition
                tokens.push_back( PartialPacketToken(PARTIAL_PACKET_ADDITION, _("+")) );
            tokens.push_back( PartialPacketToken(PARTIAL_PACKET_VALUE, val) );
        }
        else if( 
            tokens.size() > 0 &&
            (tokens.back().type == PARTIAL_PACKET_ADDITION ||
             tokens.back().type == PARTIAL_PACKET_SUBTRACTION ||
             tokens.back().type == PARTIAL_PACKET_MULTIPLICATION ||
             tokens.back().type == PARTIAL_PACKET_DIVISION) )
        {
            tokens.pop_back(); // can't end with a symbol
        }
    }
Example #26
0
    void
    modifVec(std::list<ElementRange> const& __r, eltType const& u,vectorType & UnVec,ExprType const& expr,
             size_type rowstart, int ComponentShiftFactor,
             mpl::int_<MESH_EDGES> /**/ )
    {
        const size_type context = ExprType::context|vm::POINT;

        auto mesh = u.functionSpace()->mesh().get();
        auto const* dof = u.functionSpace()->dof().get();
        auto const* fe = u.functionSpace()->fe().get();


        if ( __r.size() == 0 ) return;
        auto edge_it =  __r.begin()->template get<1>();
        auto edge_en =  __r.begin()->template get<2>();

        bool findAEdge = false;
        for( auto lit = __r.begin(), len = __r.end(); lit != len; ++lit )
        {
            edge_it = lit->template get<1>();
            edge_en = lit->template get<2>();
            if ( edge_it != edge_en )
            {
                findAEdge=true;
                break;
            }
        }
        if ( !findAEdge ) return;

        auto const& edgeForInit = boost::unwrap_ref( *edge_it );

        auto gm = mesh->gm();
        //auto const& firstEntity = *entity_it;
        size_type eid = edgeForInit.elements().begin()->first;
        size_type ptid_in_element = edgeForInit.elements().begin()->second;
        auto const& elt = mesh->element( eid );
        auto geopc = gm->preCompute( fe->edgePoints(ptid_in_element) );
        auto ctx = gm->template context<context>( elt, geopc );
        auto expr_evaluator = expr.evaluator( mapgmc(ctx) );
        auto IhLoc = fe->edgeLocalInterpolant();

        std::vector<bool> dofdone( dof->nLocalDofWithGhost(), false );

        for( auto const& lit : __r )
        {
            edge_it = lit.template get<1>();
            edge_en = lit.template get<2>();
            for ( ; edge_it != edge_en;++edge_it )
            {
                auto const& theedge = boost::unwrap_ref( *edge_it );

                if ( theedge.isGhostCell() )
                {
                    LOG(WARNING) << "edge id : " << theedge.id() << " is a ghost edge";
                    continue;
                }

                size_type eid = theedge.elements().begin()->first;
                size_type edgeid_in_element = theedge.elements().begin()->second;
                auto const& elt = mesh->element( eid );
                geopc = gm->preCompute( fe->edgePoints(edgeid_in_element) );
                ctx->update( elt, geopc );
                expr_evaluator.update( mapgmc( ctx ) );
                fe->edgeInterpolate( expr_evaluator, IhLoc );

                for( auto const& ldof : u.functionSpace()->dof()->edgeLocalDof( eid, edgeid_in_element ) )
                {
                    size_type index = ldof.index();
                    if ( dofdone[index] ) continue;
                    //size_type thedof = u.start()+ (is_comp_space?Elem1::nComponents:1)*ldof.index();
                    size_type thedof = u.start() + ComponentShiftFactor*index;
                    double value = ldof.sign()*IhLoc( ldof.localDofInFace() );
                    UnVec->set(rowstart+thedof,value);
                    dofdone[index] = true;
                }
            } // edge_it
        } // lit
    }
Example #27
0
/// Called by gold to see whether this file is one that our plugin can handle.
/// We'll try to open it and register all the symbols with add_symbol if
/// possible.
static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
                                        int *claimed) {
  LLVMContext Context;
  MemoryBufferRef BufferRef;
  std::unique_ptr<MemoryBuffer> Buffer;
  if (get_view) {
    const void *view;
    if (get_view(file->handle, &view) != LDPS_OK) {
      message(LDPL_ERROR, "Failed to get a view of %s", file->name);
      return LDPS_ERR;
    }
    BufferRef =
        MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
  } else {
    int64_t offset = 0;
    // Gold has found what might be IR part-way inside of a file, such as
    // an .a archive.
    if (file->offset) {
      offset = file->offset;
    }
    ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
        MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
                                       offset);
    if (std::error_code EC = BufferOrErr.getError()) {
      message(LDPL_ERROR, EC.message().c_str());
      return LDPS_ERR;
    }
    Buffer = std::move(BufferOrErr.get());
    BufferRef = Buffer->getMemBufferRef();
  }

  Context.setDiagnosticHandler(diagnosticHandlerForContext);
  ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
      object::IRObjectFile::create(BufferRef, Context);
  std::error_code EC = ObjOrErr.getError();
  if (EC == object::object_error::invalid_file_type ||
      EC == object::object_error::bitcode_section_not_found)
    return LDPS_OK;

  *claimed = 1;

  if (EC) {
    message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
            EC.message().c_str());
    return LDPS_ERR;
  }
  std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);

  Modules.resize(Modules.size() + 1);
  claimed_file &cf = Modules.back();

  cf.handle = file->handle;

  // If we are doing ThinLTO compilation, don't need to process the symbols.
  // Later we simply build a combined index file after all files are claimed.
  if (options::thinlto && options::thinlto_index_only)
    return LDPS_OK;

  for (auto &Sym : Obj->symbols()) {
    uint32_t Symflags = Sym.getFlags();
    if (shouldSkip(Symflags))
      continue;

    cf.syms.push_back(ld_plugin_symbol());
    ld_plugin_symbol &sym = cf.syms.back();
    sym.version = nullptr;

    SmallString<64> Name;
    {
      raw_svector_ostream OS(Name);
      Sym.printName(OS);
    }
    sym.name = strdup(Name.c_str());

    const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());

    ResolutionInfo &Res = ResInfo[sym.name];

    sym.visibility = LDPV_DEFAULT;
    if (GV) {
      Res.UnnamedAddr &= GV->hasUnnamedAddr();
      Res.IsLinkonceOdr &= GV->hasLinkOnceLinkage();
      Res.Visibility = getMinVisibility(Res.Visibility, GV->getVisibility());
      switch (GV->getVisibility()) {
      case GlobalValue::DefaultVisibility:
        sym.visibility = LDPV_DEFAULT;
        break;
      case GlobalValue::HiddenVisibility:
        sym.visibility = LDPV_HIDDEN;
        break;
      case GlobalValue::ProtectedVisibility:
        sym.visibility = LDPV_PROTECTED;
        break;
      }
    }

    if (Symflags & object::BasicSymbolRef::SF_Undefined) {
      sym.def = LDPK_UNDEF;
      if (GV && GV->hasExternalWeakLinkage())
        sym.def = LDPK_WEAKUNDEF;
    } else {
      sym.def = LDPK_DEF;
      if (GV) {
        assert(!GV->hasExternalWeakLinkage() &&
               !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
        if (GV->hasCommonLinkage())
          sym.def = LDPK_COMMON;
        else if (GV->isWeakForLinker())
          sym.def = LDPK_WEAKDEF;
      }
    }

    sym.size = 0;
    sym.comdat_key = nullptr;
    if (GV) {
      const GlobalObject *Base = getBaseObject(*GV);
      if (!Base)
        message(LDPL_FATAL, "Unable to determine comdat of alias!");
      const Comdat *C = Base->getComdat();
      if (C)
        sym.comdat_key = strdup(C->getName().str().c_str());
    }

    sym.resolution = LDPR_UNKNOWN;
  }

  if (!cf.syms.empty()) {
    if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
      message(LDPL_ERROR, "Unable to add symbols!");
      return LDPS_ERR;
    }
  }

  return LDPS_OK;
}
Example #28
0
    void
    modifVec(std::list<ElementRange> const& __r, eltType const& u,vectorType & UnVec,ExprType const& expr,
             size_type rowstart, int ComponentShiftFactor,
             mpl::int_<MESH_POINTS> /**/ )
    {
        const size_type context = ExprType::context|vm::POINT;

        auto mesh = u.functionSpace()->mesh().get();
        auto const* dof = u.functionSpace()->dof().get();
        auto const* fe = u.functionSpace()->fe().get();

        if ( __r.size() == 0 ) return;
        auto point_it =  __r.begin()->template get<1>();
        auto point_en =  __r.begin()->template get<2>();

        bool findAPoint = false;
        for( auto lit = __r.begin(), len = __r.end(); lit != len; ++lit )
        {
            point_it = lit->template get<1>();
            point_en = lit->template get<2>();
            if ( point_it != point_en )
            {
                findAPoint=true;
                break;
            }
        }
        if ( !findAPoint ) return;

        auto const& pointForInit = boost::unwrap_ref( *point_it );

        size_type eid = pointForInit.elements().begin()->first;
        size_type ptid_in_element = pointForInit.elements().begin()->second;

        auto const& elt = mesh->element( eid );
        auto gm = mesh->gm();
        auto geopc = gm->preCompute( fe->vertexPoints(ptid_in_element) );
        auto ctx = gm->template context<context>( elt, geopc );
        auto expr_evaluator = expr.evaluator( mapgmc(ctx) );
        auto IhLoc = fe->vertexLocalInterpolant();

        std::vector<bool> dofdone( dof->nLocalDofWithGhost(), false );

        for( auto const& lit : __r )
        {
            point_it = lit.template get<1>();
            point_en = lit.template get<2>();
            DVLOG(2) << "point " << point_it->id() << " with marker " << point_it->marker() << " nb: " << std::distance(point_it,point_en);

            if ( point_it == point_en )
                continue;

            for ( ; point_it != point_en;++point_it )
            {
                auto const& thept = boost::unwrap_ref( *point_it );

                size_type eid = thept.elements().begin()->first;
                size_type ptid_in_element = thept.elements().begin()->second;
                auto const& elt = mesh->element( eid );
                geopc = gm->preCompute( fe->vertexPoints(ptid_in_element) );
                ctx->update( elt, ptid_in_element, geopc, mpl::int_<0>() );
                expr_evaluator.update( mapgmc( ctx ) );
                fe->vertexInterpolate( expr_evaluator, IhLoc );

                for (int c1=0;c1<eltType::nComponents1;c1++)
                    //for( int c = 0; c < (is_product?nComponents:1); ++c )
                {
                    size_type index = dof->localToGlobal( eid, ptid_in_element, c1 ).index();
                    //size_type thedof = u.start()+ (is_comp_space?Elem1::nComponents:1)*index; // global dof
                    size_type thedof = u.start() + ComponentShiftFactor*index;
                    if ( dofdone[index] ) continue;
                    double value = IhLoc( c1 );
                    UnVec->set(rowstart+thedof,value);
                    dofdone[index] = true;
                }
            }
        }

    }
Example #29
0
bool test_generator::constructBlock(CryptoNote::Block& blk, uint32_t height, const Crypto::Hash& previousBlockHash,
                                    const CryptoNote::AccountBase& minerAcc, uint64_t timestamp, uint64_t alreadyGeneratedCoins,
                                    std::vector<size_t>& blockSizes, const std::list<CryptoNote::Transaction>& txList) {
  blk.majorVersion = defaultMajorVersion;
  blk.minorVersion = defaultMinorVersion;
  blk.timestamp = timestamp;
  blk.previousBlockHash = previousBlockHash;

  blk.transactionHashes.reserve(txList.size());
  for (const Transaction &tx : txList) {
    Crypto::Hash tx_hash;
    getObjectHash(tx, tx_hash);
    blk.transactionHashes.push_back(tx_hash);
  }

  uint64_t totalFee = 0;
  size_t txsSize = 0;
  for (auto& tx : txList) {
    uint64_t fee = 0;
    bool r = get_tx_fee(tx, fee);
    CHECK_AND_ASSERT_MES(r, false, "wrong transaction passed to construct_block");
    totalFee += fee;
    txsSize += getObjectBinarySize(tx);
  }

  blk.baseTransaction = boost::value_initialized<Transaction>();
  size_t targetBlockSize = txsSize + getObjectBinarySize(blk.baseTransaction);
  while (true) {
    if (!m_currency.constructMinerTx(blk.majorVersion, height, Common::medianValue(blockSizes), alreadyGeneratedCoins, targetBlockSize,
      totalFee, minerAcc.getAccountKeys().address, blk.baseTransaction, BinaryArray(), 10)) {
      return false;
    }

    size_t actualBlockSize = txsSize + getObjectBinarySize(blk.baseTransaction);
    if (targetBlockSize < actualBlockSize) {
      targetBlockSize = actualBlockSize;
    } else if (actualBlockSize < targetBlockSize) {
      size_t delta = targetBlockSize - actualBlockSize;
      blk.baseTransaction.extra.resize(blk.baseTransaction.extra.size() + delta, 0);
      actualBlockSize = txsSize + getObjectBinarySize(blk.baseTransaction);
      if (actualBlockSize == targetBlockSize) {
        break;
      } else {
        CHECK_AND_ASSERT_MES(targetBlockSize < actualBlockSize, false, "Unexpected block size");
        delta = actualBlockSize - targetBlockSize;
        blk.baseTransaction.extra.resize(blk.baseTransaction.extra.size() - delta);
        actualBlockSize = txsSize + getObjectBinarySize(blk.baseTransaction);
        if (actualBlockSize == targetBlockSize) {
          break;
        } else {
          CHECK_AND_ASSERT_MES(actualBlockSize < targetBlockSize, false, "Unexpected block size");
          blk.baseTransaction.extra.resize(blk.baseTransaction.extra.size() + delta, 0);
          targetBlockSize = txsSize + getObjectBinarySize(blk.baseTransaction);
        }
      }
    } else {
      break;
    }
  }

  if (blk.majorVersion >= BLOCK_MAJOR_VERSION_2) {
    blk.parentBlock.majorVersion = BLOCK_MAJOR_VERSION_1;
    blk.parentBlock.minorVersion = BLOCK_MINOR_VERSION_0;
    blk.parentBlock.transactionCount = 1;
    blk.parentBlock.baseTransaction.version = 0;
    blk.parentBlock.baseTransaction.unlockTime = 0;

    CryptoNote::TransactionExtraMergeMiningTag mmTag;
    mmTag.depth = 0;
    if (!CryptoNote::get_aux_block_header_hash(blk, mmTag.merkleRoot)) {
      return false;
    }

    blk.parentBlock.baseTransaction.extra.clear();
    if (!CryptoNote::appendMergeMiningTagToExtra(blk.parentBlock.baseTransaction.extra, mmTag)) {
      return false;
    }
  }

  // Nonce search...
  blk.nonce = 0;
  Crypto::cn_context context;
  while (!miner::find_nonce_for_given_block(context, blk, getTestDifficulty())) {
    blk.timestamp++;
  }

  addBlock(blk, txsSize, totalFee, blockSizes, alreadyGeneratedCoins);

  return true;
}
Example #30
0
 /**
    \return The number of values.
 */
 int get_nb_values(void) const
 {
     return static_cast<int>(_values.size());
 }