// I'd love to have this not duplicate so much code from Pickup::pick_one_up(),
// but I don't see a clean way to do that.
static void move_items( const tripoint &src, bool from_vehicle,
                        const tripoint &dest, bool to_vehicle,
                        std::list<int> &indices, std::list<int> &quantities )
{
    tripoint source = src + g->u.pos();
    tripoint destination = dest + g->u.pos();

    int s_cargo, d_cargo;   // oui oui, mon frere
    s_cargo = d_cargo = -1;
    vehicle *s_veh, *d_veh; // 2diva4me
    s_veh = d_veh = nullptr;

    // load vehicle information if requested
    if(from_vehicle == true) {
        s_veh = g->m.veh_at(source, s_cargo);
        assert(s_veh != nullptr);
        s_cargo = s_veh->part_with_feature(s_cargo, "CARGO", false);
        assert(s_cargo >= 0);
    }
    if(to_vehicle == true) {
        d_veh = g->m.veh_at(destination, d_cargo);
        assert(d_veh != nullptr);
        d_cargo = d_veh->part_with_feature(d_cargo, "CARGO", false);
        assert(d_cargo >= 0);
    }

    std::vector<item> dropped_items;
    std::vector<item> dropped_worn;

    while( g->u.moves > 0 && !indices.empty() ) {
        int index = indices.back();
        int quantity = quantities.back();
        indices.pop_back();
        quantities.pop_back();

        item *temp_item = nullptr;

        temp_item = (from_vehicle == true) ?
            g->m.item_from(s_veh, s_cargo, index) :
            g->m.item_from(source, index);

        if( temp_item == nullptr ) {
            continue; // No such item.
        }

        item leftovers = *temp_item;

        if( quantity != 0 && temp_item->count_by_charges() ) {
            // Reinserting leftovers happens after item removal to avoid stacking issues.
            leftovers.charges = temp_item->charges - quantity;
            if( leftovers.charges > 0 ) {
                temp_item->charges = quantity;
            }
        } else {
            leftovers.charges = 0;
        }

        // Check that we can pick it up.
        if( !temp_item->made_of(LIQUID) ) {
            // Is it too bulky? We'll have to use our hands, then.
            if( !g->u.can_pickVolume(temp_item->volume()) && g->u.is_armed() ) {
                g->u.moves -= 20; // Pretend to be unwielding our gun.
            }

            // Is it too heavy? It'll take a while...
            if( !g->u.can_pickWeight(temp_item->weight(), true) ) {
                int overweight = temp_item->weight() - (g->u.weight_capacity() - g->u.weight_carried());

                // ...like one move cost per 100 grams over your leftover carry capacity.
                g->u.moves -= int(overweight / 100);
            }

            // Drop it first since we're going to delete the original.
            dropped_items.push_back( *temp_item );
            // I changed this to use a tripoint as an argument, but the function is not 3D yet.
            g->drop( dropped_items, dropped_worn, 0, destination, to_vehicle );

            // Remove from map or vehicle.
            if(from_vehicle == true) {
                s_veh->remove_item(s_cargo, index);
            } else {
                g->m.i_rem(source, index);
            }
            g->u.moves -= 100;

        }

        // If we didn't pick up a whole stack, put the remainder back where it came from.
        if( leftovers.charges > 0 ) {
            bool to_map = !from_vehicle;
            if( !to_map ) {
                to_map = !s_veh->add_item(s_cargo, leftovers);
            }
            if( to_map ){
                g->m.add_item_or_charges(source, leftovers);
            }
        }

        dropped_items.clear();
    }
}
void EarClipper::AddTriangle_R(std::vector<const FVector2*>& triangles,
                               const FVector2* trianglePoint1, std::list<const FVector2*>& collinearPoints1, 
                               const FVector2* trianglePoint2, std::list<const FVector2*>& collinearPoints2,
                               const FVector2* trianglePoint3, std::list<const FVector2*>& collinearPoints3)
{
   if (collinearPoints1.empty() && collinearPoints2.empty() && collinearPoints3.empty())
   {
      triangles.push_back(trianglePoint1);
      triangles.push_back(trianglePoint2);
      triangles.push_back(trianglePoint3);
   }
   else
   {
      if (!collinearPoints1.empty())
      {
         bool point3HasCollinearVertices = !collinearPoints3.empty();

         const FVector2* anchorPoint = point3HasCollinearVertices ? collinearPoints3.back() : trianglePoint3;

         const FVector2* lastPoint = trianglePoint1;

         for (const FVector2* collinearPoint : collinearPoints1)
         {
            triangles.push_back(lastPoint);
            triangles.push_back(collinearPoint);
            triangles.push_back(anchorPoint);

            lastPoint = collinearPoint;
         }

         std::list<const FVector2*> emptyList;

         if (point3HasCollinearVertices)
         {
            collinearPoints3.pop_back();

            if (collinearPoints3.empty())
            {
               triangles.push_back(anchorPoint);
               triangles.push_back(lastPoint);
               triangles.push_back(trianglePoint3);

               AddTriangle_R(triangles, trianglePoint2, collinearPoints2, trianglePoint3, collinearPoints3, lastPoint, emptyList);
            }
            else
            {
               triangles.push_back(lastPoint);
               triangles.push_back(trianglePoint2);
               triangles.push_back(anchorPoint);

               AddTriangle_R(triangles, trianglePoint3, collinearPoints3, anchorPoint, emptyList, trianglePoint2, collinearPoints2);
            }
         }
         else
         {
            AddTriangle_R(triangles, trianglePoint2, collinearPoints2, trianglePoint3, collinearPoints3, lastPoint, emptyList);
         }
      }
      else if (!collinearPoints2.empty())
      {
         AddTriangle_R(triangles, trianglePoint2, collinearPoints2, trianglePoint3, collinearPoints3, trianglePoint1, collinearPoints1);
      }
      else
      {
         AddTriangle_R(triangles, trianglePoint3, collinearPoints3, trianglePoint1, collinearPoints1, trianglePoint2, collinearPoints2);
      }
   }
}
Esempio n. 3
0
	void ReplaceScene(ETransitionType transition, float time)
	{
		Ak_CScene* pNewScene = new Ak_CScene;
		pNewScene->Create();

		cocos2d::Scene *pReplaceScene = NULL;
		if (NONE == transition)
		{
			pReplaceScene = pNewScene->GetScene();
		}
		else if (CROSS_FADE == transition)
		{
			pReplaceScene = cocos2d::TransitionCrossFade::create(time, pNewScene->GetScene());
		}
		else if (FADE == transition)
		{
			pReplaceScene = cocos2d::TransitionFade::create(time, pNewScene->GetScene());
		}
		else if (FADE_BL == transition)
		{
			pReplaceScene = cocos2d::TransitionFadeBL::create(time, pNewScene->GetScene());
		}
		else if (FADE_DOWN == transition)
		{
		}
		else if (FADE_TR == transition)
		{
		}
		else if (FADE_UP == transition)
		{
		}
		else if (FLIP_ANGULAR == transition)
		{
		}
		else if (FLIP_X == transition)
		{
		}
		else if (FLIP_Y == transition)
		{
		}
		else if (JUMP_ZOOM == transition)
		{
		}
		else if (MOVE_IN_B == transition)
		{
		}
		else if (MOVE_IN_L == transition)
		{
		}
		else if (MOVE_IN_R == transition)
		{
		}
		else if (MOVE_IN_T == transition)
		{
		}
		else if (PAGE_TURN == transition)
		{
		}
		else if (PROGRESS == transition)
		{
		}
		else if (PROGRESS_HORIZONTAL == transition)
		{
		}
		else if (PROGRESS_IN_OUT == transition)
		{
		}
		else if (PROGRESS_OUT_IN == transition)
		{
		}
		else if (PROGRESS_RADIAL_CCW == transition)
		{
		}
		else if (PROGRESS_RADIAL_CW == transition)
		{
		}
		else if (PROGRESS_VERTICAL == transition)
		{
		}

		cocos2d::Director::getInstance()->replaceScene(pReplaceScene);

		Ak_CScene* pOldScene = *(g_sceneList.rbegin());
		pOldScene->Destroy();
		delete pOldScene;
		g_sceneList.pop_back();
		g_sceneList.push_back(pNewScene);

	}
