示例#1
0
	void TileList::update() {
		if(!m_model) {
			m_entries.clear();
			return;
		}

		m_entries.resize(m_model->size());
		for(int n = 0, count = m_model->size(); n < count; n++) {
			Entry &entry = m_entries[n];
			entry.group_id = -1;
			entry.tile = m_model->get(n, entry.group_id);
			entry.is_selected = false;
			entry.model_id = n;
			entry.size = entry.tile->rect().size();
		}
		std::stable_sort(m_entries.begin(), m_entries.end());

		if(!m_entries.empty())
			m_entries[0].group_size = 1;
		for(int n = 1; n < (int)m_entries.size(); n++) {
			Entry &cur = m_entries[n], &prev = m_entries[n - 1];
			cur.group_size = cur.group_id == prev.group_id? prev.group_size + 1 : 1;
		}
		for(int n = (int)m_entries.size() - 2; n >= 0; n--) {
			Entry &cur = m_entries[n], &prev = m_entries[n + 1];
			if(cur.group_id == prev.group_id)
				cur.group_size = prev.group_size;
		}

		// TODO: jesus, this one call makes the obj file 37KB bigger :(
		std::stable_sort(m_entries.begin(), m_entries.end(),
				[](const Entry &a, const Entry &b) { return a.group_size > b.group_size; } );

		int2 cur_pos(0, 0);
		int cur_height = 0;

		for(int e = 0; e < (int)m_entries.size(); e++) {
			Entry &entry = m_entries[e];
			entry.pos = cur_pos;
			cur_pos.x += m_spacing + entry.size.x;
			cur_height = max(cur_height, entry.size.y);
			int next_width = e + 1 < (int)m_entries.size()? m_entries[e + 1].size.x : 0;
			int next_group = e + 1 < (int)m_entries.size()? m_entries[e + 1].group_id : entry.group_id;

			if(next_width + cur_pos.x > m_max_width || (next_group != entry.group_id && entry.group_size > 1)) {
				cur_pos.x = 0;
				cur_pos.y += m_spacing + cur_height;
				cur_height = 0;
			}
		}

		m_height = cur_pos.y + cur_height;
	}
