Example #1
0
std::list<MovePathNode> Fleet::MovePath(const std::list<int>& route) const {
    std::list<MovePathNode> retval;

    if (route.empty())
        return retval;                                      // nowhere to go => empty path
    // if (route.size() == 1) do nothing special.  this fleet is probably on the starlane leading to
    //                        its final destination.  normal looping to read destination should work fine
    if (route.size() == 2 && route.front() == route.back())
        return retval;                                      // nowhere to go => empty path
    if (this->Speed() < FLEET_MOVEMENT_EPSILON) {
        retval.push_back(MovePathNode(this->X(), this->Y(), true, ETA_NEVER, this->SystemID(), UniverseObject::INVALID_OBJECT_ID, UniverseObject::INVALID_OBJECT_ID));
        return retval;                                      // can't move => path is just this system with explanatory ETA
    }

    double fuel =       Fuel();
    double max_fuel =   MaxFuel();

    //Logger().debugStream() << "Fleet " << this->Name() << " movePath fuel: " << fuel << " sys id: " << this->SystemID();

    // determine all systems where fleet(s) can be resupplied if fuel runs out
    int owner = this->Owner();
    const Empire* empire = Empires().Lookup(owner);
    std::set<int> fleet_supplied_systems;
    std::set<int> unobstructed_systems;
    if (empire) {
        fleet_supplied_systems = empire->FleetSupplyableSystemIDs();
        unobstructed_systems = empire->SupplyUnobstructedSystems();
    }

    // determine if, given fuel available and supplyable systems, fleet will ever be able to move
    if (fuel < 1.0 &&
        this->SystemID() != UniverseObject::INVALID_OBJECT_ID &&
        fleet_supplied_systems.find(this->SystemID()) == fleet_supplied_systems.end())
    {
        MovePathNode node(this->X(), this->Y(), true, ETA_OUT_OF_RANGE,
                          this->SystemID(),
                          UniverseObject::INVALID_OBJECT_ID,
                          UniverseObject::INVALID_OBJECT_ID);
        retval.push_back(node);
        return retval;      // can't move => path is just this system with explanatory ETA
    }


    const ObjectMap& objects = GetMainObjectMap();


    // get iterator pointing to System* on route that is the first after where this fleet is currently.
    // if this fleet is in a system, the iterator will point to the system after the current in the route
    // if this fleet is not in a system, the iterator will point to the first system in the route
    std::list<int>::const_iterator route_it = route.begin();
    if (*route_it == SystemID())
        ++route_it;     // first system in route is current system of this fleet.  skip to the next system
    if (route_it == route.end())
        return retval;  // current system of this fleet is the *only* system in the route.  path is empty.


    // get current, previous and next systems of fleet
    const System* cur_system = objects.Object<System>(this->SystemID());            // may be 0
    const System* prev_system = objects.Object<System>(this->PreviousSystemID());   // may be 0 if this fleet is not moving or ordered to move
    const System* next_system = objects.Object<System>(*route_it);                  // can't use this->NextSystemID() because this fleet may not be moving and may not have a next system. this might occur when a fleet is in a system, not ordered to move or ordered to move to a system, but a projected fleet move line is being calculated to a different system
    if (!next_system) {
        Logger().errorStream() << "Fleet::MovePath couldn't get next system with id " << *route_it << " for this fleet " << this->Name();
        return retval;
    }

    //Logger().debugStream() << "initial cur system: " << (cur_system ? cur_system->Name() : "(none)") <<
    //                          "  prev system: " << (prev_system ? prev_system->Name() : "(none)") <<
    //                          "  next system: " << (next_system ? next_system->Name() : "(none)");



    // place initial position MovePathNode
    MovePathNode initial_pos(this->X(), this->Y(), false /* not an end of turn node */, 0 /* turns taken to reach position of node */,
                             (cur_system  ? cur_system->ID()  : INVALID_OBJECT_ID),
                             (prev_system ? prev_system->ID() : INVALID_OBJECT_ID),
                             (next_system ? next_system->ID() : INVALID_OBJECT_ID));
    retval.push_back(initial_pos);


    const int       TOO_LONG =              100;        // limit on turns to simulate.  99 turns max keeps ETA to two digits, making UI work better
    int             turns_taken =           1;
    double          turn_dist_remaining =   m_speed;    // additional distance that can be travelled in current turn of fleet movement being simulated
    double          cur_x =                 this->X();
    double          cur_y =                 this->Y();
    double          next_x =                next_system->X();
    double          next_y =                next_system->Y();

    // simulate fleet movement given known speed, starting position, fuel limit and systems on route
    // need to populate retval with MovePathNodes that indicate the correct position, whether this
    // fleet will end a turn at the node, the turns it will take to reach the node, and (when applicable)
    // the current (if at a system), previous and next system IDs at which the fleet will be.  the
    // previous and next system ids are needed to know what starlane a given node is located on, if any.
    // nodes at systems don't need previous system ids to be valid, but should have next system ids
    // valid so that when rendering starlanes using the returned move path, lines departing a system
    // can be drawn on the correct side of the system icon

    while (turns_taken < TOO_LONG) {
        // each loop iteration moves the current position to the next location of interest along the move
        // path, and then adds a node at that position.

        //Logger().debugStream() << " starting iteration";
        //if (cur_system)
        //    Logger().debugStream() << "     at system " << cur_system->Name() << " with id " << cur_system->ID();
        //else
        //    Logger().debugStream() << "     at (" << cur_x << ", " << cur_y << ")";


        // check if fuel limits movement or current system refuels passing fleet
        if (cur_system) {
            // check if current system has fuel supply available
            if (fleet_supplied_systems.find(cur_system->ID()) != fleet_supplied_systems.end()) {
                // current system has fuel supply.  replenish fleet's supply and don't restrict movement
                fuel = max_fuel;
                //Logger().debugStream() << " ... at system with fuel supply.  replenishing and continuing movement";

            } else {
                // current system has no fuel supply.  require fuel to proceed
                if (fuel >= 1.0) {
                    //Logger().debugStream() << " ... at system without fuel supply.  consuming unit of fuel to proceed";
                    fuel -= 1.0;

                } else {
                    //Logger().debugStream() << " ... at system without fuel supply.  have insufficient fuel to continue moving";
                    turns_taken = ETA_OUT_OF_RANGE;
                    break;
                }
            }
        }


        // find distance to next system along path from current position
        double dist_to_next_system = std::sqrt((next_x - cur_x)*(next_x - cur_x) + (next_y - cur_y)*(next_y - cur_y));
        //Logger().debugStream() << " ... dist to next system: " << dist_to_next_system;


        // move ship as far as it can go this turn, or to next system, whichever is closer, and deduct
        // distance travelled from distance travellable this turn
        if (turn_dist_remaining >= FLEET_MOVEMENT_EPSILON) {
            double dist_travelled_this_step = std::min(turn_dist_remaining, dist_to_next_system);

            //Logger().debugStream() << " ... fleet moving " << dist_travelled_this_step << " this iteration.  dist to next system: " << dist_to_next_system << " and turn_dist_remaining: " << turn_dist_remaining;

            double x_dist = next_x - cur_x;
            double y_dist = next_y - cur_y;
            // dist_to_next_system = std::sqrt(x_dist * x_dist + y_dist * y_dist);  // should already equal this distance, so don't need to recalculate
            double unit_vec_x = x_dist / dist_to_next_system;
            double unit_vec_y = y_dist / dist_to_next_system;

            cur_x += unit_vec_x*dist_travelled_this_step;
            cur_y += unit_vec_y*dist_travelled_this_step;

            turn_dist_remaining -= dist_travelled_this_step;
            dist_to_next_system -= dist_travelled_this_step;

            // if moved away any distance from a system, are no longer in that system
            if (cur_system && dist_travelled_this_step >= FLEET_MOVEMENT_EPSILON) {
                prev_system = cur_system;
                cur_system = 0;
            }
        }

        bool end_turn_at_cur_position = false;

        // check if fleet can move any further this turn
        if (turn_dist_remaining < FLEET_MOVEMENT_EPSILON) {
            //Logger().debugStream() << " ... fleet can't move further this turn.";
            turn_dist_remaining = 0.0;      // to prevent any possible precision-related errors
            end_turn_at_cur_position = true;
        }

        // check if current position is close enough to next system on route to qualify as at that system.
        if (dist_to_next_system < FLEET_MOVEMENT_EPSILON) {
            // close enough to be consider to be at next system.
            // set current position to be exactly at next system to avoid rounding issues
            cur_system = next_system;
            cur_x = cur_system->X();    // update positions to ensure no round-off-errors
            cur_y = cur_system->Y();

            //Logger().debugStream() << " ... arrived at system: " << cur_system->Name();


            // attempt to get next system on route, to update next system.  if new current
            // system is the end of the route, abort.
            ++route_it;
            if (route_it == route.end())
                break;

            // update next system on route and distance to it from current position
            next_system = GetEmpireKnownObject<System>(*route_it, owner);
            if (!next_system) {
                Logger().errorStream() << "Fleet::MovePath couldn't get system with id " << *route_it;
                break;
            }
            next_x = next_system->X();
            next_y = next_system->Y();
        }

        // if new position is an obstructed system, must end turn here
        if (cur_system && unobstructed_systems.find(cur_system->ID()) == unobstructed_systems.end()) {
            turn_dist_remaining = 0.0;
            end_turn_at_cur_position = true;
        }

        // if turn done and turns taken is enough, abort simulation
        if (end_turn_at_cur_position && (turns_taken + 1 >= TOO_LONG)) {
            // exit loop before placing current node to simplify post-loop processing: now all cases require a post-loop node to be added
            ++turns_taken;
            break;
        }

        // add MovePathNode for current position (end of turn position and/or system location)
        MovePathNode cur_pos(cur_x, cur_y, end_turn_at_cur_position, turns_taken,
                             (cur_system  ? cur_system->ID()  : INVALID_OBJECT_ID),
                             (prev_system ? prev_system->ID() : INVALID_OBJECT_ID),
                             (next_system ? next_system->ID() : INVALID_OBJECT_ID));
        retval.push_back(cur_pos);


        // if the turn ended at this position, increment the turns taken and
        // reset the distance remaining to be travelled during the current (now
        // next) turn for the next loop iteration
        if (end_turn_at_cur_position) {
            //Logger().debugStream() << " ... end of simulated turn " << turns_taken;
            ++turns_taken;
            turn_dist_remaining = m_speed;
        }
    }


    // done looping.  may have exited due to reaching end of path, lack of fuel, or turns taken getting too big
    if (turns_taken == TOO_LONG)
        turns_taken = ETA_NEVER;

    MovePathNode final_pos(cur_x, cur_y, true, turns_taken,
                           (cur_system  ? cur_system->ID()  : INVALID_OBJECT_ID),
                           (prev_system ? prev_system->ID() : INVALID_OBJECT_ID),
                           (next_system ? next_system->ID() : INVALID_OBJECT_ID));
    retval.push_back(final_pos);

    return retval;
}
        void UpdateAI(const uint32 uiDiff)
        {
            if (!UpdateVictim())
                return;

            if (me->HasUnitState(UNIT_STATE_CASTING))
                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(SPELL_PENETRATING_COLD, SPELLVALUE_MAX_TARGETS, RAID_MODE(2, 5, 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)
                    {
                        EntryCheckPredicate pred(NPC_BURROWER);
                        Summons.DoAction(ACTION_SHADOW_STRIKE, pred);
                        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);
                    Talk(EMOTE_BURROWER);
                    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);
                    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(SPELL_LEECHING_SWARM);
                Talk(EMOTE_LEECHING_SWARM);
                Talk(SAY_LEECHING_SWARM);
            }

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

            DoMeleeAttackIfReady();
        }