// I'd love to have this not duplicate so much code from Pickup::pick_one_up(),
// but I don't see a clean way to do that.
static void move_items( player &p, const tripoint &src, bool from_vehicle,
                        const tripoint &dest, bool to_vehicle,
                        std::list<int> &indices, std::list<int> &quantities )
{
    tripoint source = src + p.pos();
    tripoint destination = dest + p.pos();

    int s_cargo = -1;
    vehicle *s_veh = nullptr;

    // load vehicle information if requested
    if( from_vehicle ) {
        const cata::optional<vpart_reference> vp = g->m.veh_at( source ).part_with_feature( "CARGO",
                false );
        assert( vp );
        s_veh = &vp->vehicle();
        s_cargo = vp->part_index();
        assert( s_cargo >= 0 );
    }

    while( p.moves > 0 && !indices.empty() ) {
        int index = indices.back();
        int quantity = quantities.back();
        indices.pop_back();
        quantities.pop_back();

        item *temp_item = from_vehicle ? g->m.item_from( s_veh, s_cargo, index ) :
                          g->m.item_from( source, index );

        if( temp_item == nullptr ) {
            continue; // No such item.
        }

        item leftovers = *temp_item;

        if( quantity != 0 && temp_item->count_by_charges() ) {
            // Reinserting leftovers happens after item removal to avoid stacking issues.
            leftovers.charges = temp_item->charges - quantity;
            if( leftovers.charges > 0 ) {
                temp_item->charges = quantity;
            }
        } else {
            leftovers.charges = 0;
        }

        // Check that we can pick it up.
        if( !temp_item->made_of_from_type( LIQUID ) ) {
            // This is for hauling across zlevels, remove when going up and down stairs
            // is no longer teleportation
            int distance = src.z == dest.z ? std::max( rl_dist( src, dest ), 1 ) : 1;
            p.mod_moves( -Pickup::cost_to_move_item( p, *temp_item ) * distance );
            if( to_vehicle ) {
                put_into_vehicle_or_drop( p, item_drop_reason::deliberate, { *temp_item },
                                          destination );
            } else {
                drop_on_map( p, item_drop_reason::deliberate, { *temp_item }, destination );
            }
            // Remove from map or vehicle.
            if( from_vehicle ) {
                s_veh->remove_item( s_cargo, index );
            } else {
                g->m.i_rem( source, index );
            }
        }

        // If we didn't pick up a whole stack, put the remainder back where it came from.
        if( leftovers.charges > 0 ) {
            bool to_map = !from_vehicle;
            if( !to_map ) {
                to_map = !s_veh->add_item( s_cargo, leftovers );
            }
            if( to_map ) {
                g->m.add_item_or_charges( source, leftovers );
            }
        }
    }
}
    // tokenizes the string.  Edges must NOT have []'s
    void Tokenize( const wxString &pkt )
    {
        wxString temp = pkt;
        wxString minStr, maxStr;
        unsigned long long cur; // temporary long long to hold the "current" packet
        wxString str[4]; // at most we allow 4 parts to the packet
        temp.Replace(_(":"), _(",")); // replace :'s with ,'s (they're both separators)
        temp.Replace(_(";"), _(",")); // replace ;'s with ,'s (they're both separators)
        // explode the string
        for( int i=0; i < 4; ++i ) {
            str[i] = temp.BeforeFirst(',');
            temp   = temp.AfterFirst(',');
        }

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

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

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

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

                if( tokens.back().type == PARTIAL_PACKET_ADDITION ||
                    tokens.back().type == PARTIAL_PACKET_SUBTRACTION ||
                    tokens.back().type == PARTIAL_PACKET_MULTIPLICATION ||
                    tokens.back().type == PARTIAL_PACKET_DIVISION )
                {
                    tokens.back() = pktToken; // only store last symbol
                }
                else
                    tokens.push_back(pktToken);
            }
        }
        if( val.size() > 0 )
        {
            if( tokens.size() == 0 ) // if there was no expression token before this value, then default to addition
                tokens.push_back( PartialPacketToken(PARTIAL_PACKET_ADDITION, _("+")) );
            tokens.push_back( PartialPacketToken(PARTIAL_PACKET_VALUE, val) );
        }
        else if( 
            tokens.size() > 0 &&
            (tokens.back().type == PARTIAL_PACKET_ADDITION ||
             tokens.back().type == PARTIAL_PACKET_SUBTRACTION ||
             tokens.back().type == PARTIAL_PACKET_MULTIPLICATION ||
             tokens.back().type == PARTIAL_PACKET_DIVISION) )
        {
            tokens.pop_back(); // can't end with a symbol
        }
    }
Esempio n. 6
0
CContext::~CContext()
{
	g_backtrace.pop_back();
}
// I'd love to have this not duplicate so much code from Pickup::pick_one_up(),
// but I don't see a clean way to do that.
static void move_items( const tripoint &src, bool from_vehicle,
                        const tripoint &dest, bool to_vehicle,
                        std::list<int> &indices, std::list<int> &quantities )
{
    tripoint source = src + g->u.pos();
    tripoint destination = dest + g->u.pos();

    int s_cargo, d_cargo;   // oui oui, mon frere
    s_cargo = d_cargo = -1;
    vehicle *s_veh, *d_veh; // 2diva4me
    s_veh = d_veh = nullptr;

    // load vehicle information if requested
    if( from_vehicle ) {
        const cata::optional<vpart_reference> vp = g->m.veh_at( source ).part_with_feature( "CARGO",
                false );
        assert( vp );
        s_veh = &vp->vehicle();
        s_cargo = vp->part_index();
        assert( s_cargo >= 0 );
    }
    if( to_vehicle ) {
        const cata::optional<vpart_reference> vp = g->m.veh_at( destination ).part_with_feature( "CARGO",
                false );
        assert( vp );
        d_veh = &vp->vehicle();
        d_cargo = vp->part_index();
        assert( d_cargo >= 0 );
    }

    while( g->u.moves > 0 && !indices.empty() ) {
        int index = indices.back();
        int quantity = quantities.back();
        indices.pop_back();
        quantities.pop_back();

        item *temp_item = from_vehicle ? g->m.item_from( s_veh, s_cargo, index ) : g->m.item_from( source,
                          index );

        if( temp_item == nullptr ) {
            continue; // No such item.
        }

        item leftovers = *temp_item;

        if( quantity != 0 && temp_item->count_by_charges() ) {
            // Reinserting leftovers happens after item removal to avoid stacking issues.
            leftovers.charges = temp_item->charges - quantity;
            if( leftovers.charges > 0 ) {
                temp_item->charges = quantity;
            }
        } else {
            leftovers.charges = 0;
        }

        // Check that we can pick it up.
        if( !temp_item->made_of( LIQUID ) ) {
            g->u.mod_moves( -Pickup::cost_to_move_item( g->u, *temp_item ) );
            if( to_vehicle ) {
                put_into_vehicle_or_drop( g->u, { *temp_item }, destination );
            } else {
                drop_on_map( g->u, { *temp_item }, destination );
            }
            // Remove from map or vehicle.
            if( from_vehicle ) {
                s_veh->remove_item( s_cargo, index );
            } else {
                g->m.i_rem( source, index );
            }
        }

        // If we didn't pick up a whole stack, put the remainder back where it came from.
        if( leftovers.charges > 0 ) {
            bool to_map = !from_vehicle;
            if( !to_map ) {
                to_map = !s_veh->add_item( s_cargo, leftovers );
            }
            if( to_map ) {
                g->m.add_item_or_charges( source, leftovers );
            }
        }
    }
}
void good_pop_back_list1(std::list<int> &L, int n) {
  auto i0 = L.cbegin(), i1 = L.cend(), i2 = i1--;
  L.pop_back();
  *i0; // no-warning
  *i2; // no-warning
}
void bad_pop_back_list1(std::list<int> &L, int n) {
  auto i0 = L.cbegin(), i1 = L.cend(), i2 = i1--;
  L.pop_back();
  *i1; // expected-warning{{Invalidated iterator accessed}}
}
Esempio n. 10
0
void render_screen(int fd, std::string str)
{
    // Clear the screen
    memset(frontstore, 0, sizeof(frontstore));

    auto render_string = [](std::string str, int start_line)
    {
        // The start line, and start x coordinate
        int line = start_line;
        int char_x = 1;
        // Run the entire string, char by char
        for(char& c : str)
        {
            // Find the pixel letter corresponding to the char
            Letter l = find_letter(c);

            // If we overflow this line, by adding it, do a line break
            if(char_x + l.letter_width >= YSIZE)
            {
                char_x = 1;
                line++;
                // If we overflow the screen, skip the rest of the string
                if(line > 2)
                {
                    break;
                }
            }

            // Calculate our y coord, based upon the line, we're in
            int char_y = 0 + line * (LETTER_HEIGHT + 1);
            // Do the actual printing of the character
            put_letter(char_y, char_x, l);
            // Move the size of this letter, and 1 character,
            // before rendering the next character
            char_x += l.letter_width;
            char_x += 1;
        }
        // People who start on the line after us
        return line+1;
    };
    // Write the new string
    int end_line = render_string(str, 0);
    // If the new string did not take up all the space,
    // lets reload some of the old stuff, and draw that
    for(std::string old : old_lines)
    {
        // Only draw, if we're inside the screen
        if(end_line > 2)
        {
            break;
        }
        end_line = render_string(old, end_line);
    }
    // The string we just rendered, is now an old line
    old_lines.push_front(str);
    // Garbage collect old_lines
    while(old_lines.size() > 3)
    {
        old_lines.pop_back();
    }

    // Render!
    scr_frontmap(fd);
}
Esempio n. 11
0
 T pop() {
   SpinLock::LockGuard l(lock_);
   T msg = messages_.back();
   messages_.pop_back();
   return msg;
 }
