Esempio n. 1
0
File: package.cpp Progetto: hyln9/nV
var Ctx2(const wchar *x)
{
	if(x[0] == L'`')
	{
		wstring t = ContextName[Context()];
		t.append(++x);
		return Ctx(t);
	}
	return Ctx(x);
}
 static void test3()
  {
   PrintCon out(Con);
   
   for(unsigned sw=0; sw<=Len ;sw++)
     Meta::TypeSwitch<Ret>::Switch(sw,Ctx());
  }
Esempio n. 3
0
bool CXMLElement::ParseEntityTable (IMemoryBlock &Stream, CExternalEntityTable *retEntityTable, CString *retsError)

//	ParseEntityTable
//
//	This function parses only the entity table

	{
	//	Initialize context

	ParserCtx Ctx(Stream, NULL);

	//	Parse the prologue

	if (!ParsePrologue(&Ctx))
		{
		*retsError = strPattern("Line(%d): %s", Ctx.iLine, Ctx.sError);
		return false;
		}

	//	Done

	if (retEntityTable)
		retEntityTable->AddTable(Ctx.EntityTable);

	return true;
	}
Esempio n. 4
0
bool CShieldClass::GetReferenceDamageAdj (const CItem *pItem, CSpaceObject *pInstalled, int *retiHP, int *retArray) const

//	GetReferenceDamageAdj
//
//	Returns an array of damage adj values

	{
	CItemCtx Ctx(pItem, pInstalled);
	int i;

	const CItemEnhancement &Mods = Ctx.GetMods();

	int iMinHP, iMaxHP;
	CalcMinMaxHP(Ctx, m_iMaxCharges, 0, 0, &iMinHP, &iMaxHP);

	if (retiHP)
		*retiHP = iMaxHP;

	if (retArray)
		{
		for (i = 0; i < damageCount; i++)
			{
			DamageDesc Damage((DamageTypes)i, DiceRange(0, 0, 0));
			int iAdj = GetDamageAdj(Mods, Damage);
			if (iAdj == 0)
				retArray[i] = -1;
			else
				retArray[i] = (int)((iMaxHP * 100.0 / iAdj) + 0.5);
			}
		}

	return true;
	}
Esempio n. 5
0
void CEsperEngine::OnConnect (const SArchonMessage &Msg, CSocket &NewSocket, const CString &sListener, CEsperConnection::ETypes iType)

//	OnConnect
//
//	A listener thread has received a connection.

	{
	CEsperConnectionManager::SConnectionCtx Ctx(Msg, m_DefaultSSLCtx);
	m_Connections.CreateConnection(Ctx, NewSocket, sListener, iType);
	}
Esempio n. 6
0
Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer<QApplication> App(createApplication(argc, argv));

    QTranslator Translator;
    if (!Translator.load("tr_"+QLocale::system().name(), ":/i18n"))
        Translator.load("tr_en", ":/i18n");
    App->installTranslator(&Translator);

    ConTranslator ConsoleMsgs;
    ConsoleMsgs.load("conmsgs", ":/i18n");
    App->installTranslator(&ConsoleMsgs);

    IconProvider::SetToCurrentSystemTheme();

    Context Ctx(argc, argv);
    ScopedIntercomHandler Intercom;

    if (Ctx.IfExit())
        return Intercom->GetExitCode();

    {
        ModesModel ModesList(Ctx.CheckMode(), Ctx.CheckMode()==RunModes::PRINT);
        UsersModel UsersList(Ctx.GetTargetUser(), Ctx.CheckMode()==RunModes::PRINT);
        DesktopModel AppList;
        PswTools PassCheck;
        QmlApplicationViewer Viewer;

        qmlRegisterUncreatableType<RunModes>("com.lcferrum.hmtsu", 1, 0, "RunModes", "Exports RunModes enum to QML");
        Viewer.engine()->addImageProvider("icon", new IconProvider());      //It is QDeclarativeEngine's responsibility to destroy added image providers
        Viewer.rootContext()->setContextProperty("objModesList", &ModesList);
        Viewer.rootContext()->setContextProperty("objUsersList", &UsersList);
        Viewer.rootContext()->setContextProperty("objAppList", &AppList);
        Viewer.rootContext()->setContextProperty("objContext", &Ctx);
        Viewer.rootContext()->setContextProperty("objIntercom", &Intercom);
        Viewer.rootContext()->setContextProperty("objPassCheck", &PassCheck);
        Viewer.rootContext()->setContextProperty("HMTSU_VERSION_STRING", HMTSU_VERSION_STRING IF_DEBUG(" (DEBUG)"));
        Viewer.rootContext()->setContextProperty("HMTSU_COPYRIGHT_STRING", HMTSU_COPYRIGHT_STRING);
        Viewer.rootContext()->setContextProperty("CANCELED_EXIT_CODE", CANCELED_EXIT_CODE);
        Viewer.rootContext()->setContextProperty("DENIED_EXIT_CODE", DENIED_EXIT_CODE);
        Viewer.rootContext()->setContextProperty("NORMAL_EXIT_CODE", NORMAL_EXIT_CODE);
        Viewer.rootContext()->setContextProperty("MAX_PSW_ATTEMPTS", MAX_PSW_ATTEMPTS);

        Viewer.setSource(QUrl("qrc:/main.qml"));

        Viewer.showExpanded();

        App->exec();
    }

    Ctx.Run();

    return Intercom->GetExitCode();
}
Esempio n. 7
0
File: package.cpp Progetto: hyln9/nV
var Sym2(const wchar *x)
{
	const wchar *c = wcsrchr(x,L'`');
	if(c)
	{
		wstring t;
		if(x[0] == L'`')
		{
			t.append(ContextName[Context()]);
			++x;
		}
		t.append(x,++c);
		return Sym(c,Ctx(t));
	}
	return Sym(x);
}
Esempio n. 8
0
TEST_F(ContextTest, FromDeviceType) {
  cl_context_properties *DefaultProps = GetProps();

  // Setup the filter on the CPU device -- it is the only device always
  // available.
  cl::Context Ctx(CL_DEVICE_TYPE_CPU, DefaultProps);

  std::vector<cl::Device> Devs = Ctx.getInfo<CL_CONTEXT_DEVICES>();

  // 1) Workaround for silence a googletest warning.
  // 2) The CPU device is the default device in OpenCRun.
  cl_device_type ExpectedDevTy = CL_DEVICE_TYPE_CPU | CL_DEVICE_TYPE_DEFAULT;

  EXPECT_EQ(1u, Ctx.getInfo<CL_CONTEXT_NUM_DEVICES>());
  EXPECT_EQ(1u, Devs.size());
  EXPECT_EQ(ExpectedDevTy, Devs[0].getInfo<CL_DEVICE_TYPE>());
}
Esempio n. 9
0
bool CXMLElement::ParseXML (IMemoryBlock &Stream, 
							   IXMLParserController *pController,
							   CXMLElement **retpElement, 
							   CString *retsError,
							   CExternalEntityTable *retEntityTable)

