示例#1
1
void StartGameWidget::SetBodyText()
{
	if (sectors.Empty()) return;

	const SectorData* sd = sectors[currentSector];
	Weather* weather = Weather::Instance();
	Vector2I pos = sd->CoreLoc();
	Vector2F pos2 = ToWorld2F(pos);
	GLASSERT(weather);
	const float AREA = float(SECTOR_SIZE*SECTOR_SIZE);
	int nPorts = 0;
	for (int i = 0; i < 4; ++i) {
		if ((1 << i) & sd->ports) {
			nPorts++;
		}
	}

	int bioFlora = 0;
	int flowers = 0;
	Rectangle2I bi = sd->InnerBounds();
	for (Rectangle2IIterator it(bi); !it.Done(); it.Next()) {
		const WorldGrid& wg = worldMap->GetWorldGrid(it.Pos().x, it.Pos().y);
		if (wg.Plant() >= 7) {
			flowers++;
		}
		else if (wg.Plant()) {
			bioFlora++;
		}
	}

	CStr<400> str;
	str.Format("%s\nTemperature=%d%%  Rain=%d%%  Land=%d%%  Water=%d%%  nPorts=%d\n"
		"bioFlora=%d%%  flowers=%d%%",
		sd->name.c_str(),
		LRint(weather->Temperature(pos2.x, pos2.y) * 100.0f),
		LRint(weather->RainFraction(pos2.x, pos2.y) * 100.0f),
		LRint(100.0f*float(sd->area) / AREA),
		LRint(100.0f*float(AREA - sd->area) / AREA),
		nPorts,
		LRint(100.0f*float(bioFlora) / AREA),
		LRint(100.0f*float(flowers) / AREA));

	bodyLabel.SetText(str.c_str());

	str.Format("%d/%d", currentSector+1, sectors.Size());
	countLabel.SetText(str.c_str());
}
示例#2
0
void LumosGame::ItemToButton( const GameItem* item, gamui::Button* button )
{
	CStr<64> text;

	// Set the text to the proper name, if we have it.
	// Then an icon for what it is, and a check
	// mark if the object is in use.
	int value = item->GetValue();
	const char* name = item->ProperName() ? item->ProperName() : item->Name();
	if ( value ) {
		text.Format( "%s\n%d", name, value );
	}
	else {
		text.Format( "%s\n ", name );
	}
	button->SetText( text.c_str() );

	IString decoName = item->keyValues.GetIString( "uiIcon" );
	RenderAtom atom  = LumosGame::CalcUIIconAtom( decoName.c_str(), true );
	atom.renderState = (const void*) UIRenderer::RENDERSTATE_UI_DECO_DISABLED;
	RenderAtom atomD = LumosGame::CalcUIIconAtom( decoName.c_str(), false );
	atomD.renderState = (const void*) UIRenderer::RENDERSTATE_UI_DECO_DISABLED;

	button->SetDeco( atom, atomD );
}
示例#3
0
//------------------------------------------------------------------------------
/// \brief
//------------------------------------------------------------------------------
bool NativeExpDdf::Export ()
{
  if (GetPackage()->PackageName() != Packages::DDF)
  {
    return false;
  }

  MfPackage* a_p = GetPackage();
  const double *rhofresh(0), *rhostd(0), *cstd(0);
  if (a_p->GetField(Packages::Ddf::RHOFRESH, &rhofresh) && rhofresh &&
      a_p->GetField(Packages::Ddf::RHOSTD, &rhostd) && rhostd &&
      a_p->GetField(Packages::Ddf::CSTD, &cstd) && cstd)
  {

    CStr desc = "1. RHOFRESH, RHOSTD, CSTD";
    CStr var;
    CStr line;
    int width = util::RealWidth();

    var.Format("%s ", STR(*rhofresh, -1, width, STR_FULLWIDTH));
    line += var;
    var.Format("%s ", STR(*rhostd, -1, width, STR_FULLWIDTH));
    line += var;
    var.Format("%s", STR(*cstd, -1, width, STR_FULLWIDTH));
    line += var;
    AddToStoredLinesDesc(line, desc);
  }

  WriteComments();
  WriteStoredLines();
  return true;
} // MfNativeExpDdf::Export
示例#4
0
//------------------------------------------------------------------------------
/// \brief
//------------------------------------------------------------------------------
void NativeExpGag::Line2 ()
{
  using namespace MfData::Packages;
  const int *igglst(0), *numgage(0);
  if (GetPackage()->GetField(GAGpack::IGGLST, &igglst) && igglst &&
      GetPackage()->GetField(GAGpack::NUMGAGE, &numgage) && numgage)
  {
    CStr s;
    for (int i=0; i<*numgage; ++i)
    {
      int type = igglst[i*4 + 0];
      if (type >= 0)
      {
        // line 2b: GAGESEG GAGERCH UNIT OUTTYPE
        int gageseg = type;
        int gagerch = igglst[i*4 + 1];
        int unit    = igglst[i*4 + 2];
        int outtype = igglst[i*4 + 3];
        s.Format("%3d %4d %4d %3d", gageseg, gagerch, unit, outtype);
        AddToStoredLinesDesc(s, Desc(3));
      }
      else
      {
        // line 2a: LAKE UNIT {OUTTYPE}
        int lake    = type;
        int unit    = igglst[i*4 + 2];
        int outtype = igglst[i*4 + 3];
        s.Format("%3d %4d %4d", lake, unit, outtype);
        AddToStoredLinesDesc(s, Desc(2));
      }
    }
  }
} // NativeExpGag::Line2
示例#5
0
void CUnitPane::SaveUnitListHdr()
{
    CListLayoutItem * pLI;
    int               i;
    CStr              Key;
    CStr              Val;

    if (m_pLayout)
    {
        // we are naming items dynamically, so remove them first!
        gpApp->RemoveSection(m_sConfigSectionHdr.GetData());

        for (i=0; i<m_pLayout->Count(); i++)
        {
            pLI = (CListLayoutItem*)m_pLayout->At(i);


            Key.Format("%03d", i);
            Val.Format("%d, %lu, %s, %s", GetColumnWidth(i), pLI->m_Flags, pLI->m_Name, pLI->m_Caption);
            gpApp->SetConfig(m_sConfigSectionHdr.GetData(), Key.GetData(), Val.GetData());
        }

        gpApp->SetConfig(m_sConfigSection.GetData(), SZ_KEY_SORT1, GetSortName(0 ) );
        gpApp->SetConfig(m_sConfigSection.GetData(), SZ_KEY_SORT2, GetSortName(1 ) );
        gpApp->SetConfig(m_sConfigSection.GetData(), SZ_KEY_SORT3, GetSortName(2 ) );
    }
}
示例#6
0
void MapScene::EnableButtons()
{
	Vector2I v = data->destSector;
	CoreScript* cs = CoreScript::GetCore(v);
	CoreScript* homeCore = lumosChitBag->GetHomeCore();

	if (!homeCore) {
		warButton.SetEnabled(false);
		peaceButton.SetEnabled(false);
		peaceButton.SetText("Peace Treaty");
		return;
	}

	warButton.SetEnabled(Team::Instance()->War(cs, homeCore, false, &lumosChitBag->GetSim()->GetCachedWeb()));
	int peace = Team::Instance()->Peace(cs, homeCore, false, &lumosChitBag->GetSim()->GetCachedWeb());
	const Wallet* wallet = homeCore->ParentChit()->GetWallet();

	if (peace > 0 && wallet->HasGold(peace)) {
		CStr<64> str;
		str.Format("Peace Treaty %d Au", peace);
		peaceButton.SetEnabled(true);
		peaceButton.SetText(str.c_str());
	}
	else {
		peaceButton.SetEnabled(false);
		peaceButton.SetText("Peace Treaty");
	}
}
示例#7
0
//------------------------------------------------------------------------------
/// \brief
//------------------------------------------------------------------------------
void NativeExpMf6Lak::impl::WriteStressPeriodData ()
{
  int w = util::RealWidth();
  MfPackage* p = m_pack->GetPackage();
  const int *nlakes(0), *itmp1(0);
  const Real *rnf(0), *wthdrw(0);
  const double *prcplk(0), *evaplk(0);
  MfPackage* pLak = m_pack->GetGlobal()->GetPackage(Packages::LAK);
  if (pLak->GetField(Packages::LAKpack::NLAKES, &nlakes) && nlakes &&
      p->GetField(Packages::LAKSPpack::ITMP1, &itmp1) && itmp1 &&
      p->GetField(Packages::LAKSPpack::PRCPLK, &prcplk) && prcplk &&
      p->GetField(Packages::LAKSPpack::EVAPLK, &evaplk) && evaplk &&
      p->GetField(Packages::LAKSPpack::RNF, &rnf) && rnf &&
      p->GetField(Packages::LAKSPpack::WTHDRW, &wthdrw) && wthdrw )
  {
    std::stringstream ss;
    ss << "BEGIN PERIOD " << m_pack->GetGlobal()->GetCurrentPeriod();
    m_lines.push_back(ss.str());
    for (int i=0; i<*nlakes; ++i)
    {
      CStr lakId;
      lakId.Format("  %5d ", i+1);
      std::stringstream ss1;
      ss1 << lakId << "rainfall    " << STR(prcplk[i],-1,w,STR_FULLWIDTH) << "\n"
          << lakId << "evaporation " << STR(evaplk[i],-1,w,STR_FULLWIDTH) << "\n"
          << lakId << "runoff      " << STR(rnf[i],-1,w,STR_FULLWIDTH) << "\n"
          << lakId << "withdrawal  " << STR(wthdrw[i],-1,w,STR_FULLWIDTH);
      m_lines.push_back(ss1.str());
    }
    m_lines.push_back("END PERIOD");
    m_lines.push_back("");
  }

} // NativeExpMf6Lak::impl::WriteStressPeriodData
示例#8
0
//------------------------------------------------------------------------------
/// \brief
//------------------------------------------------------------------------------
void NativeExpLak::Line7to8 ()
{
  const int *nlakes(0), *itmp(0), *nslms(0), *ic(0), *isub(0);
  const Real *sillvt(0);
  MfPackage* a_p = GetPackage();
  MfPackage* a_pLak = GetGlobal()->GetPackage(Packages::LAK);
  if (a_pLak->GetField(Packages::LAKpack::NLAKES, &nlakes) && nlakes &&
      a_p->GetField(Packages::LAKSPpack::ITMP, &itmp) && itmp &&
      a_p->GetField(Packages::LAKSPpack::NSLMS, &nslms) && nslms &&
      a_p->GetField(Packages::LAKSPpack::IC, &ic) && ic &&
      a_p->GetField(Packages::LAKSPpack::ISUB, &isub) && isub &&
      a_p->GetField(Packages::LAKSPpack::SILLVT, &sillvt) && sillvt)
  {
    if (*itmp < 1) return;

    CStr desc = " 7. NSLMS";
    CStr ln;
    ln.Format("%5d", *nslms);
    AddToStoredLinesDesc(ln, desc);

    if (*nslms < 1) return;

    for (int s=0; s<*nslms && ic[s] > 0; ++s)
    {
      desc = "8a. IC ISUB(1) ISUB(2) ............ ISUB(IC)";
      ln.Format("%5d ", ic[s]);
      for (int i=0; i<ic[s]; ++i)
      {
        CStr tmp;
        tmp.Format("%5d ", isub[i*(*nlakes)+s]);
        ln += tmp;
      }
      AddToStoredLinesDesc(ln, desc);

      int width = util::RealWidth();
      ln = "";
      desc = "8b. SILLVT(2) ............. SILLVT(IC)";
      for (int i=0; i<ic[s]-1; ++i)
      {
        CStr tmp;
        tmp.Format("%s ", STR(sillvt[i*(*nlakes)+s], -1, width, STR_FULLWIDTH));
        ln += tmp;
      }
      AddToStoredLinesDesc(ln, desc);
    }
  }
} // NativeExpLak::Line7to8
示例#9
0
//------------------------------------------------------------------------------
/// \brief
//------------------------------------------------------------------------------
void NativeExpLak::Line9 ()
{
  const int *nlakes(0), *itmp1(0);
  const Real *rnf(0), *wthdrw(0), *ssmn(0), *ssmx(0);
  const double *prcplk(0), *evaplk(0);
  MfPackage* a_p = GetPackage();
  MfPackage* a_pLak = GetGlobal()->GetPackage(Packages::LAK);
  if (a_pLak->GetField(Packages::LAKpack::NLAKES, &nlakes) && nlakes &&
      a_p->GetField(Packages::LAKSPpack::ITMP1, &itmp1) && itmp1 &&
      a_p->GetField(Packages::LAKSPpack::PRCPLK, &prcplk) && prcplk &&
      a_p->GetField(Packages::LAKSPpack::EVAPLK, &evaplk) && evaplk &&
      a_p->GetField(Packages::LAKSPpack::RNF, &rnf) && rnf &&
      a_p->GetField(Packages::LAKSPpack::WTHDRW, &wthdrw) && wthdrw &&
      a_p->GetField(Packages::LAKSPpack::SSMN, &ssmn) && ssmn &&
      a_p->GetField(Packages::LAKSPpack::SSMX, &ssmx) && ssmx)
  {
    if (*itmp1 < 0 || *nlakes < 1) return;

    int width = util::RealWidth();
    CStr desc = "9a. PRCPLK EVAPLK RNF WTHDRW [SSMN] [SSMX]";
    CStr ln;
    std::set<int>& ssPer(GetNative()->GetExp()->SetOfSteadyStateStressPeriods());
    for (int i=0; i<*nlakes; ++i)
    {
      ln.Format("%s %s %s %s",
                STR(prcplk[i], -1, width, STR_FULLWIDTH),
                STR(evaplk[i], -1, width, STR_FULLWIDTH),
                STR(rnf[i], -1, width, STR_FULLWIDTH),
                STR(wthdrw[i], -1, width, STR_FULLWIDTH));
      if (GetGlobal()->GetCurrentPeriod() != 1 &&
          ssPer.find(GetGlobal()->GetCurrentPeriod()) != ssPer.end())
      {
        CStr tmp;
        tmp.Format(" %s %s",
                   STR(ssmn[i], -1, width, STR_FULLWIDTH),
                   STR(ssmx[i], -1, width, STR_FULLWIDTH));
        ln += tmp;
      }
      AddToStoredLinesDesc(ln, desc);
    }
  }
} // NativeExpLak::Line9
示例#10
0
//------------------------------------------------------------------------------
/// \brief
//------------------------------------------------------------------------------
CStr NativeExpGag::Line1 ()
{
  using namespace MfData::Packages;
  CStr rval;
  const int *numgage(0);
  if (GetPackage()->GetField(GAGpack::NUMGAGE, &numgage) && numgage)
  {
    rval.Format("%d", *numgage);
  }
  return rval;
} // NativeExpGag::Line1
示例#11
0
int CoreScript::DoTick(U32 delta)
{
	int nScoreTicks = scoreTicker.Delta(delta);
	int nAITicks = aiTicker.Delta(delta);

	Citizens(0);	// if someone was deleted, the spawn tick will reset.
	int nSpawnTicks = spawnTick.Delta(delta);

	// Clean rock off the core.
	Vector2I pos2i = ToWorld2I(parentChit->Position());
	const WorldGrid& wg = Context()->worldMap->GetWorldGrid(pos2i);
	if (wg.RockHeight()) {
		Context()->worldMap->SetRock(pos2i.x, pos2i.y, 0, false, 0);
	}

	if (InUse()) {
		DoTickInUse(delta, nSpawnTicks);
		UpdateScore(nScoreTicks);
	}
	else {
		DoTickNeutral(delta, nSpawnTicks);
	}
	workQueue->DoTick();

	if (nAITicks) {
		UpdateAI();
	}

	for (int i = 0; i < MAX_SQUADS; ++i) {
		if (squads[i].Empty()) {
			waypoints[i].Clear();
		}
	}

	if (strategicTicker.Delta(delta)) {
		if (this->InUse() && Context()->chitBag->GetHomeCore() != this) {
			DoStrategicTick();
		}
	}

	RenderComponent* rc = parentChit->GetRenderComponent();
	if (rc) {
		int team = parentChit->Team();
		CStr<40> str = "";
		if (this->InUse() && Team::IsDenizen(team)) {
			IString teamName = Team::Instance()->TeamName(team);
			str.Format("%s", teamName.safe_str());
		}
		rc->SetDecoText(str.safe_str());
	}

	return Min(spawnTick.Next(), aiTicker.Next(), scoreTicker.Next());
}
示例#12
0
const GameItem* PlantScript::PlantDef(int plant0Based)
{
	GLASSERT(plant0Based >= 0 && plant0Based < NUM_EXTENDED_PLANT_TYPES);
	if (plantDef[0] == 0) {
		for (int i = 0; i < NUM_EXTENDED_PLANT_TYPES; ++i) {
			CStr<32> str;
			str.Format("plant%d", i);
			plantDef[i] = &ItemDefDB::Instance()->Get(str.c_str());
		}
	}
	GLASSERT(plantDef[plant0Based]);
	return plantDef[plant0Based];
}
示例#13
0
//------------------------------------------------------------------------------
/// \brief
//------------------------------------------------------------------------------
void NativeExpLak::Line4 ()
{
  const int *itmp(0), *itmp1(0), *lwrt(0);
  MfPackage* a_p = GetPackage();
  if (a_p->GetField(Packages::LAKSPpack::ITMP, &itmp) && itmp &&
      a_p->GetField(Packages::LAKSPpack::ITMP1, &itmp1) && itmp1 &&
      a_p->GetField(Packages::LAKSPpack::LWRT, &lwrt) && lwrt)
  {
    CStr desc = " 4. ITMP ITMP1 LWRT";
    CStr ln;
    ln.Format("%5d %5d %5d", *itmp, *itmp1, *lwrt);
    AddToStoredLinesDesc(ln, desc);
  }
} // NativeExpLak::Line4
示例#14
0
WNoticeContactInvite::WNoticeContactInvite(TContact * pContact) : INoticeWithIcon("Invite Peer?", eMenuIcon_Question)
	{
	Assert(pContact != NULL);
	mu_sponsor.pContact = pContact;	// This line is necessary for the notice to delete itself if the contact is deleted
	TAccountXmpp * pAccount = pContact->m_pAccount;
	PSZUC pszNickNameContact = pContact->ChatLog_PszGetNickname();
	setMaximumHeight(300);

	CStr strInvitationXml;
	strInvitationXml.Format("<i u='{C@}' f='^S' p='$i' h='{B/}'/>", &pContact->m_strJidBare, &pAccount->m_strJID, pAccount->m_uServerPort, pAccount->Certificate_PGetBinaryFingerprint());
//	pContact->Invitation_InitFromXml(strInvitationXml);

	NoticeMessage_SetText_VE("Until now, you never received any message from <b>^S</b>.  The text below is a <i>canned invitation</i> you may wish to send <b>^s</b> by email or via other messaging system.", &pContact->m_strJidBare, pszNickNameContact);
	Notice_AddButton(PA_CHILD new WButtonTextWithIcon("Copy|Copy the invitation text below into the clipboard", eMenuIcon_Copy), SL_WNoticeContactInvite(SL_ButtonCopy_clicked));

	CStr strInvitation;
	strInvitation.Format("Hi $s,\nThis is an invitation to create a chat account to communicate with $S.\n\n"
	"If you do not have SocietyPro installed, please click on this download link:\n"
	d_szUrlBaseDowloadInvitation "?Invitation={S/}\n\n"
	"Otherwise, just copy & paste the invitation below into SocietyPro:\n\n" d_szInvitationPrefix "{S/}" d_szInvitationPostfix "\n", pszNickNameContact, &pAccount->m_strJID, &strInvitationXml, &strInvitationXml);
	m_pwEditInvitation = new WEditTextArea(strInvitation);

	PSZAC pszaLabelAndToolTip = (PSZAC)strInvitation.Format("Suggested Invitation to Send:|"
		"<html>Copy and paste this invitation and send it to the person you wish to invite.<br/></br/>"
		"You may use email or other messaging system to send your invitation.<br/><br/>"
		"The content of<br/><br/>{S/}<br/><br/>is<br/><br/>^S<br/><br/>encoded in Base64.  Likewise h='{B/}' is the certificate fingerprint encoded in Base64.</html>", &strInvitationXml, &strInvitationXml, pAccount->Certificate_PGetBinaryFingerprint());
	//m_pwEditInvitationBase64->setMaximumHeight(100);
	m_poLayoutNotice->Layout_PoAddRowLabelsAndWidgets_VEZA(pszaLabelAndToolTip, m_pwEditInvitation, NULL);
	/*
	WEdit * pwEditEmail = new WEdit;
	m_poLayoutBody->Layout_AddLabelAndWidgetH_PA("Email Address:|Enter the email address of the peer you wish to send the invitation.", pwEditEmail);
	WButtonTextWithIcon * m_pButtonConnectNow = new WButtonTextWithIcon("Send Email", eMenuAction_ContactInvite);
	m_poLayoutBody->Layout_PoAddLayoutVerticalWithWidgets_VEZA(m_pButtonConnectNow, NULL);
	Notice_LayoutBodyMoveToBottom(); // Move the fields: Edit Email and the Send button at the bottom.  This is done by removing the layout, and adding it at the bottom
	*/
	}