Esempio n. 12
0
void Krane::parse_commandline_options(int& argc, char**& argv, std::list<KTools::VirtualPath>& input_paths, Compat::Path& output_path) {
	using namespace Krane;
	using namespace TCLAP;
	using namespace Krane::options_custom;
	using namespace std;

	try {
		Output myOutput(license);

		CmdLine cmd(usage_message, ' ', PACKAGE_VERSION);
		cmd.setOutput(&myOutput);

		list<Arg*> args;

		{
			list<Arg*>& raw_args = cmd.getArgList();
			raw_args.push_back( raw_args.front() );
			raw_args.pop_front();
		}

		
		myOutput.addCategory(INPUT_CTRL);
		myOutput.addCategory(OUTPUT_CTRL);
		myOutput.addCategory(TO_SCML);
		//myOutput.addCategory(TO_BIN);


		/*
		SwitchArg info_flag("i", "info", "Prints information for the given input files instead of performing any conversion.");
		args.push_back(&info_flag);
		*/

		MyValueArg<string> allowed_build_opt("", "build", "Selects only a build with the given name.", false, "", "build name");
		args.push_back(&allowed_build_opt);
		myOutput.setArgCategory(allowed_build_opt, INPUT_CTRL);

		MyMultiArg<string> allowed_banks_opt("", "bank", "Selects only animations in the given banks.", false, "bank name");
		args.push_back(&allowed_banks_opt);
		myOutput.setArgCategory(allowed_banks_opt, INPUT_CTRL);

		SwitchArg mark_atlas_opt("", "mark-atlases", "Instead of performing any conversion, saves the atlases in the specified build as PNG, with their clipped regions shaded grey.");
		args.push_back(&mark_atlas_opt);
		myOutput.setArgCategory(mark_atlas_opt, OUTPUT_CTRL);

		MyValueArg<string> build_rename_opt("", "rename-build", "Renames the input build to the given name.", false, "", "build name");
		args.push_back(&build_rename_opt);
		//myOutput.setArgCategory(build_rename_opt, TO_SCML);

		MyValueArg<string> banks_rename_opt("", "rename-bank", "Renames the input banks to the given name.", false, "", "bank name");
		args.push_back(&banks_rename_opt);
		//myOutput.setArgCategory(banks_rename_opt, TO_SCML);

		SwitchArg check_anim_fidelity_opt("", "check-animation-fidelity", "Checks if the Spriter representation of the animations is faithful to the source animations.");
		args.push_back(&check_anim_fidelity_opt);
		myOutput.setArgCategory(check_anim_fidelity_opt, TO_SCML);

		MultiSwitchArg verbosity_flag("v", "verbose", "Increases output verbosity.");
		args.push_back(&verbosity_flag);

		SwitchArg quiet_flag("q", "quiet", "Disables text output. Overrides the verbosity value.");
		args.push_back(&quiet_flag);


		MultiArgumentOption multiinput_opt("INPUT-PATH", "Input path.", true, "INPUT-PATH");
		cmd.add(multiinput_opt);

		/*
		 * This only marks the option visually, since all paths are globbed by multiinput_opt.
		 */
		ArgumentOption dummy_output_opt("OUTPUT-PATH", "Output path.", false, "OUTPUT-DIR");
		dummy_output_opt.setVisuallyRequired(true);
		cmd.add(dummy_output_opt);


		for(list<Arg*>::reverse_iterator it = args.rbegin(); it != args.rend(); ++it) {
			cmd.add(*it);
		}


		cmd.parse(argc, argv);


		if(allowed_build_opt.isSet()) {
			options::allowed_build = Just(allowed_build_opt.getValue());
		}
		if(allowed_banks_opt.isSet()) {
			const vector<string>& banks = allowed_banks_opt.getValue();
			options::allowed_banks.insert(options::allowed_banks.begin(), banks.begin(), banks.end());
		}
		options::mark_atlas = mark_atlas_opt.getValue();
		if(build_rename_opt.isSet()) {
			options::build_rename = Just(build_rename_opt.getValue());
		}
		if(banks_rename_opt.isSet()) {
			options::banks_rename = Just(banks_rename_opt.getValue());
		}
		options::check_animation_fidelity = check_anim_fidelity_opt.getValue();

		if(quiet_flag.getValue()) {
			options::verbosity = -1;
		}
		else {
			options::verbosity = verbosity_flag.getValue();
		}
		
		/*
		options::info = info_flag.getValue();
		*/

		const std::vector<std::string>& all_paths = multiinput_opt.getValue();

		if(all_paths.size() < 2) {
			dummy_output_opt.forceRequired();
			cmd.parse(argc, argv);
			// This should never be throws, because the above cmd.parse() is meant
			// to raise an error and exit the program.
			throw KToolsError("Missing output-path argument.");
		}

		std::copy(all_paths.begin(), all_paths.end(), std::back_inserter(input_paths));

		output_path = input_paths.back();
		input_paths.pop_back();

	} catch (ArgException& e) {
		cerr << "error: " << e.error() << " for arg " << e.argId() << endl;
		exit(1);
	} catch(exception& e) {
		cerr << "error: " << e.what() << endl;
		exit(1);
	}
}
Esempio n. 13
0
void extract_peers_from_bootstrap_nodes_dat(const unsigned char *buffer, std::list<Contact *>& bootstrap_list)
{
    /*
        The header is so composed:
          uint32_t reserved0          set to zero
          uint32_t reserved1          set to 0x00000003
          uint32_t bootstrap_edition  nodes.dat bootstrap version
          uint32_t num_entries        number of entries in the file
    */

    if(!bootstrap_list.empty())
        return;

    uint32_t reserved0 = *(uint32_t *)&(buffer[0]);
    uint32_t reserved1 = *(uint32_t *)&(buffer[4]);
    uint32_t num_entries = *(uint32_t *)&(buffer[12]);

    if(reserved0 != 0 || reserved1 != 3)
        // wow: this bootstrap nodes.dat is invalid
        return;

    unsigned char *peer = (unsigned char *)&(buffer[16]);

    /*
        The peer is so composed:
          uint64_t low_peer_id        128-bit peer identifier (MD4 of node ID)
          uint64_t high_peer_id
          uint32_t peer_ip            IP address of the peer
          uint16_t udp_port           peer UDP port number
          uint16_t tcp_port           peer TCP port number
          unsigned char version       peer contact version
    */

    for(unsigned int i = 0; i < num_entries; i++, peer += 25)
    {
        uint32_t peer_ip = ntohl(*(uint32_t *)&(peer[16]));
        uint16_t udp_port = *(uint16_t *)&(peer[20]);
        uint16_t tcp_port = *(uint16_t *)&(peer[22]);
        unsigned char version = peer[24];

        if(version > 7)
        {
            // Only the 50 closest nodes, please
            uint128_t distance(Kad::get_instance().get_client_id());
            uint128_t peer_id = uint128_t::get_from_buffer(peer);
            distance ^= peer_id;

            if(bootstrap_list.size() < 50 || bootstrap_list.back()->get_distance() > distance)
            {
                Contact *new_peer = new Contact(uint128_t::get_from_buffer(peer),
                                                peer_ip,
                                                udp_port,
                                                tcp_port,
                                                version,
                                                0,
                                                false);

                bool peer_added = false;
                for(std::list<Contact *>::iterator peerIt = bootstrap_list.begin();
                    peerIt != bootstrap_list.end();
                    peerIt++)
                {
                    if((*peerIt)->get_distance() > distance)
                    {
                        bootstrap_list.insert(peerIt, new_peer);
                        peer_added = true;
                        break;
                    }
                }

                if(!peer_added)
                {
                    bootstrap_list.push_back(new_peer);
                }
                else if(bootstrap_list.size() > 50)
                {
                    delete bootstrap_list.back();
                    bootstrap_list.pop_back();
                }
            }
        }
    }
}
Esempio n. 14
0
int hexchat_plugin_deinit(hexchat_plugin *plugin_handle)
{
	/******************************************/
	/****** Remove the Icon from the tray *****/
	/******************************************/
	StopBlink(g_hXchatWnd, 1, g_hIcons[0]);
	RemoveIcon(g_hXchatWnd, 1);
	
	/*******************************************/
	/*******************************************/
	/*******************************************/
	if(g_dwPrefs & (1<<PREF_DNSIT))
	{
		DWORD dwStyle;
		dwStyle = GetWindowLong(g_hXchatWnd, GWL_STYLE);
		dwStyle &= ~(1<<WS_CHILD);
		SetWindowLongPtr(g_hXchatWnd, GWL_STYLE, (LONG_PTR)dwStyle);
		SetWindowLongPtr(g_hXchatWnd, GWL_HWNDPARENT, NULL);
	}

	/******************************************/
	/****** Unload our resources **************/
	/******************************************/
	DestroyMenu(g_hTrayMenu);

	for(int i = 0; i <= 11; i++)
	{
		DestroyIcon(g_hIcons[i]);
	}

	/******************************************/
	/****** Remove our window hook ************/
	/******************************************/
	SetWindowLongPtr(g_hXchatWnd, GWLP_WNDPROC, (LONG_PTR)g_hOldProc);

	/******************************************/
	/****** Remove our hotkey, and destroy ****/
	/****** the window that receives its   ****/
	/****** messages                       ****/
	/******************************************/
	UnregisterHotKey(g_hHotkeyWnd, 1);
	DestroyWindow(g_hHotkeyWnd);
	DestroyWindow(g_hPrefDlg);

	/******************************************/
	/************* Clean up Isle 7 ************/
	/******************************************/
	if(sdAlertNum())
	{
		sdCloseAlerts();
	}
	/******************************************/
	/****** remove our hexchat_hook_*s **********/
	/******************************************/
	while(!g_vHooks.empty())
	{
		if(g_vHooks.back() != NULL)
		{
			hexchat_unhook(ph, g_vHooks.back());
		}
		g_vHooks.pop_back();
	}

	return 1;
}
Esempio n. 15
0
Colour Raytracer::Trace(const Ray& ray, RandomGenerator* random, int depth, int depth2, std::list<IMedium*>& mediumList)
{
	if(depth >= this->maxIterations)
		return Vec3(0,0,0);

	// First find intersection with closes geometry.
	IntersectResult result;
	geometry->Intersect(ray, result);

	// First depth2=0, we also include "singular light geometry"
	if(depth2 == 0 && this->singularLightGeometry)
		singularLightGeometry->Intersect(ray, result);

	if(result.distance >= std::numeric_limits<Scalar>::max())
		return Vec3(0,0,0); //< Return "sky" radiance

	// Calculate position of intersection.
	
	Vec3 position = result.distance * ray.direction + ray.origin;
	Vec3 cameraDirection = -ray.direction;

	// Check for interaction with medium (scaterring)
	ColourScalar scateringWeight;
	Vec3 scatteringPos, scatteringDir;
	if(ray.medium->SampleScattering(ray.origin, result.normal, position, random, scateringWeight,
		scatteringPos, scatteringDir))
	{
		Ray newRay(scatteringPos, scatteringDir);
		newRay.medium = ray.medium;
		return scateringWeight.CMultiply(Trace(newRay, random, depth+1, depth2, mediumList));
	}


	// Now calculate mediums.
	bool isInsideMedium = cameraDirection * result.normal < 0;
	IMedium* insideMedium, *outsideMedium;
	if(isInsideMedium)
	{
		// FIXME: sometimes due to numerical errors, we ignore those hits (alternative - set to vacuum).
		if(mediumList.size() == 0)
			return Vec3(0,0,0);
		outsideMedium = mediumList.back();
		insideMedium = ray.medium;
	} else {
		outsideMedium = ray.medium;
		insideMedium = result.material->insideMedium;
	}

	// Compute radiance of point.
	Vec3 L(0,0,0);

	// 1) self radiance
	if(SELF_LIGHTNING_BIT(depth, depth2) && result.material->surfaceLight != 0)
		L = SELF_LIGHTNING_MASK(depth, depth2, result.material->surfaceLight->Radiance(position, cameraDirection, result.normal));
	
	// Early exit for non-reflective materials. This is useful for singular lights.
	if(result.material->bsdf == 0)
		return scateringWeight.CMultiply(L);
	SamplingType samplingType = result.material->bsdf->GetSamplingType(cameraDirection, result.normal);
	

	// 2) radiance from singular sources
	if(DIRECT_LIGHTNING_BIT(depth, depth2) && ((samplingType & Singular) != 0))
	{
		for(std::vector<ISingularLight*>::iterator i = lights.begin(); i != lights.end(); i++)
		{
			ISingularLight* light = *i;
			Vec3 towardsLightDirection;

			// We can use radiance at position for point lights (no translate).
			Vec3 Li = light->Radiance(position, towardsLightDirection, geometry);

			// Early exit for shadowed lights (no BRDF execution) && when backfacing lights.
			if(Li.x == 0 && Li.y == 0 && Li.z == 0)
				continue;
			 
			// Weights with cosine.
			Vec3 t = (result.normal * towardsLightDirection)*Li.CMultiply(result.material->bsdf->BSDF(position, result.normal,
				 cameraDirection, towardsLightDirection, result.materialData, insideMedium, outsideMedium));
			L += DIRECT_LIGHTNING_MASK(depth, depth2, t);
		}
	}
	// 3) caustics map lightning
	if(PHOTONMAP_CAUSTICS_BIT(depth, depth2) && this->causticsMap)
	{
		std::vector<Photon*> photons;
		causticsMap->FindInRange(position, this->causticsPhotonMapGatherRadius, photons);

		// We estimate radiance at the point.
		Vec3 Flux(0,0,0);
		for(std::vector<Photon*>::iterator i = photons.begin(); i != photons.end(); i++)
		{
			Photon* p = *i;

			// Cull backfacings.
			if(p->outDirection * result.normal < 0)
				continue;

			Flux += p->power.CMultiply((result.normal * p->outDirection) * result.material->bsdf->BSDF(position, result.normal, p->outDirection, cameraDirection, result.materialData,
				insideMedium, outsideMedium));
		}

		Vec3 t = Flux / (PI*this->causticsPhotonMapGatherRadius*this->causticsPhotonMapGatherRadius);

		L += PHOTONMAP_CAUSTICS_MASK(depth, depth2, t);
	}

	// Calculate number of samples
	int numberOfSamples = std::min(result.material->bsdf->GetMaxNumberOfSamples(cameraDirection, result.normal), 
		(int)(this->secondaryRays * exp(-secondaryRayDecay*depth2)));

	bool isPerfectReflection = numberOfSamples <= this->gatherIterationThreeshold;	//< This will only allow bigger iteration depth.

	// 4a) indirect photon map rendering (it is either this or hemisphere integration), reflection is still handled with
	// normal raytracing
	if(PHOTONMAP_GLOBAL_BIT(depth, depth2) && !isPerfectReflection && this->globalMap)
	{
		std::vector<Photon*> photons;
		globalMap->FindInRange(position, this->globalPhotonMapGatherRadius, photons);

		// We estimate radiance at the point.
		Vec3 Flux(0,0,0);
		for(std::vector<Photon*>::iterator i = photons.begin(); i != photons.end(); i++)
		{
			Photon* p = *i;

			// Cull backfacings.
			if(p->outDirection * result.normal < 0)
				continue;

			Flux += p->power.CMultiply((result.normal * p->outDirection) * result.material->bsdf->BSDF(position, result.normal, p->outDirection, cameraDirection, result.materialData,
				insideMedium, outsideMedium));
		}

		Vec3 t = Flux / (PI*this->globalPhotonMapGatherRadius*this->globalPhotonMapGatherRadius);

		L += PHOTONMAP_GLOBAL_MASK(depth, depth2, t);

		// We skip through
		return scateringWeight.CMultiply(L);
	}


	// 4b) integrated radiance over hemisphere
	if((samplingType & MultipleSample) == 0 || INDIRECT_LIGHTNING_BIT(depth, depth2) == false)
		return scateringWeight.CMultiply(L);

	
	if(depth2 < this->maxGatherIterations || isPerfectReflection)
	{
		// If perfect reflection, we need only one ray to approximate.
		for(int i = 0; i < numberOfSamples; i++)
		{
			Vec3 newDirection;
			ColourScalar S = result.material->bsdf->Sample(i, numberOfSamples, position, result.normal, 
				cameraDirection, random, result.materialData, insideMedium, outsideMedium, newDirection); 

			// Trace new ray.
			Ray newRay(position, newDirection);
			bool needsPop = false, needsPush = false;
			Scalar translateInwards = -1;
			if(isInsideMedium)
			{
				// In-Out combination
				if(newDirection * result.normal > 0)
				{
					newRay.medium = mediumList.back();
					mediumList.pop_back();
					needsPush = true;
					translateInwards = 1;
				}
				// In-In combination
				else
					newRay.medium = ray.medium;
			}
			else {
				// Out-out combination
				if(newDirection * result.normal > 0)
					newRay.medium = ray.medium;
				else
				{
					newRay.medium = result.material->insideMedium;
					mediumList.push_back(ray.medium);
					needsPop = true;
					translateInwards = 1;
				}
			}

			// Translation of ray position so the whole solid angle can be sampled (also in corners)
			newRay.origin = newRay.origin + (translateInwards * this->hitTranslate) * ray.direction;

			ColourScalar newL = Trace(newRay, random, depth+1, depth2 + (isPerfectReflection ? 0 : 1), mediumList);

			// Undo medium list to prev state
			if(needsPush)
				mediumList.push_back(newRay.medium);
			if(needsPop)
				mediumList.pop_back();

			// NaN check (FIXME: must get rid of it and find the source).
			if(newL.x != newL.x || newL.y != newL.y || newL.z != newL.z)
			{
				continue;
			}

			// Add already weighted result to intensity.
			Vec3 t = S.CMultiply(newL);
			L += INDIRECT_LIGHTNING_MASK(depth,depth2,t);
		}
	}

	return scateringWeight.CMultiply(L);

}
Esempio n. 16
0
bool PointProjectionTools::extractConvexHull2D(	std::vector<IndexedCCVector2>& points,
												std::list<IndexedCCVector2*>& hullPoints)
{
	size_t n = points.size();

	// Sort points lexicographically
	std::sort(points.begin(), points.end(), LexicographicSort);

	// Build lower hull
	{
		for (size_t i=0; i<n; i++)
		{
			while (hullPoints.size() >= 2)
			{
				std::list<IndexedCCVector2*>::iterator itB = hullPoints.end(); itB--;
				std::list<IndexedCCVector2*>::iterator itA = itB; itA--;
				if (cross(**itA, **itB, points[i]) <= 0)
				{
					hullPoints.pop_back();
				}
				else
				{
					break;
				}
			}

			try
			{
				hullPoints.push_back(&points[i]);
			}
			catch (std::bad_alloc)
			{
				//not enough memory
				return false;
			}
		}
	}

	// Build upper hull
	{
		size_t t = hullPoints.size()+1;
		for (int i=static_cast<int>(n)-2; i>=0; i--)
		{
			while (hullPoints.size() >= t)
			{
				std::list<IndexedCCVector2*>::iterator itB = hullPoints.end(); itB--;
				std::list<IndexedCCVector2*>::iterator itA = itB; itA--;
				if (cross(**itA, **itB, points[i]) <= 0)
				{
					hullPoints.pop_back();
				}
				else
				{
					break;
				}
			}

			try
			{
				hullPoints.push_back(&points[i]);
			}
			catch (std::bad_alloc)
			{
				//not enough memory
				return false;
			}
		}
	}

	//remove last point if it's the same as the first one
	if (hullPoints.size() > 1
		&&	hullPoints.front()->x == hullPoints.back()->x
		&&	hullPoints.front()->y == hullPoints.back()->y )
	{
		hullPoints.pop_back();
	}

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

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

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

 // if (aProf !=1) fprintf(aFileH," // %d ",aProf);
        if (isH) fprintf(aFile,"        ");
        fprintf
        (
                aFile,
                "%s%s & %s%s()%s",
                aContsQual.c_str(),
                NameImplemOfClass().c_str(),
                aPortee.c_str(),
                mValTag.c_str(),
                aContsQual.c_str()
         );
         
         if (isH)
         {
             fprintf(aFile,";\n");
         }
         else
         {
             fprintf(aFile,"\n");
             fprintf(aFile,"{\n"); 
             fprintf(aFile,"   return ");
             if (aProf ==1)
                 fprintf(aFile,"m%s",mValTag.c_str());
             else
             {
                std::list<cElXMLTree *>::iterator itT = aList.begin();
                itT++;
                int aK=0;
                int aL = (int) aList.size();
                while (itT != aList.end())
                {
                   if (aK!=0)  fprintf(aFile,".");
                   fprintf(aFile,"%s()",(*itT)->mValTag.c_str());
                   const std::string & aPatLoc = (*itT)->ValAttr("Nb");
                   if ((aK!= aL-2) && (aPatLoc == "?"))
                      fprintf(aFile,".Val()");
                   itT++;
                   aK++;
                }
             }
             fprintf(aFile,";\n");
             fprintf(aFile,"}\n\n");
         }
   }  
   aList.pop_back();
}
Esempio n. 18
0
 void post(const std::shared_ptr<Node> node)
 {
     if (stack.size() > 0)
         stack.pop_back();
 }