//	ParseXML
//
//	Parses the block and returns an XML element

	{
	//	Initialize context

	ParserCtx Ctx(Stream, pController);

	//	Parse the prologue

	if (!ParsePrologue(&Ctx))
		{
		*retsError = strPattern("Line(%d): %s", Ctx.iLine, Ctx.sError);
		return false;
		}

	//	Next token must be an element open tag

	if (Ctx.iToken != tkTagOpen)
		{
		*retsError = strPattern("Line(%d): root element expected.", Ctx.iLine);
		return false;
		}

	//	Parse the root element

	if (!ParseElement(&Ctx, retpElement))
		{
		*retsError = strPattern("Line(%d): %s", Ctx.iLine, Ctx.sError);
		return false;
		}

	//	Done

	if (retEntityTable)
		retEntityTable->AddTable(Ctx.EntityTable);

	return true;
	}
Esempio n. 10
0
bool CXMLElement::ParseRootElement (IMemoryBlock &Stream, CXMLElement **retpRoot, CExternalEntityTable *retEntityTable, CString *retsError)

//	ParseRootElement
//
//	Parses the entity definitions and the root element (but not the contents
//	of the root element).

	{
	//	Initialize context

	ParserCtx Ctx(Stream, NULL);

	//	Parse the prologue

	if (!ParsePrologue(&Ctx))
		{
		*retsError = strPattern("Line(%d): %s", Ctx.iLine, Ctx.sError);
		return false;
		}

	//	Next token must be an element open tag

	if (Ctx.iToken != tkTagOpen)
		{
		*retsError = strPattern("Line(%d): Root element expected.", Ctx.iLine);
		return false;
		}

	//	Parse the root element

	Ctx.m_bParseRootElement = true;
	if (!ParseElement(&Ctx, retpRoot))
		{
		*retsError = strPattern("Line(%d): %s", Ctx.iLine, Ctx.sError);
		return false;
		}

	//	Done

	if (retEntityTable)
		retEntityTable->AddTable(Ctx.EntityTable);

	return true;
	}
Esempio n. 11
0
bool CXMLElement::ParseRootTag (IMemoryBlock &Stream, CString *retsTag)

//	ParseRootTag
//
//	This function parses only enough to determine the root tag, either by reading
//	as far as the first open tag or by getting the DOCTYPE.
//
//	This function is a hack to allow Transcendence to read the root tag for an
//	extension without loading the whole file.

	{
	//	Initialize context

	ParserCtx Ctx(Stream, NULL);
	Ctx.m_bParseRootTag = true;

	//	Parse the prologue

	if (!ParsePrologue(&Ctx))
		return false;

	if (!Ctx.m_sRootTag.IsEmpty())
		{
		*retsTag = Ctx.m_sRootTag;
		return true;
		}

	//	Next token must be an element open tag

	if (Ctx.iToken != tkTagOpen)
		return false;

	//	Parse the root element name

	if (ParseToken(&Ctx) != tkText)
		return false;

	*retsTag = Ctx.sToken;

	//	Done

	return true;
	}
Esempio n. 12
0
TEST_F(ContextTest, FromDeviceList) {
  cl::Device Dev = GetDevice();
  cl_context_properties *DefaultProps = GetProps();

  cl::Context Ctx(std::vector<cl::Device>(1, Dev), DefaultProps);

  std::vector<cl::Device> Devs = Ctx.getInfo<CL_CONTEXT_DEVICES>();

  std::vector<cl_context_properties> Props;
  Props = Ctx.getInfo<CL_CONTEXT_PROPERTIES>();

  EXPECT_EQ(1u, Ctx.getInfo<CL_CONTEXT_NUM_DEVICES>());
  EXPECT_EQ(1u, Devs.size());

  // Note: the following check make sense only into OpenCRun.
  EXPECT_EQ(Dev(), Devs[0]());

  EXPECT_EQ(3u, Props.size());

  // Unroll the checking loop by hand, to provide better error reporting.
  EXPECT_EQ(DefaultProps[0], Props[0]);
  EXPECT_EQ(DefaultProps[1], Props[1]);
  EXPECT_EQ(DefaultProps[2], Props[2]);
}
Esempio n. 13
0
void CUIHelper::PaintItemEntry (CG16bitImage &Dest, CSpaceObject *pSource, const CItem &Item, const RECT &rcRect, DWORD dwOptions) const