Example #3
0
void Floor::addWaitingPeople(const std::list<HumanPtr>& people) {
	containedPeople_.insert(containedPeople_.end(), people.begin(), people.end());
}
Example #4
0
MDFNGI *MDFNI_LoadGame(const char *force_module, const char *name)
{
        MDFNFILE GameFile;
	struct stat stat_buf;
	std::vector<FileExtensionSpecStruct> valid_iae;

	if(strlen(name) > 4 && (!strcasecmp(name + strlen(name) - 4, ".cue") || !strcasecmp(name + strlen(name) - 4, ".toc") || !strcasecmp(name + strlen(name) - 4, ".m3u")))
	{
	 return(MDFNI_LoadCD(force_module, name));
	}
	
	if(!stat(name, &stat_buf) && !S_ISREG(stat_buf.st_mode))
	{
	 return(MDFNI_LoadCD(force_module, name));
	}

	MDFNI_CloseGame();

	LastSoundMultiplier = 1;

	MDFNGameInfo = NULL;

	MDFN_printf(_("Loading %s...\n"),name);

	MDFN_indent(1);

        GetFileBase(name);

	// Construct a NULL-delimited list of known file extensions for MDFN_fopen()
	for(unsigned int i = 0; i < MDFNSystems.size(); i++)
	{
	 const FileExtensionSpecStruct *curexts = MDFNSystems[i]->FileExtensions;

	 // If we're forcing a module, only look for extensions corresponding to that module
	 if(force_module && strcmp(MDFNSystems[i]->shortname, force_module))
	  continue;

	 if(curexts)	
 	  while(curexts->extension && curexts->description)
	  {
	   valid_iae.push_back(*curexts);
           curexts++;
 	  }
	}
	{
	 FileExtensionSpecStruct tmpext = { NULL, NULL };
	 valid_iae.push_back(tmpext);
	}

	if(!GameFile.Open(name, &valid_iae[0], _("game")))
        {
	 MDFNGameInfo = NULL;
	 return 0;
	}

	if(!LoadIPS(GameFile, MDFN_MakeFName(MDFNMKF_IPS, 0, 0).c_str()))
	{
	 MDFNGameInfo = NULL;
         GameFile.Close();
         return(0);
	}

	MDFNGameInfo = NULL;

	for(std::list<MDFNGI *>::iterator it = MDFNSystemsPrio.begin(); it != MDFNSystemsPrio.end(); it++)  //_unsigned int x = 0; x < MDFNSystems.size(); x++)
	{
	 char tmpstr[256];
	 trio_snprintf(tmpstr, 256, "%s.enable", (*it)->shortname);

	 if(force_module)
	 {
          if(!strcmp(force_module, (*it)->shortname))
          {
	   if(!(*it)->Load)
	   {
            GameFile.Close();

	    if((*it)->LoadCD)
             MDFN_PrintError(_("Specified system only supports CD(physical, or image files, such as *.cue and *.toc) loading."));
	    else
             MDFN_PrintError(_("Specified system does not support normal file loading."));
            MDFN_indent(-1);
            MDFNGameInfo = NULL;
            return 0;
	   }
           MDFNGameInfo = *it;
           break;
          }
	 }
	 else
	 {
	  // Is module enabled?
	  if(!MDFN_GetSettingB(tmpstr))
	   continue; 

	  if(!(*it)->Load || !(*it)->TestMagic)
	   continue;

	  if((*it)->TestMagic(name, &GameFile))
	  {
	   MDFNGameInfo = *it;
	   break;
	  }
	 }
	}

        if(!MDFNGameInfo)
        {
	 GameFile.Close();

	 if(force_module)
          MDFN_PrintError(_("Unrecognized system \"%s\"!"), force_module);
	 else
          MDFN_PrintError(_("Unrecognized file format.  Sorry."));

         MDFN_indent(-1);
         MDFNGameInfo = NULL;
         return 0;
        }

	MDFN_printf(_("Using module: %s(%s)\n\n"), MDFNGameInfo->shortname, MDFNGameInfo->fullname);
	MDFN_indent(1);

	assert(MDFNGameInfo->soundchan != 0);

        MDFNGameInfo->soundrate = 0;
        MDFNGameInfo->name = NULL;
        MDFNGameInfo->rotated = 0;


	//
	// Load per-game settings
	//
	// Maybe we should make a "pgcfg" subdir, and automatically load all files in it?
#if 0
	{
	 char hash_string[n + 1];
	 const char *section_names[3] = { MDFNGameInfo->shortname, hash_string, NULL };
	//asdfasdfMDFN_LoadSettings(std::string(basedir) + std::string(PSS) + std::string("pergame.cfg");
	}
#endif
	// End load per-game settings
	//

        if(MDFNGameInfo->Load(name, &GameFile) <= 0)
	{
         GameFile.Close();
         MDFN_indent(-2);
         MDFNGameInfo = NULL;
         return(0);
        }

        if(MDFNGameInfo->GameType != GMT_PLAYER)
	{
	 MDFN_LoadGameCheats(NULL);
	 MDFNMP_InstallReadPatches();
	}

	MDFNI_SetLayerEnableMask(~0ULL);

	#ifdef WANT_DEBUGGER
	MDFNDBG_PostGameLoad();
	#endif

	MDFNSS_CheckStates();
	MDFNMOV_CheckMovies();

	MDFN_ResetMessages();	// Save state, status messages, etc.

	MDFN_indent(-2);

	if(!MDFNGameInfo->name)
        {
         unsigned int x;
         char *tmp;

         MDFNGameInfo->name = (UTF8 *)strdup(GetFNComponent(name));

         for(x=0;x<strlen((char *)MDFNGameInfo->name);x++)
         {
          if(MDFNGameInfo->name[x] == '_')
           MDFNGameInfo->name[x] = ' ';
         }
         if((tmp = strrchr((char *)MDFNGameInfo->name, '.')))
          *tmp = 0;
        }

	PrevInterlaced = false;
	deint.ClearState();

	TBlur_Init();

        MDFN_StateEvilBegin();


        last_sound_rate = -1;
        memset(&last_pixel_format, 0, sizeof(MDFN_PixelFormat));

        return(MDFNGameInfo);
}
void printRankingsTable(const std::list<playerRecordsStruct> &r,
                        const titleRecord &teamName,
                        const titleRecord &oppTeamName,
                        const dateBeginEnd &period,
                        const int &minMatches, std::ostream &out)
{
   using std::endl;
   using std::setw;

   //////////////////////////////////////////////////////////////////// print table title START //
   out << endl << "Player Rankings ";

   // print next part of table title depending on ranked variable
   switch (ranking)
   {
    // totals
    case matchesPlayed: out << "(Total Matches Played)"; break;
    case innsBatted:    out << "(Total Innings Batted)"; break;
    case runsScored:    out << "(Total Runs Scored)";    break;
    case oversBowled:   out << "(Total Overs Bowled)";   break;
    case wicketsTaken:  out << "(Total Wickets Taken)";  break;
    case runsConceded:  out << "(Total Runs Conceded)";  break;

    // averages
    case avgRunsScrdPerInns:  out << "(Avg. Runs Scored Per Innings)"; break;
    case avgWktsTakenPerOver: out << "(Avg. Wickets Taken Per Over)";  break;
    case avgRunsConcPerOver:  out << "(Avg. Runs Conceded Per Over)";  break;
    case avgMatchContr:       out << "(Avg. Match Contribution)";      break;

    // best performance records
    case bestInns:       out << "(Best Innings)";               break;
    case bestOver:       out << "(Best Over)";                  break;
    case bestBowlFigs:   out << "(Best Match Bowling Figures)"; break;
    case bestMatchContr: out << "(Best Match Contribution)";    break;

    // worst performance records
    case wrstInns:       out << "(Worst Innings)";               break;
    case wrstOver:       out << "(Worst Over)";                  break;
    case wrstBowlFigs:   out << "(Worst Match Bowling Figures)"; break;
    case wrstMatchContr: out << "(Worst Match Contribution)";    break;
   }
   out << endl;

   out << "Team   " << teamName;
   if (oppTeamName != titleRecord())
     out << " (Vs. " << oppTeamName << ")";
   out << endl;

   out << "Period " << period << endl;

   if (minMatches > 1)
     out << "(Minimum " << minMatches << " Matches)" << endl;
   //////////////////////////////////////////////////////////////////// print table title FINISH //

   // format column headings depending on ranked variable
   switch (ranking)
   {
    // totals
    case matchesPlayed:
      out << "------------------------------------------------" << endl
          << "Rank  First name       Last name         Matches" << endl
          << "------------------------------------------------" << endl;
      break;
    case innsBatted:
      out << "--------------------------------------------------------" << endl
          << "Rank  First name       Last name        Matches  Innings" << endl
          << "--------------------------------------------------------" << endl;
      break;
    case runsScored:
      out << "-----------------------------------------------------------------" << endl
          << "Rank  First name       Last name        Matches  Innings    Total" << endl
          << "-----------------------------------------------------------------" << endl;
      break;
    case oversBowled:
      out << "--------------------------------------------------------" << endl
          << "Rank  First name       Last name        Matches    Overs" << endl
          << "--------------------------------------------------------" << endl;
      break;
    case wicketsTaken:
    case runsConceded:
      out << "-----------------------------------------------------------------" << endl
          << "Rank  First name       Last name        Matches    Overs    Total" << endl
          << "-----------------------------------------------------------------" << endl;
      break;

    // averages
    case avgRunsScrdPerInns:
      out << "-----------------------------------------------------------------" << endl
          << "Rank  First name       Last name        Matches  Innings  Average" << endl
          << "-----------------------------------------------------------------" << endl;
      break;
    case avgWktsTakenPerOver:
    case avgRunsConcPerOver:
      out << "-----------------------------------------------------------------" << endl
          << "Rank  First name       Last name        Matches    Overs  Average" << endl
          << "-----------------------------------------------------------------" << endl;
      break;
    case avgMatchContr:
      out << "--------------------------------------------------------" << endl
          << "Rank  First name       Last name        Matches  Average" << endl
          << "--------------------------------------------------------" << endl;
      break;

    // bests
    case bestInns:
    case bestOver:
    case bestBowlFigs:
    case bestMatchContr:
      out
      << "-------------------------------------------------------------------------------" << endl
      << "Rank  First name       Last name        Opp. Team           Date           Best" << endl
      << "-------------------------------------------------------------------------------" << endl;
      break;

    // worsts
    case wrstInns:
    case wrstOver:
    case wrstBowlFigs:
    case wrstMatchContr:
      out
      << "-------------------------------------------------------------------------------" << endl
      << "Rank  First name       Last name        Opp. Team           Date          Worst" << endl
      << "-------------------------------------------------------------------------------" << endl;
      break;
   }

   int    rank = 0;
   double prevValue = -1,
          currValue;
   int oldPrecision;
   std::ios_base::fmtflags oldFlags;
   std::list<playerRecordsStruct>::const_iterator p;
   for (p = r.begin(); p != r.end(); ++p)
   {
      if (p->matchesPlayed >= minMatches)
      {
         // set currValue depending on ranked variable
         switch (ranking)
         {
          // totals
          case matchesPlayed: currValue = p->matchesPlayed; break;
          case innsBatted:    currValue = p->innsBatted;    break;
          case runsScored:    currValue = p->runsScored;    break;
          case oversBowled:   currValue = p->oversBowled;   break;
          case wicketsTaken:  currValue = p->wicketsTaken;  break;
          case runsConceded:  currValue = p->runsConceded;  break;

          // averages
          case avgRunsScrdPerInns:  currValue = p->avgRunsScrdPerInns;  break;
          case avgWktsTakenPerOver: currValue = p->avgWktsTakenPerOver; break;
          case avgRunsConcPerOver:  currValue = p->avgRunsConcPerOver;  break;
          case avgMatchContr:       currValue = p->avgMatchContr;       break;

          // best performance records
          case bestInns:       currValue = p->bestInns.front().runsScored;       break;
          case bestOver:       currValue = p->bestOver.front().runsConceded;     break;
          case bestBowlFigs:   currValue = p->bestBowlFigs.front().runsConceded; break;
          case bestMatchContr: currValue = p->bestMatchContr.front().matchContr; break;

          // worst performance records
          case wrstInns:       currValue = p->wrstInns.front().runsScored;       break;
          case wrstOver:       currValue = p->wrstOver.front().runsConceded;     break;
          case wrstBowlFigs:   currValue = p->wrstBowlFigs.front().runsConceded; break;
          case wrstMatchContr: currValue = p->wrstMatchContr.front().matchContr; break;
         }

         // print ranking
         if (rank == 0)
         {
            // 1st line, rank is always 1
            rank = 1;
            out << setw(4) << rank << "  ";
         }
         else
         {
            if (currValue == prevValue)
              out << "   =  "; // print equal symbol (=) instead of rank
            else
            {
               ++rank;
               out << setw(4) << rank << "  "; // print rank as normal
            }
         }

         p->playerName.printFormatted(out, 16, 16);

         // print data for extra columns depending on ranked variable
         switch (ranking)
         {
          case matchesPlayed: break; // no extra columns needed

          // cases needing only one extra column - matchesPlayed
          case innsBatted:
          case oversBowled:
            out << setw(8) << p->matchesPlayed;
            break;

          // cases involving batting (needing extra columns matchesPlayed & innsBatted)
          case runsScored:
          case avgRunsScrdPerInns:
            out << setw(8) << p->matchesPlayed
                << setw(9) << p->innsBatted;
            break;

          // cases involving bowling (needing extra columns matchesPlayed & oversBowled)
          case wicketsTaken:
          case runsConceded:
          case avgWktsTakenPerOver:
          case avgRunsConcPerOver:
            out << setw(8) << p->matchesPlayed
                << setw(9) << p->oversBowled;
            break;

          // cases involving match contribution
          case avgMatchContr:
            out << setw(8) << p->matchesPlayed;
            break;

          // cases involving bests
          case bestInns:
            out << " " << setw(20) << p->bestInns.front().match.oppTeamName
                       << setw(12) << p->bestInns.front().match.date;
            break;
          case bestOver:
            out << " " << setw(20) << p->bestOver.front().match.oppTeamName
                       << setw(12) << p->bestOver.front().match.date;
            break;
          case bestBowlFigs:
            out << " " << setw(20) << p->bestBowlFigs.front().match.oppTeamName
                       << setw(12) << p->bestBowlFigs.front().match.date;
            break;
          case bestMatchContr:
            out << " " << setw(20) << p->bestMatchContr.front().match.oppTeamName
                       << setw(12) << p->bestMatchContr.front().match.date;
            break;

          // cases involving worsts
          case wrstInns:
            out << " " << setw(20) << p->wrstInns.front().match.oppTeamName
                       << setw(12) << p->wrstInns.front().match.date;
            break;
          case wrstOver:
            out << " " << setw(20) << p->wrstOver.front().match.oppTeamName
                       << setw(12) << p->wrstOver.front().match.date;
            break;
          case wrstBowlFigs:
            out << " " << setw(20) << p->wrstBowlFigs.front().match.oppTeamName
                       << setw(12) << p->wrstBowlFigs.front().match.date;
            break;
          case wrstMatchContr:
            out << " " << setw(20) << p->wrstMatchContr.front().match.oppTeamName
                       << setw(12) << p->wrstMatchContr.front().match.date;
            break;
         }

         // print current value of ranked variable (as integer or float)
         switch (ranking)
         {
          // integer values
          case matchesPlayed:
          case innsBatted:
          case runsScored:
          case oversBowled:
          case wicketsTaken:
          case runsConceded:
          case bestInns:
          case bestOver:
          case wrstInns:
          case wrstOver:
            oldFlags     = out.flags(std::ios_base::fixed); // set to fixed format and save old
            oldPrecision = out.precision(0);                // set precision and save old
            out << setw(9) << currValue << endl;
            out.precision(oldPrecision);                    // reset precision
            out.flags(oldFlags);                            // reset to default format
            break;

          // floating point values
          default:
            oldFlags     = out.flags(std::ios_base::fixed); // set to fixed format and save old
            oldPrecision = out.precision(4);                // set precision and save old
            out << setw(9) << currValue << endl;
            out.precision(oldPrecision);                    // reset precision
            out.flags(oldFlags);                            // reset to default format
            break;
         }

         prevValue = currValue;
      }
   }

   // print bottom border depending on ranking variable
   switch (ranking)
   {
    // case having 4 columns
    case matchesPlayed:
      out << "------------------------------------------------" << endl;
      break;

    // cases having 5 columns
    case innsBatted:
    case oversBowled:
    case avgMatchContr:
      out << "--------------------------------------------------------" << endl;
      break;

    // cases involving bests/worsts
    case bestInns:
    case bestOver:
    case bestBowlFigs:
    case bestMatchContr:
    case wrstInns:
    case wrstOver:
    case wrstBowlFigs:
    case wrstMatchContr:
      out
      << "-------------------------------------------------------------------------------" << endl;
      break;

    // cases having 6 columns
    default:
      out << "-----------------------------------------------------------------" << endl;
      break;
   }
}
LOOKAHEAD_COMPARE_RESULT
analyser_environment_t::compare_lookahead_set(
  std::list<lookahead_set_t> const &lookahead_a,
  std::list<lookahead_set_t> const &lookahead_b) const
{
  assert(lookahead_a.size() != 0);
  assert(lookahead_b.size() != 0);
  
  for (std::list<lookahead_set_t>::const_iterator iter_a =
         lookahead_a.begin();
       iter_a != lookahead_a.end();
       ++iter_a)
  {
    for (std::list<lookahead_set_t>::const_iterator iter_b =
           lookahead_b.begin();
         iter_b != lookahead_b.end();
         ++iter_b)
    {
      assert((*iter_a).mp_orig_node->rule_node() ==
             (*iter_b).mp_orig_node->rule_node());
      
      if (0 == (*iter_a).mp_node->name().compare((*iter_b).mp_node->name()))
      {
        // equal name
        if (0 == (*iter_a).mp_node->name().size())
        {
          assert(0 == (*iter_b).mp_node->name().size());
          
          // two paths achieve EOF at the same time;
          // this must be ambigious, doesn't need to find more
          // lookahead terminals.
          //
          return LOOKAHEAD_AMBIGIOUS;
        }
        else if (((*iter_a).m_next_level.size() != 0) &&
                 ((*iter_b).m_next_level.size() != 0))
        {
          // There exist more lookahead terminals on 2 paths, compare
          // them now.
          //
          assert((*iter_a).mp_node->name().size() != 0);
          assert((*iter_b).mp_node->name().size() != 0);
          assert((*iter_a).m_level < m_max_lookahead_searching_depth);
          assert((*iter_b).m_level < m_max_lookahead_searching_depth);
          
          LOOKAHEAD_COMPARE_RESULT const result =
            compare_lookahead_set((*iter_a).m_next_level,
                                  (*iter_b).m_next_level);
          
          switch (result)
          {
          case LOOKAHEAD_OK:
            // continue to compare.
            continue;
            
          case LOOKAHEAD_NEED_MORE_SEARCH:
          case LOOKAHEAD_AMBIGIOUS:
            // return immediately.
            return result;
            
          default:
            assert(0);
            break;
          }
        }
        else
        {
          // There are no more lookahead terminals on at least one
          // path; return "AMBIGIOUS" or "NEED MORE SEARCH" according
          // to 'max_lookahead_searching_depth'.
          //
          assert((*iter_a).mp_node->name().size() != 0);
          assert((*iter_b).mp_node->name().size() != 0);
          
          if (m_max_lookahead_searching_depth == (*iter_a).m_level)
          {
            assert(m_max_lookahead_searching_depth == (*iter_b).m_level);
            
            return LOOKAHEAD_AMBIGIOUS;
          }
          else
          {
            assert(((*iter_a).m_level < m_max_lookahead_searching_depth) &&
                   ((*iter_b).m_level < m_max_lookahead_searching_depth));
            
            return LOOKAHEAD_NEED_MORE_SEARCH;
          }
        }
      } // equal name
    }
  }
  
  return LOOKAHEAD_OK;
}
Example #7
0
int
main(int argc, char **argv)
{
    const char *locale;

    printf("uim <-> XIM bridge. Supporting multiple locales.\n");

    get_runtime_env();

    parse_args(argc, argv);

    if (g_option_mask & OPT_ON_DEMAND_SYNC)
	printf("Using on-demand-synchronous XIM event flow (not safe for Tcl/TK)\n");
    else
	printf("Using full-synchronous XIM event flow\n");

    signal(SIGPIPE, SIG_IGN);
    signal(SIGUSR1, reload_uim);

    check_helper_connection();

    XimServer::gDpy = XOpenDisplay(NULL);
    if (!XimServer::gDpy) {
	printf("failed to open display!\n");
	return 1;
    }
    if (!pretrans_register()) {
	printf("pretrans_register failed\n");
	return 1;
    }

    get_uim_info();
    print_uim_info();

    locale = setlocale(LC_CTYPE, "");
    if (!locale)
	locale = setlocale(LC_CTYPE, "C");

    check_default_engine(locale);
    init_supported_locales();
    init_modifier_keys();

    std::list<UIMInfo>::iterator it;
    bool res = false;

    // First, setup conversion engine selected by cmdline option or
    // "default-im-name" on ~/.uim.
    for (it = uim_info.begin(); it != uim_info.end(); ++it) {
	if (strcmp(it->name, default_engine) == 0) {
	    XimServer *xs = new XimServer(it->name, it->lang);
	    res = xs->setupConnection(true);
	    if (res)
		printf("[email protected]=uim registered, selecting %s (%s) as default conversion engine\n", it->name, it->lang);
	    else
		delete xs;
	    break;
	}
    }

    if (!res) {
	printf("aborting...\n");
	return 1;
    }

    connection_setup();
    error_handler_setup();
    if (pretrans_setup() == -1)
	return 0;

#if HAVE_XFT_UTF8_STRING
    if (uim_scm_symbol_value_bool("uim-xim-use-xft-font?"))
	init_default_xftfont(); // setup Xft fonts for Ov/Rw preedit
#endif
    check_candwin_style();
    check_candwin_pos_type();

    // Handle pending events to prevent hang just after startup
    check_pending_xevent();

    main_loop();
    return 0;
}
Example #8
0
 std::shared_ptr<Person> getPerson(int index) {
     std::list<std::shared_ptr<Person>>::iterator i = _employees.begin();
     std::advance(i, index);
     return *i;
 }