// I'd love to have this not duplicate so much code from Pickup::pick_one_up(),
// but I don't see a clean way to do that.
static void move_items( point source, point destination,
                        std::list<int> &indices, std::list<int> &quantities )
{
    source.x += g->u.xpos();
    source.y += g->u.ypos();
    destination.x += g->u.xpos();
    destination.y += g->u.ypos();
    int veh_root_part = -1;
    vehicle *veh = g->m.veh_at( source.x, source.y, veh_root_part );
    int cargo_part = -1;
    if( veh != nullptr ) {
        cargo_part = veh->part_with_feature( veh_root_part, "CARGO", false );
    }

    std::vector<item> &here = (cargo_part >= 0) ?
        veh->parts[cargo_part].items : g->m.i_at( source.x, source.y );

    std::vector<item> dropped_items;
    std::vector<item> dropped_worn;
    while( g->u.moves > 0 && !indices.empty() ) {
        int index = indices.back();
        int quantity = quantities.back();
        indices.pop_back();
        quantities.pop_back();

        item &temp_item = here[index];
        item leftovers = temp_item.clone();

        if( quantity != 0 ) {
            // Reinserting leftovers happens after item removal to avoid stacking issues.
            int leftover_charges = temp_item.charges - quantity;
            if (leftover_charges > 0) {
                leftovers.charges = leftover_charges;
                here[index].charges = quantity;
            }
        }

        // Check that we can pick it up.
        if( !temp_item.made_of(LIQUID) ) {
            // Is it too bulky? We'll have to use our hands, then.
            if( !g->u.can_pickVolume(temp_item.volume()) && g->u.is_armed() ) {
                g->u.moves -= 20; // Pretend to be unwielding our gun.
            }

            // Is it too heavy? It'll take a while...
            if( !g->u.can_pickWeight(temp_item.weight(), true) ) {
                int overweight = temp_item.weight() - (g->u.weight_capacity() - g->u.weight_carried());

                // ...like one move cost per 100 grams over your leftover carry capacity.
                g->u.moves -= int(overweight / 100);
            }

            // Drop it first since we're going to delete the original.
            dropped_items.push_back( temp_item );
            g->drop( dropped_items, dropped_worn, 0, destination.x, destination.y );

            // Remove from map.
            if( veh != nullptr && cargo_part >= 0 ) {
                veh->remove_item( cargo_part, index );
            } else {
                g->m.i_rem( source.x, source.y, index );
            }
            g->u.moves -= 100;

        }

        // If we didn't pick up a whole stack, put the remainder back where it came from.
        if( quantity != 0 ) {
            bool to_map = veh != nullptr;
            if( !to_map ) {
                to_map = !veh->add_item( cargo_part, leftovers );
            }
            if( to_map ){
                g->m.add_item_or_charges( source.x, source.y, leftovers );
            }
        }

        dropped_items.clear();
    }
}
Esempio n. 20
0
		void Parse()
		{
			ReadNextNode();

			WriteElement();

			int nDepth = GetDepth();
			if (!IsEmptyElement())
			{
				XmlNodeType eNodeType = XmlNodeType_None;

				int nCurDepth = -1;
				// У закрывающего тэга глубина на 1 больше, чем у открывающего
				while (true)
				{
					if (1 != xmlTextReaderRead(reader))
						break;

					int nTempType = xmlTextReaderNodeType(reader);
					if (-1 == nTempType)
						break;
					eNodeType = (XmlNodeType)nTempType;

					nCurDepth = GetDepth();
					if (eNodeType == XmlNodeType_Text || eNodeType == XmlNodeType_Whitespace || eNodeType == XmlNodeType_SIGNIFICANT_WHITESPACE)
					{
						m_pCurrentNode->m_sText += GetText();
					}
					else if (eNodeType == XmlNodeType_CDATA)
					{
						m_pCurrentNode->m_sText += GetText();
					}
					else if (eNodeType == XmlNodeType_Element)
					{
						WriteElement();
					}
					else if (eNodeType == XmlNodeType_EndElement)
					{
						m_list.pop_back();

						if (0 != m_list.size())
						{
							std::list<CXmlNodeBase*>::iterator iter = m_list.end();
							--iter;
							m_pCurrentNode = *iter;
						}
						else
						{
							m_pCurrentNode = m_pNode;
						}
					}

					nCurDepth = GetDepth();
					if (nCurDepth < nDepth)
						break;

					if (XmlNodeType_EndElement == eNodeType && nCurDepth == nDepth)
						break;
				}
			}
		}