//	PaintItemEntry
//
//	Paints an item entry suitable for an item list.

	{
	const CVisualPalette &VI = m_HI.GetVisuals();
	const CG16bitFont &LargeBold = VI.GetFont(fontLargeBold);
	const CG16bitFont &Medium = VI.GetFont(fontMedium);
	WORD wColorTitle = VI.GetColor(colorTextHighlight);
	WORD wColorRef = VI.GetColor(colorTextHighlight);
	WORD wColorDescSel = CG16bitImage::RGBValue(200,200,200);
	WORD wColorDesc = CG16bitImage::RGBValue(128,128,128);

	bool bSelected = ((dwOptions & OPTION_SELECTED) == OPTION_SELECTED);
	bool bNoIcon = ((dwOptions & OPTION_NO_ICON) == OPTION_NO_ICON);
	bool bTitle = ((dwOptions & OPTION_TITLE) == OPTION_TITLE);

	//	Item context

	CItemCtx Ctx(&Item, pSource);
	CItemType *pItemType = Item.GetType();

	//	Calc the rect where we will draw

	RECT rcDrawRect = rcRect;
	rcDrawRect.left += ITEM_TEXT_MARGIN_X;
	rcDrawRect.right -= ITEM_TEXT_MARGIN_X;
	rcDrawRect.top += ITEM_TEXT_MARGIN_Y;

	//	Paint the image

	if (!bNoIcon)
		{
		DrawItemTypeIcon(Dest, rcRect.left, rcRect.top, pItemType);
		rcDrawRect.left += ICON_WIDTH;
		}

	//	Paint the item name

	DWORD dwNounPhraseFlags = nounNoModifiers;
	if (bTitle)
		dwNounPhraseFlags |= nounTitleCapitalize | nounShort;
	else
		dwNounPhraseFlags |= nounCount;

	int cyHeight;
	RECT rcTitle = rcDrawRect;
	LargeBold.DrawText(Dest,
			rcTitle,
			wColorTitle,
			Item.GetNounPhrase(dwNounPhraseFlags),
			0,
			CG16bitFont::SmartQuotes | CG16bitFont::TruncateLine,
			&cyHeight);

	rcDrawRect.top += cyHeight;
	if (bTitle)
		rcDrawRect.top += ITEM_TITLE_EXTRA_MARGIN;

	//	Paint the display attributes

	TArray<SDisplayAttribute> Attribs;
	if (Item.GetDisplayAttributes(Ctx, &Attribs))
		{
		FormatDisplayAttributes(Attribs, rcDrawRect, &cyHeight);
		PaintDisplayAttributes(Dest, Attribs);
		rcDrawRect.top += cyHeight + ATTRIB_SPACING_Y;
		}

	//	Stats

	CString sStat;

	int iLevel = pItemType->GetApparentLevel();
	CString sReference = pItemType->GetReference(Ctx);
	DamageTypes iDamageType;
	CString sDamageRef;
	int iDamageAdj[damageCount];
	int iHP;

	if (Item.GetReferenceDamageType(pSource, -1, 0, &iDamageType, &sDamageRef))
		{
		//	Paint the damage type reference

		PaintReferenceDamageType(Dest,
				rcDrawRect.left + DAMAGE_ADJ_SPACING_X,
				rcDrawRect.top,
				iDamageType,
				sDamageRef);

		rcDrawRect.top += Medium.GetHeight();

		//	Paint additional reference in the line below

		if (!sReference.IsBlank())
			{
			Medium.DrawText(Dest, 
					rcDrawRect,
					wColorRef,
					sReference,
					0,
					0,
					&cyHeight);

			rcDrawRect.top += cyHeight;
			}
		}
	else if (Item.GetReferenceDamageAdj(pSource, 0, &iHP, iDamageAdj))
		{
		//	Paint the initial text

		sStat = strPatternSubst("hp: %d ", iHP);
		int cxWidth = Medium.MeasureText(sStat, &cyHeight);
		Medium.DrawText(Dest, 
				rcDrawRect,
				wColorRef,
				sStat,
				0,
				0,
				&cyHeight);

		//	Paint the damage type array

		PaintReferenceDamageAdj(Dest,
				rcDrawRect.left + cxWidth + DAMAGE_ADJ_SPACING_X,
				rcDrawRect.top,
				iLevel,
				iHP,
				iDamageAdj);

		rcDrawRect.top += cyHeight;

		//	Paint additional reference in the line below

		if (!sReference.IsBlank())
			{
			Medium.DrawText(Dest, 
					rcDrawRect,
					wColorRef,
					sReference,
					0,
					0,
					&cyHeight);

			rcDrawRect.top += cyHeight;
			}
		}
	else
		{
		Medium.DrawText(Dest, 
				rcDrawRect,
				wColorRef,
				sReference,
				0,
				0,
				&cyHeight);

		rcDrawRect.top += cyHeight;
		}

	//	Description

	CString sDesc = Item.GetDesc();
	Medium.DrawText(Dest,
			rcDrawRect,
			(bSelected ? wColorDescSel : wColorDesc),
			sDesc,
			0,
			CG16bitFont::SmartQuotes,
			&cyHeight);
	rcDrawRect.top += cyHeight;
	}
Esempio n. 14
0
 static Ctx Array()
 { return Ctx(&arrayFn); }
Esempio n. 15
0
void GenerateSnapshot (CUniverse &Universe, CXMLElement *pCmdLine)
	{
	ALERROR error;
	int i;

	//	Get some parameters

	int iInitialUpdateTime = 10;
	int iUpdateTime = pCmdLine->GetAttributeInteger(CONSTLIT("wait"));

	//	Criteria

	CString sNode = pCmdLine->GetAttribute(CONSTLIT("node"));
	CString sCriteria = pCmdLine->GetAttribute(CONSTLIT("criteria"));

	//	Output

	int cxWidth;
	int cyHeight;
	if (pCmdLine->FindAttributeInteger(CONSTLIT("size"), &cxWidth))
		{
		cyHeight = cxWidth;
		}
	else
		{
		cxWidth = 1024;
		cyHeight = 1024;
		}

	//	Output file

	CString sFilespec = pCmdLine->GetAttribute(CONSTLIT("output"));
	if (!sFilespec.IsBlank())
		sFilespec = pathAddExtensionIfNecessary(sFilespec, CONSTLIT(".bmp"));

	//	Loop over all systems until we find what we're looking for

	int iLoops = 20;
	CTopologyNode *pNode = Universe.GetFirstTopologyNode();
	while (true)
		{
		//	Create the system

		CSystem *pSystem;
		if (error = Universe.CreateStarSystem(pNode, &pSystem))
			{
			printf("ERROR: Unable to create star system.\n");
			return;
			}

		//	If this is the node we want, then search

		CSpaceObject *pTarget;
		if (sNode.IsBlank() || strEquals(sNode, pNode->GetID()))
			{
			printf("Searching %s...\n", pNode->GetSystemName().GetASCIIZPointer());

			//	Set the POV

			CSpaceObject *pPOV = pSystem->GetObject(0);
			Universe.SetPOV(pPOV);
			pSystem->SetPOVLRS(pPOV);

			//	Prepare system

			Universe.UpdateExtended();
			Universe.GarbageCollectLibraryBitmaps();

			//	Update for a while

			for (i = 0; i < iInitialUpdateTime; i++)
				Universe.Update(g_SecondsPerUpdate, true);

			//	Compose the criteria

			CSpaceObject::Criteria Criteria;
			CSpaceObject::ParseCriteria(pPOV, sCriteria, &Criteria);

			//	Get the list of all objects in the system that match the criteria

			CSpaceObject::SCriteriaMatchCtx Ctx(Criteria);
			TArray<CSpaceObject *> Results;
			for (i = 0; i < pSystem->GetObjectCount(); i++)
				{
				CSpaceObject *pObj = pSystem->GetObject(i);
				if (pObj && pObj->MatchesCriteria(Ctx, Criteria))
					Results.Insert(pObj);
				}

			//	Pick the appropriate object from the list

			if (Results.GetCount() == 0)
				pTarget = NULL;
			else if (Criteria.bNearestOnly || Criteria.bFarthestOnly)
				pTarget = Ctx.pBestObj;
			else
				pTarget = Results[mathRandom(0, Results.GetCount() - 1)];
			}
		else
			pTarget = NULL;

		//	If we found the target, then output

		if (pTarget)
			{
			//	If we found the target, take a snapshot

			printf("Found %s.\n", pTarget->GetNounPhrase(0).GetASCIIZPointer());

			//	Wait a bit

			for (i = 0; i < iUpdateTime; i++)
				{
				if ((i % 100) == 99)
					printf(".");

				Universe.Update(g_SecondsPerUpdate, true);
				}

			if (iUpdateTime >= 99)
				printf("\n");

			//	Paint

			CG16bitImage Output;
			Output.CreateBlank(cxWidth, cyHeight, false);
			RECT rcViewport;
			rcViewport.left = 0;
			rcViewport.top = 0;
			rcViewport.right = cxWidth;
			rcViewport.bottom = cyHeight;
			
			pSystem->PaintViewport(Output, rcViewport, pTarget, false);

			//	Write to file

			if (!sFilespec.IsBlank())
				{
				CFileWriteStream OutputFile(sFilespec);
				if (OutputFile.Create() != NOERROR)
					{
					printf("ERROR: Unable to create '%s'\n", sFilespec.GetASCIIZPointer());
					return;
					}

				Output.WriteToWindowsBMP(&OutputFile);
				OutputFile.Close();
				printf("%s\n", sFilespec.GetASCIIZPointer());
				}

			//	Otherwise, clipboard

			else
				{
				if (error = Output.CopyToClipboard())
					{
					printf("ERROR: Unable to copy image to clipboard.\n");
					return;
					}

				printf("Image copied to clipboard.\n");
				}

			//	Done

			break;
			}

		//	Otherwise, loop to the next system

		CString sEntryPoint;
		pNode = pSystem->GetStargateDestination(CONSTLIT("Outbound"), &sEntryPoint);

		//	Done with old system

		Universe.DestroySystem(pSystem);

		//	If no next node, then we loop through another universe

		if (pNode == NULL || pNode->IsEndGame())
			{
			if (--iLoops > 0)
				{
				Universe.Reinit();
				pNode = Universe.GetFirstTopologyNode();
				}
			else
				{
				printf("ERROR: Specified target could not be found.\n");
				return;
				}
			}
		}
	}