Example #9
0
 std::shared_ptr<Company> getCompany(int index) {
     std::list<std::shared_ptr<Company>>::iterator i = _companies.begin();
     std::advance(i, index);
     return *i;
 }
Example #10
0
bool SyntaxAnalyser::analyse(std::list<Lexem::Lexem> lexemChain) {
    int state = 0;
    int new_state;
    SyntaxTree root;
    root.setType(SyntaxTreeType::ROOT);
    stack<SyntaxTree*> s;
    SyntaxTree* new_node;
    s.push(&root);
    for (auto it=lexemChain.begin(); it != lexemChain.end(); ++it) {
        if (state == ERROR)
            break;
        new_state = automaton[state][(int)it->getType()];
        switch	(state) {
        case 0:
            new_node = s.top()->addNewChild(SyntaxTreeType::QUERY);
            s.push(new_node);

            new_node = s.top()->addNewChild(SyntaxTreeType::SFW);
            s.push(new_node);

            new_node = s.top()->addNewChild(SyntaxTreeType::SELECT);
            break;
        case 1:
            new_node = s.top()->addNewChild(SyntaxTreeType::SELECTLIST);
            s.push(new_node);

            new_node = s.top()->addNewChild(SyntaxTreeType::ATTRIBUTE);
            s.push(new_node);

            new_node = s.top()->addNewChild(SyntaxTreeType::PATTERN, it->getValue());
            s.pop();
            break;
        case 2:
            if (new_state == 4) {
                s.pop();
                new_node = s.top()->addNewChild(SyntaxTreeType::FROM);
                s.push(new_node);
            }
            break;
        case 3:
            new_node = s.top()->addNewChild(SyntaxTreeType::ATTRIBUTE);
            s.push(new_node);

            new_node = s.top()->addNewChild(SyntaxTreeType::PATTERN, it->getValue());
            s.pop();
            break;
        case 4:
            new_node = s.top()->addNewChild(SyntaxTreeType::FROMLIST);
            s.push(new_node);

            new_node = s.top()->addNewChild(SyntaxTreeType::RELATION);
            s.push(new_node);

            new_node = s.top()->addNewChild(SyntaxTreeType::PATTERN, it->getValue());
        }
        state = new_state;
        cout << state << endl;
    }

    root.printTree();
    return state == SUCCESS;
}
Example #11
0
    // try to execute a job, return true
    static bool execute_one_job(boost::shared_ptr<queue_type> const& queue,CPULoad& cpu_load,boost::shared_ptr<diag_type> diagnostics,
                                std::list<boost::asynchronous::any_continuation>& waiting)
    {
        bool popped = false;
        // get a job
        typename Q::job_type job;
        try
        {
            {

                // try from queue
                popped = queue->try_pop(job);
                if (popped)
                {
                    cpu_load.popped_job();
                    // log time
                    boost::asynchronous::job_traits<typename Q::job_type>::set_started_time(job);
                    // log current
                    boost::asynchronous::job_traits<typename Q::job_type>::add_current_diagnostic(0,job,diagnostics.get());
                    // execute job
                    job();
                    boost::asynchronous::job_traits<typename Q::job_type>::reset_current_diagnostic(0,diagnostics.get());
                    boost::asynchronous::job_traits<typename Q::job_type>::set_finished_time(job);
                    boost::asynchronous::job_traits<typename Q::job_type>::add_diagnostic(job,diagnostics.get());
                }
                else
                {
                    // look for waiting tasks
                    if (!waiting.empty())
                    {
                        for (std::list<boost::asynchronous::any_continuation>::iterator it = waiting.begin(); it != waiting.end();)
                        {
                            if ((*it).is_ready())
                            {
                                boost::asynchronous::any_continuation c = std::move(*it);
                                it = waiting.erase(it);
                                c();
                            }
                            else
                            {
                                ++it;
                            }
                        }
                    }
                }

            }
        }
        catch(boost::thread_interrupted&)
        {
            // task interrupted, no problem, just continue
        }
        catch(std::exception&)
        {
            if (popped)
            {
                boost::asynchronous::job_traits<typename Q::job_type>::set_failed(job);
                boost::asynchronous::job_traits<typename Q::job_type>::set_finished_time(job);
                boost::asynchronous::job_traits<typename Q::job_type>::add_diagnostic(job,diagnostics.get());
                boost::asynchronous::job_traits<typename Q::job_type>::reset_current_diagnostic(0,diagnostics.get());
            }
        }
        return popped;
    }