Esempio n. 21
0
bool Pickup::do_pickup( const tripoint &pickup_target_arg, bool from_vehicle,
                        std::list<int> &indices, std::list<int> &quantities, bool autopickup )
{
    bool got_water = false;
    int cargo_part = -1;
    vehicle *veh = nullptr;
    bool weight_is_okay = ( g->u.weight_carried() <= g->u.weight_capacity() );
    bool volume_is_okay = ( g->u.volume_carried() <= g->u.volume_capacity() );
    bool offered_swap = false;
    // Convert from player-relative to map-relative.
    tripoint pickup_target = pickup_target_arg + g->u.pos();
    // Map of items picked up so we can output them all at the end and
    // merge dropping items with the same name.
    PickupMap mapPickup;

    if( from_vehicle ) {
        const cata::optional<vpart_reference> vp = g->m.veh_at( pickup_target ).part_with_feature( "CARGO",
                false );
        veh = &vp->vehicle();
        cargo_part = vp->part_index();
    }

    bool problem = false;
    while( !problem && g->u.moves >= 0 && !indices.empty() ) {
        // Pulling from the back of the (in-order) list of indices insures
        // that we pull from the end of the vector.
        int index = indices.back();
        int quantity = quantities.back();
        // Whether we pick the item up or not, we're done trying to do so,
        // so remove it from the list.
        indices.pop_back();
        quantities.pop_back();

        item *target = nullptr;
        if( from_vehicle ) {
            target = g->m.item_from( veh, cargo_part, index );
        } else {
            target = g->m.item_from( pickup_target, index );
        }

        if( target == nullptr ) {
            continue; // No such item.
        }

        problem = !pick_one_up( pickup_target, *target, veh, cargo_part, index, quantity,
                                got_water, offered_swap, mapPickup, autopickup );
    }

    if( !mapPickup.empty() ) {
        show_pickup_message( mapPickup );
    }

    if( got_water ) {
        add_msg( m_info, _( "You can't pick up a liquid!" ) );
    }
    if( weight_is_okay && g->u.weight_carried() > g->u.weight_capacity() ) {
        add_msg( m_bad, _( "You're overburdened!" ) );
    }
    if( volume_is_okay && g->u.volume_carried() > g->u.volume_capacity() ) {
        add_msg( m_bad, _( "You struggle to carry such a large volume!" ) );
    }

    return !problem;
}
Esempio n. 22
0
 inline void object_end()
 {
     state_stack.pop_back();
     _consume();
     _check_post();
 }