Esempio n. 16
0
int CUIHelper::CalcItemEntryHeight (CSpaceObject *pSource, const CItem &Item, const RECT &rcRect, DWORD dwOptions) const

//	CalcItemEntryHeight
//
//	Computes the height necessary to paint the item entry.

	{
	const CVisualPalette &VI = m_HI.GetVisuals();
	const CG16bitFont &LargeBold = VI.GetFont(fontLargeBold);
	const CG16bitFont &Medium = VI.GetFont(fontMedium);

	bool bNoIcon = ((dwOptions & OPTION_NO_ICON) == OPTION_NO_ICON);
	bool bTitle = ((dwOptions & OPTION_TITLE) == OPTION_TITLE);

	//	Get the item

	CItemCtx Ctx(&Item, pSource);
	CItemType *pType = Item.GetType();
	if (pType == NULL)
		return ITEM_DEFAULT_HEIGHT;

	//	Compute the rect where the reference text will paint

	RECT rcDrawRect = rcRect;
	rcDrawRect.left += ITEM_TEXT_MARGIN_X;
	rcDrawRect.right -= ITEM_TEXT_MARGIN_X;
	if (!bNoIcon)
		rcDrawRect.left += ICON_WIDTH;

	int iLevel = pType->GetApparentLevel();

	//	Compute the height of the row

	int cyHeight = 0;

	//	Account for margin

	cyHeight += ITEM_TEXT_MARGIN_Y;

	//	Item title

	cyHeight += LargeBold.GetHeight();
	if (bTitle)
		cyHeight += ITEM_TITLE_EXTRA_MARGIN;

	//	Attributes

	TArray<SDisplayAttribute> Attribs;
	if (Item.GetDisplayAttributes(Ctx, &Attribs))
		{
		int cyAttribs;
		FormatDisplayAttributes(Attribs, rcDrawRect, &cyAttribs);
		cyHeight += cyAttribs + ATTRIB_SPACING_Y;
		}

	//	Reference

	CString sReference = pType->GetReference(Ctx);

	//	If this is a weapon, then add room for the weapon damage

	if (Item.GetReferenceDamageType(pSource, -1, 0, NULL, NULL))
		cyHeight += Medium.GetHeight();

	//	If this is armor or a shield, then add room for damage resistance

	else if (Item.GetReferenceDamageAdj(pSource, 0, NULL, NULL))
		cyHeight += Medium.GetHeight();

	//	Measure the reference text

	int iLines;
	if (!sReference.IsBlank())
		{
		iLines = Medium.BreakText(sReference, RectWidth(rcDrawRect), NULL, 0);
		cyHeight += iLines * Medium.GetHeight();
		}

	//	Measure the description

	CString sDesc = Item.GetDesc();
	iLines = Medium.BreakText(sDesc, RectWidth(rcDrawRect), NULL, 0);
	cyHeight += iLines * Medium.GetHeight();

	//	Margin

	cyHeight += ITEM_TEXT_MARGIN_BOTTOM;

	//	Done

	cyHeight = Max(ITEM_DEFAULT_HEIGHT, cyHeight);

	return cyHeight;
	}