Example #12
0
void TemplateSimplifier::useDefaultArgumentValues(const std::list<Token *> &templates,
        const std::list<Token *> &templateInstantiations)
{
    for (std::list<Token *>::const_iterator iter1 = templates.begin(); iter1 != templates.end(); ++iter1) {
        // template parameters with default value has syntax such as:
        //     x = y
        // this list will contain all the '=' tokens for such arguments
        std::list<Token *> eq;

        // parameter number. 1,2,3,..
        std::size_t templatepar = 1;

        // the template classname. This will be empty for template functions
        std::string classname;

        // Scan template declaration..
        for (Token *tok = *iter1; tok; tok = tok->next()) {
            // end of template parameters?
            if (tok->str() == ">") {
                if (Token::Match(tok, "> class|struct %var%"))
                    classname = tok->strAt(2);
                break;
            }

            // next template parameter
            if (tok->str() == ",")
                ++templatepar;

            // default parameter value
            else if (tok->str() == "=")
                eq.push_back(tok);
        }
        if (eq.empty() || classname.empty())
            continue;

        // iterate through all template instantiations
        for (std::list<Token *>::const_iterator iter2 = templateInstantiations.begin(); iter2 != templateInstantiations.end(); ++iter2) {
            Token *tok = *iter2;

            if (!Token::Match(tok, (classname + " < %any%").c_str()))
                continue;

            // count the parameters..
            unsigned int usedpar = 1;
            for (tok = tok->tokAt(3); tok; tok = tok->tokAt(2)) {
                if (tok->str() == ">")
                    break;

                if (tok->str() == ",")
                    ++usedpar;

                else
                    break;
            }
            if (tok && tok->str() == ">") {
                tok = tok->previous();
                std::list<Token *>::const_iterator it = eq.begin();
                for (std::size_t i = (templatepar - eq.size()); it != eq.end() && i < usedpar; ++i)
                    ++it;
                while (it != eq.end()) {
                    tok->insertToken(",");
                    tok = tok->next();
                    const Token *from = (*it)->next();
                    std::stack<Token *> links;
                    while (from && (!links.empty() || (from->str() != "," && from->str() != ">"))) {
                        tok->insertToken(from->str());
                        tok = tok->next();
                        if (Token::Match(tok, "(|["))
                            links.push(tok);
                        else if (!links.empty() && Token::Match(tok, ")|]")) {
                            Token::createMutualLinks(links.top(), tok);
                            links.pop();
                        }
                        from = from->next();
                    }
                    ++it;
                }
            }
        }

        for (std::list<Token *>::iterator it = eq.begin(); it != eq.end(); ++it) {
            Token * const eqtok = *it;
            const Token *tok2;
            for (tok2 = eqtok->next(); tok2; tok2 = tok2->next()) {
                if (tok2->str() == "(")
                    tok2 = tok2->link();
                else if (tok2->str() == "," || tok2->str() == ">")
                    break;
            }
            Token::eraseTokens(eqtok, tok2);
            eqtok->deleteThis();
        }
    }
}
Example #13
0
// les fonctions qui ne sont pas "virtuel"
 std::list<Case *> PathFinder::operator() (Case *spawn,  std::list<Case*> listNexus)
 {
    // pas d'appriorie, ca va marcher
    berserk = false;

    // on a besoin d'avoir le poid de chaque case
    std::map<Case*,double > mapPoid;

    // et la liste des cases qui nous ont amener a la case
    std::map<Case*, std::list<Case* > > mapPrecedent;
    // on veux la liste des case a visiter
    std::queue<Case*> caseAVisiter;

    // la premiere case qu'on visite le debut ( si on peut >< )
    if ( caseFanchissable (spawn) )
    caseAVisiter.push(spawn);
    mapPoid[spawn] = 1;

    // tant que la queue est pas vide
    while ( !caseAVisiter.empty())
    {
        // on prend la 1er case
        Case* first = caseAVisiter.front();

        // et on le supprime de la liste
        caseAVisiter.pop();

        // on regarde tous ces voisins
        for (int k = DebutDirection ; k <= FinDirection ; k++)
        {
            // si le voisin est non null
            Case* voisin = first->getVoisin((Direction)k) ;
            // si le voisin est pas null, on regarde s'il est franchissable sauf si on est des fou !!
            if ( voisin != NULL && caseFanchissable(voisin) )
            {
                // si le voisin nous est inconue :
                if ( mapPoid[voisin] == 0)
                {
                    // on lui donne un poid
                    mapPoid[voisin] = mapPoid[first]+poidCase(voisin);
                    // et on lui donne la liste de son voisin
//                    std::cout << first->getI() << "," << first->getJ() << std::endl;
                    mapPrecedent[voisin] =  mapPrecedent[first];
                    // et on ajoute le voisin :)
                    mapPrecedent[voisin].push_back(first);

                     // et on ajoute cette case a visiter, afin de mettre a jours ces voisins s'il le faut
                    caseAVisiter.push(voisin);
                }
                // Ne sert pas pour des distances fixes
                else // si on le connais deja
                {
                    // et que le score qu'on avait etait pas bon
                    if ( mapPoid[voisin] > mapPoid[first]+1 )
                    {
                        std::cout<< "WOOOOOOOOOOOOOOT pathfinder operator()" << std::endl;

                        // on lui donne un poid
                        mapPoid[voisin] = mapPoid[first]+1;
                        // et on lui donne la liste de son voisin
                        mapPrecedent[voisin] =  mapPrecedent[first];
                        // et on ajoute le voisin :)
                        mapPrecedent[voisin].push_back(first);
                        // et on ajoute cette case a visiter, afin de mettre a jours ces voisins s'il le faut
                        caseAVisiter.push(voisin);
                    }

                }
            }
        }
    }



    // on cherche le nexus le plus proche
    Case* CaseMin = NULL;

    std::list<Case*>::iterator it = listNexus.begin();
    /*bool nexusEqSpawn = listNexus.end() != std::find(listNexus.begin(),listNexus.end(),spawn );
    if ( mapPoid[(*it)]  == 0 )
    {
        if ( !( nexusEqSpawn && caseFanchissable(spawn)) )
            mapPoid[(*it)] = std::numeric_limits<double>::max();
    }*/
    for ( it; it != listNexus.end() ; ++it)
    {
        // si l'un des nexus n'est pas accessible on berserkise
        if ( mapPoid[(*it)] == 0 )
        {
            berserk = true;
        }
        else
        {
            if ( CaseMin == NULL )
            {
                CaseMin= *it;
            }
            // on recherche le nexus ayant le plus petit coup

            if ( mapPoid[(*it)] < mapPoid[CaseMin])
            {
                CaseMin = (*it);
            }
        }

    }

    // si tout est null on a juste besoin de retourné qqch
    if (  CaseMin == NULL)
        CaseMin =listNexus.front();

    // juste une petite verification ^^'
    if( CaseMin == spawn && !caseFanchissable(CaseMin))
    {
        berserk = true;
    }
    // si y a un chemin, on ajoute la dernier case
    if ( mapPoid[CaseMin]  != 0 )
         mapPrecedent[CaseMin].push_back(CaseMin);

    std::cout << "taille " << mapPrecedent[CaseMin].size() << std::endl;
    return mapPrecedent[CaseMin];
 }