Esempio n. 23
0
int main(int argc, char **argv)
{

	// No arguments, no game.
	if (argc == 1)	
	{
		std::cout << "Syntax: findsum targetvalue operands_list" << std::endl;
		std::cout << "Example: findsum 13 5 4 3" << std::endl;
		std::cout << "Output: Target value is: 13\nOperands are: 5 4 3\nSequence: 5 4 4" << std::endl;

		return -1;
	}	
	
	std::vector<int> vOperands;
	 
	// the first parameter after command is the target value
	int target = atoi(argv[1]);
	
	// No second parameters (use default: foe house population)
	if (argc == 2)
	{
		vOperands.push_back(1380);
		vOperands.push_back(1330);
		vOperands.push_back(1087);	
		vOperands.push_back(900);
		vOperands.push_back(680);
		vOperands.push_back(510);
		vOperands.push_back(474);
		vOperands.push_back(380);
		vOperands.push_back(285);
		vOperands.push_back(259);
		vOperands.push_back(207);
		vOperands.push_back(205);
		vOperands.push_back(156);
		vOperands.push_back(155);
		vOperands.push_back(123);
		vOperands.push_back(111);
		vOperands.push_back(94);
		vOperands.push_back(73);
		vOperands.push_back(67);
		vOperands.push_back(44);
		vOperands.push_back(32);
		vOperands.push_back(27);
		vOperands.push_back(22);
		vOperands.push_back(14);
	}
	else
	{
		// second and followinf arguments: list of operands.
		for (int i = 2; i < argc; i++ )
		{
			int iVal = atoi(argv[i]);
			vOperands.push_back(iVal);
		}
	}
	
	std::cout << "Target value is: " << target << std::endl;
	std::cout << "Operands are:";
	for (auto&& i: vOperands)
	{
		std::cout << " " << i;
	}
	std::cout << std::endl;
	
	// Search the sequence!
	for(auto&& i: vOperands)
	{
		current_sequence.push_back(i);
		search_sum_sequence(vOperands, i, target, 1, i);
		current_sequence.pop_back();
	}
	
	if (best_number == 0)
	{
		std::cout << "No sequence found." << std::endl;
	}
	
	return 0;
}
Esempio n. 24
0
 inline void array_end()
 {
     state_stack.pop_back();
     _consume();
     _check_post();
 }
Esempio n. 25
0
void SysMtgsThread::ExecuteTaskInThread()
{
#ifdef RINGBUF_DEBUG_STACK
	PacketTagType prevCmd;
#endif

	RingBufferLock busy (*this);

	while(true) {
		busy.Release();

		// Performance note: Both of these perform cancellation tests, but pthread_testcancel
		// is very optimized (only 1 instruction test in most cases), so no point in trying
		// to avoid it.

		m_sem_event.WaitWithoutYield();
		StateCheckInThread();
		busy.Acquire();

		// note: m_ReadPos is intentionally not volatile, because it should only
		// ever be modified by this thread.
		while( m_ReadPos != volatize(m_WritePos))
		{
			if (EmuConfig.GS.DisableOutput) {
				m_ReadPos = m_WritePos;
				continue;
			}

			pxAssert( m_ReadPos < RingBufferSize );

			const PacketTagType& tag = (PacketTagType&)RingBuffer[m_ReadPos];
			u32 ringposinc = 1;

#ifdef RINGBUF_DEBUG_STACK
			// pop a ringpos off the stack.  It should match this one!

			m_lock_Stack.Lock();
			uptr stackpos = ringposStack.back();
			if( stackpos != m_ReadPos )
			{
				Console.Error( "MTGS Ringbuffer Critical Failure ---> %x to %x (prevCmd: %x)\n", stackpos, m_ReadPos, prevCmd.command );
			}
			pxAssert( stackpos == m_ReadPos );
			prevCmd = tag;
			ringposStack.pop_back();
			m_lock_Stack.Release();
#endif

			switch( tag.command )
			{
#if COPY_GS_PACKET_TO_MTGS == 1
				case GS_RINGTYPE_P1:
				{
					uint datapos = (m_ReadPos+1) & RingBufferMask;
					const int qsize = tag.data[0];
					const u128* data = &RingBuffer[datapos];

					MTGS_LOG( "(MTGS Packet Read) ringtype=P1, qwc=%u", qsize );

					uint endpos = datapos + qsize;
					if( endpos >= RingBufferSize )
					{
						uint firstcopylen = RingBufferSize - datapos;
						GSgifTransfer( (u32*)data, firstcopylen );
						datapos = endpos & RingBufferMask;
						GSgifTransfer( (u32*)RingBuffer.m_Ring, datapos );
					}
					else
					{
						GSgifTransfer( (u32*)data, qsize );
					}

					ringposinc += qsize;
				}
				break;

				case GS_RINGTYPE_P2:
				{
					uint datapos = (m_ReadPos+1) & RingBufferMask;
					const int qsize = tag.data[0];
					const u128* data = &RingBuffer[datapos];

					MTGS_LOG( "(MTGS Packet Read) ringtype=P2, qwc=%u", qsize );

					uint endpos = datapos + qsize;
					if( endpos >= RingBufferSize )
					{
						uint firstcopylen = RingBufferSize - datapos;
						GSgifTransfer2( (u32*)data, firstcopylen );
						datapos = endpos & RingBufferMask;
						GSgifTransfer2( (u32*)RingBuffer.m_Ring, datapos );
					}
					else
					{
						GSgifTransfer2( (u32*)data, qsize );
					}

					ringposinc += qsize;
				}
				break;

				case GS_RINGTYPE_P3:
				{
					uint datapos = (m_ReadPos+1) & RingBufferMask;
					const int qsize = tag.data[0];
					const u128* data = &RingBuffer[datapos];

					MTGS_LOG( "(MTGS Packet Read) ringtype=P3, qwc=%u", qsize );

					uint endpos = datapos + qsize;
					if( endpos >= RingBufferSize )
					{
						uint firstcopylen = RingBufferSize - datapos;
						GSgifTransfer3( (u32*)data, firstcopylen );
						datapos = endpos & RingBufferMask;
						GSgifTransfer3( (u32*)RingBuffer.m_Ring, datapos );
					}
					else
					{
						GSgifTransfer3( (u32*)data, qsize );
					}

					ringposinc += qsize;
				}
				break;
#endif
				case GS_RINGTYPE_GSPACKET: {
					Gif_Path& path   = gifUnit.gifPath[tag.data[2]];
					u32       offset = tag.data[0];
					u32       size   = tag.data[1];
					if (offset != ~0u) GSgifTransfer((u32*)&path.buffer[offset], size/16);
					AtomicExchangeSub(path.readAmount, size);
					break;
				}

				case GS_RINGTYPE_MTVU_GSPACKET: {
					MTVU_LOG("MTGS - Waiting on semaXGkick!");
					vu1Thread.KickStart(true);
					busy.m_lock2.Release();
					// Wait for MTVU to complete vu1 program
					vu1Thread.semaXGkick.WaitWithoutYield();
					busy.m_lock2.Acquire();
					Gif_Path& path   = gifUnit.gifPath[GIF_PATH_1];
					GS_Packet gsPack = path.GetGSPacketMTVU(); // Get vu1 program's xgkick packet(s)
					if (gsPack.size) GSgifTransfer((u32*)&path.buffer[gsPack.offset], gsPack.size/16);
					AtomicExchangeSub(path.readAmount, gsPack.size + gsPack.readAmount);
					path.PopGSPacketMTVU(); // Should be done last, for proper Gif_MTGS_Wait()
					break;
				}

				default:
				{
					switch( tag.command )
					{
						case GS_RINGTYPE_VSYNC:
						{
							const int qsize = tag.data[0];
							ringposinc += qsize;

							MTGS_LOG( "(MTGS Packet Read) ringtype=Vsync, field=%u, skip=%s", !!(((u32&)RingBuffer.Regs[0x1000]) & 0x2000) ? 0 : 1, tag.data[1] ? "true" : "false" );

							// Mail in the important GS registers.
							// This seemingly obtuse system is needed in order to handle cases where the vsync data wraps
							// around the edge of the ringbuffer.  If not for that I'd just use a struct. >_<

							uint datapos = (m_ReadPos+1) & RingBufferMask;
							MemCopy_WrappedSrc( RingBuffer.m_Ring, datapos, RingBufferSize, (u128*)RingBuffer.Regs, 0xf );

							u32* remainder = (u32*)&RingBuffer[datapos];
							((u32&)RingBuffer.Regs[0x1000])				= remainder[0];
							((u32&)RingBuffer.Regs[0x1010])				= remainder[1];
							((GSRegSIGBLID&)RingBuffer.Regs[0x1080])	= (GSRegSIGBLID&)remainder[2];

							// CSR & 0x2000; is the pageflip id.
							GSvsync(((u32&)RingBuffer.Regs[0x1000]) & 0x2000);
							gsFrameSkip();

							// if we're not using GSOpen2, then the GS window is on this thread (MTGS thread),
							// so we need to call PADupdate from here.
							if( (GSopen2 == NULL) && (PADupdate != NULL) )
								PADupdate(0);

							AtomicDecrement( m_QueuedFrameCount );
							if (!!AtomicExchange(m_VsyncSignalListener, false))
								m_sem_Vsync.Post();

							busy.Release();
							StateCheckInThread();
							busy.Acquire();
						}
						break;

						case GS_RINGTYPE_FRAMESKIP:
							MTGS_LOG( "(MTGS Packet Read) ringtype=Frameskip" );
							_gs_ResetFrameskip();
						break;

						case GS_RINGTYPE_FREEZE:
						{
							MTGS_FreezeData* data = (MTGS_FreezeData*)tag.pointer;
							int mode = tag.data[0];
							data->retval = GetCorePlugins().DoFreeze( PluginId_GS, mode, data->fdata );
						}
						break;

						case GS_RINGTYPE_RESET:
							MTGS_LOG( "(MTGS Packet Read) ringtype=Reset" );
							if( GSreset != NULL ) GSreset();
						break;

						case GS_RINGTYPE_SOFTRESET:
						{
							int mask = tag.data[0];
							MTGS_LOG( "(MTGS Packet Read) ringtype=SoftReset" );
							GSgifSoftReset( mask );
						}
						break;

						case GS_RINGTYPE_MODECHANGE:
							// [TODO] some frameskip sync logic might be needed here!
						break;

						case GS_RINGTYPE_CRC:
							GSsetGameCRC( tag.data[0], 0 );
						break;

						case GS_RINGTYPE_INIT_READ_FIFO1:
							MTGS_LOG( "(MTGS Packet Read) ringtype=Fifo1" );
							if (GSinitReadFIFO)
								GSinitReadFIFO( (u64*)tag.pointer);
						break;

						case GS_RINGTYPE_INIT_READ_FIFO2:
							MTGS_LOG( "(MTGS Packet Read) ringtype=Fifo2, size=%d", tag.data[0] );
							if (GSinitReadFIFO2)
								GSinitReadFIFO2( (u64*)tag.pointer, tag.data[0]);
						break;

#ifdef PCSX2_DEVBUILD
						default:
							Console.Error("GSThreadProc, bad packet (%x) at m_ReadPos: %x, m_WritePos: %x", tag.command, m_ReadPos, m_WritePos);
							pxFail( "Bad packet encountered in the MTGS Ringbuffer." );
							m_ReadPos = m_WritePos;
						continue;
#else
						// Optimized performance in non-Dev builds.
						jNO_DEFAULT;
#endif
					}
				}
			}

			uint newringpos = (m_ReadPos + ringposinc) & RingBufferMask;

			if( EmuConfig.GS.SynchronousMTGS )
			{
				pxAssert( m_WritePos == newringpos );
			}
			
			m_ReadPos = newringpos;

			if( m_SignalRingEnable != 0 )
			{
				// The EEcore has requested a signal after some amount of processed data.
				if( AtomicExchangeSub( m_SignalRingPosition, ringposinc ) <= 0 )
				{
					// Make sure to post the signal after the m_ReadPos has been updated...
					AtomicExchange( m_SignalRingEnable, 0 );
					m_sem_OnRingReset.Post();
					continue;
				}
			}
		}

		busy.Release();

		// Safety valve in case standard signals fail for some reason -- this ensures the EEcore
		// won't sleep the eternity, even if SignalRingPosition didn't reach 0 for some reason.
		// Important: Need to unlock the MTGS busy signal PRIOR, so that EEcore SetEvent() calls
		// parallel to this handler aren't accidentally blocked.
		if( AtomicExchange( m_SignalRingEnable, 0 ) != 0 )
		{
			//Console.Warning( "(MTGS Thread) Dangling RingSignal on empty buffer!  signalpos=0x%06x", AtomicExchange( m_SignalRingPosition, 0 ) );
			AtomicExchange( m_SignalRingPosition, 0 );
			m_sem_OnRingReset.Post();
		}

		if (!!AtomicExchange(m_VsyncSignalListener, false))
			m_sem_Vsync.Post();

		//Console.Warning( "(MTGS Thread) Nothing to do!  ringpos=0x%06x", m_ReadPos );
	}
}
Esempio n. 26
0
 inline void _consume()
 {
     m_helpers_stack.pop_back();
 }