Esempio n. 17
0
void nuiGLPainter::ApplyTexture(const nuiRenderState& rState, bool ForceApply)
{
//  if ((rState.mTexturing && !rState.mpTexture) || (!rState.mTexturing && rState.mpTexture))
//  {
//    printf("bleh!\n");
//    char* bleh = NULL;
//    bleh[0] = 0;
//  }

  // 2D Textures: 
  std::map<nuiTexture*, TextureInfo>::const_iterator it = mTextures.find(rState.mpTexture);
  bool uptodate = (it == mTextures.end()) ? false : ( !it->second.mReload && it->second.mTexture >= 0 );
  if (ForceApply || (mState.mpTexture != rState.mpTexture) || (mState.mpTexture && !uptodate))
  { 
    GLenum intarget = 0;
    GLenum outtarget = 0;

    if (mState.mpTexture)
    {      
      outtarget = GetTextureTarget(mState.mpTexture->IsPowerOfTwo());

      //mState.mpTexture->UnapplyGL(this); #TODO Un apply the texture
      nuiCheckForGLErrors();
      mState.mpTexture->Release();
      nuiCheckForGLErrors();
    }

    //NGL_OUT(_T("Change texture to 0x%x (%ls)\n"), rState.mpTexture, rState.mpTexture?rState.mpTexture->GetSource().GetChars() : nglString::Empty.GetChars());
    mState.mpTexture = rState.mpTexture ;

    if (mState.mpTexture)
    {
      intarget = GetTextureTarget(mState.mpTexture->IsPowerOfTwo());

      mState.mpTexture->Acquire();
  
      nuiSurface* pSurface = mState.mpTexture->GetSurface();
      if (pSurface)
      {
        std::map<nuiSurface*, FramebufferInfo>::const_iterator it = mFramebuffers.find(pSurface);
        bool create = (it == mFramebuffers.end()) ? true : false;  
        if (create || pSurface->IsDirty())
        {
          PushClipping();
          nuiRenderState s(mState);// PushState();
          PushProjectionMatrix();
          PushMatrix();

#ifdef _OPENGL_ES_
          if (mpSurfaceStack.empty())
          {
            //  mDefaultFramebuffer = 0;
            //  mDefaultRenderbuffer = 0;
            glGetIntegerv(GL_FRAMEBUFFER_BINDING_NUI, &mDefaultFramebuffer);
            glGetIntegerv(GL_RENDERBUFFER_BINDING_NUI, (GLint *) &mDefaultRenderbuffer);
          }
#endif

          PushSurface();


          SetState(nuiRenderState());
          ResetClipRect();
          mClip.Set(0, 0, pSurface->GetWidth(), pSurface->GetHeight());

          LoadMatrix(nglMatrixf());

          NGL_ASSERT(pSurface);
          SetSurface(pSurface);
          //Set2DProjectionMatrix(nuiRect(0.0f, 0.0f, pSurface->GetWidth(), pSurface->GetHeight()));
          nuiMatrix m;
          m.Translate(-1.0f, 1.0f, 0.0f);
          m.Scale(2.0f / pSurface->GetWidth(), -2.0f / pSurface->GetHeight(), 1.0f);
          LoadProjectionMatrix(nuiRect(pSurface->GetWidth(), pSurface->GetHeight()), m);

          // clear the surface with transparent black:
//          nuiRenderState s2(mState);// PushState();
//          mState.mClearColor = nuiColor(0.0f, 0.0f, 0.0f, 0.0f);
          SetState(mState);
//          ClearColor();  
//          SetState(s2);

//////////////////////////////          
          nuiDrawContext Ctx(nuiRect(pSurface->GetWidth(), pSurface->GetHeight()));
          Ctx.SetPainter(this);
          pSurface->Realize(&Ctx);
          Ctx.SetPainter(NULL);
//////////////////////////////

          PopSurface();
          PopMatrix();
          PopProjectionMatrix();
          //PopState();
          SetState(s);
          PopClipping();
        }
      }

      UploadTexture(mState.mpTexture);
      nuiCheckForGLErrors();
    }

    //NGL_OUT(_T("Change texture type from 0x%x to 0x%x\n"), outtarget, intarget);

    mTextureTarget = intarget;
    if (intarget != outtarget)
    {
      // Texture Target has changed
      if (outtarget)
      {
        glDisable(outtarget);
        nuiCheckForGLErrors();
      }
      //NGL_OUT(_T("disable outtarget\n"));
      if (intarget && mState.mTexturing && mState.mpTexture)
      {
        mState.mTexturing = rState.mTexturing;
        //NGL_OUT(_T("enable intarget\n"));
        glEnable(intarget);
        nuiCheckForGLErrors();
      }
    }
    else
    {
      // Texture Target have not changed     
      if (mState.mTexturing != rState.mTexturing) // Have texture on/off changed?
      {
        // Should enable or disable texturing
        mState.mTexturing = rState.mTexturing;
        if (mState.mTexturing)
        {
          glEnable(mTextureTarget);
          nuiCheckForGLErrors();
        }
        else
        {
          glDisable(mTextureTarget);
          nuiCheckForGLErrors();
        }
      }
    }
  }

  if (ForceApply || (mState.mTexturing != rState.mTexturing))
  {
    // Texture have not changed, but texturing may have been enabled / disabled
    mState.mTexturing = rState.mTexturing;

    if (mState.mpTexture)
    {
      if (mTextureTarget && mState.mTexturing)
      {
        //NGL_OUT(_T("Enable 0x%x\n"), mTextureTarget);
        glEnable(mTextureTarget);
        nuiCheckForGLErrors();
      }
      else
      {
        //NGL_OUT(_T("Disable 0x%x\n"), mTextureTarget);
        glDisable(mTextureTarget);
        nuiCheckForGLErrors();
      }
    }
    else
    {
      if (mTextureTarget)
      {
        //NGL_OUT(_T("Disable 0x%x\n"), mTextureTarget);
        glDisable(mTextureTarget);
      }
      nuiCheckForGLErrors();
    }
  }
}
Esempio n. 18
0
int CGItemListArea::CalcRowHeight (int iRow)

//	CalcRowHeight
//
//	Returns the height of the given row

	{
	//	Set the position

	int iOldPos = m_pListData->GetCursor();
	m_pListData->SetCursor(iRow);

	//	Compute the rect where we're painting (we only care about width)

	RECT rcRect = GetRect();

	//	Compute row height based on type of list

	int cyHeight;
	switch (m_iType)
		{
		case listItem:
			{
			//	Get the item

			if (!m_pListData->IsCursorValid())
				{
				cyHeight = DEFAULT_ROW_HEIGHT;
				break;
				}

			const CItem &Item = m_pListData->GetItemAtCursor();
			CItemCtx Ctx(&Item, m_pListData->GetSource());
			CItemType *pType = Item.GetType();
			if (pType == NULL)
				{
				cyHeight = DEFAULT_ROW_HEIGHT;
				break;
				}

			int iLevel = pType->GetApparentLevel();

			//	Compute the height of the row

			cyHeight = 0;

			//	Account for margin

			cyHeight += ITEM_TEXT_MARGIN_Y;

			//	Item title

			cyHeight += m_pFonts->LargeBold.GetHeight();

			//	Reference

			CString sReference = pType->GetReference(Ctx);

			//	If this is a weapon, then add room for the weapon damage

			if (Item.GetReferenceDamageType(m_pListData->GetSource(), -1, 0, NULL, NULL))
				cyHeight += m_pFonts->Medium.GetHeight();

			//	If this is armor or a shield, then add room for damage resistance

			else if (Item.GetReferenceDamageAdj(m_pListData->GetSource(), 0, NULL, NULL))
				cyHeight += m_pFonts->Medium.GetHeight();

			//	Otherwise, we add the level to the reference

			else
				{
				if (sReference.IsBlank())
					sReference = strPatternSubst("Level %s", strLevel(iLevel));
				else
					sReference = strPatternSubst("Level %s — %s", 
							strLevel(iLevel),
							sReference);
				}

			//	Compute the rect where the reference text will paint

			RECT rcDrawRect = rcRect;
			rcDrawRect.left += ICON_WIDTH + ITEM_TEXT_MARGIN_X;
			rcDrawRect.right -= ITEM_TEXT_MARGIN_X;

			//	Measure the reference text

			int iLines = m_pFonts->Medium.BreakText(sReference, RectWidth(rcDrawRect), NULL, 0);
			cyHeight += iLines * m_pFonts->Medium.GetHeight();

			//	Measure the description

			CString sDesc = Item.GetDesc();
			iLines = m_pFonts->Medium.BreakText(sDesc, RectWidth(rcDrawRect), NULL, 0);
			cyHeight += iLines * m_pFonts->Medium.GetHeight();

			//	Margin

			cyHeight += ITEM_TEXT_MARGIN_BOTTOM;

			//	Done

			cyHeight = Max(DEFAULT_ROW_HEIGHT, cyHeight);
			break;
			}

		case listCustom:
			cyHeight = m_cyRow;
			break;

		default:
			cyHeight = DEFAULT_ROW_HEIGHT;
			break;
		}

	//	Done

	m_pListData->SetCursor(iOldPos);
	return cyHeight;
	}