示例#2
0
/*************************************************************************
    Draw a line of text.  No formatting is applied.
*************************************************************************/
void Font::drawTextLine(const String& text, const Vector3& position, const Rect& clip_rect, const ColourRect& colours, float x_scale, float y_scale)
{
    Vector3	cur_pos(position);

    const FontGlyph* glyph;
    float base_y = position.d_y;

    for (size_t c = 0; c < text.length(); ++c)
    {
        glyph = getGlyphData(text[c]);

        if (glyph)
        {
            const Image* img = glyph->getImage();
            cur_pos.d_y = base_y - (img->getOffsetY() - img->getOffsetY() * y_scale);
            img->draw(cur_pos, glyph->getSize(x_scale, y_scale), clip_rect, colours);
            cur_pos.d_x += glyph->getAdvance(x_scale);
        }
    }
}
示例#3
0
/*************************************************************************
    Draw a justified line of text.
*************************************************************************/
void Font::drawTextLineJustified (const String& text, const Rect& draw_area, const Vector3& position, const Rect& clip_rect, const ColourRect& colours, float x_scale, float y_scale)
{
    Vector3	cur_pos(position);

    const FontGlyph* glyph;
    float base_y = position.d_y;
    size_t char_count = text.length();

    // Calculate the length difference between the justified text and the same text, left aligned
    // This space has to be shared between the space characters of the line
    float lost_space = getFormattedTextExtent(text, draw_area, Justified, x_scale) - getTextExtent(text, x_scale);

    // The number of spaces and tabs in the current line
    uint space_count = 0;
    size_t c;
    for (c = 0; c < char_count; ++c)
        if ((text[c] == ' ') || (text[c] == '\t'))
            ++space_count;

    // The width that must be added to each space character in order to transform the left aligned text in justified text
    float shared_lost_space = 0.0;
    if (space_count > 0)
        shared_lost_space = lost_space / (float)space_count;

    for (c = 0; c < char_count; ++c)
    {
        glyph = getGlyphData(text[c]);

        if (glyph)
        {
            const Image* img = glyph->getImage();
            cur_pos.d_y = base_y - (img->getOffsetY() - img->getOffsetY() * y_scale);
            img->draw(cur_pos, glyph->getSize(x_scale, y_scale), clip_rect, colours);
            cur_pos.d_x += glyph->getAdvance(x_scale);

            // That's where we adjust the size of each space character
            if ((text[c] == ' ') || (text[c] == '\t'))
                cur_pos.d_x += shared_lost_space;
        }
    }
}
示例#4
0
void eos::TextEditor::MoveToCursorPosition()
{
    ax::Point cur_pos(_logic.GetCursorPosition());
    
    // Cursor is bellow last shown line.
    if(cur_pos.y > _file_start_index + _n_line_shown - 1)
    {
        //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        // Possible problem when file size is smaller than _n_line_shown.
        //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        
        _file_start_index = cur_pos.y - _n_line_shown + 1;
    }
    else if(cur_pos.y < _file_start_index)
    {
        _file_start_index = cur_pos.y;
    }
    
    // Move scroll bar.
    int diff = (int)_logic.GetFileData().size() - _n_line_shown;
    double scroll_ratio = _file_start_index / double(diff);
    _scrollBar->SetZeroToOneValue(scroll_ratio);
}
示例#5
0
void throw_item(Actor& actor_throwing, const Pos& tgt_cell, Item& item_thrown)
{
    Throw_att_data data(actor_throwing, item_thrown, tgt_cell, actor_throwing.pos);

    const Actor_size aim_lvl = data.intended_aim_lvl;

    vector<Pos> path;
    line_calc::calc_new_line(actor_throwing.pos, tgt_cell, false, THROW_RANGE_LMT, false, path);

    const auto& item_thrown_data = item_thrown.get_data();

    const string item_name_a = item_thrown.get_name(Item_ref_type::a);

    if (&actor_throwing == map::player)
    {
        msg_log::clear();
        msg_log::add("I throw " + item_name_a + ".");
    }
    else
    {
        const Pos& p = path.front();

        if (map::cells[p.x][p.y].is_seen_by_player)
        {
            msg_log::add(actor_throwing.get_name_the() + " throws " + item_name_a + ".");
        }
    }

    render::draw_map_and_interface(true);

    int         blocked_in_element    = -1;
    bool        is_actor_hit          = false;
    const char  glyph               = item_thrown.get_glyph();
    const Clr   clr                 = item_thrown.get_clr();
    int         chance_to_destroy_item = 0;

    Pos cur_pos(-1, -1);

    for (size_t i = 1; i < path.size(); ++i)
    {
        render::draw_map_and_interface(false);

        cur_pos.set(path[i]);

        Actor* const actor_here = utils::get_actor_at_pos(cur_pos);

        if (actor_here)
        {
            if (cur_pos == tgt_cell || actor_here->get_data().actor_size >= Actor_size::humanoid)
            {

                data = Throw_att_data(actor_throwing, item_thrown, tgt_cell, cur_pos, aim_lvl);

                if (data.attack_result >= success_small && !data.is_ethereal_defender_missed)
                {

                    if (map::cells[cur_pos.x][cur_pos.y].is_seen_by_player)
                    {
                        render::draw_glyph('*', Panel::map, cur_pos, clr_red_lgt);
                        render::update_screen();
                        sdl_wrapper::sleep(config::get_delay_projectile_draw() * 4);
                    }

                    const Clr hit_message_clr   = actor_here == map::player ? clr_msg_bad : clr_msg_good;
                    const bool CAN_SEE_ACTOR  = map::player->can_see_actor(*actor_here, nullptr);
                    string defender_name       = CAN_SEE_ACTOR ? actor_here->get_name_the() : "It";

                    msg_log::add(defender_name + " is hit.", hit_message_clr);

                    actor_here->hit(data.dmg, Dmg_type::physical);
                    is_actor_hit = true;

                    //If throwing a potion on an actor, let it make stuff happen...
                    if (item_thrown_data.type == Item_type::potion)
                    {
                        static_cast<Potion*>(&item_thrown)->collide(cur_pos, actor_here);
                        delete &item_thrown;
                        game_time::tick();
                        return;
                    }

                    blocked_in_element = i;
                    chance_to_destroy_item = 25;
                    break;
                }
            }
        }

        if (map::cells[cur_pos.x][cur_pos.y].is_seen_by_player)
        {
            render::draw_glyph(glyph, Panel::map, cur_pos, clr);
            render::update_screen();
            sdl_wrapper::sleep(config::get_delay_projectile_draw());
        }

        const auto* feature_here = map::cells[cur_pos.x][cur_pos.y].rigid;

        if (!feature_here->is_projectile_passable())
        {
            blocked_in_element = item_thrown_data.type == Item_type::potion ? i : i - 1;
            break;
        }

        if (cur_pos == tgt_cell && data.intended_aim_lvl == Actor_size::floor)
        {
            blocked_in_element = i;
            break;
        }
    }

    //If potion, collide it on the landscape
    if (item_thrown_data.type == Item_type::potion)
    {
        if (blocked_in_element >= 0)
        {
            static_cast<Potion*>(&item_thrown)->collide(path[blocked_in_element], nullptr);
            delete &item_thrown;
            game_time::tick();
            return;
        }
    }

    if (rnd::percent() < chance_to_destroy_item)
    {
        delete &item_thrown;
    }
    else
    {
        const int DROP_ELEMENT = blocked_in_element == -1 ?
                                 path.size() - 1 : blocked_in_element;
        const Pos drop_pos = path[DROP_ELEMENT];
        const Matl matl_at_drop_pos =
            map::cells[drop_pos.x][drop_pos.y].rigid->get_matl();

        bool is_noisy = false;

        switch (matl_at_drop_pos)
        {
        case Matl::empty:
            is_noisy = false;
            break;

        case Matl::stone:
            is_noisy = true;
            break;

        case Matl::metal:
            is_noisy = true;
            break;

        case Matl::plant:
            is_noisy = false;
            break;

        case Matl::wood:
            is_noisy = true;
            break;

        case Matl::cloth:
            is_noisy = false;
            break;

        case Matl::fluid:
            is_noisy = false;
            break;
        }

        if (is_noisy)
        {
            const Alerts_mon alerts = &actor_throwing == map::player ?
                                      Alerts_mon::yes :
                                      Alerts_mon::no;

            if (!is_actor_hit)
            {
                Snd snd(item_thrown_data.land_on_hard_snd_msg, item_thrown_data.land_on_hard_sfx,
                        Ignore_msg_if_origin_seen::yes, drop_pos, nullptr, Snd_vol::low, alerts);

                snd_emit::emit_snd(snd);
            }
        }

        item_drop::drop_item_on_map(drop_pos, item_thrown);
    }

    render::draw_map_and_interface();
    game_time::tick();
}
示例#6
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(), INVALID_OBJECT_ID, 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() != 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(),
                          INVALID_OBJECT_ID,
                          INVALID_OBJECT_ID);
        retval.push_back(node);
        return retval;      // can't move => path is just this system with explanatory ETA
    }


    // 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 = GetSystem(this->SystemID());         // may be 0
    const System* prev_system = GetSystem(this->PreviousSystemID());// may be 0 if this fleet is not moving or ordered to move
    const System* next_system = GetSystem(*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 = GetEmpireKnownSystem(*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;
}
示例#7
0
    void operator()(TrackingInfo& info)
    {
        image::vector<3,short> cur_pos(info.position);
        unsigned int cur_pos_index;
        cur_pos_index = image::pixel_index<3>(cur_pos[0],cur_pos[1],cur_pos[2],info.fib_data.dim).index();

        std::vector<image::vector<3,float> > next_voxels_dir;
        std::vector<image::vector<3,short> > next_voxels_pos;
        std::vector<unsigned int> next_voxels_index;
        std::vector<float> voxel_angle;
        // assume isotropic
        int radius = 2;
        int radius2 = 6;
        for(char z = -radius;z <= radius;++z)
            for(char y = -radius;y <= radius;++y)
                for(char x = -radius;x <= radius;++x)
                {
                    if((x == 0 && y == 0 && z == 0) ||
                            x*x+y*y+z*z > radius2)
                        continue;
                    image::vector<3,float> dis(x,y,z);
                    image::vector<3,short> pos(cur_pos);
                    pos += dis;
                    if(!info.fib_data.dim.is_valid(pos))
                        continue;
                    dis.normalize();
                    float angle_cos = dis*info.dir;
                    if(angle_cos < info.param.cull_cos_angle)
                        continue;
                    next_voxels_pos.push_back(pos);
                    next_voxels_index.push_back(image::pixel_index<3>(pos[0],pos[1],pos[2],info.fib_data.dim).index());
                    next_voxels_dir.push_back(dis);
                    voxel_angle.push_back(angle_cos);
                }

        char max_i;
        char max_j;
        float max_angle_cos = 0;
        for(char i = 0;i < next_voxels_index.size();++i)
        {
            for (char j = 0;j < info.fib_data.fib.num_fiber;++j)
            {
                if (info.fib_data.fib.getFA(next_voxels_index[i],j) <= info.param.threshold)
                    break;
                float value = std::abs(next_voxels_dir[i]*info.fib_data.fib.getDir(next_voxels_index[i],j));
                if(value < info.param.cull_cos_angle)
                    continue;
                if(voxel_angle[i]*value*info.fib_data.fib.getFA(next_voxels_index[i],j) > max_angle_cos)
                {
                    max_i = i;
                    max_j = j;
                    max_angle_cos = voxel_angle[i]*value*info.fib_data.fib.getFA(next_voxels_index[i],j);
                }
            }
        }
        if(max_angle_cos == 0)
        {
            info.terminated = true;
            return;
        }


        info.dir = info.fib_data.fib.getDir(next_voxels_index[max_i],max_j);
        if(info.dir*next_voxels_dir[max_i] < 0)
            info.dir = -info.dir;
        info.position = next_voxels_pos[max_i];
    }
示例#8
0
    bool http_client::grab_url(const std::string& url, const std::string& method, const std::string& post_body)
    {
        error_field.clear();
        returned_headers.clear();
        http_return = 0;
        returned_body.clear();

        std::string to_use_method = strtoupper(method);

        std::string scheme, user, pass, host, path;
        short port;
        if ( !parse_url(url, scheme, user, pass, host, port, path) )
        {
            error_field = "Couldn't parse the URL!";
            return false;
        }

        // Build request
        std::stringstream ret;
        ret << to_use_method << ' ' << path << " HTTP/1.0\r\n"
            << "Host: " << host;
        if (port != 80 && port != 443) ret << ':' << port;
        ret << "\r\n";

        bool content_length_said = false;

        set_header("Connection", "Close");
        for (stringmap::iterator ci = headers.begin(); ci != headers.end(); ++ci)
        {
            std::string head = strtolower(ci->first);

            if ( head == "content-length" )
            {
                content_length_said = true;
            }

            ret << ci->first << ':' << ' ' << ci->second << "\r\n";
        }

        if ( !content_length_said && to_use_method != "GET" )
            ret << "Content-Length: " << static_cast<unsigned int>(post_body.size()) << "\r\n";

        std::stringstream cookie_ss;
        for (stringmap::iterator ci = cookies.begin(); ci != cookies.end(); ++ci)
        {
            std::string var = ci->first ; trim(var);
            std::string val = ci->second; trim(val);

            if ( val.empty() || var.empty() )
                continue;

            if ( !cookie_ss.str().empty() )
                cookie_ss << ';' << ' ';

            cookie_ss << urlencode(var) << '=' << urlencode(val);
        }

        if ( !cookie_ss.str().empty() )
            ret << "Cookie: " << cookie_ss.str() << "\r\n";

        ret << "\r\n";
        ret << post_body;

        std::string request_build = ret.str();

        std::stringstream ss;
        {
            dlib::connection * conn(0);
            try
            {
                if (timeout > 0)
                    conn = dlib::connect(host, port, timeout);
                else
                    conn = dlib::connect(host, port);
            }
            catch (const dlib::socket_error& e)
            {
                error_field = e.what();
                return false;
            }

            // Implement a timeout
            timeout_ptr t;
            if ( timeout > 0 )
                t.reset( new dlib::timeout(*conn, &dlib::connection::shutdown, timeout) );

            // Write our request
            conn->write(request_build.c_str(), static_cast<long>(request_build.size()));

            t.reset();

            // And read the response
            char buf[512];
            long bytes_read(0), bytes_total(0);
            bool read_headers(true);

            if ( timeout > 0 )
                t.reset( new dlib::timeout(*conn, &dlib::connection::shutdown, timeout) );

            while ( (bytes_read = conn->read(buf, 512)) > 0 )
            {
                ss.write(buf, bytes_read);

                // Incremental read headers
                if ( read_headers )
                {
                    std::string body_with_headers = ss.str();
                    std::string::size_type ctr(0);

                    while ( true )
                    {
                        std::string::size_type pos = body_with_headers.find("\r\n", ctr);
                        if ( pos == std::string::npos )
                        {
                            // This is our last position of "\r\n"
                            ss.str("");
                            ss.write( body_with_headers.substr(ctr).c_str(), body_with_headers.size() - ctr );
                            break;
                        }

                        std::string header = body_with_headers.substr(ctr, pos-ctr);
                        if ( header.empty() )
                        {
                            // Ok, we're done reading the headers
                            read_headers = false;
                            // What follows now is the body
                            ss.str("");
                            ss.write( body_with_headers.substr(pos + 2).c_str(), body_with_headers.size() - pos - 2 );
                            break;
                        }
                        ctr = pos + 2;

                        if ( returned_headers.empty() )
                        {
                            if (
                                header[0] == 'H' &&
                                header[1] == 'T' &&
                                header[2] == 'T' &&
                                header[3] == 'P' &&
                                header[4] == '/' &&
                                (header[5] >= '0' && header[5] <= '9') &&
                                header[6] == '.' &&
                                (header[7] >= '0' && header[7] <= '9') &&
                                header[8] == ' '
                            )
                            {
                                http_return = (header[9 ] - '0') * 100 +
                                    (header[10] - '0') * 10 +
                                    (header[11] - '0');
                                continue;
                            }
                        }

                        std::string::size_type pos_dp = header.find_first_of(':');
                        std::string header_name, header_value;
                        if ( pos_dp == std::string::npos )
                        {
                            // **TODO** what should I do here??
                            header_name = header;
                        }
                        else
                        {
                            header_name  = trim(header.substr(0, pos_dp));
                            header_value = trim(header.substr(pos_dp+1));
                        }

                        returned_headers[ header_name ].push_back(header_value);

                        if ( BR_CASECMP(header_name.c_str(), "Content-Length", 14) == 0 )
                        {
                            bytes_total = atol( header_value.c_str() );
                        }
                        else if ( BR_CASECMP(header_name.c_str(), "Set-Cookie", 10) == 0 )
                        {
                            std::string::size_type cur_pos(0), pos_pk, pos_is;
                            std::string work, var, val;
                            for ( cur_pos = 0; cur_pos < header_value.size(); cur_pos++ )
                            {
                                pos_pk = header_value.find(';', cur_pos);
                                work   = trim( header_value.substr(cur_pos, pos_pk - cur_pos) );

                                pos_is = work.find('=');
                                if ( pos_is != std::string::npos )
                                { // Hmmm? what in the else case?
                                    var = trim( http_client::urldecode( work.substr(0, pos_is) ) );
                                    val = trim( http_client::urldecode( work.substr(pos_is + 1) ) );

                                    if ( var != "expires" && var != "domain" && var != "path" )
                                        set_cookie( var, val );
                                }
                                cur_pos = pos_pk == std::string::npos ? pos_pk - 1 : pos_pk;
                            }
                        } // Set-Cookie?

                    } // while (true)
                } // read_headers?

                // Call the OnDownload function if it's set
                if ( OnDownload && !read_headers )
                {
                    if ( (*OnDownload)(static_cast<long>(ss.tellp()), bytes_total, user_info) == false )
                    {
                        t.reset();
                        break;
                    }
                }

                if ( bytes_total != 0 && static_cast<long>(ss.tellp()) == bytes_total )
                {
                    t.reset();
                    break;
                }

                if ( timeout > 0 )
                    t.reset( new dlib::timeout(*conn, &dlib::connection::shutdown, timeout) );
            } // while still data to read

            t.reset();

            delete conn;


            switch ( bytes_read )
            {
                case dlib::TIMEOUT:      error_field = "Timeout";     return false; break;
                case dlib::WOULDBLOCK:   error_field = "Would block"; return false; break;
                case dlib::OTHER_ERROR:  error_field = "Other error"; return false; break;
                case dlib::SHUTDOWN:     error_field = "Timeout";     return false; break;
                case dlib::PORTINUSE:    error_field = "Port in use"; return false; break;
            }
        }

        returned_body = ss.str();

        return true;
    }
示例#9
0
文件: jblotpiece.cpp 项目: skopp/rush
void JBlotPiece::Render()
{
    DWORD color = GetFgColor();
    float scale;
    if (m_bSelected) scale = m_Scale; else scale = 1.0f;

    //Moving the piece to m_MovePos
    if (m_bMoving)
    {
        Frame ext   = GetExt();
        float t     = JAnimServer::s_pInstance->GetCurTime() - m_StartMoveTime; 
        if (t >= 1.0f)
        {
            t = 1.0f;
            m_bMoving = false;
        }
        else if (t <= 0.0f) 
        {
            t = 0.0f;
        }
        Vec2 cur_pos( ext.x , ext.y );
        Vec2 pos    = cur_pos + t * (m_MovePos - cur_pos);
        ext.x       = pos.x;
        ext.y       = pos.y;
        SetExt( ext );
    }

    if (IsHovered()||m_bSelected) 
    {
        color = GetHoverFgColor();
    }

    Frame ext = GetLocalExt();
    Vec2 pos( ext.x, ext.y );
    float dist = pos.dist( m_HomePos );
    float c_SnapBias = 10.0f;
    if (dist < c_SnapBias)
    {
        m_bAtHome = true; 
    }
    else 
    {
        m_bAtHome = false;
    }

    ext = GetExt();
    ext.w = scale*g_pDrawServer->GetFrameW( GetSkinPackID(), GetSkinFrame() );
    ext.h = scale*g_pDrawServer->GetFrameH( GetSkinPackID(), GetSkinFrame() );
    
    if (m_bRipple)
    {
        //Start Rippling
        s_pThis = this;
        g_pDrawServer->Flush();
        g_pDrawServer->SetVertexCB( RippleCallback );
        g_pDrawServer->DrawSprite( ext, GetSkinPackID(), GetSkinFrame(), color );
        g_pDrawServer->Flush();
        g_pDrawServer->SetVertexCB( NULL );
        s_pThis = NULL;
        //Stop Rippling
    } else
    {
        //Simple drawing
        g_pDrawServer->DrawSprite( ext, GetSkinPackID(), GetSkinFrame(), color );
        g_pDrawServer->Flush();
    }

    JAnmContext& ctx = JAnimation::PushContext();

    ctx.m_Pos.x = ext.x;
    ctx.m_Pos.y = ext.y;
} // JBlotPiece::Render
示例#10
0
glm::vec3 CTracer::TraceRay(SRay ray)
{
	int max_iter = 400;
	int straight_iters_num = 7;
	double time_step = 4;	// in seconds
	double eps = 1e-5;
	double ztol = 1e-7;

	glm::vec4 disk_color(-1, -1, -1, -1);
	bool crossed_disk = false;
	bool crossed_other = false;
	glm::vec3 color(0, 0, 1);
	glm::vec4 other_color;
	
	glm::dvec3 cur_pos(m_camera.m_pos), cur_speed(ray.m_dir / glm::length(ray.m_dir) * light_speed);
	int iter = 0;
	glm::dvec3 cur_dir(0.0, 0.0, 0.0);
	glm::dvec3 prev_dir(0.0, 0.0, 0.0);
	Segment segm;
	SRay changed;
	double cam_to_bh = glm::length(m_camera.m_pos - black_hole.center);
	glm::dvec3 accel;
	int last_iter_straight = -1;
	double cur_pos_abs_sq;
	//while (iter < max_iter) {
	while (true) {
		// simple:
		//cur_pos += ray.m_dir * light_speed * time_step;
		//cur_speed = ray.m_dir / glm::length(ray.m_dir) * light_speed;
		// with acceleration:
		cur_pos_abs_sq = glm::dot(cur_pos, cur_pos);
		accel = -(cur_pos / glm::length(cur_pos)) * grav_const * black_hole.mass / cur_pos_abs_sq;		// assuming coordinates center is in center of black hole.
		//fout << "accel: " << accel.x << ' ' << accel.y << ' ' << accel.z << ", module: " << glm::length(accel) << std::endl;
		segm.start = cur_pos;
		//changed.m_start = cur_pos;
		cur_pos += (cur_speed + accel * time_step / 2.0) * time_step;
		cur_speed += accel * time_step;
		cur_speed *= light_speed / glm::length(cur_speed);
		// choosing non-uniform time step
		//time_step = 2 / glm::length(accel);
	
		// Checking intersection for segment.
		segm.end = cur_pos;
		auto intersn = intersection(segm);
		if (intersn.first == SPHERE_INTERSN) {
			other_color = intersn.second;
			crossed_other = true;
			if (!alpha_blending_enable) {
				return rgb_cut(other_color);
			}
			break;
		}
		else if (intersn.first == DISK_INTERSN
			&& intersn.second.w > ztol) {
			if (!crossed_disk) {
				disk_color = intersn.second;
				crossed_disk = true;
				if (!alpha_blending_enable) {
					return rgb_cut(disk_color);
				}
			}
			else {
				// encountered disk previously. 
				// It is impossible to come to this point if alpha blending is disabled.
				disk_color = alpha_blend(disk_color, intersn.second);
			}
		}
		
		// another way is to compute cross product
		//if (glm::dot(cur_pos, cur_pos) > 3 * (cam_to_bh + black_hole.radius) * (cam_to_bh + black_hole.radius) ||
		//if	(glm::dot(cur_speed, prev_dir) < (1 - eps) * light_speed * light_speed) {		// speeds must be of length light_speed
									    														// has put light_speed^2 in the right side of equation
		if (glm::length(glm::cross(cur_speed, prev_dir)) < eps * light_speed * light_speed &&
			glm::dot(cur_pos, cur_pos) > 2 * (cam_to_bh + black_hole.radius) * (cam_to_bh + black_hole.radius)) {
			if (last_iter_straight == -1) {
				last_iter_straight = iter;
			}
			else if (iter - last_iter_straight > straight_iters_num) {
				glm::dvec2 spher(0, 0);
				glm::dvec3 dir_normd = cur_speed / glm::length(cur_speed);
				spher.x = atan2(dir_normd.x, dir_normd.y) + PI;		// (at least in MS library) atan2 returns value in [-pi, pi]
				spher.y = asin(dir_normd.z);
				//fout << "final iter no: " << iter << std::endl;
				//fout << "spher coords: " << spher.y << ' ' << spher.x << std::endl;
				std::pair<unsigned, unsigned> stars_shape = img_shape(1);
				double H = stars_shape.second;
				spher.x *= H / PI;	// transforming [0, 2pi) to [0, 2H)
				spher.y = (spher.y + PI / 2.0) * H / PI;		// transforming [-pi/2, pi/2] to [0, H]
				spher.x = glm::clamp(spher.x, 0.0, 2 * H - 1);
				spher.y = glm::clamp(spher.y, 0.0, H - 1);
				//fout << "ray start: " << ray.m_start.x << ' ' << ray.m_start.y << ' ' << ray.m_start.z << std::endl;
				//fout << "ray dir: " << ray.m_dir.x << ' ' << ray.m_dir.y << ' ' << ray.m_dir.z << std::endl;
				//fout << "spher coords: " << spher.y << ' ' << spher.x << std::endl;
				
				other_color = img_get_pxl_rgba(1, int(spher.x), int(spher.y));
				other_color.w = 1;
				crossed_other = true;
				break;
			}
		}
		prev_dir = cur_speed;
		
		iter++;
	}
	//fout << "min dist to black hole: " << *min_element(dist_to_bh.begin(), dist_to_bh.end()) << std::endl;
	//std::cout << alpha_blending_enable << std::endl;
	if (!alpha_blending_enable) {
		color = rgb_cut(other_color);
	}
	else {
		if (crossed_disk) {
			if (!crossed_other) {
				color = rgb_cut(disk_color);
			}
			else {
				// Alpha-blending
				color = rgb_cut(alpha_blend(disk_color, other_color));
			}
		}
		else {
			color = rgb_cut(other_color);
		}
	}
	
	return color;
}
示例#11
0
 Status GestureSkill::
  update(Model const & model)
  {
    Status st;    
    Vector cur_eepos(Vector::Zero(3));
    Vector delta;
    Vector op_vel;

    switch (state_) {
    case STATE_OP_:
      for (size_t ii(0); ii < op_task_table_.size(); ++ii) {
	st = op_task_table_[ii]->update(model);
	if ( ! st) { return st; }
      }
      for(int ii=0; ii<3; ii++) {
	cur_eepos[ii] = eepos_[3*cur_row_+ii];
      }

      delta = cur_eepos - eepos_task_->getActual();
      op_vel = eepos_task_->getJacobian()*model.getState().velocity_;
      
      if (delta.norm() < threshold_ && op_vel.norm() < vel_threshold_) {
	count_++;
	if (cur_row_ < (eepos_.rows()/3)-1 && count_>hold_count_[cur_row_]) {
	  count_=0;
	  ++cur_row_;
	  Vector cur_eeori_x(Vector::Zero(3));
	  Vector cur_eeori_y(Vector::Zero(3));
	  Vector cur_eeori_z(Vector::Zero(3));
	  for(int ii=0; ii<3; ii++) {
	    cur_eepos[ii] = eepos_[3*cur_row_+ii];
	    cur_eeori_x[ii] = eeori_x_[3*cur_row_+ii];
	    cur_eeori_y[ii] = eeori_y_[3*cur_row_+ii];
	    cur_eeori_z[ii] = eeori_z_[3*cur_row_+ii];
	  }
	  Vector cur_posture(Vector::Zero(7));
	  for(int jj=0; jj<7; jj++) {
	    cur_posture[jj] = posture_[7*cur_row_+jj];
	  }
	  
	  st = eepos_goal_->set(cur_eepos);
	  if (! st) { return st; }
	  st = eeori_goal_x_->set(cur_eeori_x);
	  if (! st) { return st; }
	  st = eeori_goal_y_->set(cur_eeori_y);
	  if (! st) { return st; }
	  st = eeori_goal_z_->set(cur_eeori_z);
	  if (! st) { return st; }
	  st = posture_goal_->set(cur_posture);
	  if (! st) { return st; } 
	}
	else  {
	  // cur_row_=0;
	  // state_=STATE_JOINT_;	  
	}
      }
      break;
    case STATE_JOINT_:
	for (size_t ii(0); ii < joint_task_table_.size(); ++ii) {
	  st = joint_task_table_[ii]->update(model);
	  if ( ! st) { return st; }
	}
	Vector cur_pos(Vector::Zero(7));
	for(int ii=0; ii<7; ii++) {
	  cur_pos[ii] = joint_pos_[7*cur_row_+ii];
	}

	Vector joint_diff( cur_pos - posture_task_->getActual());

	if (joint_diff.norm() < threshold_*5) {
	  if (cur_row_ < (joint_pos_.rows()/7)-1) {
	    ++cur_row_;
	    for(int ii=0; ii<7; ii++) {
	      cur_pos[ii] = joint_pos_[7*cur_row_+ii];
	    }
	    //st = joint_goal_->set(cur_pos);
	    if (! st) { return st; } 
	  }
	}

	    st = posture_goal_->set(cur_pos);
	break;
      }
      
      
      return st;
    }