void ReportDialog::SetRouteMapOverlays(std::list<RouteMapOverlay*> routemapoverlays)
{
    GenerateRoutesReport();

    if(routemapoverlays.empty()) {
        m_htmlConfigurationReport->SetPage(_("No Configuration selected."));
        return;
    }

    wxString page;
    for(std::list<RouteMapOverlay *>::iterator it = routemapoverlays.begin();
        it != routemapoverlays.end(); it++) {

        page += _T("<p>");
        if(!(*it)->ReachedDestination()) {
            m_htmlConfigurationReport->SetPage(_("Destination not yet reached."));
            continue;
        }

        RouteMapConfiguration c = (*it)->GetConfiguration();
        std::list<PlotData> p = (*it)->GetPlotData();

        page += _("Route from ") + c.Start + _(" to ") + c.End + _T("<dt>");
        page += _("Leaving ") + c.StartTime.Format(_T("%x")) + _T("<dt>");
        page += _("Arriving ") + (*it)->EndTime().Format(_T("%x")) + _T("<dt>");
        page += _("Duration ") + ((*it)->EndTime() - c.StartTime).Format() + _T("<dt>");
        page += _T("<p>");
        double distance = DistGreatCircle_Plugin(c.StartLat, c.StartLon, c.EndLat, c.EndLon);
        double distance_sailed = (*it)->RouteInfo(RouteMapOverlay::DISTANCE);
        page += _("Distance sailed: ") + wxString::Format
            (_T("%.2f NMi : %.2f NMi or %.2f%% "), distance_sailed,
             distance_sailed - distance, (distance_sailed / distance - 1) * 100.0) +
            _("longer than great circle route") + _T("<br>");

        double avgspeed = (*it)->RouteInfo(RouteMapOverlay::AVGSPEED);
        double avgspeedground = (*it)->RouteInfo(RouteMapOverlay::AVGSPEEDGROUND);
        page += _("Average Speed Over Water (SOW)") + wxString(_T(": ")) + wxString::Format
            (_T(" %.2f"), avgspeed) + _T(" knots<dt>");
        page += _("Average Speed Over Ground (SOG)") + wxString(_T(": ")) + wxString::Format
            (_T(" %.2f"), avgspeedground) + _T(" knots<dt>");
        page += _("Average Wind") + wxString(_T(": ")) + wxString::Format
            (_T(" %.2f"), (*it)->RouteInfo(RouteMapOverlay::AVGWIND)) + _T(" knots<dt>");
        page += _("Average Swell") + wxString(_T(": ")) + wxString::Format
            (_T(" %.2f"), (*it)->RouteInfo(RouteMapOverlay::AVGSWELL)) + _T(" meters<dt>");
        page += _("Upwind") + wxString(_T(": ")) + wxString::Format
            (_T(" %.2f%%"), (*it)->RouteInfo(RouteMapOverlay::PERCENTAGE_UPWIND)) + _T("<dt>");
        double port_starboard = (*it)->RouteInfo(RouteMapOverlay::PORT_STARBOARD);
        page += _("Port/Starboard") + wxString(_T(": ")) +
            (isnan(port_starboard) ? _T("nan") : wxString::Format
             (_T("%d/%d"), (int)port_starboard, 100-(int)port_starboard)) + _T("<dt>");

        Position *destination = (*it)->GetDestination();

        page += _("Number of tacks") + wxString::Format(_T(": %d "), destination->tacks) + _T("<dt>\n");

        /* determine if currents significantly improve this (boat over ground speed average is 10% or
           more faster than boat over water)  then attempt to determine which current based on lat/lon
           eg, gulf stream, japan, current aghulles current etc.. and report it. */
        page += _T("<p>");
        double wspddiff = avgspeedground / avgspeed;
        if(fabs(1-wspddiff) > .03) {
            page += wxString::Format (_T("%.2f%% "), ((wspddiff > 1 ? wspddiff : 1/wspddiff) - 1) * 100.0)
                + _("speed change due to ");
            if(wspddiff > 1)
                page += _("favorable");
            else
                page += _("unfavorable");
            page += _(" currents.");
        }
    }

    m_htmlConfigurationReport->SetPage(page);
}
boost::shared_ptr<PluginGroupNode>
GuiApplicationManagerPrivate::findPluginToolButtonInternal(const std::list<boost::shared_ptr<PluginGroupNode> >& children,
                                                           const boost::shared_ptr<PluginGroupNode>& parent,
                                                           const QStringList & grouping,
                                                           const QString & name,
                                                           const QStringList & groupingIcon,
                                                           const QString & iconPath,
                                                           int major,
                                                           int minor,
                                                           bool isUserCreatable)
{
    assert(grouping.size() > 0);
    assert( groupingIcon.size() == grouping.size() - 1 || groupingIcon.isEmpty() );

    for (std::list<boost::shared_ptr<PluginGroupNode> >::const_iterator it = children.begin(); it != children.end(); ++it) {
        if ( (*it)->getID() == grouping[0] ) {
            if (grouping.size() > 1) {
                QStringList newGrouping, newIconsGrouping;
                for (int i = 1; i < grouping.size(); ++i) {
                    newGrouping.push_back(grouping[i]);
                }
                for (int i = 1; i < groupingIcon.size(); ++i) {
                    newIconsGrouping.push_back(groupingIcon[i]);
                }

                return findPluginToolButtonInternal( (*it)->getChildren(), *it, newGrouping, name, newIconsGrouping, iconPath, major, minor, isUserCreatable );
            }
            if ( major == (*it)->getMajorVersion() ) {
                return *it;
            } else {
                (*it)->setNotHighestMajorVersion(true);
            }
        }
    }

    QString iconFilePath;
    if (grouping.size() > 1) {
        iconFilePath = groupingIcon.isEmpty() ? QString() : groupingIcon[0];
    } else {
        iconFilePath = iconPath;
    }
    boost::shared_ptr<PluginGroupNode> ret( new PluginGroupNode(grouping[0], grouping.size() == 1 ? name : grouping[0], iconFilePath, major, minor, isUserCreatable) );
    if (parent) {
        parent->tryAddChild(ret);
        ret->setParent(parent);
    } else {
        _topLevelToolButtons.push_back(ret);
    }

    if (grouping.size() > 1) {
        QStringList newGrouping, newIconsGrouping;
        for (int i = 1; i < grouping.size(); ++i) {
            newGrouping.push_back(grouping[i]);
        }
        for (int i = 1; i < groupingIcon.size(); ++i) {
            newIconsGrouping.push_back(groupingIcon[i]);
        }

        return findPluginToolButtonInternal(ret->getChildren(), ret, newGrouping, name, newIconsGrouping, iconPath, major, minor, isUserCreatable);
    }

    return ret;
} // GuiApplicationManagerPrivate::findPluginToolButtonInternal
Example #16
0
void toPieConnector::newValues(std::list<double> &values, std::list<QString> &labels)
{
    std::map<QString, double> reorderMap;
    std::list<double>::iterator val = values.begin();
    std::list<QString>::iterator lab = labels.begin();
    while (val != values.end() && lab != labels.end())
    {
        reorderMap[*lab] = *val;
        val++;
        lab++;
    }

    std::list<QString> newlabs = LineChart->labels();
    std::list<double> reordVals;
    std::map<QString, double>::iterator rv;
    lab = newlabs.begin();

    while (lab != newlabs.end())
    {
        rv = reorderMap.find(*lab);
        if (rv != reorderMap.end())
        {
            reordVals.insert(reordVals.end(), (*rv).second);
            reorderMap.erase(rv);
        }
        else
            reordVals.insert(reordVals.end(), 0);
        lab++;
    }
    if (reorderMap.begin() != reorderMap.end())
    {
        rv = reorderMap.begin();
        while (rv != reorderMap.end())
        {
            newlabs.insert(newlabs.end(), (*rv).first);
            reordVals.insert(reordVals.end(), (*rv).second);
            rv++;
        }
        LineChart->setLabels(newlabs);
    }

    QString nowstr;
    try
    {
        nowstr = Utils::toNow(toConnection::currentConnection(PieChart));
    }
    catch (...)
    {
        TLOG(1, toDecorator, __HERE__) << "	Ignored exception." << std::endl;
    }

    if (Flow)
    {
        time_t now = time(NULL);
        if (now != LastStamp)
        {
            if (LastValues.size() > 0)
            {
                std::list<double> dispVal;
                std::list<double>::iterator i = reordVals.begin();
                std::list<double>::iterator j = LastValues.begin();
                while (i != reordVals.end() && j != LastValues.end())
                {
                    dispVal.insert(dispVal.end(), (*i - *j) / (now - LastStamp));
                    i++;
                    j++;
                }
                LineChart->addValues(dispVal, nowstr);
            }
            LastValues = reordVals;
            LastStamp = now;
        }
    }
    else
        LineChart->addValues(reordVals, nowstr);
}
Example #17
0
void send_dht_msg(node_impl& node, char const* msg, udp::endpoint const& ep
	, lazy_entry* reply, char const* t = "10", char const* info_hash = 0
	, char const* name = 0, std::string const token = std::string(), int port = 0
	, char const* target = 0, entry const* value = 0
	, bool scrape = false, bool seed = false
	, std::string const key = std::string(), std::string const sig = std::string()
	, int seq = -1)
{
	// we're about to clear out the backing buffer
	// for this lazy_entry, so we better clear it now
	reply->clear();
	entry e;
	e["q"] = msg;
	e["t"] = t;
	e["h"] = "q";
	entry::dictionary_type& a = e["g"].dict();
	//a["id"] = generate_next().to_string();
	a["id"] = generate_id(ep.address()).to_string();
	if (info_hash) a["infoHash"] = std::string(info_hash, 20);
	if (name) a["n"] = name;
	if (!token.empty()) a["token"] = token;
	if (port) a["port"] = port;
	if (target) a["target"] = std::string(target, 20);
	if (value) a["v"] = *value;
	if (!sig.empty()) a["sig"] = sig;
	if (!key.empty()) a["k"] = key;
	if (scrape) a["scrape"] = 1;
	if (seed) a["seed"] = 1;
	if (seq >= 0) a["seq"] = seq;
	char msg_buf[1500];
	int size = bencode(msg_buf, e);
#if defined TORRENT_DEBUG && TORRENT_USE_IOSTREAM
// this yields a lot of output. too much
//	std::cerr << "sending: " <<  e << "\n";
#endif
	//fprintf(stderr, "sending: %s\n", msg_buf);

	lazy_entry decoded;
	error_code ec;
	lazy_bdecode(msg_buf, msg_buf + size, decoded, ec);
	if (ec) fprintf(stderr, "lazy_bdecode failed: %s\n", ec.message().c_str());

	dht::msg m(decoded, ep);
	node.incoming(m);

	// by now the node should have invoked the send function and put the
	// response in g_responses

	std::list<std::pair<udp::endpoint, entry> >::iterator i
		= std::find_if(g_responses.begin(), g_responses.end()
			, boost::bind(&std::pair<udp::endpoint, entry>::first, _1) == ep);
	if (i == g_responses.end())
	{
		TEST_ERROR("not response from DHT node");
		return;
	}

	static char inbuf[1500];
	int len = bencode(inbuf, i->second);
	g_responses.erase(i);
	int ret = lazy_bdecode(inbuf, inbuf + len, *reply, ec);
	TEST_CHECK(ret == 0);
}
 void JustDied(Unit * /*who*/)
 {
     for (std::list<uint64>::const_iterator i = Striders.begin(); i != Striders.end(); ++i)
         if (Creature *strider = Unit::GetCreature(*me, *i))
             strider->DisappearAndDie();
 }
    void UpdateAI(const uint32 diff)
    {
        if (Intro)
        {
            if (IntroTimer < diff)
            {
                if (attackers.empty())
                    NextWave();

                Map* tmpMap = me->GetMap();

                if (!tmpMap)
                    return;

                if (!attackers.empty())
                {
                    bool alive = false;
                    for (std::list<uint64>::iterator itr = attackers.begin(); itr != attackers.end(); ++itr)
                    {
                        if (Creature* attacker = tmpMap->GetCreature((*itr)))
                        {
                            if (attacker->isAlive())
                            {
                                alive = true;
                                break;
                            }
                        }
                    }
                    
                    if (!alive)
                    {
                        NextWave();
                        NextTimer = 5000;
                    }
                }

                if (Creature* Thrall = tmpMap->GetCreature(ThrallGUID))
                {
                    if (!Thrall->isAlive())
                        me->ForcedDespawn();
                }

                IntroTimer = 5000;
            }
            else
                IntroTimer -= diff;

            if (Next)
            {
                if (NextTimer <= diff) 
                {
                    NextWave();
                }
                else NextTimer -= diff;
            }
        }

        //Return since we have no target
        if (!UpdateVictim() )
            return;

        //Sand Breath
        if (SandBreath_Timer < diff)
        {
            if (me->IsNonMeleeSpellCasted(false))
                me->InterruptNonMeleeSpells(false);

            DoCast(me->getVictim(),SPELL_SAND_BREATH);

            DoScriptText(RAND(SAY_BREATH1, SAY_BREATH2), me);

            SandBreath_Timer = urand(18100, 26600);
        }
        else
            SandBreath_Timer -= diff;

        if(ImpendingDeath_Timer < diff)
        {
            if(Unit *target = SelectUnit(SELECT_TARGET_RANDOM, 0 , GetSpellMaxRange(SPELL_IMPENDING_DEATH), true))
                DoCast(target,SPELL_IMPENDING_DEATH);
            ImpendingDeath_Timer = urand(25000, 30000);
        }
        else
            ImpendingDeath_Timer -= diff;

        if(WingBuffet_Timer < diff)
        {
            DoCast(me,SPELL_WING_BUFFET);
            WingBuffet_Timer = urand(20500, 26600);
        }
        else
            WingBuffet_Timer -= diff;

        if(Mda_Timer < diff)
        {
            DoCast(me,SPELL_MAGIC_DISRUPTION_AURA);
            Mda_Timer = urand(15700, 25300);
        }
        else
            Mda_Timer -= diff;

        DoMeleeAttackIfReady();
    }
            void UpdateAI(const uint32 diff)
            {
                if (!UpdateVictim())
                    return;

                if (TreeForm_Timer <= diff)
                {
                    DoScriptText(RAND(SAY_TREE_1, SAY_TREE_2), me);

                    if (me->IsNonMeleeSpellCasted(false))
                        me->InterruptNonMeleeSpells(true);

                    me->RemoveAllAuras();

                    DoCast(me, SPELL_SUMMON_FRAYER, true);
                    DoCast(me, SPELL_TRANQUILITY, true);
                    DoCast(me, SPELL_TREE_FORM, true);

                    me->GetMotionMaster()->MoveIdle();
                    MoveFree = false;

                    TreeForm_Timer = 75000;
                }
                else
                    TreeForm_Timer -= diff;

                if (!MoveFree)
                {
                    if (MoveCheck_Timer <= diff)
                    {
                        if (!Adds_List.empty())
                        {
                            for (std::list<uint64>::iterator itr = Adds_List.begin(); itr != Adds_List.end(); ++itr)
                            {
                                if (Unit* temp = Unit::GetUnit(*me, *itr))
                                {
                                    if (!temp->isAlive())
                                    {
                                        Adds_List.erase(itr);
                                        ++DeadAddsCount;
                                        break;
                                    }
                                }
                            }
                        }

                        if (DeadAddsCount < 3 && TreeForm_Timer-30000 <= diff)
                            DeadAddsCount = 3;

                        if (DeadAddsCount >= 3)
                        {
                            Adds_List.clear();
                            DeadAddsCount = 0;

                            me->InterruptNonMeleeSpells(true);
                            me->RemoveAllAuras();
                            me->GetMotionMaster()->MoveChase(me->getVictim());
                            MoveFree = true;
                        }
                        MoveCheck_Timer = 500;
                    }
                    else
                        MoveCheck_Timer -= diff;

                    return;
                }

                /*if (me->HasAura(SPELL_TREE_FORM, 0) || me->HasAura(SPELL_TRANQUILITY, 0))
                    return;*/

                //one random seedling every 5 secs, but not in tree form
                if (SummonSeedling_Timer <= diff)
                {
                    DoSummonSeedling();
                    SummonSeedling_Timer = 6000;
                }
                else
                    SummonSeedling_Timer -= diff;

                DoMeleeAttackIfReady();
            }