Esempio n. 19
0
void CGItemListArea::PaintItem (CG16bitImage &Dest, const CItem &Item, const RECT &rcRect, bool bSelected)

//	PaintItem
//
//	Paints the item

	{
	//	Item context

	CItemCtx Ctx(&Item, m_pListData->GetSource());
	CItemType *pItemType = Item.GetType();

	//	Paint the image

	DrawItemTypeIcon(Dest, rcRect.left, rcRect.top, pItemType);

	RECT rcDrawRect = rcRect;
	rcDrawRect.left += ICON_WIDTH + ITEM_TEXT_MARGIN_X;
	rcDrawRect.right -= ITEM_TEXT_MARGIN_X;
	rcDrawRect.top += ITEM_TEXT_MARGIN_Y;

	//	Paint the attribute blocks

	RECT rcAttrib;
	rcAttrib = rcDrawRect;
	rcAttrib.bottom = rcAttrib.top + m_pFonts->MediumHeavyBold.GetHeight();

	if (Item.IsDamaged())
		PaintItemModifier(Dest,
				CONSTLIT("Damaged"),
				RGB_ILLEGAL_BACKGROUND,
				&rcAttrib);
	else if (Item.IsDisrupted())
		PaintItemModifier(Dest,
				CONSTLIT("Ionized"),
				RGB_ILLEGAL_BACKGROUND,
				&rcAttrib);

	if (pItemType->IsKnown()
			&& pItemType->HasAttribute(CONSTLIT("Military")))
		PaintItemModifier(Dest, 
				CONSTLIT("Military"),
				RGB_MILITARY_BACKGROUND,
				&rcAttrib);

	if (pItemType->IsKnown()
			&& pItemType->HasAttribute(CONSTLIT("Illegal")))
		PaintItemModifier(Dest, 
				CONSTLIT("Illegal"),
				RGB_ILLEGAL_BACKGROUND,
				&rcAttrib);

	CString sEnhanced = Item.GetEnhancedDesc(m_pListData->GetSource());
	if (!sEnhanced.IsBlank())
		{
		bool bDisadvantage = (*(sEnhanced.GetASCIIZPointer()) == '-');
		PaintItemModifier(Dest,
				sEnhanced,
				(bDisadvantage ? RGB_ILLEGAL_BACKGROUND : RGB_MILITARY_BACKGROUND),
				&rcAttrib);
		}

	//	Paint the item name

	int cyHeight;
	RECT rcTitle = rcDrawRect;
	rcTitle.right = rcAttrib.right;
	m_pFonts->LargeBold.DrawText(Dest,
			rcTitle,
			m_pFonts->wItemTitle,
			Item.GetNounPhrase(nounCount | nounNoModifiers),
			0,
			CG16bitFont::SmartQuotes | CG16bitFont::TruncateLine,
			&cyHeight);

	rcDrawRect.top += cyHeight;

	//	Stats

	CString sStat;

	int iLevel = pItemType->GetApparentLevel();
	CString sReference = pItemType->GetReference(Ctx);
	DamageTypes iDamageType;
	CString sDamageRef;
	int iDamageAdj[damageCount];
	int iHP;

	if (Item.GetReferenceDamageType(m_pListData->GetSource(), -1, 0, &iDamageType, &sDamageRef))
		{
		//	Paint the initial text

		sStat = strPatternSubst("Level %s —", strLevel(iLevel));
		int cxWidth = m_pFonts->Medium.MeasureText(sStat, &cyHeight);
		m_pFonts->Medium.DrawText(Dest, 
				rcDrawRect,
				m_pFonts->wItemRef,
				sStat,
				0,
				0,
				&cyHeight);

		//	Paint the damage type reference

		m_pUIRes->DrawReferenceDamageType(Dest,
				rcDrawRect.left + cxWidth + DAMAGE_ADJ_SPACING_X,
				rcDrawRect.top,
				iDamageType,
				sDamageRef);

		rcDrawRect.top += cyHeight;

		//	Paint additional reference in the line below

		if (!sReference.IsBlank())
			{
			m_pFonts->Medium.DrawText(Dest, 
					rcDrawRect,
					m_pFonts->wItemRef,
					sReference,
					0,
					0,
					&cyHeight);

			rcDrawRect.top += cyHeight;
			}
		}
	else if (Item.GetReferenceDamageAdj(m_pListData->GetSource(), 0, &iHP, iDamageAdj))
		{
		//	Paint the initial text

		sStat = strPatternSubst("Level %s — hp: %d ", strLevel(iLevel), iHP);
		int cxWidth = m_pFonts->Medium.MeasureText(sStat, &cyHeight);
		m_pFonts->Medium.DrawText(Dest, 
				rcDrawRect,
				m_pFonts->wItemRef,
				sStat,
				0,
				0,
				&cyHeight);

		//	Paint the damage type array

		m_pUIRes->DrawReferenceDamageAdj(Dest,
				rcDrawRect.left + cxWidth + DAMAGE_ADJ_SPACING_X,
				rcDrawRect.top,
				iLevel,
				iHP,
				iDamageAdj);

		rcDrawRect.top += cyHeight;

		//	Paint additional reference in the line below

		if (!sReference.IsBlank())
			{
			m_pFonts->Medium.DrawText(Dest, 
					rcDrawRect,
					m_pFonts->wItemRef,
					sReference,
					0,
					0,
					&cyHeight);

			rcDrawRect.top += cyHeight;
			}
		}
	else
		{
		if (sReference.IsBlank())
			sStat = strPatternSubst("Level %s", strLevel(iLevel));
		else
			sStat = strPatternSubst("Level %s — %s", 
					strLevel(iLevel),
					sReference);

		m_pFonts->Medium.DrawText(Dest, 
				rcDrawRect,
				m_pFonts->wItemRef,
				sStat,
				0,
				0,
				&cyHeight);

		rcDrawRect.top += cyHeight;
		}

	//	Description

	CString sDesc = Item.GetDesc();
	m_pFonts->Medium.DrawText(Dest,
			rcDrawRect,
			(bSelected ? m_pFonts->wItemDescSelected : m_pFonts->wItemDesc),
			sDesc,
			0,
			CG16bitFont::SmartQuotes,
			&cyHeight);
	rcDrawRect.top += cyHeight;
	}
Esempio n. 20
0
void PLH::VEHHook::SetupHook(BYTE* Src, BYTE* Dest,VEHMethod Method)
{
	HookCtx Ctx(Src, Dest, Method);
	m_ThisCtx = Ctx;
}
bool CWeaponBenchmarkCtx::GetStats (CItemType *pWeaponItem, SStats &retStats)

