/* Not dirs, not . or .. */ static void GetDirectoryContents(const char *name, std::list<std::string> &files) { DIR *dir = opendir(name); if (!dir) { //if (-1 == mkdir(name, 0770) Gui::Screen::ShowBadError(stringf(128, Lang::COULD_NOT_OPEN_FILENAME, name).c_str()); return; } struct dirent *entry; while ((entry = readdir(dir))) { if (strcmp(entry->d_name, ".")==0) continue; if (strcmp(entry->d_name, "..")==0) continue; files.push_back(entry->d_name); } closedir(dir); files.sort(); }
static std::string glerr_to_string(GLenum err) { switch (err) { case GL_INVALID_ENUM: return "GL_INVALID_ENUM"; case GL_INVALID_VALUE: return "GL_INVALID_VALUE"; case GL_INVALID_OPERATION: return "GL_INVALID_OPERATION"; case GL_OUT_OF_MEMORY: return "GL_OUT_OF_MEMORY"; case GL_STACK_OVERFLOW: //deprecated in GL3 return "GL_STACK_OVERFLOW"; case GL_STACK_UNDERFLOW: //deprecated in GL3 return "GL_STACK_UNDERFLOW"; case GL_INVALID_FRAMEBUFFER_OPERATION_EXT: return "GL_INVALID_FRAMEBUFFER_OPERATION"; default: return stringf("Unknown error 0x0%0{x}", err); } }
void MsgLogWidget::ShowNext() { if (m_msgQueue.empty()) { // current message expired and queue empty m_msgLabel->SetText(""); m_msgAge = 0; onUngrabFocus.emit(); } else { // current message expired and more in queue Pi::BoinkNoise(); Pi::SetTimeAccel(1); Pi::RequestTimeAccel(1); message_t msg("","",NONE); // use MUST_SEE messages first for (std::list<message_t>::iterator i = m_msgQueue.begin(); i != m_msgQueue.end(); ++i) { if ((*i).type == MUST_SEE) { msg = *i; m_msgQueue.erase(i); break; } } if (msg.type == NONE) { msg = m_msgQueue.front(); m_msgQueue.pop_front(); } if (msg.sender == "") { m_msgLabel->SetText("#0f0" + msg.message); } else { m_msgLabel->SetText( std::string("#ca0") + stringf(Lang::MESSAGE_FROM_X, formatarg("sender", msg.sender)) + std::string("\n#0f0") + msg.message); } m_msgAge = SDL_GetTicks(); m_curMsgType = msg.type; onGrabFocus.emit(); } }
int option(char *arg) { if (strncmp(arg, "-lccdir=", 8) == 0) { strcpy(lccdir, &arg[8]); if (lccdir[strlen(lccdir)-1] == '/') lccdir[strlen(lccdir)-1] = '\0'; cpp[0] = stringf("%s/cpp", lccdir); include[0] = stringf("-I%s/include", lccdir); ld[11] = stringf("-L%s", lccdir); com[0] = stringf("%s/rcc", lccdir); ld2[1] = stringf("%s/prelink.sh", lccdir); ld2[11] = stringf("%s/startup.o", lccdir); ld2[18] = ld[11]; } else if (strcmp(arg, "-g") == 0) ; else if (strcmp(arg, "-p") == 0) { ld[5] = SUNDIR "mcrt1.o"; ld[9] = "P," SUNDIR "libp:/usr/ccs/lib/libp:/usr/lib/libp:" SUNDIR ":/usr/ccs/lib:/usr/lib"; } else if (strcmp(arg, "-b") == 0) ; else if (strncmp(arg, "-ld=", 4) == 0) { ld[0] = &arg[4]; ld2[0] = &arg[4]; } else if (strcmp(arg, "-g4") == 0) { extern char *tempdir; extern int getpid(void); ld2[3] = stringf("%s/%d.o", tempdir, getpid()); ld2[14] = ld2[3]; ld2[29] = ld2[3]; ld2[30] = stringf("%s/%d.c", tempdir, getpid()); memcpy(ld, ld2, sizeof ld2); com[2] = "-g4"; } else return 0; return 1; }
MultiProgram::MultiProgram(const MaterialDescriptor &desc, int lights) { lights = Clamp(lights, 1, 4); //build some defines std::stringstream ss; if (desc.textures > 0) ss << "#define TEXTURE0\n"; if (desc.vertexColors) ss << "#define VERTEXCOLOR\n"; if (desc.alphaTest) ss << "#define ALPHA_TEST\n"; if (desc.pointsMode) ss << "#define POINTS\n"; if (desc.colorTint) ss << "#define COLOR_TINT\n"; //using only one light if (desc.lighting && lights > 0) ss << stringf("#define NUM_LIGHTS %0{d}\n", lights); else ss << "#define NUM_LIGHTS 0\n"; if (desc.specularMap) ss << "#define MAP_SPECULAR\n"; if (desc.glowMap) ss << "#define MAP_EMISSIVE\n"; if (desc.usePatterns) ss << "#define MAP_COLOR\n"; if (desc.quality & HAS_HEAT_GRADIENT) ss << "#define HEAT_COLOURING\n"; m_name = "multi"; m_defines = ss.str(); LoadShaders(m_name, m_defines); InitUniforms(); }
inline void LuaEventQueueBase::DoEventCall(lua_State *l, LuaEventBase *e) { if (m_debugTimer) { int top = lua_gettop(l); lua_pushvalue(l, -1); lua_Debug ar; lua_getinfo(l, ">S", &ar); PrepareLuaStack(l, e); Uint32 start = SDL_GetTicks(); pi_lua_protected_call(l, lua_gettop(l) - top, 0); Uint32 end = SDL_GetTicks(); Pi::luaConsole->AddOutput(stringf("DEBUG: %0 %1{u}ms %2:%3{d}", m_name, end-start, ar.source, ar.linedefined)); } else { int top = lua_gettop(l); PrepareLuaStack(l, e); pi_lua_protected_call(l, lua_gettop(l) - top, 0); } }
void NotifyOfCrime(Ship *s, enum Crime crime) { // ignore crimes of NPCs for the time being if (!s->IsType(Object::PLAYER)) return; // find nearest starport to this evil criminal SpaceStation *station = static_cast<SpaceStation*>(Pi::game->GetSpace()->FindNearestTo(s, Object::SPACESTATION)); if (station) { double dist = station->GetPositionRelTo(s).Length(); // too far away for crime to be noticed :) if (dist > 100000.0) return; const int crimeIdx = GetCrimeIdxFromEnum(crime); Pi::cpan->MsgLog()->ImportantMessage(station->GetLabel(), stringf(Lang::X_CANNOT_BE_TOLERATED_HERE, formatarg("crime", crimeNames[crimeIdx]))); float lawlessness = Pi::game->GetSpace()->GetStarSystem()->GetSysPolit().lawlessness.ToFloat(); Sint64 oldCrimes, oldFine; GetCrime(&oldCrimes, &oldFine); Sint64 newFine = std::max(1, 1 + int(crimeBaseFine[crimeIdx] * (1.0-lawlessness))); // don't keep compounding fines (maybe should for murder, etc...) if ( (!(crime & CRIME_MURDER)) && (newFine < oldFine) ) newFine = 0; AddCrime(crime, newFine); } }
void query_filter(query_t *query, query_field_t field, const char *filter) { string_t *string; if (!filter) { query->filters[field] = NULL; return; } if (!id_fields[field]) { query->filters[field] = stringf("%%%s%%", filter); return; } /* The field is an id field. Ensure the filter is a comma-separated list of * decimal numbers. */ string = string_new(); for (; *filter != '\0'; ++filter) { if (*filter == ',' || (*filter >= '0' && *filter <= '9')) { string_push_back(string, *filter); } } query->filters[field] = string_release(string); }
void NotifyOfCrime(Ship *s, enum Crime crime) { // ignore crimes of NPCs for the time being if (s != (Ship*)Pi::player) return; // find nearest starport to this evil criminal SpaceStation *station = static_cast<SpaceStation*>(Space::FindNearestTo(s, Object::SPACESTATION)); if (station) { double dist = station->GetPositionRelTo(s).Length(); // too far away for crime to be noticed :) if (dist > 100000.0) return; const int crimeIdx = GetCrimeIdxFromEnum(crime); Pi::cpan->MsgLog()->ImportantMessage(station->GetLabel(), stringf(512, "%s cannot be tolerated here.", crimeNames[crimeIdx])); float lawlessness = Pi::currentSystem->GetSysPolit().lawlessness.ToFloat(); Sint64 oldCrimes, oldFine; GetCrime(&oldCrimes, &oldFine); Sint64 newFine = std::max(1, 1 + (int)(crimeBaseFine[crimeIdx] * (1.0-lawlessness))); // don't keep compounding fines (maybe should for murder, etc...) if ( (!(crime & CRIME_MURDER)) && (newFine < oldFine) ) newFine = 0; AddCrime(crime, newFine); } }
void LuaChatForm::OnClickSell(int t) { lua_State *l = Lua::manager->GetLuaState(); LUA_DEBUG_START(l); _get_trade_function(l, GetAdvert()->ref, "onClickSell"); lua_pushinteger(l, GetAdvert()->ref); lua_pushstring(l, EnumStrings::GetString("EquipType", t)); pi_lua_protected_call(l, 2, 1); bool allow_sell = lua_toboolean(l, -1) != 0; lua_pop(l, 1); LUA_DEBUG_END(l, 0); if (allow_sell) { if (BuyFrom(Pi::player, static_cast<Equip::Type>(t), true)) { Pi::Message(stringf(Lang::SOLD_1T_OF, formatarg("commodity", Equip::types[t].name))); } m_commodityTradeWidget->UpdateStock(t); } }
static void I(defsymbol)(Symbol p) { if (p->scope == CONSTANTS) switch (optype(ttob(p->type))) { case I: p->x.name = stringf("%D", p->u.c.v.i); break; case U: p->x.name = stringf("%U", p->u.c.v.u); break; case P: p->x.name = stringf("%U", p->u.c.v.p); break; case F: { // JDC: added this to get inline floats floatint_t temp; temp.f = p->u.c.v.d; p->x.name = stringf("%U", temp.ui ); } break;// JDC: added this default: assert(0); } else if (p->scope >= LOCAL && p->sclass == STATIC) p->x.name = stringf("$%d", genlabel(1)); else if (p->scope == LABELS || p->generated) p->x.name = stringf("$%s", p->name); else p->x.name = p->name; }
void JettisonCargo(Equip::Type t) { if (Pi::player->Jettison(t)) { Pi::cpan->MsgLog()->Message("", stringf(Lang::JETTISONED_1T_OF_X, formatarg("commodity", EquipType::types[t].name))); m_infoView->UpdateInfo(); } }
/* scan: parse the contents of fp, expecting the input side (phase) of a rule if ph=='i', or the output side if ph=='o' */ List scan (FILE *fp, int ph) { int c = 0; /* Current char on fp */ int nb = 0, nw = 0; /* Position in rule (bit/word) */ Symbol csym = 0L; /* Current variable being scanned */ T f_msk=(T)0, f_val=(T)0; /* Current constant mask and value */ List pats = 0L; /* All the patterns (words) for this phase */ List vars = 0L; /* All the vars for a given pattern */ while ((c=getc(fp)) != EOF) { if (debugp) fprintf(stdout, "/* bit: %c msk: 0x%x val: 0x%x */\n", c, (unsigned)f_msk, (unsigned)f_val); /* Inputs end with '=', outputs with '+' */ if ((c == '=' && ph == 'i') || (c == '+' && ph == 'o')) break; switch(c) { case ' ': case '\f': case '\n': case '\r': case '\t': case '\v': continue; case '#': /* Comment character */ while ((c=getc(fp)) != EOF && c != '\n'); if (c == EOF && (nb > 0 || (ph == 'i' && nw > 0))) error(stringf("Unexpected end of file reading patterns at " "rule %d, word %c%d, bit %d", nr,ph,nw,nb)); continue; case '-': /* Denotes body of a variable */ if (!csym) /* We must be defining a variable */ error(stringf("'-' appears with no leading symbol " "at rule %d, word %c%d, bit %d", nr, ph, nw, nb)); else { /* Extend the variable's right boundary */ ++csym->r; assert(csym->r == nb); } break; case '0': case '1': /* Constant characters */ if (csym) { /* End any variable definition */ vars = mkvar(csym, vars); csym = 0L; } f_msk |= 1; f_val |= (c-'0'); break; default: c = tolower(c); /* Variables named by a-z, case insensitive */ if (c >= 'a' && c <= 'z') { char *s = stringf("%c", c); if (csym) vars = mkvar(csym, vars); if (!lookup(s, stab) && ph == 'o') error(stringf("Symbol '%c' used with no prior " "definition at rule %d, word o%d", c, nr, nw)); csym = install(s, stab); csym->l = csym->r = nb; } else error(stringf("Illegal character in rule file at rule %d, " "word %c%d, bit %d", nr, ph, nw, nb)); } if (nb == SZ-1) { /* End of a pattern (word): append this info */ pat_t *pat; /* to list of patterns, and reset current */ if (csym) { /* pattern state (masks, vars, bit count) */ vars = mkvar(csym, vars); csym = 0L; } NEW(pat, 1, ARENA0); pat->f_msk = f_msk; f_msk = (T)0; pat->f_val = f_val; f_val = (T)0; pat->nv = l_length(vars); if (debugp) fprintf(stdout, "/* msk: 0x%x, val: 0x%x, nv: 0x%x */\n", (unsigned)pat->f_msk, (unsigned)pat->f_val, pat->nv); l_ltov(pat->v, var_t *, vars, ARENA0); pats = l_append(pat, pats, ARENA0); ++nw; nb = 0; vars = 0L; } else { /* Still more to go: move on to next bit */ ++nb; f_msk <<= 1; f_val <<= 1;
/* checksame: aborts program if s and a1 refer to the same variable but have different bit widths */ void checksame (Symbol s, void *a1, void *a2) { Symbol cs = (Symbol)a1; if (s->name == cs->name && s->r - s->l != cs->r - cs->l) error(stringf("Symbol '%s' has two different sizes in rule %d", cs->name, nr)); }
static void write_opengl_info(std::ostream &out) { out << "OpenGL version " << glGetString(GL_VERSION); out << ", running on " << glGetString(GL_VENDOR); out << " " << glGetString(GL_RENDERER) << "\n"; out << "Available extensions:" << "\n"; { out << "Shading language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << "\n"; GLint numext = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &numext); for (int i = 0; i < numext; ++i) { out << " " << glGetStringi(GL_EXTENSIONS, i) << "\n"; } } out << "\nImplementation Limits:\n"; // first, clear all OpenGL error flags dump_and_clear_opengl_errors(out); #define DUMP_GL_VALUE(name) dump_opengl_value(out, #name, name, 1) #define DUMP_GL_VALUE2(name) dump_opengl_value(out, #name, name, 2) DUMP_GL_VALUE(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS); DUMP_GL_VALUE(GL_MAX_CUBE_MAP_TEXTURE_SIZE); DUMP_GL_VALUE(GL_MAX_DRAW_BUFFERS); DUMP_GL_VALUE(GL_MAX_ELEMENTS_INDICES); DUMP_GL_VALUE(GL_MAX_ELEMENTS_VERTICES); DUMP_GL_VALUE(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS); DUMP_GL_VALUE(GL_MAX_TEXTURE_IMAGE_UNITS); DUMP_GL_VALUE(GL_MAX_TEXTURE_LOD_BIAS); DUMP_GL_VALUE(GL_MAX_TEXTURE_SIZE); DUMP_GL_VALUE(GL_MAX_VERTEX_ATTRIBS); DUMP_GL_VALUE(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS); DUMP_GL_VALUE(GL_MAX_VERTEX_UNIFORM_COMPONENTS); DUMP_GL_VALUE(GL_NUM_COMPRESSED_TEXTURE_FORMATS); DUMP_GL_VALUE(GL_SAMPLE_BUFFERS); DUMP_GL_VALUE(GL_SAMPLES); DUMP_GL_VALUE2(GL_ALIASED_LINE_WIDTH_RANGE); DUMP_GL_VALUE2(GL_MAX_VIEWPORT_DIMS); DUMP_GL_VALUE2(GL_SMOOTH_LINE_WIDTH_RANGE); DUMP_GL_VALUE2(GL_SMOOTH_POINT_SIZE_RANGE); #undef DUMP_GL_VALUE #undef DUMP_GL_VALUE2 // enumerate compressed texture formats { dump_and_clear_opengl_errors(out); out << "\nCompressed texture formats:\n"; GLint nformats; GLint formats[128]; // XXX 128 should be enough, right? glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &nformats); GLenum err = glGetError(); if (err != GL_NO_ERROR) { out << "Get NUM_COMPRESSED_TEXTURE_FORMATS failed\n"; dump_and_clear_opengl_errors(out, err); } else { assert(nformats >= 0 && nformats < int(COUNTOF(formats))); glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, formats); err = glGetError(); if (err != GL_NO_ERROR) { out << "Get COMPRESSED_TEXTURE_FORMATS failed\n"; dump_and_clear_opengl_errors(out, err); } else { for (int i = 0; i < nformats; ++i) { out << stringf(" %0{x#}\n", unsigned(formats[i])); } } } } // one last time dump_and_clear_opengl_errors(out); }
void ObjectViewerView::OnRandomSeed() { m_sbodySeed->SetText(stringf("%0{i}", int(Pi::rng.Int32()))); OnChangeTerrain(); }
void Pi::HandleEvents() { PROFILE_SCOPED() SDL_Event event; // XXX for most keypresses SDL will generate KEYUP/KEYDOWN and TEXTINPUT // events. keybindings run off KEYUP/KEYDOWN. the console is opened/closed // via keybinding. the console TextInput widget uses TEXTINPUT events. thus // after switching the console, the stray TEXTINPUT event causes the // console key (backtick) to appear in the text entry field. we hack around // this by setting this flag if the console was switched. if its set, we // swallow the TEXTINPUT event this hack must remain until we have a // unified input system bool skipTextInput = false; Pi::mouseMotion[0] = Pi::mouseMotion[1] = 0; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { if (Pi::game) Pi::EndGame(); Pi::Quit(); } if (skipTextInput && event.type == SDL_TEXTINPUT) { skipTextInput = false; continue; } if (ui->DispatchSDLEvent(event)) continue; bool consoleActive = Pi::IsConsoleActive(); if (!consoleActive) KeyBindings::DispatchSDLEvent(&event); else KeyBindings::toggleLuaConsole.CheckSDLEventAndDispatch(&event); if (consoleActive != Pi::IsConsoleActive()) { skipTextInput = true; continue; } if (Pi::IsConsoleActive()) continue; Gui::HandleSDLEvent(&event); switch (event.type) { case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_ESCAPE) { if (Pi::game) { // only accessible once game started if (currentView != 0) { if (currentView != Pi::game->GetSettingsView()) { Pi::game->SetTimeAccel(Game::TIMEACCEL_PAUSED); SetView(Pi::game->GetSettingsView()); } else { Pi::game->RequestTimeAccel(Game::TIMEACCEL_1X); SetView(Pi::player->IsDead() ? static_cast<View*>(Pi::game->GetDeathView()) : static_cast<View*>(Pi::game->GetWorldView())); } } } break; } // special keys. LCTRL+turd if ((KeyState(SDLK_LCTRL) || (KeyState(SDLK_RCTRL)))) { switch (event.key.keysym.sym) { case SDLK_q: // Quit if (Pi::game) Pi::EndGame(); Pi::Quit(); break; case SDLK_PRINTSCREEN: // print case SDLK_KP_MULTIPLY: // screen { char buf[256]; const time_t t = time(0); struct tm *_tm = localtime(&t); strftime(buf, sizeof(buf), "screenshot-%Y%m%d-%H%M%S.png", _tm); Graphics::ScreendumpState sd; Pi::renderer->Screendump(sd); write_screenshot(sd, buf); break; } #if WITH_DEVKEYS case SDLK_i: // Toggle Debug info Pi::showDebugInfo = !Pi::showDebugInfo; break; #ifdef PIONEER_PROFILER case SDLK_p: // alert it that we want to profile if (KeyState(SDLK_LSHIFT) || KeyState(SDLK_RSHIFT)) Pi::doProfileOne = true; else { Pi::doProfileSlow = !Pi::doProfileSlow; Output("slow frame profiling %s\n", Pi::doProfileSlow ? "enabled" : "disabled"); } break; #endif case SDLK_F12: { if(Pi::game) { vector3d dir = -Pi::player->GetOrient().VectorZ(); /* add test object */ if (KeyState(SDLK_RSHIFT)) { Missile *missile = new Missile(ShipType::MISSILE_GUIDED, Pi::player); missile->SetOrient(Pi::player->GetOrient()); missile->SetFrame(Pi::player->GetFrame()); missile->SetPosition(Pi::player->GetPosition()+50.0*dir); missile->SetVelocity(Pi::player->GetVelocity()); game->GetSpace()->AddBody(missile); missile->AIKamikaze(Pi::player->GetCombatTarget()); } else if (KeyState(SDLK_LSHIFT)) { SpaceStation *s = static_cast<SpaceStation*>(Pi::player->GetNavTarget()); if (s) { Ship *ship = new Ship(ShipType::POLICE); int port = s->GetFreeDockingPort(ship); if (port != -1) { Output("Putting ship into station\n"); // Make police ship intent on killing the player ship->AIKill(Pi::player); ship->SetFrame(Pi::player->GetFrame()); ship->SetDockedWith(s, port); game->GetSpace()->AddBody(ship); } else { delete ship; Output("No docking ports free dude\n"); } } else { Output("Select a space station...\n"); } } else { Ship *ship = new Ship(ShipType::POLICE); if( KeyState(SDLK_LCTRL) ) ship->AIFlyTo(Pi::player); // a less lethal option else ship->AIKill(Pi::player); // a really lethal option! lua_State *l = Lua::manager->GetLuaState(); pi_lua_import(l, "Equipment"); LuaTable equip(l, -1); LuaObject<Ship>::CallMethod<>(ship, "AddEquip", equip.Sub("laser").Sub("pulsecannon_dual_1mw")); LuaObject<Ship>::CallMethod<>(ship, "AddEquip", equip.Sub("misc").Sub("laser_cooling_booster")); LuaObject<Ship>::CallMethod<>(ship, "AddEquip", equip.Sub("misc").Sub("atmospheric_shielding")); lua_pop(l, 5); ship->SetFrame(Pi::player->GetFrame()); ship->SetPosition(Pi::player->GetPosition()+100.0*dir); ship->SetVelocity(Pi::player->GetVelocity()); ship->UpdateEquipStats(); game->GetSpace()->AddBody(ship); } } break; } #endif /* DEVKEYS */ #if WITH_OBJECTVIEWER case SDLK_F10: Pi::SetView(Pi::game->GetObjectViewerView()); break; #endif case SDLK_F11: // XXX only works on X11 //SDL_WM_ToggleFullScreen(Pi::scrSurface); #if WITH_DEVKEYS renderer->ReloadShaders(); #endif break; case SDLK_F9: // Quicksave { if(Pi::game) { if (Pi::game->IsHyperspace()) Pi::game->log->Add(Lang::CANT_SAVE_IN_HYPERSPACE); else { const std::string name = "_quicksave"; const std::string path = FileSystem::JoinPath(GetSaveDir(), name); try { Game::SaveGame(name, Pi::game); Pi::game->log->Add(Lang::GAME_SAVED_TO + path); } catch (CouldNotOpenFileException) { Pi::game->log->Add(stringf(Lang::COULD_NOT_OPEN_FILENAME, formatarg("path", path))); } catch (CouldNotWriteToFileException) { Pi::game->log->Add(Lang::GAME_SAVE_CANNOT_WRITE); } } } break; } default: break; // This does nothing but it stops the compiler warnings } } Pi::keyState[event.key.keysym.sym] = true; Pi::keyModState = event.key.keysym.mod; Pi::onKeyPress.emit(&event.key.keysym); break; case SDL_KEYUP: Pi::keyState[event.key.keysym.sym] = false; Pi::keyModState = event.key.keysym.mod; Pi::onKeyRelease.emit(&event.key.keysym); break; case SDL_MOUSEBUTTONDOWN: if (event.button.button < COUNTOF(Pi::mouseButton)) { Pi::mouseButton[event.button.button] = 1; Pi::onMouseButtonDown.emit(event.button.button, event.button.x, event.button.y); } break; case SDL_MOUSEBUTTONUP: if (event.button.button < COUNTOF(Pi::mouseButton)) { Pi::mouseButton[event.button.button] = 0; Pi::onMouseButtonUp.emit(event.button.button, event.button.x, event.button.y); } break; case SDL_MOUSEWHEEL: Pi::onMouseWheel.emit(event.wheel.y > 0); // true = up break; case SDL_MOUSEMOTION: Pi::mouseMotion[0] += event.motion.xrel; Pi::mouseMotion[1] += event.motion.yrel; // SDL_GetRelativeMouseState(&Pi::mouseMotion[0], &Pi::mouseMotion[1]); break; case SDL_JOYAXISMOTION: if (!joysticks[event.jaxis.which].joystick) break; if (event.jaxis.value == -32768) joysticks[event.jaxis.which].axes[event.jaxis.axis] = 1.f; else joysticks[event.jaxis.which].axes[event.jaxis.axis] = -event.jaxis.value / 32767.f; break; case SDL_JOYBUTTONUP: case SDL_JOYBUTTONDOWN: if (!joysticks[event.jaxis.which].joystick) break; joysticks[event.jbutton.which].buttons[event.jbutton.button] = event.jbutton.state != 0; break; case SDL_JOYHATMOTION: if (!joysticks[event.jaxis.which].joystick) break; joysticks[event.jhat.which].hats[event.jhat.hat] = event.jhat.value; break; } } }
int MalieExec::ExportStrByCode(void) { CMalie_VMParse vm(this); vector<wstring> chapterName; vector<DWORD> chapterIndex; vector<DWORD> chapterRegion; vector<Malie_Moji> && moji = vm.ParseScenario(chapterName,chapterIndex); if (!chapterName.size()) { vector<DWORD>::iterator it = unique(chapterIndex.begin(),chapterIndex.end()); chapterIndex.erase(it,chapterIndex.end()); } auto exportFunc = [&](pair<DWORD,wstring>(&x),FILE *fp){ fwprintf(fp,L"○%08d○\n%s●%08d●\n%s◇%08d◇\n\n\n", x.first,x.second.c_str(),x.first,x.second.c_str(),x.first); }; fprintf(stderr,"\nStarting dumping text to file...\n"); if (chapterIndex.size()) { chapterRegion = chapterIndex; chapterRegion.erase(chapterRegion.begin()); chapterRegion.push_back(moji.size()); for (size_t i=0;i<chapterIndex.size();++i) { wstring && name = i<chapterName.size()? stringf(L"%02d %ls.txt",i,chapterName[i].c_str()): stringf(L"%02d.txt",i); FILE *fp; _wfopen_s(&fp,name.c_str(),L"wt,ccs=UNICODE"); for_each(moji.begin()+chapterIndex[i],moji.begin()+chapterRegion[i],[&](Malie_Moji x) { wstring kotoba; if (!x.name.empty()) { kotoba = x.name+L"※"; } kotoba += ParseString(x.index); exportFunc(pair<DWORD,wstring>(x.index,kotoba),fp); fflush(fp); }); fclose(fp); } } else { FILE *fp; _wfopen_s(&fp,L"MalieMoji.txt",L"wb"); fwrite("\xff\xfe", 1, 2, fp); //for_each(moji.begin(), moji.end(), [&](Malie_Moji x) //{ // wstring kotoba; // if (!x.name.empty()) // { // kotoba = x.name + L"※"; // } // kotoba += ParseString(x.index); // exportFunc(pair<DWORD, wstring>(x.index, kotoba), fp); //}); auto write_crln = [](FILE* fp) { fwrite(L"\r\n", 2, 2, fp); }; for (auto& x : moji) { wchar_t tag[100]; auto cnt = swprintf_s(tag, L"#%05d %s", x.index, x.name.c_str()); fwrite(tag, 2, cnt, fp); write_crln(fp); auto s = GetString(x.index); MalieString str(s); str.init(); auto v = str.export_str(); for (auto& s : v) { fwrite(s.c_str(), 2, s.length(), fp); write_crln(fp); } } fclose(fp); fp = fopen("str.txt", "wb"); fwrite("\xff\xfe", 1, 2, fp); auto fp2 = fopen("str.idx", "wb"); auto write_tbl = [&](map<int, wstring>& tbl) { for (auto& itr : tbl) { fwrite(&itr.first, 1, 4, fp2); fwrite(itr.second.c_str(), 2, itr.second.length(), fp); write_crln(fp); } }; write_tbl(vm.get_name_data_table()); write_tbl(vm.get_sel_data_table()); fclose(fp); fclose(fp2); } fprintf(stderr,"Done.\n"); return 0; }
void SystemInfoView::OnBodyViewed(SystemBody *b) { std::string desc, data; m_infoBox->DeleteAllChildren(); Gui::Fixed *outer = new Gui::Fixed(600, 200); m_infoBox->PackStart(outer); Gui::VBox *col1 = new Gui::VBox(); Gui::VBox *col2 = new Gui::VBox(); outer->Add(col1, 0, 0); outer->Add(col2, 300, 0); #define _add_label_and_value(label, value) { \ Gui::Label *l = (new Gui::Label(label))->Color(255,255,0); \ col1->PackEnd(l); \ l = (new Gui::Label(value))->Color(255,255,0); \ col2->PackEnd(l); \ } bool multiple = (b->GetSuperType() == SystemBody::SUPERTYPE_STAR && b->GetParent() && b->GetParent()->GetType() == SystemBody::TYPE_GRAVPOINT && b->GetParent()->GetParent()); { Gui::Label *l = new Gui::Label(b->GetName() + ": " + b->GetAstroDescription() + (multiple ? (std::string(" (")+b->GetParent()->GetName() + ")") : "")); l->Color(255,255,0); m_infoBox->PackStart(l); } _add_label_and_value(Lang::MASS, stringf(Lang::N_WHATEVER_MASSES, formatarg("mass", b->GetMassAsFixed().ToDouble()), formatarg("units", std::string(b->GetSuperType() == SystemBody::SUPERTYPE_STAR ? Lang::SOLAR : Lang::EARTH)))); _add_label_and_value(Lang::RADIUS, stringf(Lang::N_WHATEVER_RADII, formatarg("radius", b->GetRadiusAsFixed().ToDouble()), formatarg("units", std::string(b->GetSuperType() == SystemBody::SUPERTYPE_STAR ? Lang::SOLAR : Lang::EARTH)), formatarg("radkm", b->GetRadius() / 1000.0))); if (b->GetSuperType() == SystemBody::SUPERTYPE_STAR) { _add_label_and_value(Lang::EQUATORIAL_RADIUS_TO_POLAR_RADIUS_RATIO, stringf("%0{f.3}", b->GetAspectRatio())); } if (b->GetType() != SystemBody::TYPE_STARPORT_ORBITAL) { _add_label_and_value(Lang::SURFACE_TEMPERATURE, stringf(Lang::N_CELSIUS, formatarg("temperature", b->GetAverageTemp()-273))); _add_label_and_value(Lang::SURFACE_GRAVITY, stringf("%0{f.3} m/s^2", b->CalcSurfaceGravity())); } if (b->GetParent()) { float days = float(b->GetOrbit().Period()) / float(60*60*24); if (days > 1000) { data = stringf(Lang::N_YEARS, formatarg("years", days/365)); } else { data = stringf(Lang::N_DAYS, formatarg("days", b->GetOrbit().Period() / (60*60*24))); } if (multiple) { float pdays = float(b->GetParent()->GetOrbit().Period()) /float(60*60*24); data += " (" + (pdays > 1000 ? stringf(Lang::N_YEARS, formatarg("years", pdays/365)) : stringf(Lang::N_DAYS, formatarg("days", b->GetParent()->GetOrbit().Period() / (60*60*24)))) + ")"; } _add_label_and_value(Lang::ORBITAL_PERIOD, data); _add_label_and_value(Lang::PERIAPSIS_DISTANCE, format_distance(b->GetOrbMin()*AU, 3) + (multiple ? (std::string(" (") + format_distance(b->GetParent()->GetOrbMin()*AU, 3)+ ")") : "")); _add_label_and_value(Lang::APOAPSIS_DISTANCE, format_distance(b->GetOrbMax()*AU, 3) + (multiple ? (std::string(" (") + format_distance(b->GetParent()->GetOrbMax()*AU, 3)+ ")") : "")); _add_label_and_value(Lang::ECCENTRICITY, stringf("%0{f.2}", b->GetOrbit().GetEccentricity()) + (multiple ? (std::string(" (") + stringf("%0{f.2}", b->GetParent()->GetOrbit().GetEccentricity()) + ")") : "")); if (b->GetType() != SystemBody::TYPE_STARPORT_ORBITAL) { _add_label_and_value(Lang::AXIAL_TILT, stringf(Lang::N_DEGREES, formatarg("angle", b->GetAxialTilt() * (180.0/M_PI)))); if (b->IsRotating()) { _add_label_and_value( std::string(Lang::DAY_LENGTH)+std::string(Lang::ROTATIONAL_PERIOD), stringf(Lang::N_EARTH_DAYS, formatarg("days", b->GetRotationPeriodInDays()))); } } int numSurfaceStarports = 0; std::string nameList; for (const SystemBody* kid : b->GetChildren()) { if (kid->GetType() == SystemBody::TYPE_STARPORT_SURFACE) { nameList += (numSurfaceStarports ? ", " : "") + kid->GetName(); numSurfaceStarports++; } } if (numSurfaceStarports) { _add_label_and_value(Lang::STARPORTS, nameList); } } m_infoBox->ShowAll(); m_infoBox->ResizeRequest(); }
void SystemInfoView::SystemChanged(const SystemPath &path) { DeleteAllChildren(); m_tabs = 0; m_bodyIcons.clear(); if (!path.HasValidSystem()) return; m_system = StarSystemCache::GetCached(path); m_sbodyInfoTab = new Gui::Fixed(float(Gui::Screen::GetWidth()), float(Gui::Screen::GetHeight()-100)); if (m_system->GetUnexplored()) { Add(m_sbodyInfoTab, 0, 0); std::string _info = Lang::UNEXPLORED_SYSTEM_STAR_INFO_ONLY; Gui::Label *l = (new Gui::Label(_info))->Color(255,255,0); m_sbodyInfoTab->Add(l, 35, 300); m_selectedBodyPath = SystemPath(); ShowAll(); return; } m_econInfoTab = new Gui::Fixed(float(Gui::Screen::GetWidth()), float(Gui::Screen::GetHeight()-100)); Gui::Fixed *demographicsTab = new Gui::Fixed(); m_tabs = new Gui::Tabbed(); m_tabs->AddPage(new Gui::Label(Lang::PLANETARY_INFO), m_sbodyInfoTab); m_tabs->AddPage(new Gui::Label(Lang::ECONOMIC_INFO), m_econInfoTab); m_tabs->AddPage(new Gui::Label(Lang::DEMOGRAPHICS), demographicsTab); Add(m_tabs, 0, 0); m_sbodyInfoTab->onMouseButtonEvent.connect(sigc::mem_fun(this, &SystemInfoView::OnClickBackground)); int majorBodies, starports, onSurface; { float pos[2] = { 0, 0 }; float psize = -1; majorBodies = starports = onSurface = 0; PutBodies(m_system->GetRootBody().Get(), m_econInfoTab, 1, pos, majorBodies, starports, onSurface, psize); majorBodies = starports = onSurface = 0; pos[0] = pos[1] = 0; psize = -1; PutBodies(m_system->GetRootBody().Get(), m_sbodyInfoTab, 1, pos, majorBodies, starports, onSurface, psize); majorBodies = starports = onSurface = 0; pos[0] = pos[1] = 0; psize = -1; PutBodies(m_system->GetRootBody().Get(), demographicsTab, 1, pos, majorBodies, starports, onSurface, psize); } std::string _info = stringf( Lang::STABLE_SYSTEM_WITH_N_MAJOR_BODIES_STARPORTS, formatarg("bodycount", majorBodies), formatarg("body(s)", std::string(majorBodies == 1 ? Lang::BODY : Lang::BODIES)), formatarg("portcount", starports), formatarg("starport(s)", std::string(starports == 1 ? Lang::STARPORT : Lang::COUNT_STARPORTS))); if (starports > 0) _info += stringf(Lang::COUNT_ON_SURFACE, formatarg("surfacecount", onSurface)); _info += ".\n\n"; _info += m_system->GetLongDescription(); { // astronomical body info tab m_infoBox = new Gui::VBox(); Gui::HBox *scrollBox = new Gui::HBox(); scrollBox->SetSpacing(5); m_sbodyInfoTab->Add(scrollBox, 35, 250); Gui::VScrollBar *scroll = new Gui::VScrollBar(); Gui::VScrollPortal *portal = new Gui::VScrollPortal(730); scroll->SetAdjustment(&portal->vscrollAdjust); Gui::Label *l = (new Gui::Label(_info))->Color(255,255,0); m_infoBox->PackStart(l); portal->Add(m_infoBox); scrollBox->PackStart(scroll); scrollBox->PackStart(portal); } { // economy tab Gui::HBox *scrollBox2 = new Gui::HBox(); scrollBox2->SetSpacing(5); m_econInfoTab->Add(scrollBox2, 35, 300); Gui::VScrollBar *scroll2 = new Gui::VScrollBar(); Gui::VScrollPortal *portal2 = new Gui::VScrollPortal(730); scroll2->SetAdjustment(&portal2->vscrollAdjust); scrollBox2->PackStart(scroll2); scrollBox2->PackStart(portal2); m_econInfo = new Gui::Label(""); m_econInfoTab->Add(m_econInfo, 35, 250); Gui::Fixed *f = new Gui::Fixed(); m_econMajImport = new Gui::Label(""); m_econMinImport = new Gui::Label(""); m_econMajExport = new Gui::Label(""); m_econMinExport = new Gui::Label(""); m_econIllegal = new Gui::Label(""); m_econMajImport->Color(255,255,0); m_econMinImport->Color(255,255,0); m_econMajExport->Color(255,255,0); m_econMinExport->Color(255,255,0); m_econIllegal->Color(255,255,0); f->Add(m_econMajImport, 0, 0); f->Add(m_econMinImport, 150, 0); f->Add(m_econMajExport, 300, 0); f->Add(m_econMinExport, 450, 0); f->Add(m_econIllegal, 600, 0); portal2->Add(f); UpdateEconomyTab(); } { Gui::Fixed *col1 = new Gui::Fixed(); demographicsTab->Add(col1, 200, 300); Gui::Fixed *col2 = new Gui::Fixed(); demographicsTab->Add(col2, 400, 300); const float YSEP = Gui::Screen::GetFontHeight() * 1.2f; col1->Add((new Gui::Label(Lang::SYSTEM_TYPE))->Color(255,255,0), 0, 0); col2->Add(new Gui::Label(m_system->GetShortDescription()), 0, 0); col1->Add((new Gui::Label(Lang::GOVERNMENT_TYPE))->Color(255,255,0), 0, 2*YSEP); col2->Add(new Gui::Label(m_system->GetSysPolit().GetGovernmentDesc()), 0, 2*YSEP); col1->Add((new Gui::Label(Lang::ECONOMY_TYPE))->Color(255,255,0), 0, 3*YSEP); col2->Add(new Gui::Label(m_system->GetSysPolit().GetEconomicDesc()), 0, 3*YSEP); col1->Add((new Gui::Label(Lang::ALLEGIANCE))->Color(255,255,0), 0, 4*YSEP); col2->Add(new Gui::Label(m_system->GetFaction()->name.c_str()), 0, 4*YSEP); col1->Add((new Gui::Label(Lang::POPULATION))->Color(255,255,0), 0, 5*YSEP); std::string popmsg; fixed pop = m_system->GetTotalPop(); if (pop >= fixed(1,1)) { popmsg = stringf(Lang::OVER_N_BILLION, formatarg("population", pop.ToInt32())); } else if (pop >= fixed(1,1000)) { popmsg = stringf(Lang::OVER_N_MILLION, formatarg("population", (pop*1000).ToInt32())); } else if (pop != fixed(0)) { popmsg = Lang::A_FEW_THOUSAND; } else { popmsg = Lang::NO_REGISTERED_INHABITANTS; } col2->Add(new Gui::Label(popmsg), 0, 5*YSEP); col1->Add((new Gui::Label(Lang::SECTOR_COORDINATES))->Color(255,255,0), 0, 6*YSEP); col2->Add(new Gui::Label(stringf("%0{d}, %1{d}, %2{d}", path.sectorX, path.sectorY, path.sectorZ)), 0, 6*YSEP); col1->Add((new Gui::Label(Lang::SYSTEM_NUMBER))->Color(255,255,0), 0, 7*YSEP); col2->Add(new Gui::Label(stringf("%0", path.systemIndex)), 0, 7*YSEP); } UpdateIconSelections(); ShowAll(); }
void SystemInfoView::OnBodyViewed(SBody *b) { std::string desc, data; m_infoBox->DeleteAllChildren(); Gui::Fixed *outer = new Gui::Fixed(600, 200); m_infoBox->PackStart(outer); Gui::VBox *col1 = new Gui::VBox(); Gui::VBox *col2 = new Gui::VBox(); outer->Add(col1, 0, 0); outer->Add(col2, 300, 0); #define _add_label_and_value(label, value) { \ Gui::Label *l = (new Gui::Label(label))->Color(1.0f,1.0f,0.0f); \ col1->PackEnd(l); \ l = (new Gui::Label(value))->Color(1.0f,1.0f,0.0f); \ col2->PackEnd(l); \ } { Gui::Label *l = new Gui::Label(b->name + ": " + b->GetAstroDescription()); l->Color(1,1,0); m_infoBox->PackStart(l); } _add_label_and_value(Lang::MASS, stringf(Lang::N_WHATEVER_MASSES, formatarg("mass", b->mass.ToDouble()), formatarg("units", std::string(b->GetSuperType() == SBody::SUPERTYPE_STAR ? Lang::SOLAR : Lang::EARTH)))); if (b->type != SBody::TYPE_STARPORT_ORBITAL) { _add_label_and_value(Lang::SURFACE_TEMPERATURE, stringf(Lang::N_CELSIUS, formatarg("temperature", b->averageTemp-273))); _add_label_and_value(Lang::SURFACE_GRAVITY, stringf("%0{f.3} m/s^2", b->CalcSurfaceGravity())); } if (b->parent) { float days = float(b->orbit.period) / float(60*60*24); if (days > 1000) { data = stringf(Lang::N_YEARS, formatarg("years", days/365)); } else { data = stringf(Lang::N_DAYS, formatarg("days", b->orbit.period / (60*60*24))); } _add_label_and_value(Lang::ORBITAL_PERIOD, data); _add_label_and_value(Lang::PERIAPSIS_DISTANCE, stringf("%0{f.3} AU", b->orbMin.ToDouble())); _add_label_and_value(Lang::APOAPSIS_DISTANCE, stringf("%0{f.3} AU", b->orbMax.ToDouble())); _add_label_and_value(Lang::ECCENTRICITY, stringf("%0{f.2}", b->orbit.eccentricity)); if (b->type != SBody::TYPE_STARPORT_ORBITAL) { _add_label_and_value(Lang::AXIAL_TILT, stringf(Lang::N_DEGREES, formatarg("angle", b->axialTilt.ToDouble() * (180.0/M_PI)))); if (b->rotationPeriod != 0) { _add_label_and_value( std::string(Lang::DAY_LENGTH)+std::string(Lang::ROTATIONAL_PERIOD), stringf(Lang::N_EARTH_DAYS, formatarg("days", b->rotationPeriod.ToDouble()))); } } int numSurfaceStarports = 0; std::string nameList; for (std::vector<SBody*>::iterator i = b->children.begin(); i != b->children.end(); ++i) { if ((*i)->type == SBody::TYPE_STARPORT_SURFACE) { nameList += (numSurfaceStarports ? ", " : "") + (*i)->name; numSurfaceStarports++; } } if (numSurfaceStarports) { _add_label_and_value(Lang::STARPORTS, nameList); } } m_infoBox->ShowAll(); m_infoBox->ResizeRequest(); }
void ObjectViewerView::OnPrevSeed() { m_sbodySeed->SetText(stringf("%0{i}", atoi(m_sbodySeed->GetText().c_str()) - 1)); OnChangeTerrain(); }
virtual void UpdateInfo() { char buf[512]; std::string col1, col2; const ShipType &stype = Pi::player->GetShipType(); col1 = std::string(Lang::SHIP_INFORMATION_HEADER)+std::string(stype.name); col1 += "\n\n"; col1 += std::string(Lang::HYPERDRIVE); col1 += ":\n\n"; col1 += std::string(Lang::CAPACITY); col1 += ":\n"; col1 += std::string(Lang::FREE); col1 += ":\n"; col1 += std::string(Lang::USED); col1 += ":\n"; col1 += std::string(Lang::TOTAL_WEIGHT); col1 += ":\n\n"; col1 += std::string(Lang::FRONT_WEAPON); col1 += ":\n"; col1 += std::string(Lang::REAR_WEAPON); col1 += ":\n\n"; col1 += std::string(Lang::HYPERSPACE_RANGE); col1 += ":\n\n"; col2 = "\n\n"; Equip::Type e = Pi::player->m_equipment.Get(Equip::SLOT_ENGINE); col2 += std::string(EquipType::types[e].name); const shipstats_t *stats; stats = Pi::player->CalcStats(); snprintf(buf, sizeof(buf), "\n\n%dt\n" "%dt\n" "%dt\n" "%dt", stats->max_capacity, stats->free_capacity, stats->used_capacity, stats->total_mass); col2 += std::string(buf); int numLasers = Pi::player->m_equipment.GetSlotSize(Equip::SLOT_LASER); if (numLasers >= 1) { e = Pi::player->m_equipment.Get(Equip::SLOT_LASER, 0); col2 += std::string("\n\n")+EquipType::types[e].name; } else { col2 += "\n\n"; col2 += std::string(Lang::NO_MOUNTING); } if (numLasers >= 2) { e = Pi::player->m_equipment.Get(Equip::SLOT_LASER, 1); col2 += std::string("\n")+EquipType::types[e].name; } else { col2 += "\n"; col2 += std::string(Lang::NO_MOUNTING); } col2 += "\n\n"; col2 += stringf(Lang::N_LIGHT_YEARS_N_MAX, formatarg("distance", stats->hyperspace_range), formatarg("maxdistance", stats->hyperspace_range_max)); for (int i=Equip::FIRST_SHIPEQUIP; i<=Equip::LAST_SHIPEQUIP; i++) { Equip::Type t = Equip::Type(i) ; Equip::Slot s = EquipType::types[t].slot; if ((s == Equip::SLOT_MISSILE) || (s == Equip::SLOT_ENGINE) || (s == Equip::SLOT_LASER)) continue; int num = Pi::player->m_equipment.Count(s, t); if (num == 1) { col1 += stringf("%0\n", EquipType::types[t].name); } else if (num > 1) { col1 += stringf("%0{d} %1s\n", num, EquipType::types[t].name); } } info1->SetText(col1); info2->SetText(col2); this->ResizeRequest(); }
static void fst_plugin_connect_next () { FSTNode *node; FSTSession *sess; List *l; int count = 0, nsessions, nconnecting = 0; nsessions = config_get_int (FST_PLUGIN->conf, "main/additional_sessions=0"); if (nsessions > FST_MAX_ADDITIONAL_SESSIONS) nsessions = FST_MAX_ADDITIONAL_SESSIONS; /* determine number of currently connecting sessions */ nconnecting = (FST_PLUGIN->session && FST_PLUGIN->session->state != SessEstablished) ? 1 : 0; for (l = FST_PLUGIN->sessions; l; l = l->next) { assert (l->data); if (((FSTSession*)l->data)->state != SessEstablished) nconnecting++; } /* connect to head node in node cache */ while ((!FST_PLUGIN->session || list_length (FST_PLUGIN->sessions) <= nsessions) && nconnecting <= FST_SESSION_MAX_CONCURRENT_ATTEMPTS) { if (!(node = fst_nodecache_get_front (FST_PLUGIN->nodecache))) { /* node cache empty */ FST_ERR ("All attempts at contacting peers have failed. Trying default nodes file."); if (fst_nodecache_load (FST_PLUGIN->nodecache, stringf ("%s/FastTrack/nodes", platform_data_dir())) <= 0 || !(node = fst_nodecache_get_front (FST_PLUGIN->nodecache))) { FST_ERR ("Failed to load default nodes file. Perhaps your installation is corrupt?"); return; } } /* don't connect anywhere we're already connected to */ if (node->session) { /* move node to back of cache so next loop * uses a different one */ fst_nodecache_move (FST_PLUGIN->nodecache, node, NodeInsertBack); fst_node_release (node); /* we've probably run out of nodes at this point, so * wait a while until we get some more (continuing * tends to produce an infinite loop) */ if (count++ >= list_length (FST_PLUGIN->sessions)) return; continue; } /* don't connect to anywhere too close to an existing node */ if (dataset_lookup (FST_PLUGIN->peers, &node, sizeof(node))) { #if 0 FST_DBG_2 ("not connecting to close node %s:%d", node->host, node->port); #endif /* move node to back of cache so next loop * uses a different one */ fst_nodecache_move (FST_PLUGIN->nodecache, node, NodeInsertBack); fst_node_release (node); /* we've probably run out of nodes at this point, so * wait a while until we get some more (continuing * tends to produce an infinite loop) */ if (count++ >= list_length (FST_PLUGIN->sessions)) return; continue; } /* don't connect to invalid ips */ if (!fst_utils_ip_routable (net_ip (node->host))) { FST_DBG_2 ("not connecting to unroutable node %s:%d", node->host, node->port); /* remove this node from cache */ fst_nodecache_remove (FST_PLUGIN->nodecache, node); fst_node_release (node); continue; } /* don't connect to banned ips */ if (config_get_int (FST_PLUGIN->conf, "main/banlist_filter=0") && fst_ipset_contains (FST_PLUGIN->banlist, net_ip (node->host))) { FST_DBG_2 ("not connecting to banned supernode %s:%d", node->host, node->port); /* remove this node from cache */ fst_nodecache_remove (FST_PLUGIN->nodecache, node); fst_node_release (node); continue; } /* create session and connect */ sess = fst_session_create (fst_plugin_session_callback); if (!fst_session_connect (sess, node)) { /* free session */ fst_session_free (sess); sess = NULL; /* TODO: check if name resolution in fst_session_connect() failed */ /* network down, wait a while before retrying */ FST_WARN_1 ("Internet connection seems down, sleeping...", FST_SESSION_NETFAIL_INTERVAL / SECONDS); /* move node to back of cache so next loop uses a different one; this * won't help if the network really is down, but might under other * circumstances */ fst_nodecache_move (FST_PLUGIN->nodecache, node, NodeInsertBack); fst_node_release (node); /* just wait until fst_plugin_try_connect() is next called */ return; } /* move node to back of cache so next loop uses a different one */ fst_nodecache_move (FST_PLUGIN->nodecache, node, NodeInsertBack); fst_node_release (node); /* We now have a new session object. Use it as primary session if we * don't already have one. Otherwise use it as an additional one. */ if (!FST_PLUGIN->session) { FST_PLUGIN->session = sess; } else { FST_PLUGIN->sessions = list_prepend (FST_PLUGIN->sessions, sess); } nconnecting++; } /* don't ping if we're currently connected */ if (FST_PLUGIN->stats->sessions > 0) return; /* We started a connection attempt with the head node from nodecache. * Try to quickly find some online nodes with udp in parallel now. */ if (FST_PLUGIN->discover && FST_PLUGIN->discover->pinged_nodes == 0) { List *item = FST_PLUGIN->nodecache->list; int i = 0; while (i < FST_UDP_DISCOVER_MAX_PINGS && item && item->data) { node = (FSTNode*)item->data; if (!fst_udp_discover_ping_node (FST_PLUGIN->discover, node)) { /* This may fail due to the network being down. While * we could handle this in a special way doing nothing * works fine if being somewhat inefficient. */ } item = item->next; i++; } FST_DBG_1 ("discovery cycle started with %d UDP pings", i); } }
virtual void UpdateInfo() { const float YSEP = Gui::Screen::GetFontHeight() * 1.5f; DeleteAllChildren(); Gui::Label *l = new Gui::Label(Lang::MISSIONS); Add(l, 20, 20); l = new Gui::Label(Lang::TYPE); Add(l, 20, 20+YSEP*2); l = new Gui::Label(Lang::CLIENT); Add(l, 100, 20+YSEP*2); l = new Gui::Label(Lang::LOCATION); Add(l, 260, 20+YSEP*2); l = new Gui::Label(Lang::DUE); Add(l, 420, 20+YSEP*2); l = new Gui::Label(Lang::REWARD); Add(l, 580, 20+YSEP*2); l = new Gui::Label(Lang::STATUS); Add(l, 680, 20+YSEP*2); ShowChildren(); Gui::VScrollBar *scroll = new Gui::VScrollBar(); Gui::VScrollPortal *portal = new Gui::VScrollPortal(760); scroll->SetAdjustment(&portal->vscrollAdjust); const std::list<const Mission*> &missions = Pi::player->missions.GetAll(); Gui::Fixed *innerbox = new Gui::Fixed(760, YSEP*3 * missions.size()); float ypos = 0; for (std::list<const Mission*>::const_iterator i = missions.begin(); i != missions.end(); ++i) { SystemPath path = (*i)->location; StarSystem *s = StarSystem::GetCached(path); SBody *sbody = s->GetBodyByPath(&path); l = new Gui::Label((*i)->type); innerbox->Add(l, 0, ypos); l = new Gui::Label((*i)->client); innerbox->Add(l, 80, ypos); l = new Gui::Label(stringf("%0,\n%1 [%2{d},%3{d},%4{d}]", sbody->name.c_str(), s->GetName().c_str(), path.sectorX, path.sectorY, path.sectorZ)); innerbox->Add(l, 240, ypos); l = new Gui::Label(format_date((*i)->due)); innerbox->Add(l, 400, ypos); l = new Gui::Label(format_money((*i)->reward)); innerbox->Add(l, 560, ypos); switch ((*i)->status) { case Mission::FAILED: l = new Gui::Label(std::string("#f00")+std::string(Lang::FAILED)); break; case Mission::COMPLETED: l = new Gui::Label(std::string("#ff0")+std::string(Lang::COMPLETED)); break; default: case Mission::ACTIVE: l = new Gui::Label(std::string("#0f0")+std::string(Lang::ACTIVE)); break; } innerbox->Add(l, 660, ypos); ypos += YSEP*3; } Add(portal, 20, 20 + YSEP*3); Add(scroll, 780, 20 + YSEP*3); scroll->ShowAll(); portal->Add(innerbox); portal->ShowAll(); }
StationShipViewForm::StationShipViewForm(FormController *controller, int marketIndex) : BlankForm(controller), m_marketIndex(marketIndex) { m_station = Pi::player->GetDockedWith(); m_flavour = m_station->GetShipsOnSale()[marketIndex]; const ShipType &type = ShipType::types[m_flavour.type]; SetTitle(stringf(Lang::SOMEWHERE_SHIP_MARKET, formatarg("station", m_station->GetLabel()))); Add(new ShipSpinnerWidget(m_flavour, 400, 400), 0, 0); Gui::VBox *layoutBox = new Gui::VBox(); layoutBox->SetSpacing(10.0f); Add(layoutBox, 420, 0); Gui::HBox *statsBox = new Gui::HBox(); statsBox->SetSpacing(20.0f); layoutBox->PackEnd(statsBox); Gui::VBox *labelBox = new Gui::VBox(); labelBox->PackEnd(new Gui::Label(Lang::SHIP_TYPE)); labelBox->PackEnd(new Gui::Label(Lang::PRICE)); labelBox->PackEnd(new Gui::Label(Lang::PART_EX)); labelBox->PackEnd(new Gui::Label(Lang::REGISTRATION_ID)); labelBox->PackEnd(new Gui::Label(" ")); labelBox->PackEnd(new Gui::Label(Lang::WEIGHT_EMPTY)); labelBox->PackEnd(new Gui::Label(Lang::WEIGHT_FULLY_LADEN)); labelBox->PackEnd(new Gui::Label(Lang::CAPACITY)); labelBox->PackEnd(new Gui::Label(" ")); labelBox->PackEnd(new Gui::Label(Lang::FORWARD_ACCEL_EMPTY)); labelBox->PackEnd(new Gui::Label(Lang::FORWARD_ACCEL_LADEN)); labelBox->PackEnd(new Gui::Label(Lang::REVERSE_ACCEL_EMPTY)); labelBox->PackEnd(new Gui::Label(Lang::REVERSE_ACCEL_LADEN)); labelBox->PackEnd(new Gui::Label(" ")); labelBox->PackEnd(new Gui::Label(Lang::HYPERDRIVE_FITTED)); statsBox->PackEnd(labelBox); float forward_accel_empty = type.linThrust[ShipType::THRUSTER_FORWARD] / (-9.81f*1000.0f*(type.hullMass)); float forward_accel_laden = type.linThrust[ShipType::THRUSTER_FORWARD] / (-9.81f*1000.0f*(type.hullMass+type.capacity)); float reverse_accel_empty = -type.linThrust[ShipType::THRUSTER_REVERSE] / (-9.81f*1000.0f*(type.hullMass)); float reverse_accel_laden = -type.linThrust[ShipType::THRUSTER_REVERSE] / (-9.81f*1000.0f*(type.hullMass+type.capacity)); Gui::VBox *dataBox = new Gui::VBox(); dataBox->PackEnd(new Gui::Label(type.name)); dataBox->PackEnd(new Gui::Label(format_money(m_flavour.price))); dataBox->PackEnd(new Gui::Label(format_money(m_flavour.price - Pi::player->GetFlavour()->price))); dataBox->PackEnd(new Gui::Label(m_flavour.regid)); dataBox->PackEnd(new Gui::Label(" ")); dataBox->PackEnd(new Gui::Label(stringf(Lang::NUMBER_TONNES, formatarg("mass", type.hullMass)))); dataBox->PackEnd(new Gui::Label(stringf(Lang::NUMBER_TONNES, formatarg("mass", type.hullMass + type.capacity)))); dataBox->PackEnd(new Gui::Label(stringf( Lang::NUMBER_TONNES, formatarg("mass", type.capacity)))); dataBox->PackEnd(new Gui::Label(" ")); dataBox->PackEnd(new Gui::Label(stringf(Lang::NUMBER_G, formatarg("acceleration", forward_accel_empty)))); dataBox->PackEnd(new Gui::Label(stringf(Lang::NUMBER_G, formatarg("acceleration", forward_accel_laden)))); dataBox->PackEnd(new Gui::Label(stringf(Lang::NUMBER_G, formatarg("acceleration", reverse_accel_empty)))); dataBox->PackEnd(new Gui::Label(stringf(Lang::NUMBER_G, formatarg("acceleration", reverse_accel_laden)))); dataBox->PackEnd(new Gui::Label(" ")); dataBox->PackEnd(new Gui::Label(EquipType::types[type.hyperdrive].name)); statsBox->PackEnd(dataBox); Gui::HBox *row = new Gui::HBox(); row->SetSpacing(10.0f); int row_size = 5, pos = 0; for (int drivetype = Equip::DRIVE_CLASS1; drivetype <= Equip::DRIVE_CLASS9; drivetype++) { if (type.capacity < EquipType::types[drivetype].mass) break; int hyperclass = EquipType::types[drivetype].pval; // for the sake of hyperspace range, we count ships mass as 60% of original. float range = Pi::CalcHyperspaceRange(hyperclass, type.hullMass + type.capacity); Gui::VBox *cell = new Gui::VBox(); row->PackEnd(cell); cell->PackEnd(new Gui::Label(stringf(Lang::CLASS_NUMBER, formatarg("class", hyperclass)))); if (type.capacity < EquipType::types[drivetype].mass) cell->PackEnd(new Gui::Label("---")); else cell->PackEnd(new Gui::Label(stringf(Lang::NUMBER_LY, formatarg("distance", range)))); if (++pos == row_size) { layoutBox->PackEnd(row); row = new Gui::HBox(); row->SetSpacing(15.0f); pos = 0; } } if (pos > 0) layoutBox->PackEnd(row); Gui::HBox *buttonBox = new Gui::HBox(); buttonBox->SetSpacing(5.0f); Gui::SolidButton *b = new Gui::SolidButton(); b->onClick.connect(sigc::mem_fun(this, &StationShipViewForm::BuyShip)); buttonBox->PackEnd(b); buttonBox->PackEnd(new Gui::Label(Lang::BUY_THIS_SHIP)); Add(buttonBox, 650, 30); }
GameMenuView::GameMenuView(): View() { Gui::Tabbed *tabs = new Gui::Tabbed(); Add(tabs, 0, 0); Gui::Fixed *mainTab = new Gui::Fixed(800, 600); tabs->AddPage(new Gui::Label(Lang::SIGHTS_SOUNDS_SAVES), mainTab); mainTab->Add((new Gui::Label(Lang::PIONEER))->Shadow(true), 350, 10); SetTransparency(false); Gui::Label *l = new Gui::Label(Lang::PIONEER); l->Color(1,.7f,0); m_rightRegion2->Add(l, 10, 0); { Gui::Box *hbox = new Gui::HBox(); hbox->SetSpacing(5.0f); mainTab->Add(hbox, 20, 30); m_saveButton = new Gui::LabelButton(new Gui::Label(Lang::SAVE_THE_GAME)); m_saveButton->SetShortcut(SDLK_s, KMOD_NONE); m_saveButton->onClick.connect(sigc::mem_fun(this, &GameMenuView::OpenSaveDialog)); hbox->PackEnd(m_saveButton); m_loadButton = new Gui::LabelButton(new Gui::Label(Lang::LOAD_A_GAME)); m_loadButton->onClick.connect(sigc::mem_fun(this, &GameMenuView::OpenLoadDialog)); m_loadButton->SetShortcut(SDLK_l, KMOD_NONE); hbox->PackEnd(m_loadButton); m_exitButton = new Gui::LabelButton(new Gui::Label(Lang::EXIT_THIS_GAME)); m_exitButton->onClick.connect(sigc::mem_fun(this, &GameMenuView::HideAll)); m_exitButton->onClick.connect(sigc::ptr_fun(&Pi::EndGame)); hbox->PackEnd(m_exitButton); m_menuButton = new Gui::LabelButton(new Gui::Label(Lang::RETURN_TO_MENU)); m_menuButton->onClick.connect(sigc::bind(sigc::ptr_fun(&Pi::SetView), static_cast<View*>(0))); mainTab->Add(m_menuButton, 20, 30); } Gui::Box *vbox = new Gui::VBox(); vbox->SetSizeRequest(300, 440); vbox->SetSpacing(5.0); mainTab->Add(vbox, 20, 60); { vbox->PackEnd((new Gui::Label(Lang::WINDOW_OR_FULLSCREEN))->Color(1.0f,1.0f,0.0f)); m_toggleFullscreen = new Gui::ToggleButton(); m_toggleFullscreen->onChange.connect(sigc::mem_fun(this, &GameMenuView::OnToggleFullscreen)); Gui::HBox *hbox = new Gui::HBox(); hbox->SetSpacing(5.0f); hbox->PackEnd(m_toggleFullscreen); hbox->PackEnd(new Gui::Label(Lang::FULL_SCREEN)); vbox->PackEnd(hbox); vbox->PackEnd((new Gui::Label(Lang::OTHER_GRAPHICS_SETTINGS))->Color(1.0f,1.0f,0.0f)); m_toggleShaders = new Gui::ToggleButton(); m_toggleShaders->onChange.connect(sigc::mem_fun(this, &GameMenuView::OnToggleShaders)); hbox = new Gui::HBox(); hbox->SetSpacing(5.0f); hbox->PackEnd(m_toggleShaders); hbox->PackEnd(new Gui::Label(Lang::USE_SHADERS)); m_toggleCompressTextures = new Gui::ToggleButton(); m_toggleCompressTextures->onChange.connect(sigc::mem_fun(this, &GameMenuView::OnToggleCompressTextures)); hbox->PackEnd(m_toggleCompressTextures); hbox->PackEnd(new Gui::Label(Lang::COMPRESS_TEXTURES)); vbox->PackEnd(hbox); vbox->PackEnd((new Gui::Label(Lang::SOUND_SETTINGS))->Color(1.0f,1.0f,0.0f)); m_masterVolume = new VolumeControl(Lang::VOL_MASTER, Pi::config->Float("MasterVolume"), Pi::config->Int("MasterMuted")); vbox->PackEnd(m_masterVolume); m_sfxVolume = new VolumeControl(Lang::VOL_EFFECTS, Pi::config->Float("SfxVolume"), Pi::config->Int("SfxMuted")); vbox->PackEnd(m_sfxVolume); m_musicVolume = new VolumeControl(Lang::VOL_MUSIC, Pi::config->Float("MusicVolume"), Pi::config->Int("MusicMuted")); vbox->PackEnd(m_musicVolume); m_masterVolume->onChanged.connect(sigc::mem_fun(this, &GameMenuView::OnChangeVolume)); m_sfxVolume->onChanged.connect(sigc::mem_fun(this, &GameMenuView::OnChangeVolume)); m_musicVolume->onChanged.connect(sigc::mem_fun(this, &GameMenuView::OnChangeVolume)); } // Video mode selector { m_videoModes = Graphics::GetAvailableVideoModes(); vbox->PackEnd((new Gui::Label(Lang::VIDEO_RESOLUTION))->Color(1.0f,1.0f,0.0f)); m_screenModesGroup = new Gui::RadioGroup(); // box to put the scroll portal and its scroll bar into Gui::HBox *scrollHBox = new Gui::HBox(); vbox->PackEnd(scrollHBox); Gui::VScrollBar *scroll = new Gui::VScrollBar(); Gui::VScrollPortal *portal = new Gui::VScrollPortal(280); scroll->SetAdjustment(&portal->vscrollAdjust); scrollHBox->PackEnd(portal); scrollHBox->PackEnd(scroll); Gui::VBox *vbox2 = new Gui::VBox(); portal->Add(vbox2); for (std::vector<Graphics::VideoMode>::const_iterator it = m_videoModes.begin(); it != m_videoModes.end(); ++it) { Gui::RadioButton *temp = new Gui::RadioButton(m_screenModesGroup); temp->onSelect.connect(sigc::bind(sigc::mem_fun(this, &GameMenuView::OnChangeVideoResolution), it - m_videoModes.begin())); Gui::HBox *hbox = new Gui::HBox(); hbox->SetSpacing(5.0f); hbox->PackEnd(temp); hbox->PackEnd(new Gui::Label(stringf(Lang::X_BY_X, formatarg("x", int(it->width)), formatarg("y", int(it->height))))); vbox2->PackEnd(hbox); //mark the current video mode if ((Pi::GetScrWidth() == it->width) && (Pi::GetScrHeight() == it->height)) { temp->SetSelected(true); } } } //Graphical detail settings { Gui::HBox *detailBox = new Gui::HBox(); detailBox->SetSpacing(20.0f); mainTab->Add(detailBox, 350, 60); vbox = new Gui::VBox(); vbox->SetSpacing(5.0f); detailBox->PackEnd(vbox); vbox->PackEnd((new Gui::Label(Lang::CITY_DETAIL_LEVEL))->Color(1.0f,1.0f,0.0f)); m_cityDetailGroup = new Gui::RadioGroup(); for (int i=0; i<5; i++) { Gui::RadioButton *rb = new Gui::RadioButton(m_cityDetailGroup); rb->onSelect.connect(sigc::bind(sigc::mem_fun(this, &GameMenuView::OnChangeCityDetail), i)); Gui::HBox *hbox = new Gui::HBox(); hbox->SetSpacing(5.0f); hbox->PackEnd(rb); hbox->PackEnd(new Gui::Label(planet_detail_desc[i])); vbox->PackEnd(hbox); } vbox = new Gui::VBox(); vbox->SetSpacing(5.0f); detailBox->PackEnd(vbox); vbox->PackEnd((new Gui::Label(Lang::PLANET_DETAIL_DISTANCE))->Color(1.0f,1.0f,0.0f)); m_planetDetailGroup = new Gui::RadioGroup(); for (int i=0; i<5; i++) { Gui::RadioButton *rb = new Gui::RadioButton(m_planetDetailGroup); rb->onSelect.connect(sigc::bind(sigc::mem_fun(this, &GameMenuView::OnChangePlanetDetail), i)); Gui::HBox *hbox = new Gui::HBox(); hbox->SetSpacing(5.0f); hbox->PackEnd(rb); hbox->PackEnd(new Gui::Label(planet_detail_desc[i])); vbox->PackEnd(hbox); } vbox = new Gui::VBox(); vbox->SetSpacing(5.0f); detailBox->PackEnd(vbox); vbox->PackEnd((new Gui::Label(Lang::PLANET_TEXTURES))->Color(1.0f,1.0f,0.0f)); m_planetTextureGroup = new Gui::RadioGroup(); for (int i=0; i<2; i++) { Gui::RadioButton *rb = new Gui::RadioButton(m_planetTextureGroup); rb->onSelect.connect(sigc::bind(sigc::mem_fun(this, &GameMenuView::OnChangePlanetTextures), i)); Gui::HBox *hbox = new Gui::HBox(); hbox->SetSpacing(5.0f); hbox->PackEnd(rb); hbox->PackEnd(new Gui::Label(planet_textures_desc[i])); vbox->PackEnd(hbox); } vbox = new Gui::VBox(); vbox->SetSpacing(5.0f); detailBox->PackEnd(vbox); vbox->PackEnd((new Gui::Label(Lang::FRACTAL_DETAIL))->Color(1.0f,1.0f,0.0f)); m_planetFractalGroup = new Gui::RadioGroup(); for (int i=0; i<5; i++) { Gui::RadioButton *rb = new Gui::RadioButton(m_planetFractalGroup); rb->onSelect.connect(sigc::bind(sigc::mem_fun(this, &GameMenuView::OnChangeFractalMultiple), i)); Gui::HBox *hbox = new Gui::HBox(); hbox->SetSpacing(5.0f); hbox->PackEnd(rb); hbox->PackEnd(new Gui::Label(planet_fractal_desc[i])); vbox->PackEnd(hbox); } } // language vbox = new Gui::VBox(); vbox->SetSizeRequest(300, 200); mainTab->Add(vbox, 400, 250); vbox->PackEnd((new Gui::Label(Lang::LANGUAGE_SELECTION))->Color(1.0f,1.0f,0.0f)); m_languageGroup = new Gui::RadioGroup(); const std::vector<std::string> &availableLanguages = Lang::GetAvailableLanguages(); { // box to put the scroll portal and its scroll bar into Gui::HBox *scrollHBox = new Gui::HBox(); vbox->PackEnd(scrollHBox); Gui::VScrollBar *scroll = new Gui::VScrollBar(); Gui::VScrollPortal *portal = new Gui::VScrollPortal(280); scroll->SetAdjustment(&portal->vscrollAdjust); scrollHBox->PackEnd(portal); scrollHBox->PackEnd(scroll); Gui::VBox *vbox2 = new Gui::VBox(); portal->Add(vbox2); for (std::vector<std::string>::const_iterator i = availableLanguages.begin(); i != availableLanguages.end(); ++i) { Gui::RadioButton *temp = new Gui::RadioButton(m_languageGroup); temp->onSelect.connect(sigc::bind(sigc::mem_fun(this, &GameMenuView::OnChangeLanguage), *i)); Gui::HBox *hbox = new Gui::HBox(); hbox->SetSpacing(5.0f); hbox->PackEnd(temp); hbox->PackEnd(new Gui::Label(*i)); vbox2->PackEnd(hbox); if ((*i) == Pi::config->String("Lang")) temp->SetSelected(true); } } // key binding tab 1 { Gui::Fixed *keybindingTab = new Gui::Fixed(800, 600); tabs->AddPage(new Gui::Label(Lang::CONTROLS), keybindingTab); Gui::VBox *box1 = new Gui::VBox(); box1->SetSpacing(5.0f); keybindingTab->Add(box1, 10, 10); Gui::VBox *box2 = new Gui::VBox(); box2->SetSpacing(5.0f); keybindingTab->Add(box2, 400, 10); Gui::VBox *box = box1; KeyGetter *keyg; for (int i=0; KeyBindings::bindingProtos[i].label; i++) { const char *label = KeyBindings::bindingProtos[i].label; const char *function = KeyBindings::bindingProtos[i].function; if (function) { KeyBindings::KeyBinding kb = KeyBindings::KeyBindingFromString(Pi::config->String(function)); keyg = new KeyGetter(label, kb); keyg->onChange.connect(sigc::bind(sigc::mem_fun(this, &GameMenuView::OnChangeKeyBinding), function)); box->PackEnd(keyg); } else { // section box->PackEnd((new Gui::Label(label))->Color(1.0f, 1.0f, 0.0f)); } /* 2nd column */ if (i == 20) { box = box2; } } for (int i=0; KeyBindings::axisBindingProtos[i].label; i++) { AxisGetter *axisg; const char *label = KeyBindings::axisBindingProtos[i].label; const char *function = KeyBindings::axisBindingProtos[i].function; if (function) { KeyBindings::AxisBinding ab = KeyBindings::AxisBindingFromString(Pi::config->String(function).c_str()); axisg = new AxisGetter(label, ab); axisg->onChange.connect(sigc::bind(sigc::mem_fun(this, &GameMenuView::OnChangeAxisBinding), function)); box->PackEnd(axisg); } else { // section box->PackEnd((new Gui::Label(label))->Color(1.0f, 1.0f, 0.0f)); } /* 2nd column */ if (i == 20) { box = box2; } } m_toggleJoystick = new Gui::ToggleButton(); m_toggleJoystick->onChange.connect(sigc::mem_fun(this, &GameMenuView::OnToggleJoystick)); Gui::HBox *hbox = new Gui::HBox(); hbox->SetSpacing(5.0f); hbox->PackEnd(m_toggleJoystick); hbox->PackEnd(new Gui::Label(Lang::ENABLE_JOYSTICK)); box->PackEnd(hbox); // Invert Mouse m_toggleMouseYInvert = new Gui::ToggleButton(); m_toggleMouseYInvert->onChange.connect(sigc::mem_fun(this, &GameMenuView::OnToggleMouseYInvert)); box->PackEnd((new Gui::Label(Lang::MOUSE_INPUT))->Color(1.0f,1.0f,0.0f)); Gui::HBox *mybox = new Gui::HBox(); mybox->SetSpacing(5.0f); mybox->PackEnd(m_toggleMouseYInvert); mybox->PackEnd(new Gui::Label(Lang::INVERT_MOUSE_Y)); box->PackEnd(mybox); // Toggle nav tunnel m_toggleNavTunnel = new Gui::ToggleButton(); m_toggleNavTunnel->onChange.connect(sigc::mem_fun(this, &GameMenuView::OnToggleNavTunnel)); box->PackEnd((new Gui::Label(Lang::HUD))->Color(1.0f,1.0f,0.0f)); Gui::HBox *guibox = new Gui::HBox(); guibox->SetSpacing(5.0f); guibox->PackEnd(m_toggleNavTunnel); guibox->PackEnd(new Gui::Label(Lang::DISPLAY_NAV_TUNNEL)); box->PackEnd(guibox); } // key binding tab 2 { Gui::Fixed *keybindingTab = new Gui::Fixed(800, 600); tabs->AddPage(new Gui::Label(Lang::VIEW), keybindingTab); Gui::VBox *box1 = new Gui::VBox(); box1->SetSpacing(5.0f); keybindingTab->Add(box1, 10, 10); Gui::VBox *box = box1; KeyGetter *keyg; for (int i=0; KeyBindings::camBindingProtos[i].label; i++) { const char *label = KeyBindings::camBindingProtos[i].label; const char *function = KeyBindings::camBindingProtos[i].function; if (function) { KeyBindings::KeyBinding kb = KeyBindings::KeyBindingFromString(Pi::config->String(function)); keyg = new KeyGetter(label, kb); keyg->onChange.connect(sigc::bind(sigc::mem_fun(this, &GameMenuView::OnChangeKeyBinding), function)); box->PackEnd(keyg); } else { // section box->PackEnd((new Gui::Label(label))->Color(1.0f, 1.0f, 0.0f)); } } } }
int main(int argc, char *argv[]) { int i, j, nf; progname = argv[0]; UpdatePaths( progname ); ac = argc + 50; av = alloc(ac*sizeof(char *)); if (signal(SIGINT, SIG_IGN) != SIG_IGN) signal(SIGINT, interrupt); if (signal(SIGTERM, SIG_IGN) != SIG_IGN) signal(SIGTERM, interrupt); #ifdef SIGHUP if (signal(SIGHUP, SIG_IGN) != SIG_IGN) signal(SIGHUP, interrupt); #endif if (getenv("TMP")) tempdir = getenv("TMP"); else if (getenv("TEMP")) tempdir = getenv("TEMP"); else if (getenv("TMPDIR")) tempdir = getenv("TMPDIR"); assert(tempdir); i = strlen(tempdir); for (; (i > 0 && tempdir[i-1] == '/') || tempdir[i-1] == '\\'; i--) tempdir[i-1] = '\0'; if (argc <= 1) { help(); exit(0); } plist = append("-D__LCC__", 0); initinputs(); if (getenv("LCCDIR")) option(stringf("-lccdir=%s", getenv("LCCDIR"))); for (nf = 0, i = j = 1; i < argc; i++) { if (strcmp(argv[i], "-o") == 0) { if (++i < argc) { if (suffix(argv[i], suffixes, 2) >= 0) { error("-o would overwrite %s", argv[i]); exit(8); } outfile = argv[i]; continue; } else { error("unrecognized option `%s'", argv[i-1]); exit(8); } } else if (strcmp(argv[i], "-target") == 0) { if (argv[i+1] && *argv[i+1] != '-') i++; continue; } else if (*argv[i] == '-' && argv[i][1] != 'l') { opt(argv[i]); continue; } else if (*argv[i] != '-' && suffix(argv[i], suffixes, 3) >= 0) nf++; argv[j++] = argv[i]; } if ((cflag || Sflag) && outfile && nf != 1) { fprintf(stderr, "%s: -o %s ignored\n", progname, outfile); outfile = 0; } argv[j] = 0; for (i = 0; include[i]; i++) plist = append(include[i], plist); if (ilist) { List b = ilist; do { b = b->link; plist = append(b->str, plist); } while (b != ilist); } ilist = 0; for (i = 1; argv[i]; i++) if (*argv[i] == '-') opt(argv[i]); else { char *name = exists(argv[i]); if (name) { if (strcmp(name, argv[i]) != 0 || (nf > 1 && suffix(name, suffixes, 3) >= 0)) fprintf(stderr, "%s:\n", name); filename(name, 0); } else error("can't find `%s'", argv[i]); } if (errcnt == 0 && !Eflag && !Sflag && !cflag && llist[1]) { compose(ld, llist[0], llist[1], append(outfile ? outfile : concat("a", first(suffixes[4])), 0)); if (callsys(av)) errcnt++; } rm(rmlist); return errcnt ? EXIT_FAILURE : EXIT_SUCCESS; }
Shader(GLenum type, const std::string &filename, const std::string &defines) { RefCountedPtr<FileSystem::FileData> filecode = FileSystem::gameDataFiles.ReadFile(filename); if (!filecode.Valid()) Error("Could not load %s", filename.c_str()); std::string strCode(filecode->AsStringRange().ToString()); size_t found = strCode.find("#include"); while (found != std::string::npos) { // find the name of the file to include const size_t begFilename = strCode.find_first_of("\"", found + 8) + 1; const size_t endFilename = strCode.find_first_of("\"", begFilename + 1); const std::string incFilename = strCode.substr(begFilename, endFilename - begFilename); // check we haven't it already included it (avoids circular dependencies) const std::set<std::string>::const_iterator foundIt = previousIncludes.find(incFilename); if (foundIt != previousIncludes.end()) { Error("Circular, or multiple, include of %s\n", incFilename.c_str()); } else { previousIncludes.insert(incFilename); } // build path for include const std::string incPathBuffer = stringf("shaders/opengl/%0", incFilename); // read included file RefCountedPtr<FileSystem::FileData> incCode = FileSystem::gameDataFiles.ReadFile(incPathBuffer); assert(incCode.Valid()); if (incCode.Valid()) { // replace the #include and filename with the included files text strCode.replace(found, (endFilename + 1) - found, incCode->GetData(), incCode->GetSize()); found = strCode.find("#include"); } else { Error("Could not load %s", incPathBuffer.c_str()); } } // Store the modified text with the included files (if any) const StringRange code(strCode.c_str(), strCode.size()); // Build the final shader text to be compiled AppendSource(s_glslVersion); AppendSource(defines.c_str()); if (type == GL_VERTEX_SHADER) { AppendSource("#define VERTEX_SHADER\n"); } else { AppendSource("#define FRAGMENT_SHADER\n"); } AppendSource(code.StripUTF8BOM()); #if 0 static bool s_bDumpShaderSource = true; if (s_bDumpShaderSource) { const char SHADER_OUT_DIR_NAME[] = "shaders"; const char SHADER_OGL_OUT_DIR_NAME[] = "shaders/opengl"; FileSystem::userFiles.MakeDirectory(SHADER_OUT_DIR_NAME); FileSystem::userFiles.MakeDirectory(SHADER_OGL_OUT_DIR_NAME); const std::string outFilename(FileSystem::GetUserDir() + "/" + filename); FILE *tmp = fopen(outFilename.c_str(), "wb"); if(tmp) { Output("%s", filename); for( Uint32 i=0; i<blocks.size(); i++ ) { const char *block = blocks[i]; const GLint sizes = block_sizes[i]; if(block && sizes>0) { fprintf(tmp, "%.*s", sizes, block); } } fclose(tmp); } else { Output("Could not open file %s", outFilename.c_str()); } } #endif shader = glCreateShader(type); if(glIsShader(shader)!=GL_TRUE) throw ShaderException(); Compile(shader); // CheckGLSL may use OS::Warning instead of Error so the game may still (attempt to) run if (!check_glsl_errors(filename.c_str(), shader)) throw ShaderException(); };
void Ship::StaticUpdate(const float timeStep) { // do player sounds before dead check, so they also turn off if (IsType(Object::PLAYER)) DoThrusterSounds(); if (IsDead()) return; if (m_controller) m_controller->StaticUpdate(timeStep); if (GetHullTemperature() > 1.0) Explode(); UpdateAlertState(); /* FUEL SCOOPING!!!!!!!!! */ int capacity = 0; Properties().Get("fuel_scoop_cap", capacity); if (m_flightState == FLYING && capacity > 0) { Body *astro = GetFrame()->GetBody(); if (astro && astro->IsType(Object::PLANET)) { Planet *p = static_cast<Planet*>(astro); if (p->GetSystemBody()->IsScoopable()) { double dist = GetPosition().Length(); double pressure, density; p->GetAtmosphericState(dist, &pressure, &density); double speed = GetVelocity().Length(); vector3d vdir = GetVelocity().Normalized(); vector3d pdir = -GetOrient().VectorZ(); double dot = vdir.Dot(pdir); if ((m_stats.free_capacity) && (dot > 0.95) && (speed > 2000.0) && (density > 1.0)) { double rate = speed*density*0.00000333f*double(capacity); if (Pi::rng.Double() < rate) { lua_State *l = Lua::manager->GetLuaState(); pi_lua_import(l, "Equipment"); LuaTable hydrogen = LuaTable(l, -1).Sub("cargo").Sub("hydrogen"); LuaObject<Ship>::CallMethod(this, "AddEquip", hydrogen); UpdateEquipStats(); if (this->IsType(Object::PLAYER)) { Pi::game->log->Add(stringf(Lang::FUEL_SCOOP_ACTIVE_N_TONNES_H_COLLECTED, formatarg("quantity", LuaObject<Ship>::CallMethod<int>(this, "CountEquip", hydrogen)))); } lua_pop(l, 3); } } } } } // Cargo bay life support capacity = 0; Properties().Get("cargo_life_support_cap", capacity); if (!capacity) { // Hull is pressure-sealed, it just doesn't provide // temperature regulation and breathable atmosphere // kill stuff roughly every 5 seconds if ((!m_dockedWith) && (5.0*Pi::rng.Double() < timeStep)) { std::string t(Pi::rng.Int32(2) ? "live_animals" : "slaves"); lua_State *l = Lua::manager->GetLuaState(); pi_lua_import(l, "Equipment"); LuaTable cargo = LuaTable(l, -1).Sub("cargo"); if (LuaObject<Ship>::CallMethod<int>(this, "RemoveEquip", cargo.Sub(t))) { LuaObject<Ship>::CallMethod<int>(this, "AddEquip", cargo.Sub("fertilizer")); if (this->IsType(Object::PLAYER)) { Pi::game->log->Add(Lang::CARGO_BAY_LIFE_SUPPORT_LOST); } lua_pop(l, 4); } else lua_pop(l, 3); } } if (m_flightState == FLYING) m_launchLockTimeout -= timeStep; if (m_launchLockTimeout < 0) m_launchLockTimeout = 0; if (m_flightState == JUMPING || m_flightState == HYPERSPACE) m_launchLockTimeout = 0; // lasers for (int i=0; i<ShipType::GUNMOUNT_MAX; i++) { m_gun[i].recharge -= timeStep; float rateCooling = 0.01f; float cooler = 1.0f; Properties().Get("laser_cooler_cap", cooler); rateCooling *= cooler; m_gun[i].temperature -= rateCooling*timeStep; if (m_gun[i].temperature < 0.0f) m_gun[i].temperature = 0; if (m_gun[i].recharge < 0.0f) m_gun[i].recharge = 0; if (!m_gun[i].state) continue; if (m_gun[i].recharge > 0.0f) continue; if (m_gun[i].temperature > 1.0) continue; FireWeapon(i); } if (m_ecmRecharge > 0.0f) { m_ecmRecharge = std::max(0.0f, m_ecmRecharge - timeStep); } if (m_shieldCooldown > 0.0f) { m_shieldCooldown = std::max(0.0f, m_shieldCooldown - timeStep); } if (m_stats.shield_mass_left < m_stats.shield_mass) { // 250 second recharge float recharge_rate = 0.004f; float booster = 1.0f; Properties().Get("shield_energy_booster_cap", booster); recharge_rate *= booster; m_stats.shield_mass_left = Clamp(m_stats.shield_mass_left + m_stats.shield_mass * recharge_rate * timeStep, 0.0f, m_stats.shield_mass); Properties().Set("shieldMassLeft", m_stats.shield_mass_left); } if (m_wheelTransition) { m_wheelState += m_wheelTransition*0.3f*timeStep; m_wheelState = Clamp(m_wheelState, 0.0f, 1.0f); if (is_equal_exact(m_wheelState, 0.0f) || is_equal_exact(m_wheelState, 1.0f)) m_wheelTransition = 0; } if (m_testLanded) TestLanded(); capacity = 0; Properties().Get("hull_autorepair_cap", capacity); if (capacity) { m_stats.hull_mass_left = std::min(m_stats.hull_mass_left + 0.1f*timeStep, float(m_type->hullMass)); Properties().Set("hullMassLeft", m_stats.hull_mass_left); Properties().Set("hullPercent", 100.0f * (m_stats.hull_mass_left / float(m_type->hullMass))); } // After calling StartHyperspaceTo this Ship must not spawn objects // holding references to it (eg missiles), as StartHyperspaceTo // removes the ship from Space::bodies and so the missile will not // have references to this cleared by NotifyRemoved() if (m_hyperspace.now) { m_hyperspace.now = false; EnterHyperspace(); } if (m_hyperspace.countdown > 0.0f) { // Check the Lua function bool abort = false; lua_State * l = m_hyperspace.checks.GetLua(); if (l) { m_hyperspace.checks.PushCopyToStack(); if (lua_isfunction(l, -1)) { lua_call(l, 0, 1); abort = !lua_toboolean(l, -1); lua_pop(l, 1); } } if (abort) { AbortHyperjump(); } else { m_hyperspace.countdown = m_hyperspace.countdown - timeStep; if (!abort && m_hyperspace.countdown <= 0.0f) { m_hyperspace.countdown = 0; m_hyperspace.now = true; SetFlightState(JUMPING); // We have to fire it here, because the event isn't actually fired until // after the whole physics update, which means the flight state on next // step would be HYPERSPACE, thus breaking quite a few things. LuaEvent::Queue("onLeaveSystem", this); } } } //Add smoke trails for missiles on thruster state static double s_timeAccum = 0.0; s_timeAccum += timeStep; if (m_type->tag == ShipType::TAG_MISSILE && !is_equal_exact(m_thrusters.LengthSqr(), 0.0) && (s_timeAccum > 4 || 0.1*Pi::rng.Double() < timeStep)) { s_timeAccum = 0.0; const vector3d pos = GetOrient() * vector3d(0, 0 , 5); const float speed = std::min(10.0*GetVelocity().Length()*std::max(1.0,fabs(m_thrusters.z)),100.0); SfxManager::AddThrustSmoke(this, speed, pos); } }