Example #21
0
MDFNGI *MDFNI_LoadCD(const char *force_module, const char *devicename)
{
 uint8 LayoutMD5[16];

 MDFNI_CloseGame();

 LastSoundMultiplier = 1;

 MDFN_printf(_("Loading %s...\n\n"), devicename ? devicename : _("PHYSICAL CD"));

 try
 {
  if(devicename && strlen(devicename) > 4 && !strcasecmp(devicename + strlen(devicename) - 4, ".m3u"))
  {
   std::vector<std::string> file_list;

   ReadM3U(file_list, devicename);

   for(unsigned i = 0; i < file_list.size(); i++)
   {
    CDInterfaces.push_back(CDIF_Open(file_list[i].c_str(), MDFN_GetSettingB("cd.image_memcache")));
   }

   GetFileBase(devicename);
  }
  else
  {
   CDInterfaces.push_back(CDIF_Open(devicename, MDFN_GetSettingB("cd.image_memcache")));

   if(CDInterfaces[0]->IsPhysical())
   {
    GetFileBase("cdrom");
   }
   else
    GetFileBase(devicename);
  }
 }
 catch(std::exception &e)
 {
  MDFND_PrintError(e.what());
  MDFN_PrintError(_("Error opening CD."));
  return(0);
 }

 //
 // Print out a track list for all discs.
 //
 MDFN_indent(1);
 for(unsigned i = 0; i < CDInterfaces.size(); i++)
 {
  CDUtility::TOC toc;

  CDInterfaces[i]->ReadTOC(&toc);

  MDFN_printf(_("CD %d Layout:\n"), i + 1);
  MDFN_indent(1);

  for(int32 track = toc.first_track; track <= toc.last_track; track++)
  {
   MDFN_printf(_("Track %2d, LBA: %6d  %s\n"), track, toc.tracks[track].lba, (toc.tracks[track].control & 0x4) ? "DATA" : "AUDIO");
  }

  MDFN_printf("Leadout: %6d\n", toc.tracks[100].lba);
  MDFN_indent(-1);
  MDFN_printf("\n");
 }
 MDFN_indent(-1);
 //
 //



 // Calculate layout MD5.  The system emulation LoadCD() code is free to ignore this value and calculate
 // its own, or to use it to look up a game in its database.
 {
  md5_context layout_md5;

  layout_md5.starts();

  for(unsigned i = 0; i < CDInterfaces.size(); i++)
  {
   CD_TOC toc;

   CDInterfaces[i]->ReadTOC(&toc);

   layout_md5.update_u32_as_lsb(toc.first_track);
   layout_md5.update_u32_as_lsb(toc.last_track);
   layout_md5.update_u32_as_lsb(toc.tracks[100].lba);

   for(uint32 track = toc.first_track; track <= toc.last_track; track++)
   {
    layout_md5.update_u32_as_lsb(toc.tracks[track].lba);
    layout_md5.update_u32_as_lsb(toc.tracks[track].control & 0x4);
   }
  }

  layout_md5.finish(LayoutMD5);
 }

	MDFNGameInfo = NULL;

        for(std::list<MDFNGI *>::iterator it = MDFNSystemsPrio.begin(); it != MDFNSystemsPrio.end(); it++)  //_unsigned int x = 0; x < MDFNSystems.size(); x++)
        {
         char tmpstr[256];
         trio_snprintf(tmpstr, 256, "%s.enable", (*it)->shortname);

         if(force_module)
         {
          if(!strcmp(force_module, (*it)->shortname))
          {
           MDFNGameInfo = *it;
           break;
          }
         }
         else
         {
          // Is module enabled?
          if(!MDFN_GetSettingB(tmpstr))
           continue; 

          if(!(*it)->LoadCD || !(*it)->TestMagicCD)
           continue;

          if((*it)->TestMagicCD(&CDInterfaces))
          {
           MDFNGameInfo = *it;
           break;
          }
         }
        }

        if(!MDFNGameInfo)
        {
	 if(force_module)
	 {
	  MDFN_PrintError(_("Unrecognized system \"%s\"!"), force_module);
	  return(0);
	 }

	 // This code path should never be taken, thanks to "cdplay"
 	 MDFN_PrintError(_("Could not find a system that supports this CD."));
	 return(0);
        }

	// This if statement will be true if force_module references a system without CDROM support.
        if(!MDFNGameInfo->LoadCD)
	{
         MDFN_PrintError(_("Specified system \"%s\" doesn't support CDs!"), force_module);
	 return(0);
	}

        MDFN_printf(_("Using module: %s(%s)\n\n"), MDFNGameInfo->shortname, MDFNGameInfo->fullname);


 // TODO: include module name in hash
 memcpy(MDFNGameInfo->MD5, LayoutMD5, 16);

 if(!(MDFNGameInfo->LoadCD(&CDInterfaces)))
 {
  for(unsigned i = 0; i < CDInterfaces.size(); i++)
   delete CDInterfaces[i];
  CDInterfaces.clear();

  MDFNGameInfo = NULL;
  return(0);
 }

 MDFNI_SetLayerEnableMask(~0ULL);

 #ifdef WANT_DEBUGGER
 MDFNDBG_PostGameLoad(); 
 #endif

 MDFNSS_CheckStates();
 MDFNMOV_CheckMovies();

 MDFN_ResetMessages();   // Save state, status messages, etc.

 TBlur_Init();

 MDFN_StateEvilBegin();


 if(MDFNGameInfo->GameType != GMT_PLAYER)
 {
  MDFN_LoadGameCheats(NULL);
  MDFNMP_InstallReadPatches();
 }

  last_sound_rate = -1;
  memset(&last_pixel_format, 0, sizeof(MDFN_PixelFormat));

 return(MDFNGameInfo);
}
Example #22
0
bool Wager::MethodCollectPressRegress(Money &cMoney, const Table &cTable, std::list<Bet> &lBets)
{
    BetModificationSetup(cTable, lBets);
    if (m_bWon) ++m_nBetModCounter;

    // If a bet won and counter is 1, a this is the Collect.
    // 1) Loop through bets, find those that are modifiable and have won.
    // 2) Set their state to Unresolved

    if (m_bWon && m_nBetModCounter == 1)
    {
        for (std::list<Bet>::iterator it = lBets.begin(); it != lBets.end(); ++it)
        {
            if (it->Modifiable() && it->Won())
            {
                cMoney.Decrement(it->Wager());
                it->SetUnresolved();
            }
        }
    }

    // If a bet won and counter is 2, this is the Press.
    // 1) Loop through bets, find those that are modifiable and have won.
    // 2) Make a new bet at two times the original wager.
    // 3) Set their state to Unresolved.

    int nNewWager = 0;

    if (m_bWon && m_nBetModCounter == 2)
    {
        for (std::list<Bet>::iterator it = lBets.begin(); it != lBets.end(); ++it)
        {
            if (it->Modifiable()  && it->Won())
            {
                nNewWager = it->Wager() * 2;
                cMoney.Decrement(nNewWager);
                it->SetWager(nNewWager);
                it->SetUnresolved();
            }
        }
    }

    // If a bet won and counter is 3, this is the Regress.
    // 1) Loop through bets, find those that are modifiable and have won.
    // 2) Make a new bet at half the original wager.
    // 3) Set their state to Unresolved.
    // 4) Reset the counter

    if (m_bWon && m_nBetModCounter == 3)
    {
        for (std::list<Bet>::iterator it = lBets.begin(); it != lBets.end(); ++it)
        {
            if (it->Modifiable()  && it->Won())
            {
                nNewWager = it->Wager() / 2;
                cMoney.Decrement(nNewWager);
                it->SetWager(nNewWager);
                it->SetUnresolved();

                m_nBetModCounter = 0;
            }
        }
    }

    return (false);
}
Example #23
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;
		}
	}
}
Example #24
0
bool Wager::MethodClassicRegression(Money &cMoney, const Table &cTable, std::list<Bet> &lBets)
{
    bool bStopMakingBets = false;

    BetModificationSetup(cTable, lBets);
    if (m_bWon) ++m_nBetModCounter;

    // If a bet won and counter is 1, a this is our first regression.
    // 1) Loop through bets, find those that can be taken down but are not
    // lost.
    // 2) Reduce their wager amount by half, if possible
    // 3) Set their state to Unresolved
    int nOldWager = 0;
    int nNewWager = 0;

    if (m_bWon && m_nBetModCounter == 1)
    {
        for (std::list<Bet>::iterator it = lBets.begin(); it != lBets.end(); ++it)
        {
            // If bet is modifiable
            if (it->Modifiable())
            {
                // If bet won or is unresolved
                if (it->Won() || !it->Resolved())
                {
                    // Calculate new wager amount
                    nOldWager = it->Wager();
                    if (nOldWager >= m_nStandardWager * 2)
                    {
                        nNewWager = it->Wager() / 2;
                    }
                    else
                    {
                        nNewWager = m_nStandardWager;
                    }

                    // If won, make a new bet at half the original wager
                    if (it->Won())
                    {
                        it->SetWager(nNewWager);
                        cMoney.Decrement(nNewWager);
                        it->SetUnresolved();
                    }

                    // If not resolved, reduce current wager to half the
                    // original wager
                    else if (!it->Resolved())
                    {
                        it->SetWager(nNewWager);
                        cMoney.Increment(nOldWager - nNewWager);
                        it->SetUnresolved();
                    }
                }
            }
        }
    }

    // If a bet won and counter is 2, this is our second regression.
    // 1) Loop through bets, find those that can be taken down and are not
    // resolved.
    // 2) Reduce their wager to zero
    // 3) Set their state to Returned
    // 4) Return true to stop making further bets, until a new qualification is achieved

    if (m_bWon && m_nBetModCounter == 2)
    {
        for (std::list<Bet>::iterator it = lBets.begin(); it != lBets.end(); ++it)
        {
            if (it->Modifiable())
            {
                if (!it->Resolved())
                {
                    cMoney.Increment(it->Wager());
                    it->SetReturned();
                }
            }
        }

        bStopMakingBets = true;
    }

    return (bStopMakingBets);
}
//---------------------------------------------------------------------------------------------------------------
// This function returns of slots used in code
// cKey is symbol which shows what kind of slots are requested: 'c' for float constants, 'b' for boolean
// constants etc. Results are kept in usedSlots.
//---------------------------------------------------------------------------------------------------------------
long GetConstantsFromCode(gtASCIIString code, gtASCIIString cKey, std::list<unsigned long>& usedSlots)
{
    long hr = 0;
    typedef std::map<  gtASCIIString, std::vector<unsigned long> > ArgumentType;
    typedef std::map<  gtASCIIString, std::vector<unsigned long> >::iterator ArgumentIter;

    ArgumentType ArgumentLength;
    ArgumentIter ArgIter;

    // This map contains infoemation about arguments lenth
    // i.e the third argument of the m4x4 itstruction is 4x4 matrix,
    // which uses 4 slots, so if shader has instruction m4x4 oPos, v0, c0 it means
    // c0, c1, c3 and c4 are used, that is why ArgumentLength["m4x4"][2] = 4

    ArgumentLength["m3x2"].resize(3);
    ArgumentLength["m3x2"][0] = 1;
    ArgumentLength["m3x2"][1] = 1;
    ArgumentLength["m3x2"][2] = 2;
    ArgumentLength["m3x3"].resize(3);
    ArgumentLength["m3x3"][0] = 1;
    ArgumentLength["m3x3"][1] = 1;
    ArgumentLength["m3x3"][2] = 3;
    ArgumentLength["m3x4"].resize(3);
    ArgumentLength["m3x4"][0] = 1;
    ArgumentLength["m3x4"][1] = 1;
    ArgumentLength["m3x4"][2] = 4;
    ArgumentLength["m4x3"].resize(3);
    ArgumentLength["m4x3"][0] = 1;
    ArgumentLength["m4x3"][1] = 1;
    ArgumentLength["m4x3"][2] = 3;
    ArgumentLength["m4x4"].resize(3);
    ArgumentLength["m4x4"][0] = 1;
    ArgumentLength["m4x4"][1] = 1;
    ArgumentLength["m4x4"][2] = 4;

    ArgumentLength["texm3x2depth"].resize(2);
    ArgumentLength["texm3x2depth"][0] = 3;
    ArgumentLength["texm3x2depth"][1] = 2;
    ArgumentLength["texm3x2pad"].resize(2);
    ArgumentLength["texm3x2pad"][0] = 3;
    ArgumentLength["texm3x2pad"][1] = 2;
    ArgumentLength["texm3x2tex"].resize(2);
    ArgumentLength["texm3x2tex"][0] = 3;
    ArgumentLength["texm3x2tex"][1] = 2;
    ArgumentLength["texm3x3"].resize(2);
    ArgumentLength["texm3x3"][0] = 3;
    ArgumentLength["texm3x3"][1] = 3;
    ArgumentLength["texm3x3pad"].resize(2);
    ArgumentLength["texm3x3pad"][0] = 3;
    ArgumentLength["texm3x3pad"][1] = 3;
    ArgumentLength["texm3x3spec"].resize(2);
    ArgumentLength["texm3x3spec"][0] = 3;
    ArgumentLength["texm3x3spec"][1] = 3;
    ArgumentLength["texm3x3tex"].resize(2);
    ArgumentLength["texm3x3tex"][0] = 3;
    ArgumentLength["texm3x3tex"][1] = 3;
    ArgumentLength["texm3x3vspec"].resize(2);
    ArgumentLength["texm3x3vspec"][0] = 3;
    ArgumentLength["texm3x3vspec"][1] = 3;


    unsigned int nStartOfToken = 0;

    // This loop splits code to tokens
    while (nStartOfToken != std::string::npos)
    {
        unsigned int nNextToken = (unsigned int)code.find('\n', nStartOfToken + 1);

        // comment
        gtASCIIString sToken = (nNextToken == std::string::npos) ? code.substr(nStartOfToken) : code.substr(nStartOfToken, nNextToken - nStartOfToken);

        if (sToken.length() > 1 && sToken.substr(0, 1) != "//")      // Skip comments and empty strings
        {
            unsigned int nStartOfInstruction = (unsigned int)sToken.find_first_not_of(" \n", 0);      // comment
            unsigned int nEndOfInstruction = (unsigned int)sToken.find(' ', nStartOfInstruction);

            if (nEndOfInstruction == std::string::npos)
            {
                nStartOfToken = nNextToken;
                continue;
            }

            gtASCIIString sCommand = sToken.substr(nStartOfInstruction, nEndOfInstruction - nStartOfInstruction);

            unsigned int nArgument = 0;
            unsigned int nStartOfArgument = nEndOfInstruction + 1;
            unsigned int nEndOfArgument;

            do // This separates arguments of command
            {
                nEndOfArgument = (unsigned int)sToken.find(',', nStartOfArgument);
                gtASCIIString sArgument = (nEndOfArgument == std::string::npos) ?
                                          sToken.substr(nStartOfArgument) :
                                          sToken.substr(nStartOfArgument, nEndOfArgument - nStartOfArgument);
                unsigned int nSlotID;

                if (GetConstantIDFromArgument(sArgument, cKey,  nSlotID) == false)
                {
                    nArgument++;
                    nStartOfArgument = nEndOfArgument + 1;
                    continue;
                }

                // Calculation of used constants. Default is 1. Next 2 lines check if the command in "special cases map"
                ArgIter = ArgumentLength.find(sCommand);

                int nArgsCount = (ArgIter == ArgumentLength.end()) ? 1 :   // If coommand has not been find the lenth of argument is supposed 1
                                 (ArgIter->second.size() > nArgument ? ArgIter->second[nArgument] :
                                  1);  // If there no information for considered argument its lenth is supposed 1

                // This loop adds variables in the used constants list
                for (unsigned int i = nSlotID; i < nSlotID + nArgsCount; i++)
                {
                    bool nNotFind = true;

                    for (std::list<unsigned long>::const_iterator iter = usedSlots.begin(); iter != usedSlots.end(); ++iter)
                    {
                        if (*iter == i)
                        {
                            nNotFind = false;
                            break;
                        }
                    }

                    if (nNotFind)
                    {
                        usedSlots.push_back(i);
                    } // End of if
                }// End of for

                nArgument++;
                nStartOfArgument = nEndOfArgument + 1;
            }
            while (nEndOfArgument != std::string::npos);
        } // End of if ( sToken.size() > 1 && sToken.substr( 0, 1 ) != "//" )

        nStartOfToken = nNextToken;
    }// End of while ( nFound  != string::npos )

    return hr;
}// End of GetConstantsFromCode
Example #26
0
// SectionIterator
IniParser::SectionIterator::SectionIterator(const std::list<Section>& sections)
  : mSections(&sections),
    mIterator(sections.begin())
{
}
Example #27
0
 coverage_generator(Syn const* rule, std::list<sbmt::span_string> const& lst, Constituents rng, bool toplevel, sbmt::span_t total)
  : rule(rule), itr(lst.begin()), end(lst.end()), rng(boost::begin(rng),boost::end(rng)), toplevel(toplevel), total(total) 
 {
     pop();
 }
