void mission_start::radio_repeater(mission *miss) { target_om_ter("necropolis_c_23", 3, miss, false); g->u.i_add( item("repeater_mod_guide", 0, false) ); }
int cttff = 0; int ttff_check_res = 0; enum { ITEM_PASS, ITEM_FAIL, ITEM_HTTFF, ITEM_CTTFF }; static item_t gps_items[] = { //item(ITEM_PASS, uistr_pass), //item(ITEM_FAIL, uistr_fail), //item(ITEM_HTTFF, uistr_info_gps_hot_restart), //item(ITEM_CTTFF, uistr_info_gps_cold_restart), item(-1, NULL), }; struct gps_desc { char info[INFO_SIZE]; char *mntpnt; bool exit_thd; text_t title; text_t text; pthread_t update_thd; struct ftm_module *mod; struct itemview *iv; };
void CGUIDialogProfileSettings::OnSettingAction(const CSetting *setting) { if (setting == NULL) return; CGUIDialogSettingsManualBase::OnSettingAction(setting); const std::string &settingId = setting->GetId(); if (settingId == SETTING_PROFILE_IMAGE) { VECSOURCES shares; g_mediaManager.GetLocalDrives(shares); CFileItemList items; if (!m_thumb.empty()) { CFileItemPtr item(new CFileItem("thumb://Current", false)); item->SetArt("thumb", m_thumb); item->SetLabel(g_localizeStrings.Get(20016)); items.Add(item); } CFileItemPtr item(new CFileItem("thumb://None", false)); item->SetArt("thumb", "DefaultUser.png"); item->SetLabel(g_localizeStrings.Get(20018)); items.Add(item); std::string thumb; if (CGUIDialogFileBrowser::ShowAndGetImage(items, shares, g_localizeStrings.Get(1030), thumb) && !StringUtils::EqualsNoCase(thumb, "thumb://Current")) { m_needsSaving = true; m_thumb = StringUtils::EqualsNoCase(thumb, "thumb://None") ? "" : thumb; UpdateProfileImage(); } } else if (settingId == SETTING_PROFILE_DIRECTORY) { if (!GetProfilePath(m_directory, m_isDefault)) return; m_needsSaving = true; updateProfileDirectory(); } else if (settingId == SETTING_PROFILE_LOCKS) { if (m_showDetails) { if (CProfilesManager::GetInstance().GetMasterProfile().getLockMode() == LOCK_MODE_EVERYONE && !m_isDefault) { if (CGUIDialogYesNo::ShowAndGetInput(CVariant{20066}, CVariant{20118})) g_passwordManager.SetMasterLockMode(false); if (CProfilesManager::GetInstance().GetMasterProfile().getLockMode() == LOCK_MODE_EVERYONE) return; } if (CGUIDialogLockSettings::ShowAndGetLock(m_locks, m_isDefault ? 12360 : 20068, CProfilesManager::GetInstance().GetMasterProfile().getLockMode() == LOCK_MODE_EVERYONE || m_isDefault)) m_needsSaving = true; } else { if (CGUIDialogLockSettings::ShowAndGetLock(m_locks, m_isDefault ? 12360 : 20068, false, false)) m_needsSaving = true; } } }
bool CPUDebugger::property(unsigned id, string &name, string &value) { unsigned n = 0; #define item(name_, value_) \ if(id == n++) { \ name = name_; \ value = value_; \ return true; \ } //internal item("S-CPU MDR", string("0x", strhex<2>(regs.mdr))); //$2181-2183 item("$2181-$2183", ""); item("WRAM Address", string("0x", strhex<6>(status.wram_addr))); //$4016 item("$4016", ""); item("Joypad Strobe Latch", status.joypad_strobe_latch); //$4200 item("$4200", ""); item("NMI Enable", status.nmi_enabled); item("H-IRQ Enable", status.hirq_enabled); item("V-IRQ Enable", status.virq_enabled); item("Auto Joypad Poll", status.auto_joypad_poll); //$4201 item("$4201", ""); item("PIO", string("0x", strhex<2>(status.pio))); //$4202 item("$4202", ""); item("Multiplicand", string("0x", strhex<2>(status.wrmpya))); //$4203 item("$4203", ""); item("Multiplier", string("0x", strhex<2>(status.wrmpyb))); //$4204-$4205 item("$4204-$4205", ""); item("Dividend", string("0x", strhex<4>(status.wrdiva))); //$4206 item("$4206", ""); item("Divisor", string("0x", strhex<2>(status.wrdivb))); //$4207-$4208 item("$4207-$4208", ""); item("H-Time", string("0x", strhex<4>(status.hirq_pos))); //$4209-$420a item("$4209-$420a", ""); item("V-Time", string("0x", strhex<4>(status.virq_pos))); //$420b unsigned dma_enable = 0; for(unsigned n = 0; n < 8; n++) dma_enable |= channel[n].dma_enabled << n; item("$420b", ""); item("DMA Enable", string("0x", strhex<2>(dma_enable))); //$420c unsigned hdma_enable = 0; for(unsigned n = 0; n < 8; n++) hdma_enable |= channel[n].hdma_enabled << n; item("$420c", ""); item("HDMA Enable", string("0x", strhex<2>(hdma_enable))); //$420d item("$420d", ""); item("FastROM Enable", status.rom_speed == 6); for(unsigned i = 0; i < 8; i++) { item(string("DMA Channel ", i), ""); //$43x0 item("Direction", channel[i].direction); item("Indirect", channel[i].indirect); item("Reverse Transfer", channel[i].reverse_transfer); item("Fixed Transfer", channel[i].fixed_transfer); item("Transfer Mode", (unsigned)channel[i].transfer_mode); //$43x1 item("B-Bus Address", string("0x", strhex<4>(channel[i].dest_addr))); //$43x2-$43x3 item("A-Bus Address", string("0x", strhex<4>(channel[i].source_addr))); //$43x4 item("A-Bus Bank", string("0x", strhex<2>(channel[i].source_bank))); //$43x5-$43x6 item("Transfer Size / Indirect Address", string("0x", strhex<4>(channel[i].transfer_size))); //$43x7 item("Indirect Bank", string("0x", strhex<2>(channel[i].indirect_bank))); //$43x8-$43x9 item("Table Address", string("0x", strhex<4>(channel[i].hdma_addr))); //$43xa item("Line Counter", string("0x", strhex<2>(channel[i].line_counter))); } #undef item return false; }
static inline bool isVisibleDesktopFile(const QString &filename) { LauncherItem item(filename); return item.isValid() && item.shouldDisplay(); }
void TableWidgetDragRows::dropEvent(QDropEvent *event) { if (event->source() == this && (event->dropAction() == Qt::MoveAction || dragDropMode() == QAbstractItemView::InternalMove)) { QModelIndex topIndex; int col = -1; int row = -1; if (this->dropOn(event, &row, &col, &topIndex)) { std::set<int> selRows = getSelectedRowsFast(selectionModel()->selection()); int top = *(selRows.begin()); int dropRow = topIndex.row(); if(dropRow == -1) { dropRow = rowCount(); } int offset = dropRow - top; // insert new rows std::set<int>::const_iterator it; for(it = selRows.begin(); it != selRows.end(); ++it) { int r = *it + offset ; r = qMin(r, rowCount()); r = qMax(r, 0); insertRow(r); } // copy data // note: row numbers may have changed after inserts, hence refresh selRows selRows = getSelectedRowsFast(selectionModel()->selection()); top = *(selRows.begin()); offset = dropRow - top; for(it = selRows.begin(); it != selRows.end(); ++it) { int r = *it + offset ; r = qMin(r, rowCount()); r = qMax(r, 0); for(int c = 0; c < columnCount(); ++c) { QTableWidgetItem *myItem = item(*it, c); if (myItem) { QTableWidgetItem *source = new QTableWidgetItem(*myItem); setItem(r, c, source); } QWidget *myWidget = cellWidget(*it, c); if (myWidget) { setCellWidget(r, c, myWidget); } } } // delete selected rows. std::set<int>::const_reverse_iterator rit; for(rit = selRows.rbegin(); rit != selRows.rend(); ++rit) { removeRow(*rit); } event->accept(); } } else { QTableView::dropEvent(event); } }
void mission_start::place_npc_software(mission *miss) { npc* dev = g->find_npc(miss->npc_id); if (dev == NULL) { debugmsg("Couldn't find NPC! %d", miss->npc_id); return; } g->u.i_add( item("usb_drive", 0) ); add_msg(_("%s gave you a USB drive."), dev->name.c_str()); std::string type = "house"; switch (dev->myclass) { case NC_HACKER: miss->item_id = "software_hacking"; break; case NC_DOCTOR: miss->item_id = "software_medical"; type = "s_pharm"; miss->follow_up = MISSION_GET_ZOMBIE_BLOOD_ANAL; break; case NC_SCIENTIST: miss->item_id = "software_math"; break; default: miss->item_id = "software_useless"; } int dist = 0; point place; if (type == "house") { int city_id = g->cur_om->closest_city( g->om_location() ); place = g->cur_om->random_house_in_city(city_id); // make it global coordinates place.x += g->cur_om->pos().x * OMAPX; place.y += g->cur_om->pos().y * OMAPY; } else { place = overmap_buffer.find_closest(g->om_global_location(), type, dist, false); } miss->target = place; overmap_buffer.reveal(place, 6, g->levz); tinymap compmap; compmap.load_abs(place.x * 2, place.y * 2, g->levz, false); point comppoint; oter_id oter = g->cur_om->ter(place.x, place.y, 0); if (oter == "house_north" || oter == "house_east" || oter == "house_south" || oter == "house_west") { std::vector<point> valid; for (int x = 0; x < SEEX * 2; x++) { for (int y = 0; y < SEEY * 2; y++) { if (compmap.ter(x, y) == t_floor && compmap.furn(x, y) == f_null) { bool okay = false; for (int x2 = x - 1; x2 <= x + 1 && !okay; x2++) { for (int y2 = y - 1; y2 <= y + 1 && !okay; y2++) { if (compmap.furn(x2, y2) == f_bed || compmap.furn(x2, y2) == f_dresser) { okay = true; valid.push_back( point(x, y) ); } } } } } } if (valid.empty()) { comppoint = point( rng(6, SEEX * 2 - 7), rng(6, SEEY * 2 - 7) ); } else { comppoint = valid[rng(0, valid.size() - 1)]; } } else if (oter == "s_pharm_north") { bool found = false; for (int x = SEEX * 2 - 1; x > 0 && !found; x--) { for (int y = SEEY * 2 - 1; y > 0 && !found; y--) { if (compmap.ter(x, y) == t_floor) { found = true; comppoint = point(x, y); } } } } else if (oter == "s_pharm_east") { bool found = false; for (int x = 0; x < SEEX * 2 && !found; x++) { for (int y = SEEY * 2 - 1; y > 0 && !found; y--) { if (compmap.ter(x, y) == t_floor) { found = true; comppoint = point(x, y); } } } } else if (oter == "s_pharm_south") { bool found = false; for (int x = 0; x < SEEX * 2 && !found; x++) { for (int y = 0; y < SEEY * 2 && !found; y++) { if (compmap.ter(x, y) == t_floor) { found = true; comppoint = point(x, y); } } } } else if (oter == "s_pharm_west") { bool found = false; for (int x = SEEX * 2 - 1; x > 0 && !found; x--) { for (int y = 0; y < SEEY * 2 && !found; y++) { if (compmap.ter(x, y) == t_floor) { found = true; comppoint = point(x, y); } } } } compmap.ter_set(comppoint.x, comppoint.y, t_console); computer *tmpcomp = compmap.add_computer(comppoint.x, comppoint.y, string_format(_("%s's Terminal"), dev->name.c_str()), 0); tmpcomp->mission_id = miss->uid; tmpcomp->add_option(_("Download Software"), COMPACT_DOWNLOAD_SOFTWARE, 0); compmap.save(); }
void player::fire_gun(int tarx, int tary, bool burst) { item ammotmp; item* gunmod = weapon.active_gunmod(); it_ammo *curammo = NULL; item *used_weapon = NULL; if (weapon.has_flag("CHARGE")) { // It's a charger gun, so make up a type // Charges maxes out at 8. int charges = weapon.num_charges(); it_ammo *tmpammo = dynamic_cast<it_ammo*>(itypes["charge_shot"]); tmpammo->damage = charges * charges; tmpammo->pierce = (charges >= 4 ? (charges - 3) * 2.5 : 0); if (charges <= 4) tmpammo->dispersion = 14 - charges * 2; else // 5, 12, 21, 32 tmpammo->dispersion = charges * (charges - 4); tmpammo->recoil = tmpammo->dispersion * .8; tmpammo->ammo_effects.clear(); // Reset effects. if (charges == 8) { tmpammo->ammo_effects.insert("EXPLOSIVE_BIG"); } else if (charges >= 6) { tmpammo->ammo_effects.insert("EXPLOSIVE"); } if (charges >= 5){ tmpammo->ammo_effects.insert("FLAME"); } else if (charges >= 4) { tmpammo->ammo_effects.insert("INCENDIARY"); } if (gunmod != NULL) { // TODO: range calculation in case of active gunmod. used_weapon = gunmod; } else { used_weapon = &weapon; } curammo = tmpammo; used_weapon->curammo = tmpammo; } else if (gunmod != NULL) { used_weapon = gunmod; curammo = used_weapon->curammo; } else {// Just a normal gun. If we're here, we know curammo is valid. curammo = weapon.curammo; used_weapon = &weapon; } ammotmp = item(curammo, 0); ammotmp.charges = 1; if (!used_weapon->is_gun() && !used_weapon->is_gunmod()) { debugmsg("%s tried to fire a non-gun (%s).", name.c_str(), used_weapon->tname().c_str()); return; } projectile proj; // damage will be set later proj.aoe_size = 0; proj.ammo = curammo; proj.speed = 1000; std::set<std::string> *curammo_effects = &curammo->ammo_effects; if(gunmod == NULL){ std::set<std::string> *gun_effects = &dynamic_cast<it_gun*>(used_weapon->type)->ammo_effects; proj.proj_effects.insert(gun_effects->begin(),gun_effects->end()); } proj.proj_effects.insert(curammo_effects->begin(),curammo_effects->end()); proj.wide = (curammo->phase == LIQUID || proj.proj_effects.count("SHOT") || proj.proj_effects.count("BOUNCE")); proj.drops = (curammo->type == "bolt" || curammo->type == "arrow"); //int x = xpos(), y = ypos(); // Have to use the gun, gunmods don't have a type it_gun* firing = dynamic_cast<it_gun*>(weapon.type); if (has_trait("TRIGGERHAPPY") && one_in(30)) burst = true; if (burst && used_weapon->burst_size() < 2) burst = false; // Can't burst fire a semi-auto // Use different amounts of time depending on the type of gun and our skill if (!proj.proj_effects.count("BOUNCE")) { moves -= time_to_fire(*this, firing); } // Decide how many shots to fire int num_shots = 1; if (burst) num_shots = used_weapon->burst_size(); if (num_shots > used_weapon->num_charges() && !used_weapon->has_flag("CHARGE") && !used_weapon->has_flag("NO_AMMO")) num_shots = used_weapon->num_charges(); if (num_shots == 0) debugmsg("game::fire() - num_shots = 0!"); int ups_drain = 0; int adv_ups_drain = 0; if (weapon.has_flag("USE_UPS")) { ups_drain = 5; adv_ups_drain = 3; } else if (weapon.has_flag("USE_UPS_20")) { ups_drain = 20; adv_ups_drain = 12; } else if (weapon.has_flag("USE_UPS_40")) { ups_drain = 40; adv_ups_drain = 24; } // cap our maximum burst size by the amount of UPS power left if (ups_drain > 0 || adv_ups_drain > 0) while (!(has_charges("UPS_off", ups_drain*num_shots) || has_charges("UPS_on", ups_drain*num_shots) || has_charges("adv_UPS_off", adv_ups_drain*num_shots) || has_charges("adv_UPS_on", adv_ups_drain*num_shots))) { num_shots--; } const bool debug_retarget = false; // this will inevitably be needed //const bool wildly_spraying = false; // stub for now. later, rng based on stress/skill/etc at the start, int weaponrange = weapon.range(); // this is expensive, let's cache. todo: figure out if we need weapon.range(&p); for (int curshot = 0; curshot < num_shots; curshot++) { // Burst-fire weapons allow us to pick a new target after killing the first int zid = g->mon_at(tarx, tary); if ( curshot > 0 && (zid == -1 || g->zombie(zid).hp <= 0) ) { std::vector<point> new_targets; new_targets.clear(); if ( debug_retarget == true ) { mvprintz(curshot,5,c_red,"[%d] %s: retarget: mon_at(%d,%d)",curshot,name.c_str(),tarx,tary); if(zid == -1) { printz(c_red, " = -1"); } else { printz(c_red, ".hp=%d", g->zombie(zid).hp); } } for (unsigned long int i = 0; i < g->num_zombies(); i++) { monster &z = g->zombie(i); int dummy; // search for monsters in radius if (rl_dist(z.posx(), z.posy(), tarx, tary) <= std::min(2 + skillLevel("gun"), weaponrange) && rl_dist(xpos(),ypos(),z.xpos(),z.ypos()) <= weaponrange && sees(&z, dummy) ) { if (!z.is_dead_state()) new_targets.push_back(point(z.xpos(), z.ypos())); // oh you're not dead and I don't like you. Hello! } } if ( new_targets.empty() == false ) { /* new victim! or last victim moved */ int target_picked = rng(0, new_targets.size() - 1); /* 1 victim list unless wildly spraying */ tarx = new_targets[target_picked].x; tary = new_targets[target_picked].y; zid = g->mon_at(tarx, tary); /* debug */ if (debug_retarget) printz(c_ltgreen, " NEW:(%d:%d,%d) %d,%d (%s)[%d] hp: %d", target_picked, new_targets[target_picked].x, new_targets[target_picked].y, tarx, tary, g->zombie(zid).name().c_str(), zid, g->zombie(zid).hp); } else if ( ( !has_trait("TRIGGERHAPPY") || /* double ta TRIPLE TAP! wait, no... */ one_in(3) /* on second though...everyone double-taps at times. */ ) && ( skillLevel("gun") >= 7 || /* unless trained */ one_in(7 - skillLevel("gun")) /* ...sometimes */ ) ) { return; // No targets, so return } else if (debug_retarget) { printz(c_red, " new targets.empty()!"); } } else if (debug_retarget) { const int zid = g->mon_at(tarx, tary); mvprintz(curshot,5,c_red,"[%d] %s: target == mon_at(%d,%d)[%d] %s hp %d",curshot, name.c_str(), tarx ,tary, zid, g->zombie(zid).name().c_str(), g->zombie(zid).hp); } // Drop a shell casing if appropriate. itype_id casing_type = curammo->casing; if (casing_type != "NULL" && !casing_type.empty()) { item casing; casing.make(itypes[casing_type]); // Casing needs a charges of 1 to stack properly with other casings. casing.charges = 1; if( used_weapon->has_gunmod("brass_catcher") != -1 ) { i_add( casing ); } else { int x = 0; int y = 0; int count = 0; do { x = xpos() - 1 + rng(0, 2); y = ypos() - 1 + rng(0, 2); count++; // Try not to drop the casing on a wall if at all possible. } while( g->m.move_cost( x, y ) == 0 && count < 10 ); g->m.add_item_or_charges(x, y, casing); } } // Use up a round (or 100) if (used_weapon->has_flag("FIRE_100")) { used_weapon->charges -= 100; } else if (used_weapon->has_flag("FIRE_50")) { used_weapon->charges -= 50; } else if (used_weapon->has_flag("CHARGE")) { used_weapon->active = false; used_weapon->charges = 0; } else if (!used_weapon->has_flag("NO_AMMO")) { used_weapon->charges--; } // Drain UPS power if (has_charges("adv_UPS_off", adv_ups_drain)) { use_charges("adv_UPS_off", adv_ups_drain); } else if (has_charges("adv_UPS_on", adv_ups_drain)) { use_charges("adv_UPS_on", adv_ups_drain); } else if (has_charges("UPS_off", ups_drain)) { use_charges("UPS_off", ups_drain); } else if (has_charges("UPS_on", ups_drain)) { use_charges("UPS_on", ups_drain); } if (firing->skill_used != Skill::skill("archery") && firing->skill_used != Skill::skill("throw")) { // Current guns have a durability between 5 and 9. // Misfire chance is between 1/64 and 1/1024. if (is_underwater() && !weapon.has_flag("WATERPROOF_GUN") && one_in(firing->durability)) { g->add_msg_player_or_npc(this, _("Your weapon misfires with a wet click!"), _("<npcname>'s weapon misfires with a wet click!") ); return; } else if (one_in(2 << firing->durability)) { g->add_msg_player_or_npc(this, _("Your weapon misfires!"), _("<npcname>'s weapon misfires!") ); return; } } make_gun_sound_effect(*this, burst, used_weapon); double total_dispersion = get_weapon_dispersion(used_weapon); //debugmsg("%f",total_dispersion); int range = rl_dist(xpos(), ypos(), tarx, tary); // penalties for point-blank if (range < (firing->volume/3) && firing->ammo != "shot") total_dispersion *= double(firing->volume/3) / double(range); // rifle has less range penalty past LONG_RANGE if (firing->skill_used == Skill::skill("rifle") && range > LONG_RANGE) total_dispersion *= 1 - 0.4*double(range - LONG_RANGE) / double(range); if (curshot > 0) { if (recoil_add(*this) % 2 == 1) { recoil++; } recoil += recoil_add(*this) / 2; } else { recoil += recoil_add(*this); } int mtarx = tarx; int mtary = tary; int adjusted_damage = used_weapon->gun_damage(); proj.impact = damage_instance::physical(0,adjusted_damage,0); double missed_by = projectile_attack(proj, mtarx, mtary, total_dispersion); if (missed_by <= .1) { // TODO: check head existence for headshot practice(g->turn, firing->skill_used, 5); lifetime_stats()->headshots++; } else if (missed_by <= .2) { practice(g->turn, firing->skill_used, 3); } else if (missed_by <= .4) { practice(g->turn, firing->skill_used, 2); } else if (missed_by <= .6) { practice(g->turn, firing->skill_used, 1); } } if (used_weapon->num_charges() == 0) { used_weapon->curammo = NULL; } }
double Creature::projectile_attack(const projectile &proj, int sourcex, int sourcey, int targetx, int targety, double shot_dispersion) { int range = rl_dist(sourcex,sourcey,targetx,targety); // .013 * trange is a computationally cheap version of finding the tangent. // (note that .00325 * 4 = .013; .00325 is used because deviation is a number // of quarter-degrees) // It's also generous; missed_by will be rather short. double missed_by = shot_dispersion * .00325 * range; // TODO: move to-hit roll back in here if (missed_by >= 1.) { // We missed D: // Shoot a random nearby space? targetx += rng(0 - int(sqrt(double(missed_by))), int(sqrt(double(missed_by)))); targety += rng(0 - int(sqrt(double(missed_by))), int(sqrt(double(missed_by)))); } std::vector<point> trajectory; int tart = 0; if (g->m.sees(sourcex, sourcey, targetx, targety, -1, tart)) { trajectory = line_to(sourcex,sourcey,targetx,targety,tart); } else { trajectory = line_to(sourcex,sourcey,targetx,targety,0); } // Set up a timespec for use in the nanosleep function below timespec ts; ts.tv_sec = 0; ts.tv_nsec = BULLET_SPEED; int dam = proj.impact.total_damage() + proj.payload.total_damage(); it_ammo *curammo = proj.ammo; // Trace the trajectory, doing damage in order int tx = trajectory[0].x; int ty = trajectory[0].y; int px = trajectory[0].x; int py = trajectory[0].y; for (int i = 0; i < trajectory.size() && (dam > 0 || (proj.proj_effects.count("FLAME"))); i++) { px = tx; py = ty; (void) px; (void) py; tx = trajectory[i].x; ty = trajectory[i].y; // Drawing the bullet uses player u, and not player p, because it's drawn // relative to YOUR position, which may not be the gunman's position. g->draw_bullet(g->u, tx, ty, i, trajectory, proj.proj_effects.count("FLAME")? '#':'*', ts); /* TODO: add running out of momentum back in if (dam <= 0 && !(proj.proj_effects.count("FLAME"))) { // Ran out of momentum. break; } */ int mondex = g->mon_at(tx, ty); // ignore non-point-blank digging targets (since they are underground) if (mondex != -1 && g->zombie(mondex).digging() && rl_dist(xpos(), ypos(), g->zombie(mondex).xpos(), g->zombie(mondex).ypos()) > 1) mondex = -1; // If we shot us a monster... // TODO: add size effects to accuracy // If there's a monster in the path of our bullet, and either our aim was true, // OR it's not the monster we were aiming at and we were lucky enough to hit it double cur_missed_by; if (i < trajectory.size() - 1) { // Unintentional hit cur_missed_by = std::max(rng_float(0,1.5)+(1-missed_by),0.2); } else { cur_missed_by = missed_by; } if (mondex != -1 && cur_missed_by <= 1.0) { monster &z = g->zombie(mondex); dealt_damage_instance dealt_dam; z.deal_projectile_attack(this, missed_by, proj, dealt_dam); std::vector<point> blood_traj = trajectory; blood_traj.insert(blood_traj.begin(), point(xpos(), ypos())); //splatter(this, blood_traj, dam, &z); TODO: add splatter effects //back in dam = 0; // TODO: general case this so it works for all npcs, instead of only // player } else if (g->u.xpos() == tx && g->u.ypos() == ty && cur_missed_by <= 1.0) { dealt_damage_instance dealt_dam; g->u.deal_projectile_attack(this, missed_by, proj, dealt_dam); std::vector<point> blood_traj = trajectory; blood_traj.insert(blood_traj.begin(), point(xpos(), ypos())); } else { g->m.shoot(tx, ty, dam, i == trajectory.size() - 1, proj.proj_effects); } } // Done with the trajectory! if (g->m.move_cost(tx, ty) == 0) { tx = px; ty = py; } // we can only drop something if curammo exists if (curammo != NULL && proj.drops && !(proj.proj_effects.count("IGNITE")) && !(proj.proj_effects.count("EXPLOSIVE")) && ((curammo->m1 == "wood" && !one_in(5)) || (curammo->m1 != "wood" && !one_in(15)) )) { item ammotmp = item(curammo, 0); ammotmp.charges = 1; g->m.add_item_or_charges(tx, ty, ammotmp); } ammo_effects(tx, ty, proj.proj_effects); if (proj.proj_effects.count("BOUNCE")) { for (unsigned long int i = 0; i < g->num_zombies(); i++) { monster &z = g->zombie(i); // search for monsters in radius 4 around impact site if (rl_dist(z.posx(), z.posy(), tx, ty) <= 4) { // don't hit targets that have already been hit if (!z.has_effect("bounced") && !z.dead) { g->add_msg(_("The attack bounced to %s!"), z.name().c_str()); projectile_attack(proj, tx, ty, z.posx(), z.posy(), shot_dispersion); break; } } } } return missed_by; }
requirement_data requirement_data::disassembly_requirements() const { // TODO: // Allow jsonizing those tool replacements // Make a copy // Maybe TODO: Cache it somewhere and return a reference instead requirement_data ret = *this; auto new_qualities = std::vector<quality_requirement>(); for( auto &it : ret.tools ) { bool replaced = false; for( const auto &tool : it ) { const itype_id &type = tool.type; // If crafting required a welder or forge then disassembly requires metal sawing if( type == "welder" || type == "welder_crude" || type == "oxy_torch" || type == "forge" || type == "char_forge" ) { new_qualities.emplace_back( quality_id( "SAW_M_FINE" ), 1, 1 ); replaced = true; break; } if( type == "sewing_kit" || type == "mold_plastic" ) { new_qualities.emplace_back( quality_id( "CUT" ), 1, 1 ); replaced = true; break; } if( type == "crucible" ) { replaced = true; break; } } if( replaced ) { // Replace the entire block of variants // This avoids the pesky integrated toolset it.clear(); } } // Warning: This depends on the fact that tool qualities // are all mandatory (don't use variants) // If that ever changes, this will be wrong! if( ret.qualities.empty() ) { ret.qualities.resize( 1 ); } auto &qualities = ret.qualities[0]; qualities.insert( qualities.end(), new_qualities.begin(), new_qualities.end() ); // Remove duplicate qualities { auto itr = std::unique( qualities.begin(), qualities.end(), []( const quality_requirement & a, const quality_requirement & b ) { return a.type == b.type; } ); qualities.resize( std::distance( qualities.begin(), itr ) ); } // Remove empty variant sections ret.tools.erase( std::remove_if( ret.tools.begin(), ret.tools.end(), []( const std::vector<tool_comp> &tcv ) { return tcv.empty(); } ), ret.tools.end() ); // Remove unrecoverable components ret.components.erase( std::remove_if( ret.components.begin(), ret.components.end(), []( std::vector<item_comp> &cov ) { cov.erase( std::remove_if( cov.begin(), cov.end(), []( const item_comp &comp ) { return !comp.recoverable || item( comp.type ).has_flag( "UNRECOVERABLE" ); } ), cov.end() ); return cov.empty(); } ), ret.components.end() ); return ret; }
void shoot_monster(player &p, monster &mon, int &dam, double goodhit, item* weapon, const std::set<std::string> &effects) { // Gunmods don't have a type, so use the player weapon type. it_gun* firing = dynamic_cast<it_gun*>(p.weapon.type); std::string message; bool u_see_mon = g->u_see(&(mon)); int adjusted_damage = dam; if (mon.has_flag(MF_HARDTOSHOOT) && !one_in(10 - 10 * (.8 - goodhit)) && // Maxes out at 50% chance with perfect hit weapon->curammo->phase != LIQUID && !effects.count("SHOT") && !effects.count("BOUNCE")) { if (u_see_mon) g->add_msg(_("The shot passes through the %s without hitting."), mon.name().c_str()); } else { // Not HARDTOSHOOT // Bounce applies whether it does damage or not. if (effects.count("BOUNCE")) { mon.add_effect("bounced", 1); } // Armor blocks BEFORE any critical effects. int zarm = mon.get_armor_cut(bp_torso); zarm -= weapon->gun_pierce(); if (weapon->curammo->phase == LIQUID) zarm = 0; else if (effects.count("SHOT")) // Shot doesn't penetrate armor well zarm *= rng(2, 3); if (zarm > 0) adjusted_damage -= zarm; if (adjusted_damage <= 0) { if (u_see_mon) g->add_msg(_("The shot reflects off the %s!"), mon.name_with_armor().c_str()); adjusted_damage = 0; goodhit = 1; } if (goodhit <= .1 && !mon.has_flag(MF_NOHEAD)) { message = _("Headshot!"); adjusted_damage = rng(5 * adjusted_damage, 8 * adjusted_damage); p.practice(g->turn, firing->skill_used, 5); p.lifetime_stats()->headshots++; } else if (goodhit <= .2) { message = _("Critical!"); adjusted_damage = rng(adjusted_damage * 2, adjusted_damage * 3); p.practice(g->turn, firing->skill_used, 3); } else if (goodhit <= .4) { message = _("Good hit!"); adjusted_damage = rng(adjusted_damage , adjusted_damage * 2); p.practice(g->turn, firing->skill_used, 2); } else if (goodhit <= .6) { adjusted_damage = rng(adjusted_damage / 2, adjusted_damage); p.practice(g->turn, firing->skill_used, 1); } else if (goodhit <= .8) { message = _("Grazing hit."); adjusted_damage = rng(0, adjusted_damage); } else { adjusted_damage = 0; } if(item(weapon->curammo, 0).has_flag("NOGIB")) { adjusted_damage = std::min(adjusted_damage, mon.hp+10); } // Find the zombie at (x, y) and hurt them, MAYBE kill them! if (adjusted_damage > 0) { switch (mon.type->size) { case MS_TINY: mon.moves -= rng(0, adjusted_damage * 5); break; case MS_SMALL: mon.moves -= rng(0, adjusted_damage * 3); break; case MS_MEDIUM: mon.moves -= rng(0, adjusted_damage); break; case MS_LARGE: mon.moves -= rng(0, adjusted_damage / 3); break; case MS_HUGE: mon.moves -= rng(0, adjusted_damage / 5); break; } if (&p == &(g->u) && u_see_mon) { g->add_msg(_("%s You hit the %s for %d damage."), message.c_str(), mon.name().c_str(), adjusted_damage); } else if (u_see_mon) { g->add_msg(_("%s %s shoots the %s."), message.c_str(), p.name.c_str(), mon.name().c_str()); } g->hit_monster_with_flags(mon, effects); damage_instance d; d.add_damage(DT_CUT, adjusted_damage, weapon->gun_pierce(), effects.count("SHOT")?rng(2,3):1); // Shot doesn't penetrate armor well mon.deal_damage(&p, bp_torso, -1, d); if( u_see_mon ) { g->draw_hit_mon(mon.posx(), mon.posy(), mon, mon.is_dead_state()); } } } dam = adjusted_damage; }
MSCascadeMenu::~MSCascadeMenu(void) { item()->menuDestroy(this); }
void gun_actor::shoot( monster &z, Creature &target, const std::string &mode ) const { if( require_sunlight && !g->is_in_sunlight( z.pos() ) ) { if( one_in( 3 ) && g->u.sees( z ) ) { add_msg( _( failure_msg.c_str() ), z.name().c_str() ); } return; } const bool require_targeting = ( require_targeting_player && target.is_player() ) || ( require_targeting_npc && target.is_npc() ) || ( require_targeting_monster && target.is_monster() ); const bool not_targeted = require_targeting && !z.has_effect( effect_targeted ); const bool not_laser_locked = require_targeting && laser_lock && !target.has_effect( effect_was_laserlocked ); if( not_targeted || not_laser_locked ) { if( targeting_volume > 0 && !targeting_sound.empty() ) { sounds::sound( z.pos(), targeting_volume, _( targeting_sound.c_str() ) ); } if( not_targeted ) { z.add_effect( effect_targeted, targeting_timeout ); } if( not_laser_locked ) { target.add_effect( effect_laserlocked, 5 ); target.add_effect( effect_was_laserlocked, 5 ); target.add_msg_if_player( m_warning, _( "You're not sure why you've got a laser dot on you..." ) ); } z.moves -= targeting_cost; return; } z.moves -= move_cost; item gun( gun_type ); gun.gun_set_mode( mode ); itype_id ammo = ( ammo_type != "null" ) ? ammo_type : gun.ammo_default(); if( ammo != "null" ) { gun.ammo_set( ammo, z.ammo[ ammo ] ); } if( !gun.ammo_sufficient() ) { if( !no_ammo_sound.empty() ) { sounds::sound( z.pos(), 10, _( no_ammo_sound.c_str() ) ); } return; } standard_npc tmp( _( "The " ) + z.name(), {}, 8, fake_str, fake_dex, fake_int, fake_per ); tmp.set_fake( true ); tmp.setpos( z.pos() ); tmp.attitude = z.friendly ? NPCATT_FOLLOW : NPCATT_KILL; tmp.recoil = 0; // no need to aim for( const auto &pr : fake_skills ) { tmp.set_skill_level( pr.first, pr.second ); } tmp.weapon = gun; tmp.i_add( item( "UPS_off", calendar::turn, 1000 ) ); if( g->u.sees( z ) ) { add_msg( m_warning, _( description.c_str() ), z.name().c_str(), tmp.weapon.tname().c_str() ); } z.ammo[ammo] -= tmp.fire_gun( target.pos(), gun.gun_current_mode().qty ); if( require_targeting ) { z.add_effect( effect_targeted, targeting_timeout_extend ); } if( laser_lock ) { // To prevent spamming laser locks when the player can tank that stuff somehow target.add_effect( effect_was_laserlocked, 5 ); } }
LONG CuDlgDomPropDDbProc::OnUpdateData (WPARAM wParam, LPARAM lParam) { // cast received parameters int nNodeHandle = (int)wParam; LPIPMUPDATEPARAMS pUps = (LPIPMUPDATEPARAMS)lParam; ASSERT (nNodeHandle != -1); ASSERT (pUps); // ignore selected actions on filters switch (pUps->nIpmHint) { case 0: case FILTER_DOM_SYSTEMOBJECTS: // eligible //case FILTER_DOM_BASEOWNER: case FILTER_DOM_OTHEROWNER: break; case FILTER_DOM_BKREFRESH: // eligible if UpdateType is compatible with DomGetFirst/Next object type, // or is ot_virtnode, which means refresh for all whatever the type is if (pUps->pSFilter->UpdateType != OT_VIRTNODE && pUps->pSFilter->UpdateType != OT_PROCEDURE) return 0L; break; case FILTER_SETTING_CHANGE: VDBA_OnGeneralSettingChange(&m_cListCtrl); return 0L; default: return 0L; // nothing to change on the display } ResetDisplay(); // Get info on the current item LPTREERECORD lpRecord = (LPTREERECORD)pUps->pStruct; ASSERT (lpRecord); // // Get list of Proc for the replication // m_Data.m_uaDbProc.RemoveAll(); int iret; LPUCHAR aparentsTemp[MAXPLEVEL]; UCHAR buf[MAXOBJECTNAME]; UCHAR bufOwner[MAXOBJECTNAME]; UCHAR bufComplim[MAXOBJECTNAME]; // parent preparation - added static type. switch (lpRecord->recType) { case OT_DATABASE: aparentsTemp[0] = lpRecord->objName; break; case OT_STATIC_PROCEDURE: aparentsTemp[0] = lpRecord->extra; break; default: ASSERT(FALSE); return 0L; } aparentsTemp[1] = aparentsTemp[2] = NULL; m_Data.m_objType = lpRecord->recType; // MANDATORY! memset (&bufComplim, '\0', sizeof(bufComplim)); memset (&bufOwner, '\0', sizeof(bufOwner)); iret = DOMGetFirstObject(nNodeHandle, OT_PROCEDURE, 1, // level, aparentsTemp, // Temp mandatory! pUps->pSFilter->bWithSystem, // bwithsystem (LPUCHAR)pUps->pSFilter->lpOtherOwner, // lpowner buf, bufOwner, bufComplim); if (iret != RES_SUCCESS && iret != RES_ENDOFDATA) { // Erroneous case! CuNameWithOwner errItem(VDBA_MfcResourceString (IDS_DATA_UNAVAILABLE));//"<Data Unavailable>" m_Data.m_uaDbProc.Add(errItem); } else { while (iret == RES_SUCCESS) { CuNameWithOwner item((const char*)buf, (const char*)bufOwner); m_Data.m_uaDbProc.Add(item); iret = DOMGetNextObject(buf, bufOwner, bufComplim); } } if (m_Data.m_uaDbProc.GetCount() == 0) { CuNameWithOwner noItem(VDBA_MfcResourceString (IDS_E_NO_PROCEDURE));//"<No Procedure>" m_Data.m_uaDbProc.Add(noItem); } // Refresh display RefreshDisplay(); return 0L; }
else mutex_unlock(&self->access.rx); return 1; } bool_t mtstream_accesstx(stream_t *u, bool_t onoff){ mt_stream_t* self = (mt_stream_t*)u; if (onoff) mutex_lock(&self->access.tx); else mutex_unlock(&self->access.tx); return 1; } static stream_interface_t mtstream_proxy_interface = { item(putc) (void (*) (stream_t*, short)) mtstream_putchar, item(getc) (unsigned short (*) (stream_t*)) mtstream_getchar, item(peekc) (int (*) (stream_t*)) mtstream_peekchar, item(flush) (void (*) (stream_t*)) mtstream_fflush, item(eof) (bool_t (*) (stream_t*)) mtstream_eof, item(close) (void (*) (stream_t*)) mtstream_close, item(receiver) (mutex_t *(*) (stream_t*)) mtstream_receiver, //* позволяют потребовать монопольного захвата потока item(access_rx) (bool_t (*)(stream_t *u, bool_t onoff)) mtstream_accessrx, item(access_tx) (bool_t (*)(stream_t *u, bool_t onoff)) mtstream_accesstx, }; void mtstream_init (mt_stream_t *u, stream_t* target){ u->interface = &mtstream_proxy_interface; u->target = target; //mutex_init(u->access.rx);
bool QAccessibleQuickItem::clipsChildren() const { return static_cast<QQuickItem *>(item())->clip(); }
/*********************************************************** * Fetching ***********************************************************/ void HQueryItem::Fetching() { bool some_success = false; BVolume volume; BVolumeRoster roster; while (fQueries.CountItems()) { delete static_cast<BQuery *>(fQueries.RemoveItem((int32)0)); } uint32 count_items = 0; while (roster.GetNextVolume(&volume) == B_OK) { BQuery *query = new BQuery; fQueries.AddItem((void*)query); query->Clear(); query->SetTarget(*fMessenger); query->SetVolume(&volume); query->SetPredicate(fPredicate.String()); char type[B_MIME_TYPE_LENGTH+1]; BNode node; HMailItem *item(NULL); if(query->Fetch() == B_OK) { some_success = true; entry_ref ref; char buf[4096]; dirent *dent; int32 count; int32 offset; while (((count = query->GetNextDirents((dirent *)buf, 4096)) > 0) && (!fCancel)) { offset = 0; /* Now we step through the dirents. */ while (count-- > 0) { dent = (dirent *)buf + offset; offset += dent->d_reclen; /* Skip . and .. directory */ if(::strcmp(dent->d_name,".") == 0 || ::strcmp(dent->d_name,"..")== 0) continue; ref.device = dent->d_pdev; ref.directory = dent->d_pino; ref.set_name(dent->d_name); if(node.SetTo(&ref) != B_OK) continue; node.ReadAttr("BEOS:TYPE",'MIMS',0,type,B_MIME_TYPE_LENGTH); if(::strcmp(type,B_MAIL_TYPE) == 0) { fMailList.AddItem(item = new HMailItem(ref)); if(item && !item->IsRead() ) count_items++; } } } }DEBUG_ONLY( else{ PRINT(("Query fetching was failed\n")); } ); }
bool vibrator_thread_exit = false; #ifdef FEATURE_FTM_VIBRATOR #define VIBRATOR_ENABLE "/sys/class/timed_output/vibrator/enable" extern int item_testing; bool vibrator_test_exit = false; static pthread_t vibrator_thread; enum { ITEM_PASS, ITEM_FAIL }; static item_t items[] = { item(ITEM_PASS, uistr_pass), item(ITEM_FAIL, uistr_fail), item(-1, NULL), }; #ifdef VIBRATOR_AUTOTEST static item_t items_auto[] = { {-1, NULL, 0}, }; struct mVibrator { struct ftm_module *mod; struct textview tv; struct itemview *iv; pthread_t hHeadsetThread; pthread_t hRecordThread;
/** \brief Add a package by package name, and option version */ void package_list::add_package( const std::string& package, const std::string& version, const bool force_reinstall ) { const wpkg_filename::uri_filename pck(package); list_t::const_iterator item(find_package_item(pck)); if(item != f_packages.end()) { // the user is trying to install the same package twice // (ignore if that's exactly the same one) if(item->get_type() != package_item_t::package_type_explicit) { wpkg_output::log("package %1 defined twice on your command line using two different paths.") .quoted_arg(package) .level(wpkg_output::level_error) .module(wpkg_output::module_validate_installation) .package(package) .action("install-validation"); } } else { if( pck.extension() == "deb") { // this is an explicit package package_item_t package_item( f_manager, pck ); f_packages.push_back(package_item); } else { wpkgar_repository repository( f_manager ); typedef std::map<std::string,wpkgar_repository::package_item_t> version_package_map_t; version_package_map_t version_map; for( const auto& entry : repository.upgrade_list() ) { if( entry.get_name() == package ) { version_map[entry.get_version()] = entry; } } if( version_map.empty() ) { std::stringstream ss; ss << "Cannot install package '" << package << "' because it doesn't exist in the repository!"; throw std::runtime_error(ss.str()); } if( version.empty() ) { auto greatest_version( version_map.rbegin()->first ); if( version_map.size() > 1 ) { wpkg_output::log("package '%1' has multiple versions available in the selected repositories. Selected the greatest version '%2'.") .quoted_arg(package) .quoted_arg(greatest_version) .level(wpkg_output::level_warning) .module(wpkg_output::module_validate_installation) .package(package) .action("install-validation"); } // Select the greatest version // add_package( version_map.rbegin()->second, force_reinstall ); } else { add_package( version_map[version], force_reinstall ); } } } }
//========================================================== //= Get Options //========================================================== QStringList XSettingsModel::get_fgfs_args() { //= Read --options from tree QStringList args; QString str(""); for(int row_idx=0; row_idx < rowCount(); row_idx++){ if(item(row_idx, C_ENABLED)->text() == "1"){ QString op = item(row_idx, C_OPTION)->text(); str = ""; if(op.startsWith("--")){ str.append(item(row_idx, C_OPTION)->text()).append(item(row_idx, C_VALUE)->text()); } if(str.length() > 0){ if (str.indexOf(QChar(' ')) > 0) { str = "\""+str+"\""; // encase in QUOTE if it contains a SPACE char } args << str; } } } // Process unique items, like fgcom socket if(fgcom_enabled()){ // This option needs an overhaul once. Server and port separated. It is never needed // as server:port for fgfs or fgcom. It’s just splitted everywhere ... // For the fgfs command line option we only need the port, for starting fgcom // we need the server and the port, but this can come to separated setting values (?) // Anyway ... took an age this one. QString serverandport(getx("fgcom_server")); QString portonly(serverandport.split(":").at(1)); args << QString("--generic=socket,out,10,localhost,%1,udp,fgcom").arg(portonly); } //txtFgComPort->setText( value.split(":").at(1)); //= add Extra args XOpt opt = get_opt("extra_args"); if (opt.enabled && (opt.value.length() > 0)) { QStringList parts = opt.value.split("\n"); if(parts.count() > 0){ for(int i=0; i < parts.count(); i++){ QString part = parts.at(i).trimmed(); if(part.length() > 0){ args << part; } } } } //== FgRoot str = fgroot(); if (str.length() > 0) { // only ADDED if we have a FGROOT // Maybe the user sets FG_ROOT in the environment, so do NOT need any here str = "--fg-root="+str; if (str.indexOf(QChar(' ')) > 0) { str = "\""+str+"\""; // encase in QUOTE if it contains a SPACE char } args << str; } //= Terrasync and custom scenery path // setup the DIFFERENT path separators!!! QString path_sep = ":"; // normal unix path separator #ifdef Q_OS_WIN path_sep = ";"; // oops, switch the WINDOWS spearator #endif // FIX20120410 - For Windows, and most other OSes, put paths with a SPACE in quotes // TODO - should check if paths are not BLANK, and are valid paths before blithly adding them // Helps no one to add BLANK or INVALID paths if (terrasync_enabled() && !custom_scenery_enabled()) { str = "--fg-scenery="; str.append(terrasync_data_path()).append(path_sep).append(scenery_path()); if (str.indexOf(QChar(' ')) > 0) { str = "\""+str+"\""; // encase in QUOTE if it contains a SPACE char } args << str; args << QString("--atlas=socket,out,5,localhost,5505,udp"); } else if (terrasync_enabled() && custom_scenery_enabled()) { str = "--fg-scenery="; str.append(custom_scenery_path()).append(path_sep).append(terrasync_data_path()).append(path_sep).append(scenery_path()); if (str.indexOf(QChar(' ')) > 0) { str = "\""+str+"\""; // encase in QUOTE if it contains a SPACE char } args << str; args << QString("--atlas=socket,out,5,localhost,5505,udp"); } else if (!terrasync_enabled() && custom_scenery_enabled()) { str = "--fg-scenery="; str.append(custom_scenery_path()).append(path_sep).append(scenery_path()); if (str.indexOf(QChar(' ')) > 0) { str = "\""+str+"\""; // encase in QUOTE if it contains a SPACE char } args << str; } else if (!terrasync_enabled() && !custom_scenery_enabled()) { str = "--fg-scenery="; str.append(scenery_path()); if (str.indexOf(QChar(' ')) > 0) { str = "\""+str+"\""; // encase in QUOTE if it contains a SPACE char } args << str; } return args; }
/*! \brief Start playback of media. * \param params The parameters. * \details params[0] = URL to media to play (optional). * params[1,...] = "isdir" if media is a directory (optional). * params[1,...] = "1" to start playback in fullscreen (optional). * params[1,...] = "resume" to force resuming (optional). * params[1,...] = "noresume" to force not resuming (optional). * params[1,...] = "playoffset=<offset>" to start playback from a given position in a playlist (optional). */ static int PlayMedia(const std::vector<std::string>& params) { CFileItem item(params[0], false); if (URIUtils::HasSlashAtEnd(params[0])) item.m_bIsFolder = true; // restore to previous window if needed if( g_windowManager.GetActiveWindow() == WINDOW_SLIDESHOW || g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO || g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION ) g_windowManager.PreviousWindow(); // reset screensaver g_application.ResetScreenSaver(); g_application.WakeUpScreenSaverAndDPMS(); // ask if we need to check guisettings to resume bool askToResume = true; int playOffset = 0; for (unsigned int i = 1 ; i < params.size() ; i++) { if (StringUtils::EqualsNoCase(params[i], "isdir")) item.m_bIsFolder = true; else if (params[i] == "1") // set fullscreen or windowed CMediaSettings::GetInstance().SetVideoStartWindowed(true); else if (StringUtils::EqualsNoCase(params[i], "resume")) { // force the item to resume (if applicable) (see CApplication::PlayMedia) item.m_lStartOffset = STARTOFFSET_RESUME; askToResume = false; } else if (StringUtils::EqualsNoCase(params[i], "noresume")) { // force the item to start at the beginning (m_lStartOffset is initialized to 0) askToResume = false; } else if (StringUtils::StartsWithNoCase(params[i], "playoffset=")) { playOffset = atoi(params[i].substr(11).c_str()) - 1; item.SetProperty("playlist_starting_track", playOffset); } } if (!item.m_bIsFolder && item.IsPlugin()) item.SetProperty("IsPlayable", true); if ( askToResume == true ) { if ( CGUIWindowVideoBase::ShowResumeMenu(item) == false ) return false; } if (item.m_bIsFolder) { CFileItemList items; std::string extensions = g_advancedSettings.m_videoExtensions + "|" + g_advancedSettings.GetMusicExtensions(); XFILE::CDirectory::GetDirectory(item.GetPath(),items,extensions); bool containsMusic = false, containsVideo = false; for (int i = 0; i < items.Size(); i++) { bool isVideo = items[i]->IsVideo(); containsMusic |= !isVideo; containsVideo |= isVideo; if (containsMusic && containsVideo) break; } std::unique_ptr<CGUIViewState> state(CGUIViewState::GetViewState(containsVideo ? WINDOW_VIDEO_NAV : WINDOW_MUSIC, items)); if (state.get()) items.Sort(state->GetSortMethod()); else items.Sort(SortByLabel, SortOrderAscending); int playlist = containsVideo? PLAYLIST_VIDEO : PLAYLIST_MUSIC;; if (containsMusic && containsVideo) //mixed content found in the folder { for (int i = items.Size() - 1; i >= 0; i--) //remove music entries { if (!items[i]->IsVideo()) items.Remove(i); } } g_playlistPlayer.ClearPlaylist(playlist); g_playlistPlayer.Add(playlist, items); g_playlistPlayer.SetCurrentPlaylist(playlist); g_playlistPlayer.Play(playOffset, ""); } else { int playlist = item.IsAudio() ? PLAYLIST_MUSIC : PLAYLIST_VIDEO; g_playlistPlayer.ClearPlaylist(playlist); g_playlistPlayer.SetCurrentPlaylist(playlist); // play media if (!g_application.PlayMedia(item, "", playlist)) { CLog::Log(LOGERROR, "PlayMedia could not play media: %s", params[0].c_str()); return false; } } return 0; }
bool ParserTable::loadFromData(const char* data, size_t size) { if (compareString(data, size, PARSER_TABLE)) data += strlen(PARSER_TABLE); //uchar version = *data; ++data; data += 8; // timestamp align to 8 bytes size_t vtCount = *reinterpret_cast<const size_t*>(data); data += sizeof(size_t); size_t vnCount = *reinterpret_cast<const size_t*>(data); data += sizeof(size_t); size_t rulesCount = *reinterpret_cast<const size_t*>(data); data += sizeof(size_t); size_t itemCount = *reinterpret_cast<const size_t*>(data); data += sizeof(size_t); iStart = *reinterpret_cast<const uint*>(data); data += sizeof(uint); vts.reserve(vtCount); vns.reserve(vnCount); rules.reserve(rulesCount); items.reserve(itemCount); table.reserve(itemCount * (vtCount + 1 + vnCount)); for (size_t i = 0; i < itemCount * (vtCount + 1 + vnCount); ++i) { pair<uchar, ushort> p; p.first = *data; ++data; p.second = *reinterpret_cast<const ushort*>(data); data += sizeof(ushort); table.push_back(p); } for (size_t i = 0; i < vtCount; ++i) { Production::Item item(&ruleContext); item.loadFromData(data); vts.push_back(item); } for (size_t i = 0; i < vnCount; ++i) { Production::Item item; item.loadFromData(data); vns.push_back(item); } for (size_t i = 0; i < rulesCount; ++i) { Production p; p.loadFromData(data, &ruleContext); rules.push_back(p); } for (size_t i = 0; i < itemCount; ++i) { items.push_back(*reinterpret_cast<const uint*>(data)); data += sizeof(uint); } return true; }
MSPulldownMenu::~MSPulldownMenu(void) { item()->menuDestroy(this); }
QString GetOption::getOptionValue(const QString &op) const { OptionItem item(optionMap.value(op)); return item.getOptionValue(); }
void MusicVideoTableWidget::downloadLocalMovie(int row) { MusicDownloadMgmtWidget mgmt(this); mgmt.setSongName(item(row, 2)->text() + " - " + item(row, 1)->text(), MusicDownLoadQueryThreadAbstract::MovieQuery); }
void GetOption::addOption(const QString &op, const QString &description) { OptionItem item(op,description); optionMap.insert(op,item); }
uartx_receive_lock (uartx_t *u) { return &u->receiver; } #ifdef __cplusplus #define idx(i) #define item(i) #else #define idx(i) [i] = #define item(i) .i = #endif static stream_interface_t uartx_interface = { item(putc) (void (*) (stream_t*, short)) uartx_putchar, item(getc) (unsigned short (*) (stream_t*)) uartx_getchar, item(peekc) (int (*) (stream_t*)) uartx_peekchar, item(flush) (void (*) (stream_t*)) uartx_fflush, item(eof) (bool_t (*) (stream_t*)) 0, item(close) (void (*) (stream_t*)) 0, item(receiver) (mutex_t *(*) (stream_t*)) uartx_receive_lock, }; /* * Проверка регистров UART. */ void uartx_test_registers (int port) { unsigned i, msr, spr, errors = 0;
QuetzalFieldsDialog::QuetzalFieldsDialog(const char *title, const char *primary, const char *secondary, PurpleRequestFields *fields, const char *ok_text, GCallback ok_cb, const char *cancel_text, GCallback cancel_cb, void *user_data, QWidget *parent) : QuetzalRequestDialog(PURPLE_REQUEST_FIELDS, user_data, parent) { m_ok_cb = (PurpleRequestFieldsCb) ok_cb; m_cancel_cb = (PurpleRequestFieldsCb) cancel_cb; m_fields = fields; DataItem root = createItem(title, primary, secondary); GList *group_it = purple_request_fields_get_groups(m_fields); bool useGroupBox = group_it->next; debug() << "useGroupBox" << useGroupBox; for (; group_it; group_it = group_it->next) { PurpleRequestFieldGroup *group = reinterpret_cast<PurpleRequestFieldGroup*>(group_it->data); DataItem groupItem; if (useGroupBox) groupItem = DataItem(purple_request_field_group_get_title(group)); GList *field_it = purple_request_field_group_get_fields(group); for (; field_it; field_it = field_it->next) { PurpleRequestField *field = reinterpret_cast<PurpleRequestField*>(field_it->data); debug() << field->id << purple_request_field_is_visible(field) << purple_request_field_get_type(field); if (!purple_request_field_is_visible(field)) continue; DataItem item(purple_request_field_get_id(field), purple_request_field_get_label(field), QVariant()); switch (purple_request_field_get_type(field)) { case PURPLE_REQUEST_FIELD_STRING: item.setData(QString::fromUtf8(purple_request_field_string_get_default_value(field))); item.setProperty("multiline", purple_request_field_string_is_multiline(field)); item.setProperty("password", bool(purple_request_field_string_is_masked(field))); item.setReadOnly(!purple_request_field_string_is_editable(field)); debug() << item.name() << item.data() << item.property("password") << item.isReadOnly(); break; case PURPLE_REQUEST_FIELD_INTEGER: item.setData(purple_request_field_int_get_default_value(field)); item.setProperty("minValue", G_MININT); item.setProperty("maxValue", G_MAXINT); break; case PURPLE_REQUEST_FIELD_BOOLEAN: item.setData(bool(purple_request_field_bool_get_default_value(field))); break; case PURPLE_REQUEST_FIELD_CHOICE: { GList *labels = purple_request_field_choice_get_labels(field); QStringList alternatives; for (; labels; labels = labels->next) alternatives << QString::fromUtf8(reinterpret_cast<char*>(labels->data)); item.setData(alternatives.value(purple_request_field_choice_get_default_value(field))); item.setProperty("alternatives", alternatives); } break; case PURPLE_REQUEST_FIELD_LIST: break; case PURPLE_REQUEST_FIELD_LABEL: item.setData(purple_request_field_get_label(field)); item.setReadOnly(true); item.setProperty("hideTitle", true); break; case PURPLE_REQUEST_FIELD_IMAGE: { QImageReader reader; QByteArray data = QByteArray::fromRawData(purple_request_field_image_get_buffer(field), purple_request_field_image_get_size(field)); QBuffer buffer(&data); reader.setDevice(&buffer); QSize imageSize = reader.size(); if (imageSize.isValid()) { imageSize.setWidth(imageSize.width() * purple_request_field_image_get_scale_x(field)); imageSize.setHeight(imageSize.height() * purple_request_field_image_get_scale_y(field)); reader.setScaledSize(imageSize); } item.setData(qVariantFromValue(reader.read())); item.setProperty("imageSize", qVariantFromValue(imageSize)); item.setReadOnly(true); } break; case PURPLE_REQUEST_FIELD_ACCOUNT: break; case PURPLE_REQUEST_FIELD_NONE: default: continue; } item.setProperty("mandatory", purple_request_field_is_required(field)); if (useGroupBox) groupItem.addSubitem(item); else root.addSubitem(item); } if (useGroupBox) root.addSubitem(groupItem); } createItem(root, ok_text, cancel_text); return; }
/** * Process a sentence with xml annotation * Xml tags may specifiy additional/replacing translation options * and reordering constraints * * \param line in: sentence, out: sentence without the xml * \param res vector with translation options specified by xml * \param reorderingConstraint reordering constraint zones specified by xml * \param walls reordering constraint walls specified by xml */ bool TreeInput::ProcessAndStripXMLTags(string &line, std::vector<XMLParseOutput> &sourceLabels, std::vector<XmlOption*> &xmlOptions) { //parse XML markup in translation line // no xml tag? we're done. if (line.find_first_of('<') == string::npos) { return true; } // hack. What pt should XML trans opt be assigned to? PhraseDictionary *firstPt = NULL; if (PhraseDictionary::GetColl().size() == 0) { firstPt = PhraseDictionary::GetColl()[0]; } // break up input into a vector of xml tags and text // example: (this), (<b>), (is a), (</b>), (test .) vector<string> xmlTokens = TokenizeXml(line); // we need to store opened tags, until they are closed // tags are stored as tripled (tagname, startpos, contents) typedef pair< string, pair< size_t, string > > OpenedTag; vector< OpenedTag > tagStack; // stack that contains active opened tags string cleanLine; // return string (text without xml) size_t wordPos = 0; // position in sentence (in terms of number of words) // keep this handy for later const vector<FactorType> &outputFactorOrder = StaticData::Instance().GetOutputFactorOrder(); // const string &factorDelimiter = StaticData::Instance().GetFactorDelimiter(); // loop through the tokens for (size_t xmlTokenPos = 0 ; xmlTokenPos < xmlTokens.size() ; xmlTokenPos++) { // not a xml tag, but regular text (may contain many words) if(!isXmlTag(xmlTokens[xmlTokenPos])) { // add a space at boundary, if necessary if (cleanLine.size()>0 && cleanLine[cleanLine.size() - 1] != ' ' && xmlTokens[xmlTokenPos][0] != ' ') { cleanLine += " "; } cleanLine += xmlTokens[xmlTokenPos]; // add to output wordPos = Tokenize(cleanLine).size(); // count all the words } // process xml tag else { // *** get essential information about tag *** // strip extra boundary spaces and "<" and ">" string tag = Trim(TrimXml(xmlTokens[xmlTokenPos])); VERBOSE(3,"XML TAG IS: " << tag << std::endl); if (tag.size() == 0) { TRACE_ERR("ERROR: empty tag name: " << line << endl); return false; } // check if unary (e.g., "<wall/>") bool isUnary = ( tag[tag.size() - 1] == '/' ); // check if opening tag (e.g. "<a>", not "</a>")g bool isClosed = ( tag[0] == '/' ); bool isOpen = !isClosed; if (isClosed && isUnary) { TRACE_ERR("ERROR: can't have both closed and unary tag <" << tag << ">: " << line << endl); return false; } if (isClosed) tag = tag.substr(1); // remove "/" at the beginning if (isUnary) tag = tag.substr(0,tag.size()-1); // remove "/" at the end // find the tag name and contents string::size_type endOfName = tag.find_first_of(' '); string tagName = tag; string tagContent = ""; if (endOfName != string::npos) { tagName = tag.substr(0,endOfName); tagContent = tag.substr(endOfName+1); } // *** process new tag *** if (isOpen || isUnary) { // put the tag on the tag stack OpenedTag openedTag = make_pair( tagName, make_pair( wordPos, tagContent ) ); tagStack.push_back( openedTag ); VERBOSE(3,"XML TAG " << tagName << " (" << tagContent << ") added to stack, now size " << tagStack.size() << endl); } // *** process completed tag *** if (isClosed || isUnary) { // pop last opened tag from stack; if (tagStack.size() == 0) { TRACE_ERR("ERROR: tag " << tagName << " closed, but not opened" << ":" << line << endl); return false; } OpenedTag openedTag = tagStack.back(); tagStack.pop_back(); // tag names have to match if (openedTag.first != tagName) { TRACE_ERR("ERROR: tag " << openedTag.first << " closed by tag " << tagName << ": " << line << endl ); return false; } // assemble remaining information about tag size_t startPos = openedTag.second.first; string tagContent = openedTag.second.second; size_t endPos = wordPos; // span attribute overwrites position string span = ParseXmlTagAttribute(tagContent,"span"); if (! span.empty()) { vector<string> ij = Tokenize(span, "-"); if (ij.size() != 1 && ij.size() != 2) { TRACE_ERR("ERROR: span attribute must be of the form \"i-j\" or \"i\": " << line << endl); return false; } startPos = atoi(ij[0].c_str()); if (ij.size() == 1) endPos = startPos + 1; else endPos = atoi(ij[1].c_str()) + 1; } VERBOSE(3,"XML TAG " << tagName << " (" << tagContent << ") spanning " << startPos << " to " << (endPos-1) << " complete, commence processing" << endl); if (startPos == endPos) { TRACE_ERR("WARNING: tag " << tagName << " span is empty. Ignoring: " << line << endl); continue; } else if (startPos > endPos) { TRACE_ERR("ERROR: tag " << tagName << " startPos > endPos: " << line << endl); return false; } // may be either a input span label ("label"), or a specified output translation "translation" string label = ParseXmlTagAttribute(tagContent,"label"); string translation = ParseXmlTagAttribute(tagContent,"translation"); // specified label if (translation.length() == 0 && label.length() > 0) { Range range(startPos,endPos-1); // really? XMLParseOutput item(label, range); sourceLabels.push_back(item); } // specified translations -> vector of phrases, separated by "||" if (translation.length() > 0 && StaticData::Instance().GetXmlInputType() != XmlIgnore) { vector<string> altTexts = TokenizeMultiCharSeparator(translation, "||"); vector<string> altLabel = TokenizeMultiCharSeparator(label, "||"); vector<string> altProbs = TokenizeMultiCharSeparator(ParseXmlTagAttribute(tagContent,"prob"), "||"); //TRACE_ERR("number of translations: " << altTexts.size() << endl); for (size_t i=0; i<altTexts.size(); ++i) { // set target phrase TargetPhrase targetPhrase(firstPt); // targetPhrase.CreateFromString(Output, outputFactorOrder,altTexts[i],factorDelimiter, NULL); targetPhrase.CreateFromString(Output, outputFactorOrder,altTexts[i], NULL); // set constituent label string targetLHSstr; if (altLabel.size() > i && altLabel[i].size() > 0) { targetLHSstr = altLabel[i]; } else { const UnknownLHSList &lhsList = StaticData::Instance().GetUnknownLHS(); UnknownLHSList::const_iterator iterLHS = lhsList.begin(); targetLHSstr = iterLHS->first; } Word *targetLHS = new Word(true); targetLHS->CreateFromString(Output, outputFactorOrder, targetLHSstr, true); UTIL_THROW_IF2(targetLHS->GetFactor(0) == NULL, "Null factor left-hand-side"); targetPhrase.SetTargetLHS(targetLHS); // not tested Phrase sourcePhrase = this->GetSubString(Range(startPos,endPos-1)); // get probability float probValue = 1; if (altProbs.size() > i && altProbs[i].size() > 0) { probValue = Scan<float>(altProbs[i]); } // convert from prob to log-prob float scoreValue = FloorScore(TransformScore(probValue)); targetPhrase.SetXMLScore(scoreValue); targetPhrase.EvaluateInIsolation(sourcePhrase); // set span and create XmlOption Range range(startPos+1,endPos); XmlOption *option = new XmlOption(range,targetPhrase); assert(option); xmlOptions.push_back(option); VERBOSE(2,"xml translation = [" << range << "] " << targetLHSstr << " -> " << altTexts[i] << " prob: " << probValue << endl); } altTexts.clear(); altProbs.clear(); } } } } // we are done. check if there are tags that are still open if (tagStack.size() > 0) { TRACE_ERR("ERROR: some opened tags were never closed: " << line << endl); return false; } // return de-xml'ed sentence in line line = cleanLine; return true; }
void mission_start::place_npc_software(mission *miss) { npc* dev = g->find_npc(miss->npc_id); if (dev == NULL) { debugmsg("Couldn't find NPC! %d", miss->npc_id); return; } g->u.i_add( item("usb_drive", 0) ); add_msg(_("%s gave you a USB drive."), dev->name.c_str()); std::string type = "house"; switch (dev->myclass) { case NC_HACKER: miss->item_id = "software_hacking"; break; case NC_DOCTOR: miss->item_id = "software_medical"; type = "s_pharm"; miss->follow_up = MISSION_GET_ZOMBIE_BLOOD_ANAL; break; case NC_SCIENTIST: miss->item_id = "software_math"; break; default: miss->item_id = "software_useless"; } int dist = 0; point place; if (type == "house") { place = random_house_in_closest_city(); } else { place = overmap_buffer.find_closest(dev->global_omt_location(), type, dist, false); } miss->target = place; overmap_buffer.reveal(place, 6, g->get_levz()); tinymap compmap; compmap.load(place.x * 2, place.y * 2, g->get_levz(), false); point comppoint; oter_id oter = overmap_buffer.ter(place.x, place.y, 0); if( is_ot_type("house", oter) || is_ot_type("s_pharm", oter) || oter == "" ) { std::vector<point> valid; for (int x = 0; x < SEEX * 2; x++) { for (int y = 0; y < SEEY * 2; y++) { if (compmap.ter(x, y) == t_floor && compmap.furn(x, y) == f_null) { bool okay = false; int wall = 0; for (int x2 = x - 1; x2 <= x + 1 && !okay; x2++) { for (int y2 = y - 1; y2 <= y + 1 && !okay; y2++) { if (compmap.furn(x2, y2) == f_bed || compmap.furn(x2, y2) == f_dresser) { okay = true; valid.push_back( point(x, y) ); } if ( compmap.has_flag_ter("WALL", x2, y2) ) { wall++; } } } if ( wall == 5 ) { if ( compmap.is_last_ter_wall( true, x, y, SEEX * 2, SEEY * 2, NORTH ) && compmap.is_last_ter_wall( true, x, y, SEEX * 2, SEEY * 2, SOUTH ) && compmap.is_last_ter_wall( true, x, y, SEEX * 2, SEEY * 2, WEST ) && compmap.is_last_ter_wall( true, x, y, SEEX * 2, SEEY * 2, EAST ) ) { valid.push_back( point(x, y) ); } } } } } if (valid.empty()) { comppoint = point( rng(6, SEEX * 2 - 7), rng(6, SEEY * 2 - 7) ); } else { comppoint = valid[rng(0, valid.size() - 1)]; } } compmap.ter_set(comppoint.x, comppoint.y, t_console); computer *tmpcomp = compmap.add_computer(comppoint.x, comppoint.y, string_format(_("%s's Terminal"), dev->name.c_str()), 0); tmpcomp->mission_id = miss->uid; tmpcomp->add_option(_("Download Software"), COMPACT_DOWNLOAD_SOFTWARE, 0); compmap.save(); }