//  GetStats
//
//  Returns stats for the given weapon item (this can be either a weapon or a
//  missile). We return TRUE if successful.

    {
    int i;
    CCodeChain &CC = g_pUniverse->GetCC();

    retStats.TimeTable.DeleteAll();

    if (!InitArmorTable())
        return false;

    //  Compute some stats about the weapon

    CItem WeaponItem(pWeaponItem, 1);
    CItemCtx Ctx(WeaponItem);
    CCodeChainCtx TLispCtx;

    Metric rDamage180 = WeaponItem.GetProperty(&TLispCtx, Ctx, PROPERTY_DAMAGE)->GetDoubleValue();
    DamageTypes iDamageType = (DamageTypes)WeaponItem.GetProperty(&TLispCtx, Ctx, PROPERTY_DAMAGE_TYPE)->GetIntegerValue();
    if (iDamageType == -1)
        return false;

    //  Track some averages and totals

    int iTotalTime = 0;
    int iArmorCount = 0;
    retStats.pBestArmor = NULL;
    retStats.iBestTime = 0;
    retStats.pWorstArmor = NULL;
    retStats.iWorstTime = 0;
    retStats.iInvulnerableCount = 0;

    //  For each armor of the same level as this weapon, figure out how many 
    //  ticks it would take to destroy.

    TArray<CItemType *> &Armors = *m_ArmorTable.SetAt(pWeaponItem->GetLevel());
    for (i = 0; i < Armors.GetCount(); i++)
        {
        CItem ArmorItem(Armors[i], 1);
        CItemCtx ArmorCtx(ArmorItem);
        CArmorClass *pArmorClass = ArmorCtx.GetArmorClass();
        if (pArmorClass == NULL)
            continue;

        Metric rHP = pArmorClass->GetMaxHP(ArmorCtx, true);
        Metric rDamageAdj = pArmorClass->GetDamageAdj(ArmorCtx, iDamageType);

        //  Compute number of ticks to destroy the armor

        Metric rAdjDamage180 = rDamage180 * rDamageAdj / 100.0;
        int iTicks = (rAdjDamage180 > 0.0 ? (int)((180.0 * rHP / rAdjDamage180) + 0.5) : -1);

        //  Add to our table

        retStats.TimeTable.Insert(Armors[i], iTicks);

        //  Compute totals and averages

        if (iTicks > 0)
            {
            iTotalTime += iTicks;
            iArmorCount++;

            if (retStats.pBestArmor == NULL || iTicks < retStats.iBestTime)
                {
                retStats.pBestArmor = Armors[i];
                retStats.iBestTime = iTicks;
                }

            if (retStats.pWorstArmor == NULL 
                    || (retStats.iWorstTime > 0 && iTicks > retStats.iWorstTime))
                {
                retStats.pWorstArmor = Armors[i];
                retStats.iWorstTime = iTicks;
                }
            }
        else
            {
            retStats.iInvulnerableCount++;
            retStats.pWorstArmor = Armors[i];
            retStats.iWorstTime = -1;
            }
        }

    //  Compute average

    if (iArmorCount > 0)
        retStats.iAverageTime = (int)(((Metric)iTotalTime / (Metric)iArmorCount) + 0.5);
    else
        retStats.iAverageTime = 0;

    return true;
    }
Esempio n. 22
0
int main(int ac, char **av)
{
    SourceMgr SrcMgr;

    //LLVMInitializeX86TargetInfo();
    llvm::InitializeAllTargetInfos();
    //LLVMInitializeX86AsmParser();
    llvm::InitializeAllTargetMCs();
    //LLVMInitializeX86TargetMC();
    llvm::InitializeAllAsmParsers();
    //LLVMInitializeX86AsmParser();
    llvm::InitializeAllDisassemblers();
    //LLVMInitializeX86Disassembler();

    // arg0:
    // llvm::Target encapsulating the "x86_64-apple-darwin14.5.0" information 

    // see /lib/Support/Triple.cpp for the details
    //spec = llvm::sys::getDefaultTargetTriple();
    //std::string machSpec = "x86_64-apple-windows"; // will produce a COFF
    //std::string machSpec = "x86_64-apple-darwin14.5.0"; // will produce a Mach-O
    std::string machSpec = "arm-none-none-eabi"; //
    //std::string machSpec = "x86_64-apple-darwin";
    //std::string machSpec = "x86_64-thumb-linux-gnu";
    //std::string machSpec = "x86_64-unknown-linux-gnu";
    printf("machine spec: %s\n", machSpec.c_str());
    machSpec = Triple::normalize(machSpec);
    printf("machine spec (normalized): %s\n", machSpec.c_str());
    Triple TheTriple(machSpec);

    // Get the target specific parser.
    std::string Error;
    const Target *TheTarget = TargetRegistry::lookupTarget(/*arch*/"", TheTriple, Error);
    if (!TheTarget) {
        errs() << Error;
        return -1;
    }

    machSpec = TheTriple.getTriple();
    printf("machine spec (returned): %s\n", machSpec.c_str());
    
    printf("Target.getName(): %s\n", TheTarget->getName());
    printf("Target.getShortDescription(): %s\n", TheTarget->getShortDescription());

    /* from the target we get almost everything */
    std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(machSpec));
    std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, machSpec));
    std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); /* describes target instruction set */
    MCSubtargetInfo *STI = TheTarget->createMCSubtargetInfo(machSpec, "", ""); /* subtarget instr set */
    MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, machSpec, /* specific CPU */ "");

    // arg0:
    // llvm::SourceMgr (Support/SourceMgr.h) that holds assembler source
    // has vector of llvm::SrcBuffer encaps (Support/MemoryBuffer.h) and vector of include dirs
    //std::string asmSrc = ".org 0x100, 0xAA\nfoo:\nxor %eax, %ebx\npush %rbp\njmp foo\nrdtsc\n";
	//std::string asmSrc = ".text\n" "ldr pc, data_foo\n" "\n" "data_foo:\n" "    .int 0x8\n" "\n" "loop:\n" "b loop\n";
	//std::string asmSrc = ".text\n" "mov r2, r1\n";
	std::string asmSrc = ".text\n" "ldr pc, data_foo\n" "data_foo:\n" ".int 0x8\n" "loop:\n" "b loop\n";

    std::unique_ptr<MemoryBuffer> memBuf = MemoryBuffer::getMemBuffer(asmSrc);
    SrcMgr.AddNewSourceBuffer(std::move(memBuf), SMLoc());

    // arg1: the machine code context
    MCObjectFileInfo MOFI;
    MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
    MOFI.InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default, Ctx);

    // this is the assembler interface
    // -methods per .s statements (emit bytes, handle directive, etc.)
    // -remembers current section
    // -implementations that write a .s, or .o in various formats
    //
    //   1. the output stream ... a formatted_raw_ostream wraps a raw_ostream to provide
    //   tracking of line and column position for padding and shit
    //
    //   but raw_ostream is abstract and is implemented by raw_fd_ostream, raw_string_ostream, etc.

	/* output stream:
		raw_svector_ostream is a raw_pwrite_stream is a raw_ostream
		since a SmallString is SmallVector (svector) we can use this and 
		retrieve bytes later with its .data() method */
	SmallString<1024> smallString;
    raw_svector_ostream rso(smallString);

    /* code emitter needs 1) instruction set info 2) register info */
    MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);

    MCStreamer *as = TheTarget->createMCObjectStreamer(
		TheTriple, /* Triple */	
        Ctx, /* the MCContext */
        *MAB,  /* the AsmBackend, (fixups, relaxation, objs and elfs) */
        rso, /* output stream raw_pwrite_stream */
        CE, /* code emitter */
		*STI, /* subtarget info */
		true, /* relax all fixups */
		true, /* incremental linker compatible */ 
        false /* DWARFMustBeAtTheEnd */
    );

    std::string abi = "none";
    MCTargetOptions toptions;
    toptions.MCUseDwarfDirectory = false;
    toptions.ABIName = abi;

    printf("trying to assemble, let's go..\n");
    AssembleInput(TheTarget, SrcMgr, Ctx, *as, *MAI, *STI,
        *MCII, toptions);
	printf("done with AssembleInput()\n");

	/* dump to file for debugging */
	FILE *fp;
	fp = fopen("out.bin", "wb");
	fwrite(smallString.data(), 1, smallString.size(), fp);
	fclose(fp);

	//int n = smallString.size();
	int codeOffset=0, codeSize = 0;
	char *data = smallString.data();
	if(*(uint32_t *)data == 0xFEEDFACF) {
		unsigned int idx = 0;
		idx += 0x20; /* skip mach_header_64 to first command */
		idx += 0x48; /* advance into segment_command_64 to first section */
		idx += 0x28; /* advance into section_64 to size */
		uint64_t scn_size = *(uint64_t *)(data + idx);
		idx += 0x8; /* advance into section_64 to offset */
		uint64_t scn_offset = *(uint64_t *)(data + idx);
		codeOffset = scn_offset;
		codeSize = scn_size;
	}
	else if(0==memcmp(data, "\x7F" "ELF\x01\x01\x01\x00", 8)) {
		/* assume four sections: NULL, .strtab, .text, .symtab */
		uint32_t e_shoff = *(uint32_t *)(data + 0x20);
		uint32_t sh_offset = *(uint32_t *)(data + e_shoff + 2*0x28 + 0x10); /* second shdr */
		uint32_t sh_size = *(uint32_t *)(data + e_shoff + 2*0x28 + 0x14); /* second shdr */
		codeOffset = sh_offset;
		codeSize = sh_size;
	}
	else {
		printf("ERROR: couldn't identify type of output file\n");
	}
	
	dump_bytes((unsigned char *)data + codeOffset, codeSize, 0);

    return 0;
}
Esempio n. 23
0
 static Ctx Object()
 { return Ctx(&objectFn); }