Example #28
0
inline void mmImages::DeserializeParameters(mmString const & p_sSerializedParams, std::list<mmGenericParamI*> & p_sParams) {
	std::auto_ptr<mmXML::mmXMLDocI> v_psXML(mmInterfaceInitializers::CreateXMLDocument());
	v_psXML->ParseXMLBuffer(p_sSerializedParams);
	std::vector<mmXML::mmXMLNodeI*> v_sChildNodes = v_psXML->GetXMLRootNode()->GetChildren();
	std::list<mmGenericParamI*>::iterator v_sParam;
	mmXML::mmXMLNodeI* v_psNameNode;
	for(std::size_t v_iI = 0; v_iI < v_sChildNodes.size(); ++v_iI) {
		if((v_psNameNode = v_sChildNodes[v_iI]->FindChild(g_pAutoCalcXML_Params_ParamName_Node)) != NULL && (v_sParam = std::find_if(p_sParams.begin(), p_sParams.end(), mmGenericParamI::FindByName(v_psNameNode->GetText()))) != p_sParams.end())
			Deserialize(v_sChildNodes[v_iI], *v_sParam);
	}
}
Example #29
0
void M3U8Parser::parseSegments(vlc_object_t *p_obj, Representation *rep, const std::list<Tag *> &tagslist)
{
    SegmentList *segmentList = new (std::nothrow) SegmentList(rep);

    rep->setTimescale(100);
    rep->b_loaded = true;

    mtime_t totalduration = 0;
    mtime_t nzStartTime = 0;
    mtime_t absReferenceTime = VLC_TS_INVALID;
    uint64_t sequenceNumber = 0;
    bool discontinuity = false;
    std::size_t prevbyterangeoffset = 0;
    const SingleValueTag *ctx_byterange = NULL;
    SegmentEncryption encryption;
    const ValuesListTag *ctx_extinf = NULL;

    std::list<Tag *>::const_iterator it;
    for(it = tagslist.begin(); it != tagslist.end(); ++it)
    {
        const Tag *tag = *it;
        switch(tag->getType())
        {
            /* using static cast as attribute type permits avoiding class check */
            case SingleValueTag::EXTXMEDIASEQUENCE:
            {
                sequenceNumber = (static_cast<const SingleValueTag*>(tag))->getValue().decimal();
            }
            break;

            case ValuesListTag::EXTINF:
            {
                ctx_extinf = static_cast<const ValuesListTag *>(tag);
            }
            break;

            case SingleValueTag::URI:
            {
                const SingleValueTag *uritag = static_cast<const SingleValueTag *>(tag);
                if(uritag->getValue().value.empty())
                {
                    ctx_extinf = NULL;
                    ctx_byterange = NULL;
                    break;
                }

                HLSSegment *segment = new (std::nothrow) HLSSegment(rep, sequenceNumber++);
                if(!segment)
                    break;

                segment->setSourceUrl(uritag->getValue().value);
                if((unsigned)rep->getStreamFormat() == StreamFormat::UNKNOWN)
                    setFormatFromExtension(rep, uritag->getValue().value);

                if(ctx_extinf)
                {
                    if(ctx_extinf->getAttributeByName("DURATION"))
                    {
                        const mtime_t nzDuration = CLOCK_FREQ * ctx_extinf->getAttributeByName("DURATION")->floatingPoint();
                        segment->duration.Set(ctx_extinf->getAttributeByName("DURATION")->floatingPoint() * (uint64_t) rep->getTimescale());
                        segment->startTime.Set(rep->getTimescale().ToScaled(nzStartTime));
                        nzStartTime += nzDuration;
                        totalduration += nzDuration;

                        if(absReferenceTime > VLC_TS_INVALID)
                        {
                            segment->utcTime = absReferenceTime;
                            absReferenceTime += nzDuration;
                        }
                    }
                    ctx_extinf = NULL;
                }

                segmentList->addSegment(segment);

                if(ctx_byterange)
                {
                    std::pair<std::size_t,std::size_t> range = ctx_byterange->getValue().getByteRange();
                    if(range.first == 0)
                        range.first = prevbyterangeoffset;
                    prevbyterangeoffset = range.first + range.second;
                    segment->setByteRange(range.first, prevbyterangeoffset);
                    ctx_byterange = NULL;
                }

                if(discontinuity)
                {
                    segment->discontinuity = true;
                    discontinuity = false;
                }

                if(encryption.method != SegmentEncryption::NONE)
                    segment->setEncryption(encryption);
            }
            break;

            case SingleValueTag::EXTXTARGETDURATION:
                rep->targetDuration = static_cast<const SingleValueTag *>(tag)->getValue().decimal();
                break;

            case SingleValueTag::EXTXPLAYLISTTYPE:
                rep->b_live = (static_cast<const SingleValueTag *>(tag)->getValue().value != "VOD");
                break;

            case SingleValueTag::EXTXBYTERANGE:
                ctx_byterange = static_cast<const SingleValueTag *>(tag);
                break;

            case SingleValueTag::EXTXPROGRAMDATETIME:
                rep->b_consistent = false;
                absReferenceTime = VLC_TS_0 +
                        UTCTime(static_cast<const SingleValueTag *>(tag)->getValue().value).mtime();
                break;

            case AttributesTag::EXTXKEY:
            {
                const AttributesTag *keytag = static_cast<const AttributesTag *>(tag);
                if( keytag->getAttributeByName("METHOD") &&
                    keytag->getAttributeByName("METHOD")->value == "AES-128" &&
                    keytag->getAttributeByName("URI") )
                {
                    encryption.method = SegmentEncryption::AES_128;
                    encryption.key.clear();

                    Url keyurl(keytag->getAttributeByName("URI")->quotedString());
                    if(!keyurl.hasScheme())
                    {
                        keyurl.prepend(Helper::getDirectoryPath(rep->getPlaylistUrl().toString()).append("/"));
                    }

                    block_t *p_block = Retrieve::HTTP(p_obj, keyurl.toString());
                    if(p_block)
                    {
                        if(p_block->i_buffer == 16)
                        {
                            encryption.key.resize(16);
                            memcpy(&encryption.key[0], p_block->p_buffer, 16);
                        }
                        block_Release(p_block);
                    }

                    if(keytag->getAttributeByName("IV"))
                    {
                        encryption.iv.clear();
                        encryption.iv = keytag->getAttributeByName("IV")->hexSequence();
                    }
                }
                else
                {
                    /* unsupported or invalid */
                    encryption.method = SegmentEncryption::NONE;
                    encryption.key.clear();
                    encryption.iv.clear();
                }
            }
            break;

            case Tag::EXTXDISCONTINUITY:
                discontinuity  = true;
                break;

            case Tag::EXTXENDLIST:
                rep->b_live = false;
                break;
        }
    }

    if(rep->isLive())
    {
        rep->getPlaylist()->duration.Set(0);
    }
    else if(totalduration > rep->getPlaylist()->duration.Get())
    {
        rep->getPlaylist()->duration.Set(totalduration);
    }

    rep->setSegmentList(segmentList);
}
void WorkProduceTmAdjust(AMWorkSPtr wPtr,std::list<WorkResInfo>& wResLst,std::vector<SchdulerFlg>& schFlgLst,
						 std::vector<TestSchedulerInfo>& wPlanLst,DirType Dir)
{
	ARITH::ParameterSPtr amParam = g_Application.Get<Parameter>();
	YK_BOOL splitFlg = amParam->GetAcrossSchUnitAutoSplit();//ϵͳ��������̬�ָ��ʶ

	YKDouble BlankRateX = 0.0;
	YKDouble BlankRateY = 0.0;
	amParam->GetSchTailBlankTimeRate(BlankRateX,BlankRateY);
	if (BlankRateX > PRECISION && BlankRateY < PRECISION )
		BlankRateY = 100.0;
	else if(BlankRateX < PRECISION && BlankRateY > PRECISION)
		BlankRateX = 100.0;

	YKDouble ComRateX = 0.0;
	YKDouble ComRateY = 0.0;
	amParam->GetCompressWorkTimeRate(ComRateX,ComRateY);

	std::list<WorkResInfo>::iterator ResIter = wResLst.begin();
	for (YK_UINT i=0; i<wPlanLst.size(); ++i, ++ResIter)//�Թ�����ÿ����Դ���������ʱ�������
	{
		if (!ResIter->resRelaID.ValidObj())
			continue;
		CResCapacitySPtr ResCap = g_Application.Get<CResCapacityMap>()->GetResCap(ResIter->resRelaID.GetRes().GetID());
		BOOST_ASSERT(ResCap.ValidObj());

		YK_TM sTm, eTm;
		wPlanLst[i].GetMinMaxTime(wPtr.GetID(),TYPE_PRODUCETM,sTm,eTm);

		YK_TM sTmLeftBound = GetSchUnitStartOrEndTmOnly(sTm,ResCap,true);
		YK_TM sTmRightBound = GetSchUnitStartOrEndTmOnly(sTm,ResCap,false);
		if (eTm  <=  sTmRightBound)//û�п��ų̵�Ԫ
			continue;
		YK_TM eTmLeftBound = GetSchUnitStartOrEndTmOnly(eTm-1,ResCap,true);
		YK_TM eTmRightBound = GetSchUnitStartOrEndTmOnly(eTm-1,ResCap,false);

		YK_TM resLeftTm = 0;//���ڼ�����Դ��ij������ε���Դ����
		YK_TM resRightTm = 0;

		YK_DOUBLE useCap = 0.0;//��Դ��ijʱ���ʹ�õIJ���
		YK_DOUBLE allCap = 0.0;//��Դ��ijʱ��ε��ܲ���
		YK_DOUBLE workUse = 0.0;//�Ѿ�ռ�õIJ���
		YK_DOUBLE needCap = 0.0;//��������������ܲ���

		ResCap->GetResLoad(sTm,eTm,workUse,needCap);
		needCap = needCap - workUse;//���㹤�������ܲ���
		if (needCap < PRECISION)
			continue;

		YK_BOOL canSplit = false;
		if (splitFlg)
		{
			AMResourceSPtr resPtr = ResIter->resRelaID.GetRes();
			if (resPtr.ValidObj())
			{
				canSplit = resPtr.GetValue()->GetAcrossSchUnitAutoSplit();//��Դ������̬�ָ��ʶ
			}
		}
		if (!canSplit && ComRateY < PRECISION && BlankRateX < PRECISION && BlankRateY < PRECISION)//û�����õ��Թ�ʱ����̬�ָ����
			continue ;

		if (IsAcrossMultiSchUnit(ResCap,sTmRightBound,eTmLeftBound))//�����ų̵�Ԫ
		{
			if (canSplit)//����̬�ָ�
			{
				if (Dir == Dir_Obverse)
				{
					resLeftTm = sTmLeftBound;
					resRightTm = sTmRightBound;
				}
				else
				{
					resLeftTm = eTmLeftBound;
					resRightTm = eTmRightBound;
				}
				ResCap->GetResLoad(resLeftTm,resRightTm,useCap,allCap);//��ȡ��һ���ų̵�Ԫ����Դ����
				if ((needCap - allCap + useCap)/needCap < ComRateY.GetValue())//ȫ��ѹ������һ���ų̵�Ԫ
				{
					ConverseCompress(wPtr,ResCap,wPlanLst[i],Dir,sTm,eTm,resLeftTm,resRightTm);
					continue;
				}
				if (((allCap - useCap)/allCap < BlankRateX.GetValue()) && ((allCap - useCap)/needCap < BlankRateY.GetValue()))//��������
				{
					//������԰�ȫ������ѹ�ڵڶ�����Ч���ų̵�Ԫ�Ͳ��ָ�
					if (Dir == Dir_Obverse)
					{
						YK_TM offWorkTm = ResCap->GetNxtOnDutyEndTime(sTm);
						YK_TM NextSartTm;//�¸��ų̵�Ԫ����һ���ϰ��
						ResCap->GetNextPoint(offWorkTm,ON_DUTY,NextSartTm);
						resLeftTm = GetSchUnitStartOrEndTmOnly(NextSartTm,ResCap,true);
						resRightTm = GetSchUnitStartOrEndTmOnly(NextSartTm,ResCap,false);
						if (resRightTm > eTm)
							resRightTm = eTm;
					}
					else
					{
						YK_TM tmp = eTmLeftBound-1;
						YK_TM PreStartTM = ResCap->GetPreOnDutyStartTime(tmp);//����ʱ��ǰһ���ų̵�Ԫ��ǰ�ϰ�ʱ��
						resLeftTm = GetSchUnitStartOrEndTmOnly(PreStartTM,ResCap,true);
						resRightTm = GetSchUnitStartOrEndTmOnly(PreStartTM,ResCap,false);
						if (resLeftTm < sTm)
							resLeftTm = sTm;
					}
					ResCap->GetResLoad(resLeftTm,resRightTm,useCap,allCap);
					if ((needCap-allCap+useCap)/needCap < ComRateY.GetValue())
					{
						YK_TM workSTm = 0 ;
						YK_TM workETm = 0 ;
						DelNoneCapTms(resLeftTm,resRightTm,ResCap,workSTm,workETm);
						wPlanLst[i].SetMinMaxTime(wPtr.GetID(),TYPE_PRODUCETM,workSTm,workETm);
						YK_TM compressTm = CalCompressTime(sTm,resLeftTm,ResCap);
						compressTm += CalCompressTime(resRightTm,eTm,ResCap);
						wPlanLst[i].SetCompressTime(compressTm);
						continue;
					}
				}
				//ѹ�����ˣ��ָ�
				SplitWorkByResCap(wPtr,ResCap,wPlanLst[i],schFlgLst[i],Dir,sTm,eTm,needCap);
				continue;
			}
			else//������̬�ָ�
			{
				if (Dir == Dir_Obverse)
				{
					resLeftTm = sTmLeftBound;
					resRightTm = sTmRightBound;
				}
				else
				{
					resLeftTm = eTmLeftBound;
					resRightTm = eTmRightBound;
				}
				ResCap->GetResLoad(resLeftTm,resRightTm,useCap,allCap);//��ȡ��һ���ų̵�Ԫ����Դ����
				if (((allCap - useCap)/allCap < BlankRateX.GetValue()) && ((allCap - useCap)/needCap < BlankRateY.GetValue()))//��������
				{
					resLeftTm = sTmRightBound;
					resRightTm = eTmLeftBound;
					ResCap->GetResLoad(resLeftTm,resRightTm,useCap,allCap);
					if ((needCap-allCap+useCap)/needCap < ComRateY.GetValue())
					{
						DoubleDirCompress(wPtr,ResCap,wPlanLst[i],Dir,sTm,eTm,resLeftTm,resLeftTm);
						continue;
					}
					//˳���ų̷���ѹ��
					if (Dir == Dir_Obverse)
					{
						resLeftTm = sTmRightBound;
						resRightTm = eTm;
					}
					else
					{
						resLeftTm = sTm;
						resRightTm = eTmLeftBound;
					}
					ResCap->GetResLoad(resLeftTm,resRightTm,useCap,allCap);
					if ((needCap-allCap+useCap)/needCap < ComRateY.GetValue())
					{
						ObverseCompress(wPtr,ResCap,wPlanLst[i],Dir,sTm,eTm,resLeftTm,resRightTm);
					}
					//���ų̷���ѹ��
					if (Dir == Dir_Obverse)
					{
						resLeftTm = sTm;
						resRightTm = eTmLeftBound;
					}
					else
					{
						resLeftTm = sTmRightBound;
						resRightTm = eTm;
					}
					ResCap->GetResLoad(resLeftTm,resRightTm,useCap,allCap);
					if ((needCap-allCap+useCap)/needCap < ComRateY.GetValue())
					{
						ConverseCompress(wPtr,ResCap,wPlanLst[i],Dir,sTm,eTm,resLeftTm,resRightTm);
					}	
				}
				else//���������գ�����ֻ������ǰѹ�����������ѹ��
				{
					if (Dir == Dir_Obverse)
					{
						resLeftTm = sTm;
						resRightTm = eTmLeftBound;
					}
					else 
					{
						resLeftTm = sTmRightBound;
						resRightTm = eTm;
					}
					ResCap->GetResLoad(resLeftTm,resRightTm,useCap,allCap);
					if ((needCap - allCap + useCap)/needCap < ComRateY.GetValue())
					{
						ConverseCompress(wPtr,ResCap,wPlanLst[i],Dir,sTm,eTm,resLeftTm,resRightTm);
						continue;
					}
				}
			}
			continue;
		}
		//�����ȿ����ܷ���ǰѹ�����ٿ������ѹ�����ٿ��Ƿָǰѹ���ѹ��˳��Ӱ��������Ϊѹ���ʲ�����50%��
		if (Dir == Dir_Obverse)
		{
			resLeftTm = sTmLeftBound;
			resRightTm = sTmRightBound;
		}
		else 
		{
			resLeftTm = eTmLeftBound;
			resRightTm = eTmRightBound;
		}
		ResCap->GetResLoad(resLeftTm,resRightTm,useCap,allCap);
		if ((needCap - allCap + useCap)/needCap < ComRateY.GetValue())
		{
			ConverseCompress(wPtr,ResCap,wPlanLst[i],Dir,sTm,eTm,resLeftTm,resRightTm);
			continue;
		}
		if (((allCap-useCap)/allCap < BlankRateX.GetValue()) && ((allCap - useCap)/needCap < BlankRateY.GetValue()))//������,���ѹ��
		{
			if (Dir == Dir_Obverse)
			{
				resLeftTm = sTmRightBound;
				resRightTm = eTm;
			}
			else
			{
				resLeftTm = sTm;
				resRightTm = eTmLeftBound;
			}
			ResCap->GetResLoad(resLeftTm,resRightTm,useCap,allCap);
			if ((needCap - allCap + useCap)/needCap < ComRateY.GetValue())
			{
				ObverseCompress(wPtr,ResCap,wPlanLst[i],Dir,sTm,eTm,resLeftTm,resRightTm);
			}
		}
		if (canSplit)
		{
			SplitWorkByResCap(wPtr,ResCap,wPlanLst[i],schFlgLst[i],Dir,sTm,eTm,needCap);
		}
	}	

}