Esempio n. 27
0
// stupidity countermeasure...
template<class T> T pop_back(std::list<T> &l)
{
    T result(l.back());
    l.pop_back();
    return result;
}
Esempio n. 28
0
void CTreeCanvas::RenderObject(bool expanded, HeeksObj* prev_object, bool prev_object_expanded, HeeksObj* object, HeeksObj* next_object, int level)
{
	int save_x = m_xpos;

	RenderBranchIcons(object, next_object, expanded, level);

	int label_start_x = m_xpos;
	// find icon info
	if(!render_just_for_calculation)m_dc->DrawBitmap(object->GetIcon(), m_xpos, m_ypos);
	m_xpos += 16;

	wxString str(object->GetShortStringOrTypeString());
	if(!render_just_for_calculation)
	{
		if(render_labels && wxGetApp().m_marked_list->ObjectMarked(object))
		{
			m_dc->SetBackgroundMode(wxSOLID);
			m_dc->SetTextBackground(*wxBLUE);
			m_dc->SetTextForeground(*wxWHITE);
		}
		else
		{
			m_dc->SetBackgroundMode(wxTRANSPARENT);
			m_dc->SetTextForeground(*wxBLACK);
		}
		m_dc->DrawText(str, m_xpos, m_ypos);
	}
	int text_width = 0;
	if(render_just_for_calculation || !render_labels)
	{
		// just make a guess, we don't have a valid m_dc
		text_width = 10 * str.Len();
	}
	else
	{
		wxSize text_size = m_dc->GetTextExtent(str);
		text_width = text_size.GetWidth();
	}
	int label_end_x = m_xpos + 8 + text_width;
	if(!render_just_for_calculation && render_labels)
	{
		AddLabelButton(expanded, prev_object, prev_object_expanded, object, next_object, label_start_x, label_end_x);
	}
	if(label_end_x > m_max_xpos)m_max_xpos = label_end_x;

	m_ypos += 18;

	bool end_object = (next_object == NULL);
	end_child_list.push_back(end_object);

	m_xpos = save_x;

	if(expanded)
	{
		HeeksObj* prev_child = NULL;
		bool prev_child_expanded = false;
		HeeksObj* child = object->GetFirstChild();

		while(child)
		{
			HeeksObj* next_child = object->GetNextChild();
			bool expanded = IsExpanded(child);
			RenderObject(expanded, prev_child, prev_child_expanded, child, next_child, level + 1);
			prev_child = child;
			prev_child_expanded = expanded;
			child = next_child;
		}
	}

	end_child_list.pop_back();
}
Esempio n. 29
0
int main( int argc, char** argv ){
	
	//przygotowanie polaczenia
	int clientSocket;
	int sck; 
    if(argv[1][0] == '1'){
		clientSocket = server();
		printf("Polaczono !\n");
    }
	else{
		sck = client(argv[2]);
		printf("Polaczono z serwerem ! \n");
	}
	
	//inicjowanie funkcji zwiazanych z grafika
	BITMAP* buffer = NULL;
    allegro_init();
	install_keyboard();
	set_color_depth(16);
    set_gfx_mode( GFX_AUTODETECT_WINDOWED, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0 );
	clear_to_color(screen, makecol( 0, 0, 0 ) );
	buffer = create_bitmap(SCREEN_WIDTH, SCREEN_HEIGHT);
    
	BITMAP *okrazenie1 = NULL, *okrazenie2 = NULL, *okrazenie3 = NULL, *okrazenie4 = NULL;	
	BITMAP *odliczanie3 = NULL, *odliczanie2 = NULL, *odliczanie1 = NULL, *odliczanieStart = NULL, *wygrana = NULL, *przegrana = NULL;
	
	polozenie player, player_temp;
	
	int licznikOkrazen=1;
	double x,y;
	bool zakonczenie = false;
	bool kolizja = false;
	bool lap_updown= false;
	bool zwyciestwo = true;
	
    //zaladowanie bitmap
	odliczanie3 = load_bmp("odliczanie3.bmp", NULL);
	odliczanie2 = load_bmp("odliczanie2.bmp", NULL);
	odliczanie1= load_bmp("odliczanie1.bmp", NULL);
	odliczanieStart = load_bmp("odliczanieStart.bmp", NULL);
	okrazenie1 = load_bmp("okrazenie1.bmp", NULL);
	okrazenie2 = load_bmp("okrazenie2.bmp", NULL);
	okrazenie3 = load_bmp("okrazenie3.bmp", NULL);
	okrazenie4 = load_bmp("okrazenie4.bmp", NULL);
	przegrana = load_bmp("przegrana.bmp", NULL);
	wygrana = load_bmp("Wygrana.bmp", NULL);
        
	//ustalenie pozycji poczatkowej
    if(argv[1][0] == '1'){
        player.x = 535;
        player.y = 480;
	}
    else{
        player.x = 535;
        player.y = 510;
    }
	int z = 4;
	
	//inicjalizacja wyscigu
	while(z>0){
		if(z == 4) draw_sprite(buffer, odliczanie3, 0, 0);
		if(z == 3) draw_sprite(buffer, odliczanie2, 0, 0);
		if(z == 2) draw_sprite(buffer, odliczanie1, 0, 0);
		if(z == 1){
			draw_sprite(buffer, odliczanieStart, 0, 0);
			circlefill(buffer, (int)player.x,(int)player.y, promien, makecol(128,0,0)); 
			if(player.y == 480) circlefill(buffer, 535, 510, promien, makecol(0,128,0));
			else circlefill(buffer, 535, 480, promien, makecol(0, 128, 0));
		}
		draw_sprite(screen,buffer,0,0);
		sleep(1);
		z = z - 1;
	}	
    
	while(zakonczenie == false && licznikOkrazen != 9){
		// zakonczenie wyscigu jesli wcisniety zostal ESC
		if(key[ KEY_ESC ]){	
		    printf("Gracz zamknal gre poprzez ESC. \n");
		    zakonczenie = true;
        }
	
		// wyswietlenie odpowiedniego tla planszy
        if(licznikOkrazen < 3) draw_sprite(buffer, okrazenie1, 0, 0);     
        else if(licznikOkrazen < 5) draw_sprite(buffer, okrazenie2, 0, 0);
        else if(licznikOkrazen < 7) draw_sprite(buffer, okrazenie3, 0, 0);      
        else if(licznikOkrazen < 9) draw_sprite(buffer, okrazenie4, 0, 0);
		
		// jesli nie ma kolizji...
		if(kolizja == false){
			
			//zmieniamy predkosc i kat w zaleznosci od tego, czy wcisniety jest klawisz
			if( key[ KEY_LEFT ] ){
	    			predkosc-=0.1;
	    			if(predkosc<1.0) predkosc=1.0;
	    			katSkretu+=0.1;
	    			if(katSkretu>2) katSkretu=2;
            			kierunekPoruszania = zmianaKata(kierunekPoruszania,katSkretu);
	  		}
	  		else{
	    			predkosc+=0.1;
	    			if(predkosc>3) predkosc=3;
	    			katSkretu-=0.1;
	    			if(katSkretu<1) katSkretu=1; 
	  		}
			
	  		//i wyznaczamy nowa pozycje
	  		x = predkosc*cos(kierunekPoruszania*PI/180);
	  		player.x+=x;
	  		y = predkosc*sin(kierunekPoruszania*PI/180);
	  		player.y+=y;
			
			//sprawdzamy, czy okrazenie zostalo ukonczone przez gracza
	  		if(getpixel(buffer, (int)player.x, (int)player.y) == makecol(255,255,255)){
	      			licznikOkrazen++;
	      			lap_updown = (!lap_updown);
	  		}
			
			//sprawdzamy, czy gracz nie znalazl sie poza torem
			if(getpixel(buffer, (int)player.x, (int)player.y) == makecol(0,0,0)) kolizja = true;
			circlefill(buffer, (int)player.x, (int)player.y, promien, makecol(128,0,0));
			polozeniaGracza.push_front(player); 
			while(polozeniaGracza.size()>50) polozeniaGracza.pop_back();
		}
		
		//rysowanie sladu za graczem
		for(unsigned int i = 0; i<polozeniaGracza.size();i++){
	  		player_temp = polozeniaGracza.front();
	  		polozeniaGracza.pop_front();
	  		circlefill(buffer, (int)player_temp.x, (int)player_temp.y, promien, makecol(128,0,0)); 
	  		polozeniaGracza.push_back(player_temp);	  
		}
		
		
		
	 	//klient - komunikacja: przygotowanie i przeslanie informacji o kolizji/koncu wyscigu
        if(argv[1][0] == '2'){
            if(kolizja == true){
				player.x = 1;
				player.y = 1;
			}
			else if(licznikOkrazen == 9){
				player.x = 2;
				player.y = 2;
			}
		  
			char x[sizeof(player.x)];
			char y[sizeof(player.y)];
				
			sprintf(x, "%lf", player.x);
			sprintf(y, "%lf", player.y);
				
			write(sck,x,8);
			write(sck,y,8);
			oponentSock = sck;

			char rcvx[sizeof(double)];
			char rcvy[sizeof(double)];

			polozenie rcv;

			read(sck, &rcvx, 8);
			rcv.x = atof(rcvx);
			read(sck, &rcvy, 8);
			rcv.y = atof(rcvy);
			
			if(rcv.x == 1 && rcv.y == 1){	
				zakonczenie = true;
				zwyciestwo = true;
			}
			else if (rcv.x == 2 && rcv.y == 2) kolizja = true; 
			else polozeniaPrzeciwnika.push_front(rcv);
		}
		
		
		
		// to samo dla serwera
		else{
			char rcvx[sizeof(double)];
            char rcvy[sizeof(double)];
            
            polozenie rcv;
            
            read(clientSocket, &rcvx, 8);
            rcv.x = atof(rcvx);
            read(clientSocket, &rcvy, 8);
            rcv.y = atof(rcvy);
            		
            if(rcv.x == 1 && rcv.y == 1) {
				zakonczenie = true;
				zwyciestwo = true;
			}
			else if (rcv.x == 2 && rcv.y == 2) kolizja = true; 
            else polozeniaPrzeciwnika.push_front(rcv);
			
	    	if(kolizja == true){
			    player.x = 1;
			    player.y = 1;
			}
			else if(licznikOkrazen == 9){
			    player.x = 2;
			    player.y = 2;
			}
	    		
			char x[sizeof(player.x)];
            char y[sizeof(player.y)];
			 
            sprintf(x ,"%lf",player.x);
            sprintf(y ,"%lf",player.y);

            write(clientSocket,x,8);
            write(clientSocket,y,8);
       
 		}
	
		// zredukowanie sladu przeciwnika
	 	while(polozeniaPrzeciwnika.size()>50){
			polozeniaPrzeciwnika.pop_back();
		}
	
		// rysowanie sladu przeciwnika
	 	for(unsigned int i = 0; i<polozeniaPrzeciwnika.size();i++){
	  		player_temp = polozeniaPrzeciwnika.front();
	  		polozeniaPrzeciwnika.pop_front();
	  		circlefill(buffer, (int)player_temp.x, (int)player_temp.y, promien, makecol(0,128,0)); 
	  		polozeniaPrzeciwnika.push_back(player_temp);	  
		}
	
		draw_sprite(screen, buffer, 0, 0);

		if(kolizja == true){
			zakonczenie = true;
			zwyciestwo = false;
		}		
	}
	
	//gdy wygrana wyswietlamy wygrana	
	if(zwyciestwo == true){
		printf("wygrana\n");
		draw_sprite(screen, wygrana, 0, 0);
		sleep(2);
	}
	
	//gdy przegrana wyswietlamy przegrana
	else{
		draw_sprite(screen, przegrana, 0, 0);
		sleep(2);
	}
	
	//zamykanie gniazd
	if(argv[1][0] == '1'){
        close(clientSocket);
        close(sck_in);
    }
	
	//czyszczenie listy polozen graczy
	while (!polozeniaGracza.empty()){
	    polozeniaGracza.pop_back();
	}
	while (!polozeniaPrzeciwnika.empty()){
	    polozeniaPrzeciwnika.pop_back();
	}

	//czyszczenie pamieci zajetej przez bitmapy
	destroy_bitmap(odliczanieStart);
	destroy_bitmap(odliczanie3);
	destroy_bitmap(odliczanie2);
	destroy_bitmap(odliczanie1);
	destroy_bitmap(okrazenie1);
	destroy_bitmap(okrazenie2);
	destroy_bitmap(okrazenie3);
	destroy_bitmap(okrazenie4);
	destroy_bitmap(wygrana);
	destroy_bitmap(przegrana);
	destroy_bitmap(buffer);
	allegro_exit();

	return 0;
}
Esempio n. 30
0
void Mouse::update(float dt)
{
	memcpy(m_lastButtonState, m_buttonState, sizeof(bool) * 2);
#ifdef _WIN32
	m_buttonState[0] = (GetAsyncKeyState(VK_LBUTTON) & 0x8000) ? true : false;
	m_buttonState[1] = (GetAsyncKeyState(VK_RBUTTON) & 0x8000) ? true : false;
#elif defined __APPLE__
    #ifndef MARBLE_IOS_BUILD
        Uint8 mouseState = SDL_GetMouseState(NULL, NULL);
        m_buttonState[0] = (mouseState & SDL_BUTTON(SDL_BUTTON_LEFT)) ? true : false;
        m_buttonState[1] = (mouseState & SDL_BUTTON(SDL_BUTTON_RIGHT)) ? true : false;
    #endif
#endif

	/*
	This next section of code allows for really smooth mouse movement no matter
	what the frame rate (well... within reason). The last 10 positions
	are stored in a list. Each frame a new relative position is added and the oldest is removed.
	These positions are then added together using a weighting value. The most recent position
	has the most weight, whereas the oldest as the lowest weighting. This value is then averaged
	to produce the new relative mouse position.
	*/
	elapsed_time += dt;
	if (elapsed_time > timestep_threshold)
	{
		static std::list<std::pair<float, float> > mousePositionHistory;

        if (m_mouseLocked) {
            int x, y;
            getMousePos(x, y);
            GLint viewport[4];
            glGetIntegerv(GL_VIEWPORT, viewport);
            
            if ( !firstFrame ) {
                //Add the current mouse position - starting position
                mousePositionHistory.push_front(std::make_pair((float)x - (viewport[2] / 2), (float)y - (viewport[3] / 2)));
                if (mousePositionHistory.size() > 10)
                {
                    //Make sure only the last 10 positions are stored
                    mousePositionHistory.pop_back();
                }
                
                m_relativeMousePosX = 0.0f;
                m_relativeMousePosY = 0.0f;
                float weight = 1.0f;
                
                //Calculate a weighted average
                for (std::list<std::pair<float, float> >::iterator i = mousePositionHistory.begin();
                     i != mousePositionHistory.end(); ++i)
                {
                    m_relativeMousePosX += (*i).first * weight;
                    m_relativeMousePosY += (*i).second * weight;
                    weight *= 0.5f;
                }
                m_relativeMousePosX /= 10.0f;
                m_relativeMousePosY /= 10.0f;
            }
            firstFrame = false;
            
            //Put the mouse in the middle of the screen
            setMousePos(viewport[2] / 2, viewport[3] / 2);
            showCursor(false);
        }

		elapsed_time = 0.0f;
	}
}