Esempio n. 24
0
void CAeonEngine::MsgFileUpload (const SArchonMessage &Msg, const CHexeSecurityCtx *pSecurityCtx)

//	MsgFileUpload
//
//	Aeon.fileUpload {filePath} {fileUploadDesc} {data}

	{
	AEONERR error;
    CMsgProcessCtx Ctx(*GetProcessCtx(), Msg, pSecurityCtx);

	//	Get the filePath

	CString sError;
	CString sTable;
	CString sFilePath;
	if (!CAeonTable::ParseFilePathForCreate(Msg.dPayload.GetElement(0), &sTable, &sFilePath, &sError))
		{
		SendMessageReplyError(MSG_ERROR_UNABLE_TO_COMPLY, strPattern(STR_ERROR_PARSING_FILE_PATH, sError), Msg);
		return;
		}

	//	Make sure we are allowed access to this table

	if (!ValidateTableAccess(Msg, pSecurityCtx, sTable))
		return;

	//	Get other parameters

	CDatum dUploadDesc = Msg.dPayload.GetElement(1);
	CDatum dData = Msg.dPayload.GetElement(2);

	//	Lock while we find or create a table

	CSmartLock Lock(m_cs);

	//	If the table doesn't exist, then we create a new one inside the lock

	CAeonTable *pTable;
	if (!m_Tables.Find(sTable, &pTable))
		{
		//	Compose a table descriptor

		CDatum dTableDesc;
		if (!CDatum::Deserialize(CDatum::formatAEONScript, CBuffer(strPattern(STR_FILE_TABLE_DESC_PATTERN, sTable)), &dTableDesc))
			{
			SendMessageReplyError(MSG_ERROR_UNABLE_TO_COMPLY, strPattern(STR_ERROR_INVALID_TABLE_NAME, sTable), Msg);
			return;
			}

		//	Create the table

		if (!CreateTable(dTableDesc, &pTable, NULL, &sError))
			{
			SendMessageReplyError(MSG_ERROR_UNABLE_TO_COMPLY, sError, Msg);
			return;
			}
		}

	//	Unlock

	Lock.Unlock();

	//	Generate a unique session ID from the message

	CString sSessionID = strPattern("%s/%x%s", Msg.sReplyAddr, Msg.dwTicket, sFilePath);

#ifdef DEBUG_FILE_UPLOAD
    DWORD dwStart = ::sysGetTickCount();
    Log(MSG_LOG_INFO, strPattern("Aeon.fileUpload %s [%d bytes]", sFilePath, dData.GetBinarySize()));
#endif

	//	Let the table handle the rest

	int iComplete;
	if (error = pTable->UploadFile(Ctx, sSessionID, sFilePath, dUploadDesc, dData, &iComplete, &sError))
		{
		if (error == AEONERR_OUT_OF_DATE)
			SendMessageReplyError(MSG_ERROR_OUT_OF_DATE, sError, Msg);
		else
			SendMessageReplyError(MSG_ERROR_UNABLE_TO_COMPLY, sError, Msg);
		return;
		}

#ifdef DEBUG_FILE_UPLOAD
    Log(MSG_LOG_INFO, strPattern("Aeon.fileUpload complete: %d seconds.", ::sysGetTicksElapsed(dwStart) / 1000));
#endif

	//	Reply

	if (iComplete == 100)
		SendMessageReply(MSG_OK, CDatum(), Msg);
	else
		{
		CDatum dReceipt;

		//	LATER: Fill in receipt

		SendMessageReply(MSG_AEON_FILE_UPLOAD_PROGRESS, dReceipt, Msg);
		}
	}