示例#15
0
void
ITreeItem::TreeItemW_SetTextToDisplayMessagesUnread(int cMessagesUnread)
	{
	if (cMessagesUnread <= 0)
		{
		TreeItemW_UpdateText();
		return;
		}
	else if (m_paTreeItemW_YZ != NULL)
		{
		CStr str;
		str.Format("$s ($i)", TreeItem_PszGetNameDisplay(), cMessagesUnread);
		m_paTreeItemW_YZ->setText(0, str);
		}
	}
示例#16
0
//------------------------------------------------------------------------------
/// \brief
//------------------------------------------------------------------------------
void NativeExpMf6Nam::WriteChdFile ()
{
  MfGlobal *g = m_pack->GetGlobal();
  if (!g) return;
  Mf2kNative* n = m_pack->GetNative();
  if (!n) return;
  CStr baseName = n->FileName();
  util::StripExtensionFromFilename(baseName, baseName);
  baseName += ".chd";

  std::vector<CStr> fieldStrings;
  int MAXBOUND(0);
  CStr chdStr = MfExportUtil::Mf6IboundToChd(g, MAXBOUND, fieldStrings);

  std::vector<CStr> lines;

  lines.push_back(MfExportUtil::GetMf6CommentHeader());
  lines.push_back("BEGIN OPTIONS");
  int saveFlows(0);
  if (g->GetIntVar("MF6_SAVE_FLOWS", saveFlows) && saveFlows)
  {
    lines.push_back("  SAVE_FLOWS");
  }
  lines.push_back("END OPTIONS");
  lines.push_back("");

  lines.push_back("BEGIN DIMENSIONS");
  CStr dimStr;
  dimStr.Format("  MAXBOUND %d", MAXBOUND);
  lines.push_back(dimStr);
  lines.push_back("END DIMENSIONS");
  lines.push_back("");

  lines.push_back("BEGIN PERIOD 1");
  lines.push_back(chdStr);
  lines.push_back("END PERIOD 1");

  FILE *fp = fopen(baseName.c_str(), "w");
  if (fp)
  {
    for (size_t i=0; i<lines.size(); ++i)
    {
      fprintf(fp, "%s\n", lines[i].c_str());
    }
    fclose(fp);
  }
} // NativeExpMf6Nam::WriteChdFile
示例#17
0
//------------------------------------------------------------------------------
/// \brief
//------------------------------------------------------------------------------
bool NativeExpMf6Nam::ValidPackage (const CStr& a_ftype)
{
  const int NUMTYPES = 21;
  std::string types[NUMTYPES] =
    { "DIS", "DISV", "DISU", "IC", "OC", "NPF", "HFB", "STO", "CHD", "WEL",
      "DRN", "RIV", "GHB", "RCH", "EVT", "MAW", "SFR", "LAK", "UZF", "MVR",
      "GNC" };
  std::set<std::string> setTypes(&types[0], &types[NUMTYPES]);
  if (setTypes.find(a_ftype) != setTypes.end())
  {
    return true;
  }
  CStr msg;
  msg.Format("WARNING: Package %s is not supported for conversion to MF6.", a_ftype);
  printf("%s\n", msg.c_str());
  return false;
} // NativeExpMf6Nam::ValidPackage
示例#18
0
Chit* LumosChitBag::NewLawnOrnament(const Vector2I& pos, const char* name, int team)
{
	const ChitContext* context = Context();
	Chit* chit = NewChit();

	GameItem* rootItem = ItemDefDB::Instance()->Get(name).Clone();

	// Hack...how to do this better??
	if (rootItem->IResourceName() == "ruins1.0") {
		CStr<32> str;
		str.Format("ruins1.%d", random.Rand(2));
		rootItem->SetResource(str.c_str());
	}

	int size = 1;
	rootItem->keyValues.Get(ISC::size, &size);

	MapSpatialComponent* msc = new MapSpatialComponent();
	msc->SetBuilding(size, false, 0);
	msc->SetBlocks((rootItem->flags & GameItem::PATH_NON_BLOCKING) ? false : true);
	chit->Add(msc);
	MapSpatialComponent::SetMapPosition(chit, pos.x, pos.y);


	chit->Add(new RenderComponent(rootItem->ResourceName()));
	chit->Add(new HealthComponent());
	AddItem(rootItem, chit, context->engine, team, 0);

	IString proc = rootItem->keyValues.GetIString("procedural");
	if (!proc.empty()) {
		ProcRenderInfo info;
		AssignProcedural(chit->GetItem(), &info);
		chit->GetRenderComponent()->SetProcedural(0, info);
	}
	
	context->engine->particleSystem->EmitPD(ISC::constructiondone, ToWorld3F(pos), V3F_UP, 0);

	if (XenoAudio::Instance()) {
		Vector3F pos3 = ToWorld3F(pos);
		XenoAudio::Instance()->PlayVariation(ISC::rezWAV, random.Rand(), &pos3);
	}

	return chit;
}
示例#19
0
int main()
{

	foo("hello");
	foo("world");

	// format a bunch
	CStr x;
	CStr y;
	int i;
	for (i=0;i<10;++i) {
		x.Format("%i",i);
		y=x;
	}
	
	assert(x[0]='9');

	// should still point to same location even after array/mod
	assert((const char *)x == (const char *) y);

	x << "8";
	x += "7";
	
	// should not point to same location after append
	assert((const char *)x != (const char *) y);

	assert(x[0]='9');
	assert(x[1]='8');
	assert(x[2]='7');

	assert(x.Length() == 3);

	const char * z = x + 1;

	assert(z[0]=='8');
	assert(z[1]=='7');

	CStr w("abc");
	assert(w.Length() == 3);

	printf("OK\n");

	exit(0);
}
示例#20
0
const ModelResource* PlantScript::PlantRes(int plant0Based, int stage)
{
	GLASSERT(plant0Based >= 0 && plant0Based < NUM_EXTENDED_PLANT_TYPES);
	GLASSERT(stage >= 0 && stage < MAX_PLANT_STAGES);

	if (plantResource[0][0] == 0) {
		for (int i = 0; i < NUM_EXTENDED_PLANT_TYPES; ++i) {
			const int nStage = PlantIsFlower(i) ? PLANT_BLOCKING_STAGE : MAX_PLANT_STAGES;
			for (int j = 0; j < nStage; ++j) {
				CStr<32> str;
				str.Format("plant%d.%d", i, j);
				plantResource[i][j] = ModelResourceManager::Instance()->GetModelResource(str.c_str(), false);
				GLASSERT(plantResource[i][j]);
			}
		}
	}
	GLASSERT(plantResource[plant0Based][stage]);
	return plantResource[plant0Based][stage];
}
示例#21
0
void MapScene::DrawMap()
{
	CDynArray<Chit*> query;

	const ChitContext* context = lumosChitBag->Context();
	const Web& web = lumosChitBag->GetSim()->CalcWeb();

	Rectangle2I subBounds = MapBounds2();
	float map2X = float(subBounds.min.x) / float(NUM_SECTORS);
	float map2Y = float(subBounds.min.y) / float(NUM_SECTORS);
	RenderAtom subAtom = mapImage.GetRenderAtom();
	subAtom.tx0 = map2X;
	subAtom.ty1 = map2Y;
	subAtom.tx1 = map2X + float(MAP2_SIZE) / float(NUM_SECTORS);
	subAtom.ty0 = map2Y + float(MAP2_SIZE) / float(NUM_SECTORS);
	mapImage2.SetAtom(subAtom);

	for (Rectangle2IIterator it(subBounds); !it.Done(); it.Next()) {
		Vector2I sector = it.Pos();
		const SectorData& sd = worldMap->GetSectorData( sector );

		int i = (sector.x - subBounds.min.x);
		int j = (sector.y - subBounds.min.y);
		int index = j * MAP2_SIZE + i;

		CoreScript* coreScript = CoreScript::GetCore(sector);

		CStr<64> str = "";
		const char* owner = "";
		if (coreScript) {
			if ( coreScript->InUse() ) {
				owner = Team::Instance()->TeamName( coreScript->ParentChit()->Team() ).safe_str();
			}
		}
		str.Format( "%s\n%s", sd.name.safe_str(), owner );

		Rectangle2F r = GridBounds2(i, j, true);
		gridWidget[index].SetPos(r.min.x, r.min.y);
		gridWidget[index].SetSize(r.Width(), r.Height());
		gridWidget[index].Set(context, coreScript, lumosChitBag->GetHomeCore(), &web);
	}

	Vector2I homeSector = lumosChitBag->GetHomeSector();
	if ( !data->destSector.IsZero() && data->destSector != homeSector ) {
		const SectorData& sd = worldMap->GetSectorData( data->destSector );
		CStr<64> str;
		str.Format( "Grid Travel\n%s", sd.name.c_str() );
		gridTravel.SetText(  str.c_str() );
		gridTravel.SetEnabled( true );
	}
	else {
		gridTravel.SetText( "Grid Travel" );
		gridTravel.SetEnabled( false );
	}

	// --- MAIN ---
	Rectangle2I mapBounds = data->worldMap->Bounds();
	Rectangle2I map2Bounds;
	map2Bounds.Set(subBounds.min.x*SECTOR_SIZE, subBounds.min.y*SECTOR_SIZE, 
				   subBounds.max.x*SECTOR_SIZE + SECTOR_SIZE-1, subBounds.max.y*SECTOR_SIZE + SECTOR_SIZE-1);

	Vector2F playerPos = { 0, 0 };
	Chit* player = data->player;
	if ( player ) {
		playerPos = ToWorld2F(player->Position());
	}

	const float dx = mapImage.Width() / float(NUM_SECTORS);
	const float dy = mapImage.Height() / float(NUM_SECTORS);
	for (int j = 0; j < NUM_SECTORS; ++j) {
		for (int i = 0; i < NUM_SECTORS; ++i) {
			diplomacy[j*NUM_SECTORS + i].SetSize(dx, dy);
			diplomacy[j*NUM_SECTORS + i].SetPos(mapImage.X() + dx * float(i), mapImage.Y() + dy * float(j));
		}
	}

	bool inBounds = true;
	Vector2F v;

	for (int i = 0; i < 2; ++i) {
		const Rectangle2I& b = (i == 0) ? mapBounds : map2Bounds;

		v = ToUI(i, playerPos, b, &inBounds);
		playerMark[i].SetCenterPos(v.x, v.y);
		playerMark[i].SetVisible(inBounds);

		Vector2F pos = { float(homeSector.x * SECTOR_SIZE), float(homeSector.y * SECTOR_SIZE) };
		v = ToUI(i,pos, b, &inBounds);
		homeMark[i].SetPos(v.x, v.y);
		homeMark[i].SetVisible(inBounds && !homeSector.IsZero());

		pos.Set(float(data->destSector.x * SECTOR_SIZE), float(data->destSector.y * SECTOR_SIZE));
		v = ToUI(i,pos, b, &inBounds);
//		if (i == 0) {
//			travelMark.SetPos(v.x, v.y);
//			travelMark.SetVisible(inBounds && !data->destSector.IsZero());
//		}
		for (int k = 0; k < MAX_SQUADS; ++k) {
			v = ToUI(i, ToWorld2F(data->squadDest[k]), b, &inBounds);
			squadMark[i][k].SetCenterPos(v.x, v.y);
			squadMark[i][k].SetVisible(!data->squadDest[k].IsZero() && inBounds);
		}
	}
	{
		Vector2F world = { (float)map2Bounds.min.x, (float)map2Bounds.min.y };
		Vector2F pos = ToUI(0, world, mapBounds, 0);
		selectionMark.SetPos(pos.x, pos.y);
	}

	float scale = float(mapImage.Width()) / float(NUM_SECTORS);
	{
		webCanvas.Clear();

		for (int i = 1; i < web.NumNodes(); i++) {
			const MinSpanTree::Node& node = web.NodeAt(i);
			Vector2I s0 = node.parentPos;
			Vector2I s1 = node.pos;
			Vector2F p0 = { (float(s0.x) + 0.5f) * scale, (float(s0.y) + 0.5f) * scale };
			Vector2F p1 = { (float(s1.x) + 0.5f) * scale, (float(s1.y) + 0.5f) * scale };
			webCanvas.DrawLine(p0.x, p0.y, p1.x, p1.y, 1.0f + node.strength * 2.0f);
		}
	}

	CoreScript* homeCore = context->chitBag->GetHomeCore();
	CChitArray citizens;
	if (homeCore) {
		homeCore->Citizens(&citizens);
	}
	for (int i = 0; i < MAX_CITIZENS; ++i) {
		if (i < citizens.Size()) {
			Vector2F cPos = ToWorld2F(citizens[i]->Position());
			Vector2F pos = ToUI(0, cPos, mapBounds, 0);
			unitMarker[i].SetSize(8, 8);
			unitMarker[i].SetCenterPos(pos.x, pos.y);
			unitMarker[i].SetVisible(true);
		}
		else {
			unitMarker[i].SetVisible(false);
		}
	}

	for (int j = 0; j < NUM_SECTORS; ++j) {
		for (int i = 0; i < NUM_SECTORS; ++i) {
			diplomacy[i].SetAtom(RenderAtom());

			Vector2I sector = { i, j };
			CoreScript* core = CoreScript::GetCore(sector);
			RenderAtom atom;

			if (core && homeCore && homeCore->InUse() && core->InUse()) {
				ERelate relate = Team::Instance()->GetRelationship(core->ParentChit(), homeCore->ParentChit());
				if (relate == ERelate::FRIEND) atom = LumosGame::CalcUIIconAtom("friend");
				else if (relate == ERelate::NEUTRAL) atom = LumosGame::CalcUIIconAtom("neutral");
				else if (relate == ERelate::ENEMY) atom = LumosGame::CalcUIIconAtom("enemy");
				
				diplomacy[j*NUM_SECTORS + i].SetSize(scale*0.8f, scale*0.8f);
			}

			if (core && core->InUse() && Team::IsDeity(core->ParentChit()->Team())) {
				atom = LumosGame::CalcDeityAtom(core->ParentChit()->Team());
				diplomacy[j*NUM_SECTORS + i].SetSize(scale, scale);
			}

			diplomacy[j*NUM_SECTORS + i].SetAtom(atom);
			diplomacy[j*NUM_SECTORS + i].SetCenterPos(mapImage.X() + scale * (float(i) + 0.5f), mapImage.Y() + scale * (float(j) + 0.5f));
		}
	}
}
示例#22
0
Chit* LumosChitBag::NewBuilding(const Vector2I& pos, const char* name, int team)
{
	const ChitContext* context = Context();
	Chit* chit = NewChit();

	const GameItem& rootItem = ItemDefDB::Instance()->Get(name);
	GameItem* item = rootItem.Clone();

	// Hack...how to do this better??
	if (item->IResourceName() == "pyramid0") {
		CStr<32> str;
		str.Format("pyramid%d", random.Rand(3));
		item->SetResource(str.c_str());
	}
	if (item->IResourceName() == ISC::kiosk) {
		switch (random.Rand(4)) {
			case 0: item->SetResource("kiosk.n");	break;
			case 1: item->SetResource("kiosk.m");	break;
			case 2: item->SetResource("kiosk.s");	break;
			default:item->SetResource("kiosk.c");	break;
		}
	}

	int size = 1;
	rootItem.keyValues.Get(ISC::size, &size);
	int porch = 0;
	rootItem.keyValues.Get(ISC::porch, &porch);
	const int circuit = 0;

	// Should be pre-cleared. But recover from weird situations by clearing.
	// Note that water is a real problem.
	Rectangle2I r;
	r.Set(pos.x, pos.y, pos.x + size - 1, pos.y + size - 1);
	for (Rectangle2IIterator it(r); !it.Done(); it.Next()) {
		const WorldGrid& wg = context->worldMap->GetWorldGrid(it.Pos());
		GLASSERT(wg.IsLand());
		(void)wg;
		context->worldMap->SetRock(it.Pos().x, it.Pos().y, 0, false, 0);
		context->worldMap->SetPlant(it.Pos().x, it.Pos().y, 0, 0);
	}

	MapSpatialComponent* msc = new MapSpatialComponent();
	msc->SetBuilding(size, porch != 0, circuit);
	msc->SetBlocks((rootItem.flags & GameItem::PATH_NON_BLOCKING) ? false : true);
	chit->Add(msc);
	MapSpatialComponent::SetMapPosition(chit, pos.x, pos.y);

	chit->Add(new RenderComponent(item->ResourceName()));
	chit->Add(new HealthComponent());
	AddItem(item, chit, context->engine, team, 0);

	IString script = rootItem.keyValues.GetIString("script");
	if (!script.empty()) {
		Component* s = ComponentFactory::Factory(script.c_str(), &chitContext);
		GLASSERT(s);
		chit->Add(s);
	}

	IString proc = rootItem.keyValues.GetIString("procedural");
	if (!proc.empty()) {
		ProcRenderInfo info;
		AssignProcedural(chit->GetItem(), &info);
		chit->GetRenderComponent()->SetProcedural(0, info);
	}

	IString consumes = rootItem.keyValues.GetIString(ISC::zone);
	if (!consumes.empty()) {
		Component* s = ComponentFactory::Factory("EvalBuildingScript", &chitContext);
		GLASSERT(s);
		chit->Add(s);
	}

	IString nameGen = rootItem.keyValues.GetIString( "nameGen");
	if ( !nameGen.empty() ) {
		IString p = Context()->chitBag->NameGen(nameGen.c_str(), chit->random.Rand());
		chit->GetItem()->SetProperName( p );
	}

#if 0	// debugging
	SectorPort sp;
	sp.sector.Set( pos.x/SECTOR_SIZE, pos.y/SECTOR_SIZE );
	sp.port = 1;
	worldMap->SetRandomPort( sp );
#endif

	context->engine->particleSystem->EmitPD( ISC::constructiondone, ToWorld3F( pos ), V3F_UP, 0 );

	if (XenoAudio::Instance()) {
		Vector3F pos3 = ToWorld3F(pos);
		XenoAudio::Instance()->PlayVariation(ISC::rezWAV, random.Rand(), &pos3);
	}

	return chit;
}
示例#23
0
MapScene::MapScene( LumosGame* game, MapSceneData* data ) : Scene( game ), lumosGame(game)
{
	InitStd( &gamui2D, &okay, 0 );

	lumosChitBag = data->lumosChitBag;
	worldMap     = data->worldMap;
	player       = data->player;
	this->data   = data;

	gridTravel.Init( &gamui2D, lumosGame->GetButtonLook(0) );
	viewButton.Init(&gamui2D, lumosGame->GetButtonLook(0));
	viewButton.SetText("View");

	warButton.Init(&gamui2D, lumosGame->GetButtonLook(0));
	warButton.SetText("War!");
	peaceButton.Init(&gamui2D, lumosGame->GetButtonLook(0));
	peaceButton.SetText("Peace\nTreaty");

	Texture* mapTexture = TextureManager::Instance()->GetTexture( "miniMap" );
	RenderAtom mapAtom( (const void*)UIRenderer::RENDERSTATE_UI_GRAYSCALE_OPAQUE, (const void*)mapTexture, 0, 1, 1, 0 );
	mapImage.Init( &gamui2D, mapAtom, false );
	mapImage.SetCapturesTap( true );
	
	Rectangle2I sectorBounds = MapBounds2();
	Rectangle2F map2Bounds = ToWorld2F(sectorBounds);

	mapAtom.tx0 = map2Bounds.min.x / float(worldMap->Width());
	mapAtom.ty0 = map2Bounds.max.y / float(worldMap->Height());
	mapAtom.tx1 = map2Bounds.max.x / float(worldMap->Width());
	mapAtom.ty1 = map2Bounds.min.y / float(worldMap->Height());

	mapAtom.renderState = (void*)UIRenderer::RENDERSTATE_UI_DECO;
	mapImage2.Init( &gamui2D, mapAtom, false );
	mapImage2.SetCapturesTap( true );

	RenderAtom atom = lumosGame->CalcPaletteAtom( PAL_TANGERINE*2, PAL_ZERO );
	playerMark[0].Init( &gamui2D, atom, true );
	playerMark[1].Init( &gamui2D, atom, true );

	atom = lumosGame->CalcPaletteAtom(PAL_GRAY * 2, PAL_GRAY);
	atom.renderState = (const void*)UIRenderer::RENDERSTATE_UI_DECO_DISABLED;
	homeMark[0].Init( &gamui2D, atom, true );
	homeMark[1].Init( &gamui2D, atom, true );

	for (int i = 0; i < MAX_SQUADS; ++i) {
		static const char* NAME[MAX_SQUADS] = { "alphaMark", "betaMark", "deltaMark", "omegaMark" };
		RenderAtom atom = lumosGame->CalcUIIconAtom(NAME[i], true);
		squadMark[0][i].Init(&gamui2D, atom, true);
		squadMark[1][i].Init(&gamui2D, atom, true);
	}

	for (int i = 0; i < NUM_SECTORS*NUM_SECTORS; ++i) {
		diplomacy[i].Init(&gamui2D, RenderAtom(), true);
	}

//	RenderAtom travelAtom = lumosGame->CalcPaletteAtom( PAL_GRAY*2, PAL_ZERO );
//	travelAtom.renderState = (const void*)UIRenderer::RENDERSTATE_UI_DECO_DISABLED;
//	travelMark.Init( &gamui2D, travelAtom, true );

	RenderAtom selectionAtom = lumosGame->CalcUIIconAtom("mapSelection", true);
	selectionMark.Init(&gamui2D, selectionAtom, true);

	for( int i=0; i<MAP2_SIZE2; ++i ) {
		gridWidget[i].Init(&gamui2D);
	}

	webCanvas.Init(&gamui2D, LumosGame::CalcPaletteAtom(PAL_GRAY * 2, PAL_GRAY));
	webCanvas.SetLevel(Gamui::LEVEL_ICON);

	RenderAtom unitAtom = LumosGame::CalcUIIconAtom("unitMarker");
	for (int i = 0; i < MAX_CITIZENS; ++i) {
		unitMarker[i].Init(&gamui2D, unitAtom, true);
	}

	for (int i = 1; i < NUM_SECTORS; ++i) {
		numbers[i].Init(&gamui2D);
		letters[i].Init(&gamui2D);
		CStr<16> str;
		str.Format("%c", 'A' + i);
		letters[i].SetText(str.c_str());
		str.Format("%d", i+1);
		numbers[i].SetText(str.c_str());
	}
}
int	bs_PostpSession::callBsSignup(
			 c_NvRecord& nvrec,	string sversion )
{
	CSimpleCallObj	simple_rpcobj;
	JRPCClient		clnt;
	NVMap			*m = simple_rpcobj.GetInputMap();
	CStr			output;
	char *callName = NULL;

	/* preconditions */
	if (host.empty() || port <=0 || program_name.empty())
	{
		fprintf(stderr,	"Connection info needs to be set before using callBsSignup ....");
		return CONFIG_ERROR;
	}

	/* get version */
	PostpVersion		 version = this->getVersionNumber(sversion);
	if (version==v_undef)
	{
		fprintf(stderr,	"This version is unknown: %s (%d)", sversion.c_str(), (int)version);
		return CONFIG_ERROR;
	}

	/* All versions	use	these fields --	even upgrade */
	PUT_PARAM(Juno_Username);
	PUT_PARAM(Ad_Number);
	PUT_PARAM(Request_Source);
	PUT_PARAM(Client_Version);
	PUT_PARAM(MachineID);

	/* Only	signups	use	these fields */
	if (version	== v8_S)
	{
		PUT_PARAM(Contact_LastName);
		PUT_PARAM(Contact_FirstName);
		PUT_PARAM(Contact_MiddleInitial);
		PUT_PARAM(Contact_Address1);
		PUT_PARAM(Contact_Address2);
		PUT_PARAM(Contact_City);
		PUT_PARAM(Contact_State);
		PUT_PARAM(Contact_ZipCode);
		PUT_PARAM(Billing_CardNumber);
		PUT_PARAM(Billing_CardExpiration);
		PUT_PARAM(Day_Phone);
		PUT_PARAM(Evening_Phone);
		PUT_PARAM(Billing_LastName);
		PUT_PARAM(Billing_FirstName);
		PUT_PARAM(Billing_MiddleInitial);
		PUT_PARAM(Billing_Address1);
		PUT_PARAM(Billing_Address2);
		PUT_PARAM(Billing_City);
		PUT_PARAM(Billing_State);
		PUT_PARAM(Billing_ZipCode);
		PUT_PARAM(Broadband_Key);
		PUT_PARAM(Contact_Country);
		PUT_PARAM(Billing_Country);
		PUT_PARAM(Brand_Code);
		PUT_PARAM(Bill_Type);
		PUT_PARAM(Bill_Type_Args);
		PUT_PARAM(Billing_Account_Type);
		PUT_PARAM(Action);
		PUT_PARAM(Serial_Num);
		PUT_PARAM(Referrer);
		PUT_PARAM(Referral_Program);
		PUT_PARAM(Requested_Deals);
		PUT_PARAM(Drop_Deals);
		PUT_PARAM(Cancel_User);
		PUT_PARAM(XFuture_Date);
		PUT_PARAM(Member_Number);
		PUT_PARAM(Requested_Services);
		PUT_PARAM(Drop_Services);
		PUT_PARAM(Cancel_Member_Number);
		PUT_PARAM(CVM);
		PUT_PARAM(TopUpAmount);
		callName   = (char *)MPB_SIGNUP_CALL_NAME;

	}
	else if	(version ==	v8_T)	
	{
		m->PutVal("Juno_Password", INVALID_STR);
		PUT_PARAM(Serial_Num);
		PUT_PARAM(Requested_Deals);
		PUT_PARAM(Drop_Deals);
		PUT_PARAM(Action);
		PUT_PARAM(Cancel_User);
		PUT_PARAM(XFuture_Date);
		PUT_PARAM(Member_Number);
		PUT_PARAM(Requested_Services);
		PUT_PARAM(Drop_Services);
		PUT_PARAM(Cancel_Member_Number);
		PUT_PARAM(CVM);
		PUT_PARAM(TopUpAmount);
		callName   = (char *)MPB_TRANSITION_CALL_NAME;
	} else {
		logfile.printf("This version is no longer supported: %s", sversion.c_str());
		return CONFIG_ERROR;
	}

	/* Basically, this will	never fail */
	if (clnt.Init(this->host.c_str(),	port, CALL_TIMEOUT)	!= SUCCESS)	{
		logfile.printf("s:	JRPCClient::Init() failed.", "bs_PostpSession");
		logfile.printf("%s:	host = %s, port	= %u", program_name,
			host, port);
		logfile.printf("%d||", (int) BS_SIGNUP_REQUEUE_FAILURE);
		return CONNECT_ERROR;
	}

	if (clnt.Call(callName,	&simple_rpcobj)	!= SUCCESS)	{
		logfile.printf("%s:	rpc	failed.\n",	"bs_PostpSession");
		logfile.printf("%d||", (int) BS_SIGNUP_REQUEUE_FAILURE);
		return CONNECT_ERROR;
	}

	output.Format("%s|%s|%s", simple_rpcobj.GetCode(),	simple_rpcobj.GetRequestedMpv(), 
		simple_rpcobj.GetInitialMpv());

	logfile.Close(FALSE);

	int rc = 999;
	const char * rs = simple_rpcobj.GetCode();

	if (rs)
		rc=atoi(rs);
	else
		logfile.printf("Can not get a return code from: %s\n", rs );

	return rc;
}
示例#25
0
/**
\brief Executa os processos de leitura de arquivos e inserção no banco
\details	
	Funções executadas neste método:
	- Ler cada arquivo que necessita de atualização da lista;
	- Indicar o nome do arquivo de estrutura de dados;
	- Apagar os registros das tabelas a serem atualizadas;
	- Indicar quais dados de arquivo(tabela) deve ser baixada da internet;
	- Criar a barra de progresso para cada ítem da lista;
	- Inserir os valores no banco de dados;
	- Iniciar a atualização das séries

	Erros que causam a saída deste método:
	- Erro ao indicar o nome do arquivo de estrutura;
	- Erro ao indicar um arquivo a ser baixado da internet;
	- Erro ao apagar dados da tabela;
	- Erro ao inserir dados na tabela;
	- Erro ao enviar pedido de atualização de séries.

\param LPCTSTR szSystem: Nome do sistema que serão criadas as tabelas
\return void.
*/
void CUpdateDlg::_Process(LPCTSTR szSystem)
{
	SetStatus(L"Processando as atualizações...");

	CString strSys = szSystem;
	_FIELDS_ meu_registro;
	CString nomeTabela , insertCommand, sApagaTabela;
	TB_ATUALIZACAO *dadoArquivo = NULL;
	CGetFile *fileAtualiza;

	int errors = 0;

	HCURSOR hCurs = GetCursor();
	SetCursor(LoadCursor(NULL, IDC_WAIT));

	CString sContrato = m_params->GetValue(L"contrato");
	CString sVarPma = L"transmite_" + strSys;
	CString sURL = m_params->GetValue(sVarPma);
	if(sURL.IsEmpty())
	{
		STLOG_WRITE("CUpdateDlg::_Process(): url 'transmite' esta vazia.");
	}

	//::MessageBox( NULL, (CString) this->getNomeTabela(), L"TESTE", MB_OK );
	
	for( int i = 0; i < m_list.GetItemCount() ; i++)
	{
		nomeTabela = m_list.GetItemText(i,0);
		nomeTabela.Trim();

		fileAtualiza = new CGetFile();
		fileAtualiza->SetStructFile(m_sStructPath);
		if(!fileAtualiza->SetNomeTabela(nomeTabela))
		{
			errors++;
			m_list.SetProgress(i, 0);
			STLOG_WRITE(L"CUpdateDlg::_Process(): Error setando lista %s", nomeTabela);
			STLOG_WRITE("----------------------------------------------------------");
			continue;
		}		

		if(! fileAtualiza->GetFileFromServer(sURL, sContrato))
		{
			errors++;
			m_list.SetProgress(i, 0);
			STLOG_WRITE(L"CUpdateDlg::_Process(): Error Download %s", nomeTabela);
			STLOG_WRITE("----------------------------------------------------------");
			continue;
		}

		CTableBase::BeginTransaction(CppSQLite3DB::getInstance());

		//TODO: If migração não apaga
		//sApagaTabela.Format( L"DELETE FROM %s", nomeTabela );
		sApagaTabela.Format( L"DROP TABLE %s", nomeTabela );

		try
		{
			CppSQLite3DB::getInstance()->execQuery( CStr(sApagaTabela) );
		}
		catch(CppSQLite3Exception e)
		{
			errors++;
			STLOG_WRITE("CUpdateDlg::_Process(): %s", e.errorMessage());
			STLOG_WRITE(sApagaTabela);
			STLOG_WRITE("----------------------------------------------------------");
			continue;
		}

		m_manageDB->CreateOneTable(nomeTabela);

		BOOL failed = FALSE;
		int count;

		for(count=0; !fileAtualiza->IsEOF(); count++)
		{
			if ((count%2000) == 0)
			{
				Sleep(2000);
			}

			fileAtualiza->GetRecord(&meu_registro);
			insertCommand = fileAtualiza->sqlInsertCommand;

			try
			{
				CppSQLite3DB::getInstance()->execQuery( CStr(insertCommand) );
				m_list.SetProgress(i, (int)(100*(count+1)/fileAtualiza->GetTotalRegs()));
			}
			catch(CppSQLite3Exception e)
			{
				STLOG_WRITE(L"CUpdateDlg::_Process(1): %S", e.errorMessage());
				STLOG_WRITE(insertCommand);
				STLOG_WRITE("----------------------------------------------------------");

				errors++;
				failed = TRUE;
				CTableBase::RollbackTransaction(CppSQLite3DB::getInstance());
				m_list.SetProgress(i, 0);

				break;
			}

			fileAtualiza->MoveNext();
		}

		if(count == 0 || errors == 0)
			m_list.SetProgress(i, 100);

		m_listaArquivos.Lookup(nomeTabela, dadoArquivo);

		//TODO: If migracao não atualiza
		if(!failed)
		{
			CStr sQuery;
			sQuery.Format("INSERT INTO atualizacao VALUES ('%S', '%S', '%S')",
						  dadoArquivo->nome.Trim(), 
						  dadoArquivo->data,
						  dadoArquivo->hora );

			try
			{
				CppSQLite3DB::getInstance()->execQuery( sQuery );
				CTableBase::CommitTransaction(CppSQLite3DB::getInstance());
			}
			catch(CppSQLite3Exception e)
			{
				errors++;
				m_list.SetProgress(i, 0);
				CTableBase::RollbackTransaction(CppSQLite3DB::getInstance());
				STLOG_WRITE(L"CUpdateDlg::_Process(2): %S", e.errorMessage());
				STLOG_WRITE(insertCommand);
				STLOG_WRITE("----------------------------------------------------------");
			}
		}
		delete(fileAtualiza);
	}

	if(errors > 0)
	{
		errors = 0;
		SetCursor(hCurs);
		CString sErr;
		sErr.LoadStringW(IDS_ERRO_ATUALIZACAO);
		MessageBox(sErr, L"Mensagem", MB_ICONINFORMATION|MB_OK);

		// Aplicacao nao continua...
		return;
	}

	m_wnd->Show(L"Processando atualizações...");

	SetCursor(hCurs);

	m_wnd->Hide();

	SetStatus(L"Atualização encerrada com sucesso");
	Sleep(1000);

	return;
}
示例#26
0
int smtp_next(qMailState *state, CStr &request)
{
// control
	switch (state->proto) {
	case qsOpen:
		state->errs = 0;
		state->proto = qsEhlo; 
		break;
	case qsEhlo:
		state->proto = iserror(state->code) ? qsHelo : qsMail; 
		break;
	case qsHelo:
		state->proto = iserror(state->code) ? (++state->errs, qsHelo) : qsMail; 
		break;
	case qsMail:
		state->cur_buf = smtp_rcpt_next(state, 1);
		state->cur_len = state->cur_buf ? strlen(state->cur_buf) : 0;
		state->proto = iserror(state->code) ? (++state->errs, qsMail) : qsRcpt; 
		break;

	case qsRcpt:
		if (iserror(state->code)) 
			smtp_rcpt_error(state->cur_buf);
		else 
			state->errs = 0;

		state->cur_buf = smtp_rcpt_next(state);
		if (!state->cur_buf) 
			state->proto = qsData;
		state->cur_len = state->cur_buf ? strlen(state->cur_buf) : 0;
		break;
	case qsData:
		state->proto = iserror(state->code) ? (++state->errs, qsData) : qsBlock;
		state->cur_buf = NULL;
		state->cur_buf = smtp_data_next(state, 1, state->cur_len);
		break;
	case qsBlock:
		if (iserror(state->code))
			++state->errs;
		else
			state->cur_buf = smtp_data_next(state, 0, state->cur_len);
		if (!state->cur_buf) 
			state->proto = qsEOF;
		break;
	case qsEOF:
		state->proto = qsQuit;
		break;
	case qsQuit:
		state->proto = 0;
		break;
	}

// format request
	switch (state->proto) {
	case qsEhlo:
		request.Format("EHLO %s\r\n", state->opts->helo); break;
	case qsHelo:
		request.Format("HELO %s\r\n", state->opts->helo); break;
	case qsMail:
    if (state->opts->from) {
      request = "MAIL FROM:<" << state->opts->from << ">\r\n";
    } else {
      request = "MAIL FROM:<>\r\n";
    }
    break;
	case qsRcpt:
  		if (state->cur_buf)
        request.Format("RCPT TO:<%s>\r\n", state->cur_buf);
      break;
	case qsData:
		request = "DATA\r\n"; break;
	case qsBlock:
		request = CStr(state->cur_buf, state->cur_len); break;
	case qsEOF:
		request = "\r\n.\r\n"; break;
	case qsQuit:
		request = "QUIT\r\n"; break;
	}

	return state->errs;
}
示例#27
0
//------------------------------------------------------------------------------
/// \brief Reads 3. Data: ITMP
/// \brief Reads 4. Data: WELLID Qdes {CapMult} {Cprime} {xyz}
//------------------------------------------------------------------------------
void ProcessorMNW2::impl::ReadStressPeriods (std::fstream& a_is,
                                             std::fstream& a_os)
{
  CStr str;
  std::string line;
  EReadAsciiFile e;
  e.UseExceptions();
  while (!a_is.bad())
  {
    std::getline(a_is, line);
    if (line.empty())
    {
      return;
    }

    int ITMP;
    a_os << line << "\n";
    e.SetLine(line.c_str());
    e.ReadData(ITMP);
    if (ITMP < 1)
      continue;

    std::getline(a_is, line);
    e.SetLine(line.c_str());
    e.ReadData(str);
    if ("GMS_HDF5_01" == str)
    {
      CStr fname, path;
      int sp;
      e.ReadData(fname);
      e.ReadData(path);
      path += "/07. Property";
      e.ReadData(sp);
      std::pair<int, int> myPair(0,1);
      VEC_INT_PAIR indices(3, myPair);
      indices[0].second = numMnw2Prop();
      indices[1].second = m_MNWMAX;
      indices[2].first = sp - 1;
      H5DataSetReader r(fname, path, indices);
      CAR_DBL2D vals;
      vals.SetSize(MNW2::NPROP, m_MNWMAX, 0);
      if (!r.GetData(&vals[0][0], MNW2::NPROP*m_MNWMAX))
      {
        ErrorStack::Get().PutError("Unable to read MNW2 hdf5 data.");
        throw ioError("");
      }

      for (int i = 0; i<m_MNWMAX; i++)
      {
        if (vals.at(MNW2::ACTIVE, i) != 0)
        { // this well is active
          // 4a. Data: WELLID Qdes {CapMult} {Cprime} {xyz}
          CStr ln;
          ln.Format("'%s' %s", m_wells.at(i).m_WELLID,
                               STR(vals.at(MNW2::QDES, i)));
          if (m_wells.at(i).m_PUMPCAP > 0)
          {
            ln += " ";
            ln += STR(vals.at(MNW2::CAPMULT, i));
          }
          // don't write Cprime

          // get AUX
          for (int j = 0; j<m_nAUX; j++)
          {
            ln += " ";
            ln += STR(vals.at(MNW2::AUX_0+j, i));
          }
          a_os << ln << "\n";

          if (m_wells.at(i).m_Qlimit < 0)
          {
            double QCUT = vals.at(MNW2::QCUT, i);
            ln.Format("%s %s", STR(vals.at(MNW2::HLIM, i)), STR(QCUT));
            if (QCUT != 0)
            {
              CStr ln2;
              ln2.Format(" %s %s", STR(vals.at(MNW2::QFRCMN, i)),
                                   STR(vals.at(MNW2::QFRCMX, i)));
              ln += ln2;
            }
            a_os << ln << "\n";
          }
        }
      }
    }
  }
} // ProcessorMNW2::impl::ReadStressPeriods