Ejemplo n.º 1
0
 Vec2i Texture::getSize() const
 {
     return Vec2i(width, height);
 }
Ejemplo n.º 2
0
void MiniMap::showBookEntireMap(int showLevel) {
	
	// First Load Minimap TC & DATA if needed
	if(m_levels[showLevel].m_texContainer == NULL) {
		getData(showLevel);
	}
	
	if(!m_levels[showLevel].m_texContainer) {
		return;
	}
	
	GRenderer->SetRenderState(Renderer::DepthTest, false);
	
	float zoom = 250.f;
	
	Vec2f start(140.f, 120.f);
	
	Vec2f playerPos(0.f, 0.f);
	
	if(showLevel == ARX_LEVELS_GetRealNum(m_currentLevel)) {
		playerPos = computePlayerPos(zoom, showLevel);
		playerPos += start;
	}
	
	drawBackground(showLevel, Rect(0, 0, 345, 290), start.x, start.y, zoom);
	
	GRenderer->GetTextureStage(0)->setWrapMode(TextureStage::WrapRepeat);
	
	if(showLevel == ARX_LEVELS_GetRealNum(m_currentLevel)) {
		drawPlayer(3.f, playerPos);
		drawDetectedEntities(showLevel, start, zoom);
	}
	
	TexturedVertex verts[4];
	for(int k = 0; k < 4; k++) {
		verts[k].color = Color(255, 255, 255, 255).toRGBA();
		verts[k].rhw = 1;
		verts[k].p.z = 0.00001f;
	}
	
	Vec2f casePos(zoom / ((float)MINIMAP_MAX_X), zoom / ((float)MINIMAP_MAX_Z));
	float ratio = 1.f;
	
	for(size_t i = 0; i < m_mapMarkers.size(); i++) {
		
		if(m_mapMarkers[i].m_lvl != showLevel + 1) {
			continue;
		}
		
		float pos_x = m_mapMarkers[i].m_pos.x * 8 * ratio * m_activeBkg->Xmul * casePos.x + start.x;
		float pos_y = m_mapMarkers[i].m_pos.y * 8 * ratio * m_activeBkg->Zmul * casePos.y + start.y;
		float size = 5.f * ratio;
		verts[0].color = Color(255, 0, 0, 255).toRGBA();
		verts[1].color = Color(255, 0, 0, 255).toRGBA();
		verts[2].color = Color(255, 0, 0, 255).toRGBA();
		verts[3].color = Color(255, 0, 0, 255).toRGBA();
		verts[0].p.x = (pos_x - size) * g_sizeRatio.x;
		verts[0].p.y = (pos_y - size) * g_sizeRatio.y;
		verts[1].p.x = (pos_x + size) * g_sizeRatio.x;
		verts[1].p.y = (pos_y - size) * g_sizeRatio.y;
		verts[2].p.x = (pos_x + size) * g_sizeRatio.x;
		verts[2].p.y = (pos_y + size) * g_sizeRatio.y;
		verts[3].p.x = (pos_x - size) * g_sizeRatio.x;
		verts[3].p.y = (pos_y + size) * g_sizeRatio.y;
		verts[0].uv = Vec2f_ZERO;
		verts[1].uv = Vec2f_X_AXIS;
		verts[2].uv = Vec2f_ONE;
		verts[3].uv = Vec2f_Y_AXIS;
		
		const Rect mouseTestRect(
			verts[0].p.x,
			verts[0].p.y,
			verts[2].p.x,
			verts[2].p.y
		);
		
		if(mouseTestRect.contains(Vec2i(DANAEMouse))) {
			if(!m_mapMarkers[i].m_text.empty()) {
				
				Rect bRect(140, 295, 140 + 205, 358);
				
				Rect::Num left = checked_range_cast<Rect::Num>((bRect.left) * g_sizeRatio.x);
				Rect::Num right = checked_range_cast<Rect::Num>((bRect.right) * g_sizeRatio.x);
				Rect::Num top = checked_range_cast<Rect::Num>((bRect.top) * g_sizeRatio.y);
				Rect::Num bottom = checked_range_cast<Rect::Num>((bRect.bottom) * g_sizeRatio.y);
				Rect rRect = Rect(left, top, right, bottom);
				
				long lLengthDraw = ARX_UNICODE_ForceFormattingInRect(hFontInGameNote, m_mapMarkers[i].m_text, rRect);
				
				
				ARX_UNICODE_DrawTextInRect(hFontInGameNote,
				                           (BOOKDEC + Vec2f(bRect.topLeft())) * g_sizeRatio,
				                           (BOOKDEC.x + float(bRect.right)) * g_sizeRatio.x,
				                           m_mapMarkers[i].m_text.substr(0, lLengthDraw),
				                           Color::none);
			}
		}
		
		if(m_mapMarkerTexCont == NULL) {
			m_mapMarkerTexCont = TextureContainer::Load("graph/interface/icons/mapmarker");
		}
		
		GRenderer->SetTexture(0, m_mapMarkerTexCont);
		
		EERIEDRAWPRIM(Renderer::TriangleFan, verts, 4);
	}
}
Ejemplo n.º 3
0
void Bitmap::stretchBlt(const IntRect &destRect,
                        const Bitmap &source, const IntRect &sourceRect,
                        int opacity)
{
	guardDisposed();

	GUARD_MEGA;

	if (source.isDisposed())
		return;

	opacity = clamp(opacity, 0, 255);

	if (opacity == 0)
		return;

	SDL_Surface *srcSurf = source.megaSurface();

	if (srcSurf && shState->config().subImageFix)
	{
		/* Blit from software surface, for broken GL drivers */
		Vec2i gpTexSize;
		shState->ensureTexSize(sourceRect.w, sourceRect.h, gpTexSize);
		shState->bindTex();

		GLMeta::subRectImageUpload(srcSurf->w, sourceRect.x, sourceRect.y, 0, 0,
		                           sourceRect.w, sourceRect.h, srcSurf, GL_RGBA);
		GLMeta::subRectImageEnd();

		SimpleShader &shader = shState->shaders().simple;
		shader.bind();
		shader.setTranslation(Vec2i());
		shader.setTexSize(gpTexSize);

		p->pushSetViewport(shader);
		p->bindFBO();

		Quad &quad = shState->gpQuad();
		quad.setTexRect(FloatRect(0, 0, sourceRect.w, sourceRect.h));
		quad.setPosRect(destRect);

		p->blitQuad(quad);
		p->popViewport();

		p->addTaintedArea(destRect);
		p->onModified();

		return;
	}
	else if (srcSurf)
	{
		/* Blit from software surface */
		/* Don't do transparent blits for now */
		if (opacity < 255)
			source.ensureNonMega();

		SDL_Rect srcRect = sourceRect;
		SDL_Rect dstRect = destRect;
		SDL_Rect btmRect = { 0, 0, width(), height() };
		SDL_Rect bltRect;

		if (SDL_IntersectRect(&btmRect, &dstRect, &bltRect) != SDL_TRUE)
			return;

		int bpp;
		Uint32 rMask, gMask, bMask, aMask;
		SDL_PixelFormatEnumToMasks(SDL_PIXELFORMAT_ABGR8888,
		                           &bpp, &rMask, &gMask, &bMask, &aMask);
		SDL_Surface *blitTemp =
			SDL_CreateRGBSurface(0, destRect.w, destRect.h, bpp, rMask, gMask, bMask, aMask);

		SDL_BlitScaled(srcSurf, &srcRect, blitTemp, 0);

		TEX::bind(p->gl.tex);

		if (bltRect.w == dstRect.w && bltRect.h == dstRect.h)
		{
			/* Dest rectangle lies within bounding box */
			TEX::uploadSubImage(destRect.x, destRect.y,
			                    destRect.w, destRect.h,
			                    blitTemp->pixels, GL_RGBA);
		}
		else
		{
			/* Clipped blit */
			GLMeta::subRectImageUpload(blitTemp->w, bltRect.x - dstRect.x, bltRect.y - dstRect.y,
			                           bltRect.x, bltRect.y, bltRect.w, bltRect.h, blitTemp, GL_RGBA);
			GLMeta::subRectImageEnd();
		}

		SDL_FreeSurface(blitTemp);

		p->onModified();
		return;
	}

	if (opacity == 255 && !p->touchesTaintedArea(destRect))
	{
		/* Fast blit */
		GLMeta::blitBegin(p->gl);
		GLMeta::blitSource(source.p->gl);
		GLMeta::blitRectangle(sourceRect, destRect);
		GLMeta::blitEnd();
	}
	else
	{
		/* Fragment pipeline */
		float normOpacity = (float) opacity / 255.0f;

		TEXFBO &gpTex = shState->gpTexFBO(destRect.w, destRect.h);

		GLMeta::blitBegin(gpTex);
		GLMeta::blitSource(p->gl);
		GLMeta::blitRectangle(destRect, Vec2i());
		GLMeta::blitEnd();

		FloatRect bltSubRect((float) sourceRect.x / source.width(),
		                     (float) sourceRect.y / source.height(),
		                     ((float) source.width() / sourceRect.w) * ((float) destRect.w / gpTex.width),
		                     ((float) source.height() / sourceRect.h) * ((float) destRect.h / gpTex.height));

		BltShader &shader = shState->shaders().blt;
		shader.bind();
		shader.setDestination(gpTex.tex);
		shader.setSubRect(bltSubRect);
		shader.setOpacity(normOpacity);

		Quad &quad = shState->gpQuad();
		quad.setTexPosRect(sourceRect, destRect);
		quad.setColor(Vec4(1, 1, 1, normOpacity));

		source.p->bindTexture(shader);
		p->bindFBO();
		p->pushSetViewport(shader);

		p->blitQuad(quad);

		p->popViewport();
	}

	p->addTaintedArea(destRect);
	p->onModified();
}
Ejemplo n.º 4
0
bool CinematicGrid::AllocGrille(Vec2i nb, Vec2f t, Vec2f d, int scale) {
	
	m_scale = scale;
	Vec2i oldnb = nb + Vec2i(1);
	nb *= scale;
	Vec2f oldd = d;
	d /= float(scale);
	
	m_nbvertexs = size_t(nb.x + 1) * size_t(nb.y + 1);
	m_vertexs.reserve(m_nbvertexs);
	
	m_count = nb;
	t *= .5f;
	Vec2f dep = -t;
	
	float olddyy = oldd.y;

	while(oldnb.y--) {
		nb.y = scale;

		if(!oldnb.y)
			nb.y = 1;

		while(nb.y--) {
			float olddxx = oldd.x;
			float depxx = dep.x;
			float dxx = d.x;
			int oldnbxx = oldnb.x;

			while(oldnbxx--) {
				nb.x = scale;

				if (!oldnbxx) nb.x = 1;

				while(nb.x--) {
					m_vertexs.push_back(Vec2f(depxx, dep.y));
					depxx += dxx;
				}

				olddxx += oldd.x;

				if(olddxx > (t.x * 2.f)) {
					dxx = t.x - depxx;
					dxx /= float(scale);
				}
				
			}

			dep.y += d.y;
		}
		
			olddyy += oldd.y;

			if(olddyy > (t.y * 2.f)) {
				d.y = t.y - dep.y;
				d.y /= float(scale);
			}
		
	}

	return true;
}
Ejemplo n.º 5
0
TUICore<T>::TUICore()
    :mBoundRect( Vec2i(0,0) , Vec2i(0,0))
{
    init();
}
Ejemplo n.º 6
0
void ShowInfoText() {
	
	DebugBox frameInfo = DebugBox(Vec2i(10, 10), "FrameInfo");
	frameInfo.add("Prims", EERIEDrawnPolys);
	frameInfo.add("Particles", getParticleCount());
	frameInfo.add("Polybooms", long(polyboom.size()));
	frameInfo.add("TIME", static_cast<long>(arxtime.now_ul() / 1000));
	frameInfo.print();
	
	DebugBox playerBox = DebugBox(Vec2i(10, frameInfo.size().y + 5), "Player");
	playerBox.add("Position", player.pos);
	playerBox.add("AnchorPos", player.pos - Mscenepos);
	playerBox.add("Rotation", player.angle);
	playerBox.add("Velocity", player.physics.velocity);
	
	EERIEPOLY * ep = CheckInPoly(player.pos);
	float truePolyY = -666.66f;
	if(ep) {
		float tempY = 0.f;
		if(GetTruePolyY(ep, player.pos, &tempY)) {
			truePolyY = tempY;
		}
	}
	
	ep = CheckInPoly(player.pos + Vec3f(0.f, -10.f, 0.f));
	float slope = 0.f;
	if(ep)
		slope = ep->norm.y;
	
	long zap = IsAnyPolyThere(player.pos.x,player.pos.z);
	
	playerBox.add("Ground Slope", slope);
	playerBox.add("Ground truePolyY", truePolyY);
	playerBox.add("Ground POLY", zap);
	playerBox.add("Color", CURRENT_PLAYER_COLOR);
	playerBox.add("Stealth", GetPlayerStealth());
	
	playerBox.add("Jump", player.jumplastposition);
	playerBox.add("OFFGRND", (!player.onfirmground ? "OFFGRND" : ""));
	
	playerBox.add("Life", player.lifePool);
	playerBox.add("Mana", player.manaPool);
	playerBox.add("Poisoned", player.poison);
	playerBox.add("Hunger", player.hunger);
	playerBox.add("Magic", static_cast<long>(player.doingmagic));
	playerBox.print();
	
	DebugBox miscBox = DebugBox(Vec2i(10, playerBox.size().y + 5), "Misc");
	miscBox.add("Arx version", arx_version);
	miscBox.add("Level", LastLoadedScene.string().c_str());
	miscBox.add("Spell failed seq", LAST_FAILED_SEQUENCE.c_str());
	miscBox.add("Camera focal", ACTIVECAM->focal);
	miscBox.add("Cinema", CINEMA_DECAL);
	miscBox.add("Mouse", Vec2i(DANAEMouse));
	miscBox.add("Pathfind queue", EERIE_PATHFINDER_Get_Queued_Number());
	miscBox.add("Pathfind status", (PATHFINDER_WORKING ? "Working" : "Idled"));
	miscBox.print();
	
	{
	struct ScriptDebugReport {
		std::string entityName;
		long events;
		long sends;
		
		ScriptDebugReport()
			: entityName("")
			, events(0)
			, sends(0)
		{}
	};
	
	ScriptDebugReport maxEvents;
	Entity * io = ARX_SCRIPT_Get_IO_Max_Events();
	if(io) {
		maxEvents.entityName = io->idString();
		maxEvents.events = io->stat_count;
	}
	
	ScriptDebugReport maxSender;
	io = ARX_SCRIPT_Get_IO_Max_Events_Sent();
	if(io) {
		maxSender.entityName = io->idString();
		maxSender.sends = io->stat_sent;
	}
	
	DebugBox scriptBox = DebugBox(Vec2i(10, miscBox.size().y + 5), "Script");
	scriptBox.add("Events", ScriptEvent::totalCount);
	scriptBox.add("Timers", ARX_SCRIPT_CountTimers());
	scriptBox.add("Max events", maxEvents.entityName);
	scriptBox.add("Max events#", maxEvents.events);
	scriptBox.add("Max sender", maxSender.entityName);
	scriptBox.add("Max sender#", maxSender.sends);
	scriptBox.print();
	}
	
	if(ValidIONum(LastSelectedIONum)) {
		Entity * io = entities[LastSelectedIONum];

		if(io) {
			DebugBox entityBox = DebugBox(Vec2i(500, 10), "Entity " + io->idString());
			entityBox.add("Pos", io->pos);
			entityBox.add("Angle", io->angle);
			entityBox.add("Room", static_cast<long>(io->room));
			entityBox.add("Move", io->move);
			entityBox.add("Flags", flagNames(EntityFlagNames, io->ioflags));
			entityBox.add("Show", entityVisilibityToString(io->show));
			entityBox.print();
			
			if(io->ioflags & IO_NPC) {
				IO_NPCDATA * npcData = io->_npcdata;
				
				DebugBox npcBox = DebugBox(Vec2i(500, entityBox.size().y + 5), "NPC");
				npcBox.add("Life", npcData->lifePool);
				npcBox.add("Mana", npcData->manaPool);
				npcBox.add("Poisoned", npcData->poisonned);
				npcBox.add("ArmorClass", ARX_INTERACTIVE_GetArmorClass(io));
				npcBox.add("Absorb", npcData->absorb);
				
				npcBox.add("Moveproblem", npcData->moveproblem);
				npcBox.add("Pathfind listpos", static_cast<long>(npcData->pathfind.listpos));
				npcBox.add("Pathfind listnb", npcData->pathfind.listnb);
				npcBox.add("Pathfind targ", npcData->pathfind.truetarget.handleData());
				npcBox.add("Behavior", flagNames(BehaviourFlagNames, npcData->behavior));
				
				// TODO should those really be flags ?
				PathfindFlags pflag = io->_npcdata->pathfind.flags;
				std::string pflags;
				if(pflag & PATHFIND_ALWAYS)    pflags += "ALWAYS ";
				if(pflag & PATHFIND_ONCE)      pflags += "ONCE ";
				if(pflag & PATHFIND_NO_UPDATE) pflags += "NO_UPDATE ";
				npcBox.add("Pathfind flgs", pflags);
				
				npcBox.print();
			}

			if(io->ioflags & (IO_FIX | IO_ITEM)) {
				DebugBox itemBox = DebugBox(Vec2i(500, entityBox.size().y + 5), "Item");
				
				itemBox.add("Durability", io->durability);
				itemBox.add("Durability max", io->max_durability);
				itemBox.add("Poisonous", static_cast<long>(io->poisonous));
				itemBox.add("Poisonous count", static_cast<long>(io->poisonous_count));
				itemBox.print();
			}
		}
	}
	
	ARX_SCRIPT_Init_Event_Stats();
}
Ejemplo n.º 7
0
void ShowFpsGraph() {
	
	ARX_PROFILE_FUNC();

	GRenderer->ResetTexture(0);

	static std::deque<float> lastFPSArray;
	lastFPSArray.push_front(1000 / arxtime.get_frame_delay());

	Vec2i windowSize = mainApp->getWindow()->getSize();
	if(lastFPSArray.size() == size_t(windowSize.x))
	{
		lastFPSArray.pop_back();
	}

	float avg = 0;
	float worst = lastFPSArray[0];

	std::vector<TexturedVertex> vertices;
	vertices.resize(lastFPSArray.size());

	const float SCALE_Y = 2.0f;

	for(size_t i = 0; i < lastFPSArray.size(); ++i)
	{
		float time = lastFPSArray[i];

		avg += lastFPSArray[i];
		worst = std::min(worst, lastFPSArray[i]);

		vertices[i].color = Color(255, 255, 255, 255).toRGBA();
		vertices[i].p.x = i;
		vertices[i].p.y = windowSize.y - (time * SCALE_Y);
		vertices[i].p.z = 1.0f;
		vertices[i].rhw = 1.0f;
	}
	avg /= lastFPSArray.size();

	EERIEDRAWPRIM(Renderer::LineStrip, &vertices[0], vertices.size());

	Color avgColor = Color::blue * 0.5f + Color::white * 0.5f;
	float avgPos = windowSize.y - (avg * SCALE_Y);
	drawLine2D(0, avgPos,  windowSize.x, avgPos, 1.0f, Color::blue);

	Color worstColor = Color::red * 0.5f + Color::white * 0.5f;
	float worstPos = windowSize.y - (worst * SCALE_Y);
	drawLine2D(0, worstPos,  windowSize.x, worstPos, 1.0f, Color::red);

	Font * font = hFontDebug;
	float lineOffset = font->getLineHeight() + 2;

	std::string labels[3] = { "Average: ", "Worst: ", "Current: " };
	Color colors[3] = { avgColor, worstColor, Color::white };
	float values[3] = { avg, worst, lastFPSArray[0] };

	std::string texts[3];
	float widths[3];
	static float labelWidth = 0.f;
	static float valueWidth = 0.f;
	for(size_t i = 0; i < 3; i++) {
		// Format value
		std::ostringstream oss;
		oss << std::fixed << std::setprecision(2) << values[i] << " FPS";
		texts[i] = oss.str();
		// Calculate widths (could be done more efficiently for monospace fonts...)
		labelWidth = std::max(labelWidth, float(font->getTextSize(labels[i]).x));
		widths[i] = font->getTextSize(texts[i]).x;
		valueWidth = std::max(valueWidth, widths[i]);
	}

	float x = 10;
	float y = 10;
	float xend = x + labelWidth + 10 + valueWidth;
	for(size_t i = 0; i < 3; i++) {
		font->draw(Vec2i(x, y), labels[i], Color::gray(0.8f));
		font->draw(Vec2i(xend - widths[i], y), texts[i], colors[i]);
		y += lineOffset;
	}

}
Ejemplo n.º 8
0
Vec2i Player::player_pos(){
	return p_pos = Vec2i((player.pos.x() + player.size.x() / 2) / static_cast<int>(BLOCKSIZE::WIDTH), (std::abs(player.pos.y()) + player.size.y() / 2) / static_cast<int>(BLOCKSIZE::HEIGHT));
}
Ejemplo n.º 9
0
bool Manage3DCursor(Entity * io, bool simulate) {
	
	arx_assert(io);
	
	if(BLOCK_PLAYER_CONTROLS)
		return false;

	float ag = player.angle.getYaw();

	if(ag > 180)
		ag = ag - 360;

	float drop_miny = float(g_size.center().y) - float(g_size.center().y) * ag * (1.f/70);

	if(DANAEMouse.y < drop_miny)
		return false;
	
	Anglef temp = Anglef::ZERO;

	if(io->ioflags & IO_INVERTED) {
		temp.setYaw(180.f);
		temp.setPitch(-MAKEANGLE(270.f - io->angle.getPitch() - (player.angle.getPitch() - STARTED_ANGLE)));
	} else {
		temp.setPitch(MAKEANGLE(270.f - io->angle.getPitch() - (player.angle.getPitch() - STARTED_ANGLE)));
	}
	
	EERIE_3D_BBOX bbox;
	for(size_t i = 0; i < io->obj->vertexlist.size(); i++) {
		bbox.add(io->obj->vertexlist[i].v);
	}
	
	Vec3f mvectx = angleToVectorXZ(player.angle.getPitch() - 90.f);
	
	Vec2f mod = Vec2f(Vec2i(DANAEMouse) - g_size.center()) / Vec2f(g_size.center()) * Vec2f(160.f, 220.f);
	mvectx *= mod.x;
	Vec3f mvecty(0, mod.y, 0);

	Vec3f orgn = player.pos;
	orgn += angleToVector(player.angle) * 50.f;
	orgn += mvectx;
	orgn.y += mvecty.y;

	Vec3f dest = player.pos;
	dest += angleToVector(player.angle) * 10000.f;
	dest += mvectx;
	dest.y += mvecty.y * 5.f;
	
	Vec3f pos = orgn;

	Vec3f movev = glm::normalize(dest - orgn);

	float lastanything = 0.f;
	float height = -(bbox.max.y - bbox.min.y);

	if(height > -30.f)
		height = -30.f;
	
	Vec3f objcenter = bbox.min + (bbox.max - bbox.min) * Vec3f(0.5f);
	
	Vec3f collidpos = Vec3f_ZERO;
	bool collidpos_ok = false;
	
	{
	float maxdist = 0.f;
	
	for(size_t i = 0; i < io->obj->vertexlist.size(); i++) {
		const EERIE_VERTEX & vert = io->obj->vertexlist[i];
		
		float dist = glm::distance(Vec2f(objcenter.x, objcenter.z), Vec2f(vert.v.x, vert.v.z)) - 4.f;
		maxdist = std::max(maxdist, dist);
	}

	if(io->obj->pbox) {
		Vec2f tmpVert(io->obj->pbox->vert[0].initpos.x, io->obj->pbox->vert[0].initpos.z);
		
		for(int i = 1; i < io->obj->pbox->nb_physvert; i++) {
			const PHYSVERT & physVert = io->obj->pbox->vert[i];
			
			float dist = glm::distance(tmpVert, Vec2f(physVert.initpos.x, physVert.initpos.z)) + 14.f;
			maxdist = std::max(maxdist, dist);
		}
	}
	
	Cylinder cyl2 = Cylinder(Vec3f_ZERO, glm::clamp(maxdist, 20.f, 150.f), std::min(-30.f, height));
	
	const float inc = 10.f;
	long iterating = 40;
	
	while(iterating > 0) {
		cyl2.origin = pos + movev * inc + Vec3f(0.f, bbox.max.y, 0.f);

		float anything = CheckAnythingInCylinder(cyl2, io, CFLAG_JUST_TEST | CFLAG_COLLIDE_NOCOL | CFLAG_NO_NPC_COLLIDE);

		if(anything < 0.f) {
			if(iterating == 40) {
				CANNOT_PUT_IT_HERE = EntityMoveCursor_Invalid;
				// TODO is this correct ?
				return true;
			}

			iterating = 0;

			collidpos = cyl2.origin;

			if(lastanything < 0.f) {
				pos.y += lastanything;
				collidpos.y += lastanything;
			}
		} else {
			pos = cyl2.origin;
			lastanything = anything;
		}

		iterating--;
	}
	collidpos_ok = iterating == -1;
	
	}
	
	objcenter = VRotateY(objcenter, temp.getPitch());
	
	collidpos.x -= objcenter.x;
	collidpos.z -= objcenter.z;

	pos.x -= objcenter.x;
	pos.z -= objcenter.z;

	if(!collidpos_ok) {
		CANNOT_PUT_IT_HERE = EntityMoveCursor_Invalid;
		return false;
	}

	if(collidpos_ok && closerThan(player.pos, pos, 300.f)) {
		if(simulate) {
			ARX_INTERACTIVE_Teleport(io, pos, true);

			io->gameFlags &= ~GFLAG_NOCOMPUTATION;
			
			glm::quat rotation = glm::toQuat(toRotationMatrix(temp));
			
			if(SPECIAL_DRAGINTER_RENDER) {
			if(glm::abs(lastanything) > glm::abs(height)) {
				TransformInfo t(collidpos, rotation, io->scale);

				static const float invisibility = 0.5f;

				DrawEERIEInter(io->obj, t, io, false, invisibility);
			} else {
				TransformInfo t(pos, rotation, io->scale);

				float invisibility = Cedric_GetInvisibility(io);

				DrawEERIEInter(io->obj, t, io, false, invisibility);
			}
			}
		} else {
			if(glm::abs(lastanything) > std::min(glm::abs(height), 12.0f)) {
				Entity * io = DRAGINTER;
				ARX_PLAYER_Remove_Invisibility();
				io->obj->pbox->active = 1;
				io->obj->pbox->stopcount = 0;
				io->pos = collidpos;
				io->velocity = Vec3f_ZERO;

				io->stopped = 1;

				movev.x *= 0.0001f;
				movev.y = 0.1f;
				movev.z *= 0.0001f;
				Vec3f viewvector = movev;

				Anglef angle = temp;
				io->soundtime = 0;
				io->soundcount = 0;
				EERIE_PHYSICS_BOX_Launch(io->obj, io->pos, angle, viewvector);
				ARX_SOUND_PlaySFX(SND_WHOOSH, &pos);
				io->show = SHOW_FLAG_IN_SCENE;
				Set_DragInter(NULL);
			} else {
				ARX_PLAYER_Remove_Invisibility();
				ARX_SOUND_PlayInterface(SND_INVSTD);
				ARX_INTERACTIVE_Teleport(io, pos, true);

				io->angle.setYaw(temp.getYaw());
				io->angle.setPitch(270.f - temp.getPitch());
				io->angle.setRoll(temp.getRoll());

				io->stopped = 0;
				io->show = SHOW_FLAG_IN_SCENE;
				io->obj->pbox->active = 0;
				Set_DragInter(NULL);
			}
		}

		GRenderer->SetCulling(CullNone);
		return true;
	} else {
		CANNOT_PUT_IT_HERE = EntityMoveCursor_Throw;
	}

	return false;
}
Ejemplo n.º 10
0
void CinderOpenNISkeleton::drawDebug(Font font)  {
	
	XnUserID aUsers[15];
	XnUInt16 nUsers = 15;
	
	
	gCinderOpenNISkeleton->mUserGenerator.GetUsers(aUsers, nUsers);
			
	for (int i = 0; i < nUsers; ++i){
		
		// Do the labels first
		
		XnPoint3D com;
		gCinderOpenNISkeleton->mUserGenerator.GetCoM(aUsers[i], com);
		gCinderOpenNISkeleton->mDepthGenerator.ConvertRealWorldToProjective(1, &com, &com);
	
		glColor4f(1-Colors[i%nColors][0], 1-Colors[i%nColors][1], 1-Colors[i%nColors][2], 1);
		
		if (gCinderOpenNISkeleton->mUserGenerator.GetSkeletonCap().IsTracking(aUsers[i]))
		{
			// Tracking
			gl::drawString("Tracking", Vec2i(com.X, com.Y), Color::white(), font );

		}
		else if (gCinderOpenNISkeleton->mUserGenerator.GetSkeletonCap().IsCalibrating(aUsers[i]))
		{
			gl::drawString("Calibrating", Vec2i(com.X, com.Y), Color::white(), font );
		}
		else
		{
			gl::drawString("Looking for Pose", Vec2i(com.X, com.Y), Color::white(), font );
		}
	
		
		
		if( gCinderOpenNISkeleton->mUserGenerator.GetSkeletonCap().IsTracking(aUsers[i])){ 
			
			app::console() << "Is Tracking User" << endl;
			
			glLineWidth(6.0);
			glBegin(GL_LINES);
			glColor4f(1-Colors[aUsers[i]%nColors][0], 
					  1-Colors[aUsers[i]%nColors][1], 
					  1-Colors[aUsers[i]%nColors][2], 1);
			
			
			drawLimbDebug(aUsers[i], XN_SKEL_HEAD, XN_SKEL_NECK);
			
			drawLimbDebug(aUsers[i], XN_SKEL_NECK, XN_SKEL_LEFT_SHOULDER);
			drawLimbDebug(aUsers[i], XN_SKEL_LEFT_SHOULDER, XN_SKEL_LEFT_ELBOW);
			drawLimbDebug(aUsers[i], XN_SKEL_LEFT_ELBOW, XN_SKEL_LEFT_HAND);
			
			drawLimbDebug(aUsers[i], XN_SKEL_NECK, XN_SKEL_RIGHT_SHOULDER);
			drawLimbDebug(aUsers[i], XN_SKEL_RIGHT_SHOULDER, XN_SKEL_RIGHT_ELBOW);
			drawLimbDebug(aUsers[i], XN_SKEL_RIGHT_ELBOW, XN_SKEL_RIGHT_HAND);
			
			drawLimbDebug(aUsers[i], XN_SKEL_LEFT_SHOULDER, XN_SKEL_TORSO);
			drawLimbDebug(aUsers[i], XN_SKEL_RIGHT_SHOULDER, XN_SKEL_TORSO);
			
			drawLimbDebug(aUsers[i], XN_SKEL_TORSO, XN_SKEL_LEFT_HIP);
			drawLimbDebug(aUsers[i], XN_SKEL_LEFT_HIP, XN_SKEL_LEFT_KNEE);
			drawLimbDebug(aUsers[i], XN_SKEL_LEFT_KNEE, XN_SKEL_LEFT_FOOT);
			
			drawLimbDebug(aUsers[i], XN_SKEL_TORSO, XN_SKEL_RIGHT_HIP);
			drawLimbDebug(aUsers[i], XN_SKEL_RIGHT_HIP, XN_SKEL_RIGHT_KNEE);
			drawLimbDebug(aUsers[i], XN_SKEL_RIGHT_KNEE, XN_SKEL_RIGHT_FOOT);
			
			drawLimbDebug(aUsers[i]	, XN_SKEL_LEFT_HIP, XN_SKEL_RIGHT_HIP);
			
			glEnd();
		}
	}
}
Ejemplo n.º 11
0
// copied from the orange book
GlTexture* NoiseGenerator::make3Dnoise(int size, float ampStart, float ampDiv, int startFrequency)
{

    int f, i, j, k, inc;
    //int startFrequency = 4;
    int numOctaves = NUM_OCT; //4;
    double ni[3];
    double inci, incj, inck;
    int frequency = startFrequency;
    double amp = ampStart;

    double minn = 100.0, maxn = -100.0;

// 	uint bufsize = noise3DTexSize * noise3DTexSize * noise3DTexSize * 4;
// 	if ((noise3DTexPtr = (GLubyte *) malloc(bufsize)) == nullptr)
// 	{
// 		printf("ERROR: Could not allocate 3D noise texture - %d bytes\n", bufsize);
// 		return nullptr;
// 	}
    Space3D<Vec4b> noise3DTexPtr(size, size, size);

    byte *ptr = noise3DTexPtr.ptr()->v;

    for (f = 0, inc = 0; f < numOctaves; ++f, frequency *= 2, ++inc, amp *= ampDiv)
    {
        setNoiseFrequency(frequency);
        ni[0] = ni[1] = ni[2] = 0;

        inci = 1.0 / (size / frequency);
        for (i = 0; i < size; ++i, ni[0] += inci)
        {
            incj = 1.0 / (size / frequency);
            for (j = 0; j < size; ++j, ni[1] += incj)
            {
                inck = 1.0 / (size / frequency);
                for (k = 0; k < size; ++k, ni[2] += inck, ptr+= 4)
                {
                    double ns = noise3(ni) * N_FACT;
                    *(ptr+inc) = (GLubyte)(((ns+1.0) * amp)*255.0);
                    if (ns > maxn)
                        maxn = ns;
                    if (ns < minn)
                        minn = ns;
                }
            }
        }
    }

    //GlTexture *tex = new GlTexture();
    //tex->init(GL_TEXTURE_3D, QSize(size, size), size, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, 
    //		 noise3DTexPtr, GL_LINEAR, GL_LINEAR, GL_REPEAT); //GL_NEAREST

    printf("%lf - %lf = %lf\n", maxn, minn, maxn - minn);
    Vec2i sz2d;
    uchar* buf2d = saveto2D(noise3DTexPtr, size, size/4, 8, &sz2d);

    GlTexture *tex = new GlTexture();

    tex->init(GL_TEXTURE_2D, Vec2i(sz2d.x, sz2d.y), 1, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, buf2d, GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE);
    
/*	
    QImage img(buf2d, sz2d.x, sz2d.y, QImage::Format_ARGB32);
    img.save("c:/temp/cubeTex.jpg");
*/
    delete[] buf2d;

    return tex;

}
Ejemplo n.º 12
0
void InitGameMemory(game_memory *Memory, Canvas &canvas)
{
	// �I�~�y���y�p�|�y�x�p���y��
	game_state* GameState = (game_state*)Memory->PermanentStorage;

	InitializeArena(&GameState->WorldArena, Memory->PermanentStorageSize - sizeof(game_state), (uint8*)Memory->PermanentStorage + sizeof(game_state));

	GameState->World = PushStruct(&GameState->WorldArena, world);
	world *World = GameState->World;
	World->TileMap = PushStruct(&GameState->WorldArena, tile_map);
	tile_map *TileMap = World->TileMap;

	GameState->Tick = 0;
	GameState->TimeElapsedFromLastTick = 0;

	// Camera 
	GameState->CameraPos.Tile = Vec2i(0, 0);
	GameState->CameraPos.TilePos = Vec2f(0, 0);
	GameState->CameraOrigin = GameState->ScreenSize / 2.0f;

	GameState->EntityToCameraIn = Rect(-7, -5, 7, 5);
	GameState->EntityToCameraOut = Rect(-8, -6, 8, 6);

	// �H�p�s�����x�y���� �������p�z����
	GameState->LoadGameSpriteFromImage(canvas, GameState->GameSprites.tmp_sprite, "sand_tile_01.png");
	GameState->LoadGameSpriteFromImage(canvas, GameState->GameSprites.tmp_object_sprite_001, "object_storage_01.png");
	GameState->LoadGameSpriteFromImage(canvas, GameState->GameSprites.tmp_object_sprite_stone1, "object_stone_01.png");
	GameState->LoadGameSpriteFromImage(canvas, GameState->GameSprites.tmp_player_image, "robot_base_horizontal.png");
	GameState->LoadGameSpriteFromImage(canvas, GameState->GameSprites.tmp_player_image_v, "robot_base_vertical.png");
	GameState->LoadGameSpriteFromImage(canvas, GameState->GameSprites.tmp_player_image_ur, "robot_base_diagonal_ur.png");
	GameState->LoadGameSpriteFromImage(canvas, GameState->GameSprites.tmp_player_image_ul, "robot_base_diagonal_ul.png");

	GameState->LoadGameSpriteFromResource(canvas, &GameState->game_resources, GameState->GameSprites.tmp_ground_sprite_01, "ground_concrete_tileset");
	GameState->AddGameSpriteFrameFromImage(canvas, GameState->GameSprites.tmp_ground_sprite_01, "ground_tile_01.png");

	GameState->LoadGameSpriteFromResource(canvas, &GameState->game_resources, GameState->GameSprites.tmp_player_image_torso, "robot_torso");
	GameState->LoadGameSpriteFromResource(canvas, &GameState->game_resources, GameState->GameSprites.tmp_player_image_track_down, "track_v_down");
	GameState->LoadGameSpriteFromResource(canvas, &GameState->game_resources, GameState->GameSprites.tmp_player_image_track_left, "track_h_left");
	GameState->LoadGameSpriteFromResource(canvas, &GameState->game_resources, GameState->GameSprites.tmp_player_image_track_right, "track_h_right");
	GameState->LoadGameSpriteFromResource(canvas, &GameState->game_resources, GameState->GameSprites.tmp_player_image_track_up, "track_v_up");
	GameState->LoadGameSpriteFromResource(canvas, &GameState->game_resources, GameState->GameSprites.tmp_player_image_track_ur, "track_d_ur");
	GameState->LoadGameSpriteFromResource(canvas, &GameState->game_resources, GameState->GameSprites.tmp_player_image_track_ul, "track_d_ul");
	GameState->LoadGameSpriteFromResource(canvas, &GameState->game_resources, GameState->GameSprites.tmp_player_image_track_br, "track_d_br");
	GameState->LoadGameSpriteFromResource(canvas, &GameState->game_resources, GameState->GameSprites.tmp_player_image_track_bl, "track_d_bl");

	GameState->LoadGameSpriteFromResource(canvas, &GameState->game_resources, GameState->GameSprites.tmp_wall_sprite1, "tileset_brick_wall");

	// Player entity
	//
	GameState->PlayerEntity = AddEntity(GameState);
	GameState->PlayerEntity->Position.Tile = Vec2i(0, 0);
	GameState->PlayerEntity->Position.TilePos = Vec2f(0, 0);
	GameState->PlayerEntity->EntityType = EntityType_Robot;
	GameState->PlayerEntity->CollisionType = 1;
	GameState->PlayerEntity->CollisionBox = Rectf(-0.45f, -0.25f, 0.45f, 0.25f);
	GameState->PlayerEntity->Controller.Active = 1;

	GameState->PlayerEntity->Mass = 20000.0f;
	GameState->PlayerEntity->RResistance = 0.008f;

	SetEntityToActive(GameState->PlayerEntity, GameState);

	World->TileSizeMeters = Vec2f(1.0f, 1.0f);
	World->TileSizePixels = Vec2f(100.0f, 100.0f);
	World->MetersToPixels = World->TileSizePixels / World->TileSizeMeters;

	World->g = 4.2f;

	TileMap->TileChunkSize = Vec2ui(16, 16);
	//TileMap->CenterChunkPosition = TileMap->TileChunksCount / (uint32)2;

	GameState->TilesOnHalfScreen.width = (int)((GameState->ScreenSize.width / 2) / World->TileSizePixels.x) + 1;
	GameState->TilesOnHalfScreen.height = (int)((GameState->ScreenSize.height / 2) / World->TileSizePixels.y) + 1;

	Vec2i TilesPerScreen = GameState->TilesOnHalfScreen * 2;

	for (int32 ScreenY = -16; ScreenY < 16; ScreenY++)
	{
		for (int32 ScreenX = -16; ScreenX < 16; ScreenX++)
		{
			for (int32 TY = 0; TY < TilesPerScreen.y; TY++)
			{
				for (int32 TX = 0; TX < TilesPerScreen.x; TX++)
				{
					int32 AbsTileX = ScreenX * TilesPerScreen.x + TX;
					int32 AbsTileY = ScreenY * TilesPerScreen.y + TY;

					SetTileValue(&GameState->WorldArena, TileMap, Vec2i(AbsTileX, AbsTileY), rand() % 16 + 1);
				}
			}
		}
	}
	/*
	for (int32 Y = 1; Y < 4; Y++)
	{
		for (int32 X = 1; X < 5; X++)
		{
			SetTileValue(&GameState->WorldArena, TileMap, Vec2i(X, Y), 5);
			SetTileValue(&GameState->WorldArena, TileMap, Vec2i(X - 7, Y), 5);
			SetTileValue(&GameState->WorldArena, TileMap, Vec2i(X - 5, Y + 6), 4);
		}
	}
	*/

	// Game entities
	GameState->TiledEntities.Entities = PushArray(&GameState->WorldArena, 4096, entity);
	GameState->TiledEntities.GroupSize = 4096;
	GameState->TiledEntities.EntityCount = 0;
	GameState->TiledEntities.NextGroup = 0;
	AddEntityToGroup(&GameState->WorldArena, &GameState->TiledEntities); // �N���|�u�r���z ���q���u�{�� �~�u �y�������|���x���u������

	// Add many stone entities
	world_position EntityPos;
	//Rectf CollisionBox(-0.4f, 0.0f, 0.4f, 0.3f);
	Rectf CollisionBox(-0.5f, -0.5f, 0.5f, 0.5f);
	for (int32 Y = 1; Y < 10; Y++)
	{
		for (int32 X = 1; X < 10; X++)
		{
			EntityPos.Tile = Vec2i(X, Y);
			EntityPos.TilePos = Vec2f(0, 0);

			uint32 StoneIndex = AddEntityToGroup(&GameState->WorldArena, &GameState->TiledEntities);
			entity *Entity = GetEntityFromGroupByIndex(&GameState->TiledEntities, StoneIndex);
			Entity->EntityType = EntityType_Storage;
			Entity->Position = EntityPos;
			Entity->CollisionType = 1;
			Entity->CollisionBox = CollisionBox;
			AddEntityToTile(GameState->World->TileMap, EntityPos.Tile, StoneIndex);
		}
	}

	/*
	EntityPos.Tile = Vec2i(1, 1);
	EntityPos.TilePos = Vec2f(0, 0);
	entity *Entity = AddEntity(GameState);
	Entity->EntityType = EntityType_Stone;
	Entity->Position = EntityPos;
	Entity->CollisionType = 1;
	Entity->CollisionBox = CollisionBox;
	//SetEntityToActive(Entity, GameState);

	/*
	Entity = AddEntity(GameState);
	Entity->EntityType = EntityType_Wall;
	EntityPos.Tile = Vec2i(0, -2);
	Entity->Position = EntityPos;
	Entity->CollisionType = 1;
	Entity->CollisionBox = Rectf(-0.5f, -0.1f, 0.5f, 0.1f);
	Entity->EntityFrame = 0;
	//SetEntityToActive(Entity, GameState);
	*/

	// Call to camera reset to activate entities in camera space
	MapEntitiesInCameraSpace(GameState);

	GameState->IsInitialized = 1;
}
Ejemplo n.º 13
0
Vec2i Screen::getSize() const
{
	return Vec2i( mScreen.widthPixels(), mScreen.heightPixels() );
}
Ejemplo n.º 14
0
 Vec2i Texture::getCleanSize() const
 {
     return Vec2i(width * maxU, height * maxV);
 }
Ejemplo n.º 15
0
void GUI_Button::onRender()
{
	GUI& gui = GUI::inst();
	int offset = 0;

	if(useSkin())
	{
		if(style == 0)
		{
			// Button zeichnen
			gui.renderFrame(Vec2i(0, 0), size, pushed && mouseOver ? Vec2i(48, 96) : Vec2i(0, 96));
			offset = -1;
		}
		else
		{
			Vec2i t = positionOnTexture;
			if(pushed && mouseOver) t = clickedPositionOnTexture;

			glPushMatrix();
			glTranslated(size.x / 2, size.y / 2, 0.0);
			glScaled(currentScaling, currentScaling, 1.0);
			Engine::inst().renderSprite(p_image, -size / 2, t, size, currentColor);
			glPopMatrix();
		}
	}
	else
	{
		// Hintergrund zeichnen
		glBegin(GL_QUADS);
		if(pushed && mouseOver) glColor4d(0.9, 0.9, 0.9, 1.0);
		else glColor4d(0.75, 0.75, 0.75, 1.0);
		glVertex2i(0, 0);
		glVertex2i(size.x, 0);
		if(pushed && mouseOver) glColor4d(0.8, 0.8, 0.8, 1.0);
		else glColor4d(0.65, 0.65, 0.65, 1.0);
		glVertex2i(size.x, size.y);
		glVertex2i(0, size.y);
		glEnd();

		// Rahmen zeichnen
		glColor4d(0.0, 0.0, 0.0, 1.0);
		glBegin(GL_LINE_LOOP);
		glVertex2i(0, 0);
		glVertex2i(size.x, 0);
		glVertex2i(size.x, size.y);
		glVertex2i(0, size.y);
		glEnd();
	}

	// Titel schreiben
	Vec2i dim;
	std::string title = localizeString(this->title);
	p_font->measureText(title, &dim, 0);

	if(style == 0)
	{
		p_font->renderText(title, (size - dim) / 2 + Vec2i(0, offset), active ? Vec4d(1.0, 1.0, 1.0, 1.0) : Vec4d(0.5, 0.5, 0.5, 1.0));

		if(p_image)
		{
			// Bild rendern
			Engine::inst().renderSprite(p_image, Vec2i(0, offset), positionOnTexture, size, Vec4d(1.0));
		}
	}
	else
	{
		p_font->renderText(title, Vec2i((size.x - dim.x) / 2, size.y - 4), active ? currentColor : Vec4d(0.5, 0.5, 0.5, 1.0));
	}
}
Ejemplo n.º 16
0
    DetectionQualityStructure ParticleExtractor::compareWithGroundTruth(ParticleData ground, ParticleData candidate, std::string outputFilename)
    {
        DetectionQualityStructure result;
        Vec2i shiftForGround = Vec2i(0, 0);
        Vec2i shiftForCandid = Vec2i(0, 0);

        Vec2i groundHalfSize = Vec2i(static_cast<int>(ground.size.x / 2), static_cast<int>(ground.size.y / 2));
        Vec2i candidHalfSize = Vec2i(static_cast<int>(candidate.size.x / 2), static_cast<int>(candidate.size.y / 2));

        if(!ground.coordinateOfCenter)
        {
            shiftForGround = shiftForGround + groundHalfSize;
        }
        if(!candidate.coordinateOfCenter)
        {
            shiftForCandid = shiftForCandid + candidHalfSize;
        }

        std::vector<Vec3ui> groundList;
        std::vector<Vec3ui> candidList;

        ParticleExtractor::createUniquePointsListFrom2DCoordinates(ground.data, groundList);
        ParticleExtractor::createUniquePointsListFrom2DCoordinates(candidate.data, candidList);

        std::vector<Vec3ui> correctFound;
        std::vector<Vec3ui> notFound;
        std::vector<Vec3ui> correctGuess;
        std::vector<Vec3ui> wrongGuess;

        unsigned int idGround;
        unsigned int idCandid;
        Vec2i tempGround;
        Vec2i tempCandid;
        bool found = false;
        double error = 0.0f;
        double errorSum = 0.0f;

        auto selectedGround = groundList.begin();
        std::ofstream output(outputFilename);
        output << "Pairs from (G)round and (C)andidate by IDs:" << std::endl;
        for( auto itc = candidList.begin(); itc != candidList.end(); ++itc )
        {
            idCandid = itc->z;
            tempCandid = Vec2i(static_cast<int>(itc->x) + shiftForCandid.x, static_cast<int>(itc->y) + shiftForCandid.y);

            for( auto itg = groundList.begin(); itg != groundList.end(); ++itg )
            {
                idGround = itg->z;

                tempGround = Vec2i(static_cast<int>(itg->x + shiftForGround.x), static_cast<int>(itg->y) + shiftForGround.y);

                if(   (tempCandid.x >= (tempGround.x - groundHalfSize.x)) && (tempCandid.x < (tempGround.x + groundHalfSize.x))
                   && (tempCandid.y >= (tempGround.y - groundHalfSize.y)) && (tempCandid.y < (tempGround.y + groundHalfSize.y))
                  )
                {
                    if(!idGround )   // We already marked this particle from ground truth as found
                    {
                        output << "Found correspondence between G" << itg->z << "(" << itg->x << "," << itg->y << ")" << " and "
                               << "C" << itc->z << "(" << itc->x << "," << itc->y << "), but this ground truth particle was already found once before." << std::endl;
                        continue;
                    }

                    Vec2i diff = tempGround - tempCandid;
                    if( found ) // this candidate particle overlapped another particle from ground truth before
                    {
                        // choose only one of them, with lesser error
                        if( (diff.x*diff.x + diff.y*diff.y) >= error )
                        {
                            continue;
                        }
                    }
                    error = diff.x*diff.x + diff.y*diff.y;
                    selectedGround = itg;
                    found = true;
                }
            }

            if( found )
            {
                correctFound.push_back(*selectedGround);
                correctGuess.push_back(*itc);
                errorSum += sqrt(error);
                output << "\tG" << selectedGround->z << "  \t(" << selectedGround->x << "," << selectedGround->y << ")" << " \t<=" << error << "=> "
                       << "\tC" << itc->z << "  \t(" << itc->x << "," << itc->y << ")" << std::endl;
                selectedGround->z = 0;
            } else {
                wrongGuess.push_back(*itc);
            }
            found = false;
            error = 0.0f;
        }

        int counterNotFoundParticlesFromGroundList = 0;
        for( auto itg = groundList.begin(); itg != groundList.end(); ++itg )
        {
            if( itg->z != 0 )
            {
                ++counterNotFoundParticlesFromGroundList;
                notFound.push_back(*itg);
            }
        }

        result.set(correctFound.size(), notFound.size(), wrongGuess.size(), errorSum);
        output << result << std::endl;

        output << "TruePositives[ground]:" << correctFound.size() << " FalseNegatives:" << notFound.size() << std::endl
               << " TruePositives[candidate]:" << correctGuess.size() << " FalsePositives:" << wrongGuess.size()  << std::endl
               << " Error:" << errorSum << " Ground:" << ground.data->size() << std::endl;
        ParticleExtractor::printParticleDistributionDetails(output, correctFound, notFound, correctGuess, wrongGuess);
        output.close();

        return result;
    }
Ejemplo n.º 17
0
Vec2i AppImplMsw::mouseLocation()
{
	POINT point;
	::GetCursorPos( &point );
	return Vec2i( point.x - mWindowOffset.x, point.y - mWindowOffset.y );
}
Ejemplo n.º 18
0
	void init() {
		
		{
			ButtonWidget * cb = new ButtonWidget(Vec2i(0, 0), "graph/interface/icons/menu_main_load");
			cb->SetCheckOff();
			addCenter(cb, true);
		}
		
		std::string quicksaveName = getLocalised("system_menus_main_quickloadsave", "Quicksave");
		
		// TODO make this list scrollable
		// TODO align the date part to the right!
		
		{
		size_t quicksaveNum = 0;
		
		// Show quicksaves.
		for(size_t i = 0; i < savegames.size(); i++) {
			const SaveGame & save = savegames[i];
			
			if(!save.quicksave) {
				continue;
			}
			
			std::ostringstream text;
			text << quicksaveName << ' ' << ++quicksaveNum << "   " << save.time;
			
			TextWidget * e = new TextWidget(BUTTON_MENUEDITQUEST_LOAD, hFontControls, text.str(), Vec2i(RATIO_X(20), 0));
			e->m_savegame = SavegameHandle(i);
			addCenter(e);
		}
		
		// Show regular saves.
		for(size_t i = 0; i < savegames.size(); i++) {
			const SaveGame & save = savegames[i];
			
			if(save.quicksave) {
				continue;
			}
			
			std::string text = save.name +  "   " + save.time;
			
			TextWidget * e = new TextWidget(BUTTON_MENUEDITQUEST_LOAD, hFontControls, text, Vec2i(RATIO_X(20), 0));
			e->m_savegame = SavegameHandle(i);
			addCenter(e);
		}
		
		{
			TextWidget * confirm = new TextWidget(BUTTON_INVALID, hFontControls, " ", Vec2i(RATIO_X(20), 0));
			confirm->m_targetMenu = EDIT_QUEST_SAVE_CONFIRM;
			confirm->SetCheckOff();
			confirm->m_savegame = SavegameHandle::Invalid;
			addCenter(confirm);
		}
		
		// Delete button
		{
			std::string szMenuText = getLocalised("system_menus_main_editquest_delete");
			szMenuText += "   ";
			TextWidget * me = new TextWidget(BUTTON_MENUEDITQUEST_DELETE_CONFIRM, hFontMenu, szMenuText, Vec2i(0, 0));
			me->m_targetMenu = EDIT_QUEST_LOAD;
			me->SetPos(Vec2i(RATIO_X(m_size.x-10)-me->m_rect.width(), RATIO_Y(42)));
			me->SetCheckOff();
			me->lOldColor = me->lColor;
			me->lColor = Color::grayb(127);
			add(me);
			pDeleteConfirm = me;
		}
		
		// Load button
		{
			std::string szMenuText = getLocalised("system_menus_main_editquest_load");
			szMenuText += "   ";
			TextWidget * me = new TextWidget(BUTTON_MENUEDITQUEST_LOAD_CONFIRM, hFontMenu, szMenuText, Vec2i(0, 0));
			me->m_targetMenu = MAIN;
			me->SetPos(Vec2i(RATIO_X(m_size.x-10)-me->m_rect.width(), RATIO_Y(380) + RATIO_Y(40)));
			me->SetCheckOff();
			me->lOldColor = me->lColor;
			me->lColor = Color::grayb(127);
			add(me);
			pLoadConfirm = me;
		}
		
		// Back button
		{
			ButtonWidget * cb = new ButtonWidget(RATIO_2(Vec2i(20, 420)), "graph/interface/menus/back");
			cb->clicked = boost::bind(&LoadMenuPage::onClickBack, this);
			cb->m_targetMenu = EDIT_QUEST;
			cb->SetShortCut(Keyboard::Key_Escape);
			add(cb);
		}
		}
	}
Ejemplo n.º 19
0
void ShowFPS() {
	std::ostringstream oss;
	oss << std::fixed << std::setprecision(2) << FPS << " FPS";
	hFontDebug->draw(Vec2i(10, 10), oss.str(), Color::white);
}
Ejemplo n.º 20
0
	void init() {
		
		{
			ButtonWidget * cb = new ButtonWidget(Vec2i(RATIO_X(10), 0), "graph/interface/icons/menu_main_save");
			cb->SetCheckOff();
			addCenter(cb, true);
		}
		
		std::string quicksaveName = getLocalised("system_menus_main_quickloadsave", "Quicksave");
		size_t quicksaveNum = 0;
		
		// Show quicksaves.
		for(size_t i = 0; i < savegames.size(); i++) {
			const SaveGame & save = savegames[i];
			
			if(!save.quicksave) {
				continue;
			}
			
			std::ostringstream text;
			text << quicksaveName << ' ' << ++quicksaveNum << "   " << save.time;
			
			TextWidget * e = new TextWidget(BUTTON_MENUEDITQUEST_SAVEINFO, hFontControls, text.str(), Vec2i(RATIO_X(20), 0.f));
			e->m_targetMenu = EDIT_QUEST_SAVE_CONFIRM;
			e->setColor(Color::grayb(127));
			e->SetCheckOff();
			e->m_savegame = SavegameHandle(i);
			addCenter(e);
		}
		
		// Show regular saves.
		for(size_t i = 0; i < savegames.size(); i++) {
			const SaveGame & save = savegames[i];
			
			if(save.quicksave) {
				continue;
			}
			
			std::string text = save.name +  "   " + save.time;
			
			TextWidget * e = new TextWidget(BUTTON_MENUEDITQUEST_SAVEINFO, hFontControls, text, Vec2i(RATIO_X(20), 0.f));
			e->m_targetMenu = EDIT_QUEST_SAVE_CONFIRM;
			e->m_savegame = SavegameHandle(i);
			addCenter(e);
		}
		
		for(size_t i = savegames.size(); i <= 15; i++) {
			
			std::ostringstream text;
			text << '-' << std::setfill('0') << std::setw(4) << i << '-';
			
			TextWidget * e = new TextWidget(BUTTON_MENUEDITQUEST_SAVEINFO, hFontControls, text.str(), Vec2i(RATIO_X(20), 0));
			e->m_targetMenu = EDIT_QUEST_SAVE_CONFIRM;
			e->m_savegame = SavegameHandle::Invalid;
			addCenter(e);
		}
	
		{
			TextWidget * me01 = new TextWidget(BUTTON_INVALID, hFontControls, " ", Vec2i(RATIO_X(20), 0));
			me01->m_targetMenu = EDIT_QUEST_SAVE_CONFIRM;
			me01->m_savegame = SavegameHandle::Invalid;
			me01->SetCheckOff();
			addCenter(me01);
		}
		
		{
			ButtonWidget * cb = new ButtonWidget(RATIO_2(Vec2i(20, 420)), "graph/interface/menus/back");
			cb->m_targetMenu = EDIT_QUEST;
			cb->SetShortCut(Keyboard::Key_Escape);
			add(cb);
		}
	}
Ejemplo n.º 21
0
#include <stddef.h>
#include <string>
#include <cstdlib>

#include <boost/foreach.hpp>

#include "graphics/Math.h"
#include "graphics/Renderer.h"
#include "graphics/texture/Texture.h"

#include "io/resource/ResourcePath.h"
#include "io/resource/PakReader.h"
#include "io/log/Logger.h"

static const Vec2i cinMaxSize = Vec2i(256, 256);

CinematicBitmap::~CinematicBitmap()
{
	grid.FreeGrille();
}

CinematicBitmap * CreateCinematicBitmap(const res::path & path, int scale) {
	
	std::string name = path.basename();
	if(name.empty()) {
		return 0;
	}
	
	CinematicBitmap * bi = new CinematicBitmap();
	if(!bi)
Ejemplo n.º 22
0
	void init() {
		
		// Renderer selection
		{
			HorizontalPanelWidget * pc = new HorizontalPanelWidget;
			std::string szMenuText = getLocalised("system_menus_options_video_renderer", "Renderer");
			szMenuText += "  ";
			TextWidget * me = new TextWidget(BUTTON_INVALID, hFontMenu, szMenuText, Vec2i(RATIO_X(20), 0));
			me->SetCheckOff();
			pc->AddElement(me);
			CycleTextWidget * slider = new CycleTextWidget;
			slider->valueChanged = boost::bind(&VideoOptionsMenuPage::onChangedRenderer, this, _1, _2);
			
			{
				TextWidget * text = new TextWidget(BUTTON_INVALID, hFontMenu, "Auto-Select", Vec2i(0, 0));
				slider->AddText(text);
				slider->selectLast();
			}
			
	#if ARX_HAVE_SDL1 || ARX_HAVE_SDL2
			{
				TextWidget * text = new TextWidget(BUTTON_INVALID, hFontMenu, "OpenGL", Vec2i(0, 0));
				slider->AddText(text);
				if(config.window.framework == "SDL") {
					slider->selectLast();
				}
			}
	#endif
			
			float fRatio    = (RATIO_X(m_size.x-9) - slider->m_rect.width());
			slider->Move(Vec2i(checked_range_cast<int>(fRatio), 0));
			pc->AddElement(slider);
			addCenter(pc);
		}
		
		{
			std::string szMenuText = getLocalised("system_menus_options_videos_full_screen");
			if(szMenuText.empty()) {
				// TODO once we ship our own amendmends to the loc files a cleaner
				// fix would be to just define system_menus_options_videos_full_screen
				// for the german version there
				szMenuText = getLocalised("system_menus_options_video_full_screen");
			}
			szMenuText += "  ";
			TextWidget * text = new TextWidget(BUTTON_INVALID, hFontMenu, szMenuText, Vec2i(RATIO_X(20), 0.f));
			text->SetCheckOff();
			CheckboxWidget * cb = new CheckboxWidget(text);
			cb->stateChanged = boost::bind(&VideoOptionsMenuPage::onChangedFullscreen, this, _1);
			cb->iState = config.video.fullscreen ? 1 : 0;
			addCenter(cb);
			fullscreenCheckbox = cb;
		}
		
		{
			HorizontalPanelWidget * pc = new HorizontalPanelWidget;
			std::string szMenuText = getLocalised("system_menus_options_video_resolution");
			szMenuText += "  ";
			TextWidget * me = new TextWidget(BUTTON_INVALID, hFontMenu, szMenuText, Vec2i(RATIO_X(20), 0.f));
			me->SetCheckOff();
			pc->AddElement(me);
			pMenuSliderResol = new CycleTextWidget;
			pMenuSliderResol->valueChanged = boost::bind(&VideoOptionsMenuPage::onChangedResolution, this, _1, _2);
			
			pMenuSliderResol->setEnabled(config.video.fullscreen);
			
			const RenderWindow::DisplayModes & modes = mainApp->getWindow()->getDisplayModes();
			for(size_t i = 0; i != modes.size(); ++i) {
				
				const DisplayMode & mode = modes[i];
				
				// find the aspect ratio
				unsigned a = mode.resolution.x;
				unsigned b = mode.resolution.y;
				while(b != 0) {
					unsigned t = a % b;
					a = b, b = t;
				}
				Vec2i aspect = mode.resolution / Vec2i(a);
				
				std::stringstream ss;
				ss << mode;
				
				if(aspect.x < 100 && aspect.y < 100) {
					if(aspect == Vec2i(8, 5)) {
						aspect = Vec2i(16, 10);
					}
					ss << " (" << aspect.x << ':' << aspect.y << ')';
				}
				
				pMenuSliderResol->AddText(new TextWidget(BUTTON_INVALID, hFontMenu, ss.str()));
				
				if(mode.resolution == config.video.resolution) {
					pMenuSliderResol->selectLast();
				}
			}
			
			pMenuSliderResol->AddText(new TextWidget(BUTTON_INVALID, hFontMenu, AUTO_RESOLUTION_STRING));
			
			if(config.video.resolution == Vec2i_ZERO) {
				pMenuSliderResol->selectLast();
			}
		
			float fRatio    = (RATIO_X(m_size.x-9) - pMenuSliderResol->m_rect.width()); 
		
			pMenuSliderResol->Move(Vec2i(checked_range_cast<int>(fRatio), 0));
			
			pc->AddElement(pMenuSliderResol);
			addCenter(pc);
		}
		
		{
			HorizontalPanelWidget * pc = new HorizontalPanelWidget;
			std::string szMenuText = getLocalised("system_menus_options_detail");
			szMenuText += " ";
			TextWidget * me = new TextWidget(BUTTON_INVALID, hFontMenu, szMenuText, Vec2i(RATIO_X(20), 0));
			me->SetCheckOff();
			pc->AddElement(me);
			
			CycleTextWidget * cb = new CycleTextWidget;
			cb->valueChanged = boost::bind(&VideoOptionsMenuPage::onChangedQuality, this, _1, _2);
			szMenuText = getLocalised("system_menus_options_video_texture_low");
			cb->AddText(new TextWidget(BUTTON_INVALID, hFontMenu, szMenuText));
			szMenuText = getLocalised("system_menus_options_video_texture_med");
			cb->AddText(new TextWidget(BUTTON_INVALID, hFontMenu, szMenuText));
			szMenuText = getLocalised("system_menus_options_video_texture_high");
			cb->AddText(new TextWidget(BUTTON_INVALID, hFontMenu, szMenuText));
			cb->setValue(config.video.levelOfDetail);
			
			cb->Move(Vec2i(RATIO_X(m_size.x-9) - cb->m_rect.width(), 0));
			pc->AddElement(cb);
			
			addCenter(pc);
		}
		
		{
			HorizontalPanelWidget * pc = new HorizontalPanelWidget;
			std::string szMenuText = getLocalised("system_menus_options_video_brouillard");
			TextWidget * me = new TextWidget(BUTTON_INVALID, hFontMenu, szMenuText, Vec2i(RATIO_X(20), 0.f));
			me->SetCheckOff();
			pc->AddElement(me);
			SliderWidget * sld = new SliderWidget(Vec2i(RATIO_X(200), 0));
			sld->valueChanged = boost::bind(&VideoOptionsMenuPage::onChangedFogDistance, this, _1);
			sld->setValue(config.video.fogDistance);
			pc->AddElement(sld);
			addCenter(pc);
		}
		
		{
			std::string szMenuText = getLocalised("system_menus_options_video_crosshair", "Show Crosshair");
			szMenuText += " ";
			TextWidget * text = new TextWidget(BUTTON_INVALID, hFontMenu, szMenuText, Vec2i(RATIO_X(20), 0.f));
			text->SetCheckOff();
			CheckboxWidget * cb = new CheckboxWidget(text);
			cb->stateChanged = boost::bind(&VideoOptionsMenuPage::onChangedCrosshair, this, _1);
			cb->iState = config.video.showCrosshair ? 1 : 0;
			addCenter(cb);
		}
		
		{
			std::string szMenuText = getLocalised("system_menus_options_video_antialiasing", "antialiasing");
			szMenuText += " ";
			TextWidget * text = new TextWidget(BUTTON_INVALID, hFontMenu, szMenuText, Vec2i(RATIO_X(20), 0));
			text->SetCheckOff();
			CheckboxWidget * cb = new CheckboxWidget(text);
			cb->stateChanged = boost::bind(&VideoOptionsMenuPage::onChangedAntialiasing, this, _1);
			cb->iState = config.video.antialiasing ? 1 : 0;
			addCenter(cb);
		}
		
		ARX_SetAntiAliasing();
		
		{
			std::string szMenuText = getLocalised("system_menus_options_video_vsync", "VSync");
			szMenuText += " ";
			TextWidget * text = new TextWidget(BUTTON_INVALID, hFontMenu, szMenuText, Vec2i(RATIO_X(20), 0));
			text->SetCheckOff();
			CheckboxWidget * cb = new CheckboxWidget(text);
			cb->stateChanged = boost::bind(&VideoOptionsMenuPage::onChangedVsync, this, _1);
			cb->iState = config.video.vsync ? 1 : 0;
			addCenter(cb);
		}
		
		{
			std::string szMenuText = getLocalised("system_menus_options_video_hud_scale", "Scale Hud");
			szMenuText += " ";
			TextWidget * text = new TextWidget(BUTTON_INVALID, hFontMenu, szMenuText, Vec2i(RATIO_X(20), 0));
			text->SetCheckOff();
			CheckboxWidget * cb = new CheckboxWidget(text);
			cb->stateChanged = boost::bind(&VideoOptionsMenuPage::onChangedHudScale, this, _1);
			cb->iState = config.video.hudScale ? 1 : 0;
			addCenter(cb);
		}
		
		{
			HorizontalPanelWidget * pc = new HorizontalPanelWidget;
			std::string szMenuText = getLocalised("system_menus_video_apply");
			szMenuText += "   ";
			TextWidget * me = new TextWidget(BUTTON_INVALID, hFontMenu, szMenuText, Vec2i(RATIO_X(240), 0));
			me->clicked = boost::bind(&VideoOptionsMenuPage::onClickedApply, this);
			me->SetPos(Vec2i(RATIO_X(m_size.x-10)-me->m_rect.width(), RATIO_Y(380) + RATIO_Y(40)));
			me->SetCheckOff();
			pc->AddElementNoCenterIn(me);
			pMenuElementApply = me;
			
			ButtonWidget * cb = new ButtonWidget(RATIO_2(Vec2i(20, 420)), "graph/interface/menus/back");
			cb->clicked = boost::bind(&VideoOptionsMenuPage::onClickedBack, this);
			cb->m_targetMenu = OPTIONS;
			cb->SetShortCut(Keyboard::Key_Escape);
			pc->AddElementNoCenterIn(cb);
			
			add(pc);
		}
	}
Ejemplo n.º 23
0
CinematicBitmap * CreateCinematicBitmap(const res::path & path, int scale) {
	
	std::string name = path.basename();
	if(name.empty()) {
		return 0;
	}
	
	CinematicBitmap * bi = new CinematicBitmap();
	if(!bi)
		return 0;

	LogDebug("loading cinematic texture " << path);

	res::path filename = path;
	bool foundPath = g_resources->getFile(filename.set_ext(".bmp")) != NULL;
	foundPath = foundPath || g_resources->getFile(filename.set_ext("tga"));
	if(!foundPath) {
		LogError << path << " not found";
		delete bi;
		return 0;
	}
	
	Image cinematicImage;
	cinematicImage.load(filename);
	
	Vec2i size = Vec2i(cinematicImage.getWidth(), cinematicImage.getHeight());
	Vec2i nb = size / cinMaxSize;
	
	if(size.x % cinMaxSize.x)
		nb.x++;

	if(size.y % cinMaxSize.y)
		nb.y++;
	
	bi->m_size = size;
	bi->m_count = nb;
	
	bi->grid.AllocGrille(bi->m_count, Vec2f(bi->m_size), Vec2f(((bi->m_size.x > cinMaxSize.x) ? cinMaxSize.x : bi->m_size.x), ((bi->m_size.y > cinMaxSize.y) ? cinMaxSize.y : bi->m_size.y)), scale);

	int h = bi->m_size.y;

	while(nb.y) {

		int h2;

		if((h - cinMaxSize.y) < 0)
			h2 = h;
		else
			h2 = cinMaxSize.y;

		int w = bi->m_size.x;
		int nbxx = nb.x;

		while(nbxx) {
			int w2 = (w - cinMaxSize.x) < 0 ? w : cinMaxSize.x;

			Texture * tex = GRenderer->createTexture();
			tex->create(size_t(w2), size_t(h2), cinematicImage.getFormat());
			tex->getImage().copy(cinematicImage, 0, 0,
			                     size_t(bi->m_size.x - w), size_t(bi->m_size.y - h), size_t(w2), size_t(h2));
			tex->upload();
			
			{
			Vec2i depc = Vec2i((bi->m_count.x - nbxx) * scale, (bi->m_count.y - nb.y) * scale);
			Vec2i tc = Vec2i(scale, scale);
			Vec2i bitmappos = Vec2i(bi->m_size.x - w, bi->m_size.y - h);
			Vec2i bitmapw = Vec2i(w2, h2);
			
			bi->grid.AddQuadUVs(depc, tc, bitmappos, bitmapw, tex);
			}

			w -= cinMaxSize.x;

			nbxx--;
		}

		h -= cinMaxSize.y;
		nb.y--;
	}

	bi->grid.m_scale = scale;

	bi->grid.ReajustUV();

	return bi;
}
Ejemplo n.º 24
0
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
void Rendering::calculateOverlayItemLayoutForSchemeAndCorner(OverlayItemRectMap* itemRectMap, OverlayItem::LayoutScheme layoutScheme, OverlayItem::AnchorCorner anchorCorner)
{
    CVF_ASSERT(layoutScheme == OverlayItem::HORIZONTAL || layoutScheme == OverlayItem::VERTICAL);

    const int border = 3;
    const Vec2i vpSize = Vec2i(static_cast<int>(m_camera->viewport()->width()), static_cast<int>(m_camera->viewport()->height()));
    const Vec2i vpPos  = Vec2i(m_camera->viewport()->x(), m_camera->viewport()->y());

    Vec2i cursor(0,0);
    switch (anchorCorner)
    {
        case OverlayItem::TOP_LEFT:     cursor.set(border, vpSize.y() - border); break;
        case OverlayItem::TOP_RIGHT:    cursor.set(vpSize.x() - border, vpSize.y() - border); break;
        case OverlayItem::BOTTOM_LEFT:  cursor.set(border, border); break;
        case OverlayItem::BOTTOM_RIGHT: cursor.set(vpSize.x() - border, border); break;
        default:                        cursor.set(border,border);
    }

    cursor += vpPos;

    // Adjust starting cursor position based on other already placed items in this anchor corner
    // The assumption here is that for each corner, the horizontal layout has already been added to the map
    if (layoutScheme == OverlayItem::VERTICAL)
    {
        OverlayItemRectMap::iterator it;
        for (it = itemRectMap->begin(); it != itemRectMap->end(); ++it)
        {
            const OverlayItem* placedItem = it->first;
            const Recti placedItemRect = it->second;
            if (placedItem->anchorCorner() == anchorCorner && placedItemRect.contains(cursor))
            {
                if (anchorCorner == OverlayItem::BOTTOM_LEFT || anchorCorner == OverlayItem::BOTTOM_RIGHT)
                {
                    cursor.y() += placedItemRect.height() + border;
                }
                else
                {
                    cursor.y() -= placedItemRect.height() + border;
                }
            }
        }
    }

    const size_t numOverlayItems = m_overlayItems.size();
    for (size_t i = 0; i < numOverlayItems; i++)
    {
        OverlayItem* item = m_overlayItems.at(i);
        if ((item->anchorCorner() == anchorCorner) && (item->layoutScheme() == layoutScheme))
        {
            // Find this position and size
            Vec2i position = cursor;
            Vec2ui size = item->sizeHint();
            if ((anchorCorner == OverlayItem::TOP_RIGHT) || (anchorCorner == OverlayItem::BOTTOM_RIGHT))
            {
                position.x() -= size.x();
            }

            if ((anchorCorner == OverlayItem::TOP_LEFT) || (anchorCorner == OverlayItem::TOP_RIGHT))
            {
                position.y() -= size.y();
            }

            // Store the position in the map
            Recti rect(position.x(), position.y(), static_cast<int>(size.x()), static_cast<int>(size.y()));
            (*itemRectMap)[item] = rect;

            // Find next position, moving the cursor
            if (layoutScheme == OverlayItem::HORIZONTAL)
            {
                if ((anchorCorner == OverlayItem::TOP_LEFT) || (anchorCorner == OverlayItem::BOTTOM_LEFT))
                {
                    cursor.x() += (size.x() + border);
                }
                else
                {
                    cursor.x() -= (size.x() + border);
                }
            }
            else if (layoutScheme == OverlayItem::VERTICAL)
            {
                if ((anchorCorner == OverlayItem::BOTTOM_LEFT) || (anchorCorner == OverlayItem::BOTTOM_RIGHT))
                {
                    cursor.y() += (size.y() + border);
                }
                else
                {
                    cursor.y() -= (size.y() + border);
                }
            }
            else
            {
                CVF_FAIL_MSG("Unhandled OverlayItem::LayoutDirection");
            }
        }
    }
}
Ejemplo n.º 25
0
Vec2i UtilityCinder::vectorCinderToUtilitea(const ci::Vec2i& vector)
{
	return Vec2i(vector.x, vector.y);
}
Ejemplo n.º 26
0
Archivo: game.cpp Proyecto: jokoon/eio
void game :: init(){
    pause_drawing=false;
    glines = VertexArray(Lines);
    conf.init("conf.cfg");
    cfg=&conf;
    fps_coeff = 1.f/cfg->getfloat("timestep");

    //srand((unsigned)time(0));
    window.setKeyRepeatEnabled(false);
    wincenter.x=window.getSize().x/2;
    wincenter.y=window.getSize().y/2;
    winsize.x=window.getSize().x;
    winsize.y=window.getSize().y;
    window.setFramerateLimit(fps_coeff);

    if(cfg->getint("stick_left"))
    {
        Vec2i screen_resolution;
        cfg->SET(screen_resolution);
#ifdef __APPLE__
        screen_resolution=Vec2i(1280,800);
#endif
        Vec2i windowpos(screen_resolution.x - winsize.x-10,25);
        cout << strfy(screen_resolution) << endl;
        cout << strfy(windowpos) << endl;
        window.setPosition(windowpos);
    }
    else
        window.setPosition(Vec2i(5,25));


    {
        Vec2 cons_view_size;
        cfg->SET(cons_view_size);
        console_view.setSize(Vec2(cons_view_size.x*wsize.x,cons_view_size.y*wsize.y));
        fixedview = window.getDefaultView();
        mainview=fixedview;
    }
    wsize = winsize;
    wcenter = wincenter;
    float window_coeff = conf.getfloat("window_coeff");
    if(window_coeff!=1.0)
    {
        Vec2u resized(winsize.x*window_coeff,winsize.y*window_coeff);
        window.setSize(resized);
    }
    bg = cfg->getcolor("background");
    string path="yes/";
#ifdef __APPLE__
    path = resourcePath()+path;
#endif
    if(!cursor_tx.loadFromFile(path+"cursor4.png")) cout << "did not load cursor" << endl;
    cursor.setTexture(cursor_tx);
    cursor.setOrigin(3,3);
    window.setMouseCursorVisible(false);

    confpoint(c1,3,Color::Green);
    confpoint(c2,3,Color::Red);

    // fonts and f*****g globals
    init_font();
    font1 = &ft;
    font2 = &ft2;
    charsize=chsz;
    charsize2=chsz2;

    // console
    console = new sfconsole;
    console->numlines=conf.getint("numlines");
    console->init();
    cons=console;
    draw_console = true;

    labs=new labels;
    labs->pos=Vec2(15,winsize.y-30);
    lbs=&(labs->strings);


    win=&window;

    add_symbol_to_lambdas();

    if(cfg->getint("use_menu"))
    {
        menu_loop();
    }
    else
    {
        init_gameobj();
        loop();
    }
}
Ejemplo n.º 27
0
	void bindTexture(ShaderBase &shader)
	{
		TEX::bind(gl.tex);
		shader.setTexSize(Vec2i(gl.width, gl.height));
	}
Ejemplo n.º 28
0
void TriMesh2D::compute_nbrs() {
   
   //tri_edge_counts.resize(tris.size());
  /*    
   //old brute force code; this is now done smarter in compute_edges
   std::vector<Vec3ui> tri_to_edge_old(tris.size());
   tri_to_edge_old.resize(tris.size());
   for(unsigned int i = 0; i < tris.size(); ++i) {
      Vec2ui e0(tris[i][0], tris[i][1]);
      if(e0[0] > e0[1]) swap(e0[0],e0[1]);
      int ind = 0;
      while(edges[ind] != e0) ++ind;
      tri_to_edge_old[i][0] = ind;
      
      Vec2ui e1(tris[i][1], tris[i][2]);
      if(e1[0] > e1[1]) swap(e1[0],e1[1]);
      ind = 0;
      while(edges[ind] != e1) ++ind;
      tri_to_edge_old[i][1] = ind;
      
      Vec2ui e2(tris[i][2], tris[i][0]);
      if(e2[0] > e2[1]) swap(e2[0],e2[1]);
      ind = 0;
      while(edges[ind] != e2) ++ind;
      tri_to_edge_old[i][2] = ind;
   }*/

   //create edge_to_tri_map
   std::vector<int> tri_count(edges.size());
   edge_to_tri_map.resize(edges.size(), Vec2i(-1,-1));
   for(unsigned int i = 0; i < tri_to_edge_map.size(); ++i) {
      int edge0 = tri_to_edge_map[i][0];
      edge_to_tri_map[edge0][tri_count[edge0]++] = i;

      int edge1 = tri_to_edge_map[i][1];
      edge_to_tri_map[edge1][tri_count[edge1]++] = i;

      int edge2 = tri_to_edge_map[i][2];
      edge_to_tri_map[edge2][tri_count[edge2]++] = i;
   }

   //determine the signs of the faces relative to the relevant triangle
   tri_edge_signs.resize(tris.size());
   for(unsigned int i = 0; i < tris.size(); ++i) {
      Vec3ui tri_vert_ids = tris[i];

      //get the edges for this triangle
      Vec3ui edge_ids = tri_to_edge_map[i]; 
      for(unsigned int e = 0; e < 3; ++e) {
         //pick an edge      
         int edge_id = edge_ids[e];
         Vec2ui edge_vert_ids = edges[edge_id];
         
         //find the index of the first vertex in the edge
         int ind = 0;
         while(tri_vert_ids[ind] != edge_vert_ids[0]) ++ind;

         //check if the next vertex in the tri is the next vertex in the edge
         //if so, they are orientated the same way, no need to flip the normal
         tri_edge_signs[i][e] = (tri_vert_ids[(ind+1)%3] == edge_vert_ids[1] ? 1 : -1);
      }
   }

   //swap the order of the edge_to_tri_map so that it corresponds with the
   //direction of the edge normal.
   //ie. the triangle that the normal points at should be second
   //this corresponds to the first tri having a positive sign for the edge, the second a negative sign
   for(unsigned int i = 0; i < edge_to_tri_map.size(); ++i) {
      Vec2i tris = edge_to_tri_map[i];
      int edge_ind = 0;
      while(tri_to_edge_map[tris[0]][edge_ind] != i) ++edge_ind;

      if(tri_edge_signs[tris[0]][edge_ind] == -1)
         swap(edge_to_tri_map[i][0], edge_to_tri_map[i][1]);
   }

   //create vert_to_tri_map (ideally each should be ordered, but I don't think it matters)
   vert_to_tri_map.resize(vertices.size());
   for(unsigned int i = 0; i < tris.size(); ++i) {
      Vec3ui vert_ids = tris[i];
      vert_to_tri_map[vert_ids[0]].push_back(i);
      vert_to_tri_map[vert_ids[1]].push_back(i);
      vert_to_tri_map[vert_ids[2]].push_back(i);
   }

   //create vert_to_edge_map
   vert_to_edge_map.resize(vertices.size());
   for(unsigned int i = 0; i < edges.size(); ++i) {
      //use the edge list (ie. edge_to_vert) to build the
      //vert to edge list
      Vec2ui edge = edges[i];
      vert_to_edge_map[edge[0]].push_back(i);
      vert_to_edge_map[edge[1]].push_back(i);
   }

   //compute dual edges
   dual_edge_lengths.resize(edges.size());
   dual_edge_midpoints.resize(edges.size());
   dual_edge_normals.resize(edges.size());
   for(unsigned int i = 0; i < edges.size(); ++i) {
      Vec2i triCentreIds = edge_to_tri_map[i];
      if(triCentreIds[0] == -1 || triCentreIds[1] == -1) {
         dual_edge_lengths[i] = 0;
         dual_edge_midpoints[i] = edge_midpoints[i];
         dual_edge_normals[i] = perp(edge_normals[i]);
         continue;
      }

      Vec2f c0 = tri_circumcentres[triCentreIds[0]];
      Vec2f c1 = tri_circumcentres[triCentreIds[1]];
      dual_edge_lengths[i] = dist(c0,c1);
      dual_edge_midpoints[i] = 0.5f*(c0+c1);
      dual_edge_normals[i] = perp(edge_normals[i]); //safer, because sometimes c0 and c1 are co-located, so no normal to be found.
   }

   //set the signs of dual edges
   dual_edge_signs.resize(vertices.size());
   for(unsigned int v = 0; v < vertices.size(); ++v) {
      
      dual_edge_signs[v].resize(vert_to_edge_map[v].size());
      for(unsigned int e = 0; e < vert_to_edge_map[v].size();++e) {
         int edgeId = vert_to_edge_map[v][e];
         Vec2ui edgeEnds = edges[edgeId];
         //positive one implies the edge is oriented from the voronoi centre outwards
         dual_edge_signs[v][e] = edgeEnds[0] == v? 1 : -1;
      }
   }


}
Ejemplo n.º 29
0
void Bitmap::drawText(const IntRect &rect, const char *str, int align)
{
	guardDisposed();

	GUARD_MEGA;

	std::string fixed = fixupString(str);
	str = fixed.c_str();

	if (*str == '\0')
		return;

	if (str[0] == ' ' && str[1] == '\0')
		return;

	TTF_Font *font = p->font->getSdlFont();
	const Color &fontColor = p->font->getColor();
	const Color &outColor = p->font->getOutColor();

	SDL_Color c = fontColor.toSDLColor();
	c.a = 255;

	float txtAlpha = fontColor.norm.w;

	SDL_Surface *txtSurf;

	if (shState->rtData().config.solidFonts)
		txtSurf = TTF_RenderUTF8_Solid(font, str, c);
	else
		txtSurf = TTF_RenderUTF8_Blended(font, str, c);

	p->ensureFormat(txtSurf, SDL_PIXELFORMAT_ABGR8888);

	int rawTxtSurfH = txtSurf->h;

	if (p->font->getShadow())
		applyShadow(txtSurf, *p->format, c);

	/* outline using TTF_Outline and blending it together with SDL_BlitSurface
	 * FIXME: outline is forced to have the same opacity as the font color */
	if (p->font->getOutline())
	{
		SDL_Color co = outColor.toSDLColor();
		co.a = 255;
		SDL_Surface *outline;
		/* set the next font render to render the outline */
		TTF_SetFontOutline(font, OUTLINE_SIZE);
		if (shState->rtData().config.solidFonts)
			outline = TTF_RenderUTF8_Solid(font, str, co);
		else
			outline = TTF_RenderUTF8_Blended(font, str, co);

		p->ensureFormat(outline, SDL_PIXELFORMAT_ABGR8888);
		SDL_Rect outRect = {OUTLINE_SIZE, OUTLINE_SIZE, txtSurf->w, txtSurf->h}; 

		SDL_SetSurfaceBlendMode(txtSurf, SDL_BLENDMODE_BLEND);
		SDL_BlitSurface(txtSurf, NULL, outline, &outRect);
		SDL_FreeSurface(txtSurf);
		txtSurf = outline;
		/* reset outline to 0 */
		TTF_SetFontOutline(font, 0);
	}

	int alignX = rect.x;

	switch (align)
	{
	default:
	case Left :
		break;

	case Center :
		alignX += (rect.w - txtSurf->w) / 2;
		break;

	case Right :
		alignX += rect.w - txtSurf->w;
		break;
	}

	if (alignX < rect.x)
		alignX = rect.x;

	int alignY = rect.y + (rect.h - rawTxtSurfH) / 2;

	float squeeze = (float) rect.w / txtSurf->w;

	if (squeeze > 1)
		squeeze = 1;

	FloatRect posRect(alignX, alignY, txtSurf->w * squeeze, txtSurf->h);

	Vec2i gpTexSize;
	shState->ensureTexSize(txtSurf->w, txtSurf->h, gpTexSize);

	bool fastBlit = !p->touchesTaintedArea(posRect) && txtAlpha == 1.0f;

	if (fastBlit)
	{
		if (squeeze == 1.0f && !shState->config().subImageFix)
		{
			/* Even faster: upload directly to bitmap texture.
			 * We have to make sure the posRect lies within the texture
			 * boundaries or texSubImage will generate errors.
			 * If it partly lies outside bounds we have to upload
			 * the clipped visible part of it. */
			SDL_Rect btmRect;
			btmRect.x = btmRect.y = 0;
			btmRect.w = width();
			btmRect.h = height();

			SDL_Rect txtRect;
			txtRect.x = posRect.x;
			txtRect.y = posRect.y;
			txtRect.w = posRect.w;
			txtRect.h = posRect.h;

			SDL_Rect inters;

			/* If we have no intersection at all,
			 * there's nothing to upload to begin with */
			if (SDL_IntersectRect(&btmRect, &txtRect, &inters))
			{
				bool subImage = false;
				int subSrcX = 0, subSrcY = 0;

				if (inters.w != txtRect.w || inters.h != txtRect.h)
				{
					/* Clip the text surface */
					subSrcX = inters.x - txtRect.x;
					subSrcY = inters.y - txtRect.y;
					subImage = true;

					posRect.x = inters.x;
					posRect.y = inters.y;
					posRect.w = inters.w;
					posRect.h = inters.h;
				}

				TEX::bind(p->gl.tex);

				if (!subImage)
				{
					TEX::uploadSubImage(posRect.x, posRect.y,
					                    posRect.w, posRect.h,
					                    txtSurf->pixels, GL_RGBA);
				}
				else
				{
					GLMeta::subRectImageUpload(txtSurf->w, subSrcX, subSrcY,
					                           posRect.x, posRect.y,
					                           posRect.w, posRect.h,
					                           txtSurf, GL_RGBA);
					GLMeta::subRectImageEnd();
				}
			}
		}
		else
		{
			/* Squeezing involved: need to use intermediary TexFBO */
			TEXFBO &gpTF = shState->gpTexFBO(txtSurf->w, txtSurf->h);

			TEX::bind(gpTF.tex);
			TEX::uploadSubImage(0, 0, txtSurf->w, txtSurf->h, txtSurf->pixels, GL_RGBA);

			GLMeta::blitBegin(p->gl);
			GLMeta::blitSource(gpTF);
			GLMeta::blitRectangle(IntRect(0, 0, txtSurf->w, txtSurf->h),
			                      posRect, true);
			GLMeta::blitEnd();
		}
	}
	else
	{
		/* Aquire a partial copy of the destination
		 * buffer we're about to render to */
		TEXFBO &gpTex2 = shState->gpTexFBO(posRect.w, posRect.h);

		GLMeta::blitBegin(gpTex2);
		GLMeta::blitSource(p->gl);
		GLMeta::blitRectangle(posRect, Vec2i());
		GLMeta::blitEnd();

		FloatRect bltRect(0, 0,
		                  (float) (gpTexSize.x * squeeze) / gpTex2.width,
		                  (float) gpTexSize.y / gpTex2.height);

		BltShader &shader = shState->shaders().blt;
		shader.bind();
		shader.setTexSize(gpTexSize);
		shader.setSource();
		shader.setDestination(gpTex2.tex);
		shader.setSubRect(bltRect);
		shader.setOpacity(txtAlpha);

		shState->bindTex();
		TEX::uploadSubImage(0, 0, txtSurf->w, txtSurf->h, txtSurf->pixels, GL_RGBA);
		TEX::setSmooth(true);

		Quad &quad = shState->gpQuad();
		quad.setTexRect(FloatRect(0, 0, txtSurf->w, txtSurf->h));
		quad.setPosRect(posRect);

		p->bindFBO();
		p->pushSetViewport(shader);

		p->blitQuad(quad);

		p->popViewport();
	}

	SDL_FreeSurface(txtSurf);
	p->addTaintedArea(posRect);

	p->onModified();
}
Ejemplo n.º 30
0
void Enemy::onUpdate()
{
	if(invisibility) invisibility--;

	Vec2i facing = intToDir(dir);

	if(level.getAIFlags(position) & 2)
	{
		// Vergiftung
		contamination--;
	}

	if(contamination <= 0) burst();

	if(!thinkCounter--)
	{
		// den nächsten Spieler suchen, der für den Gegner sichtbar ist
		Player* p_closestPlayer = 0;
		int closestDist = 0;
		const std::list<Player*>& players = Player::getInstances();
		for(std::list<Player*>::const_iterator i = players.begin(); i != players.end(); ++i)
		{
			if(!(*i)->isTeleporting())
			{
				int dist = (position - (*i)->getPosition()).lengthSq();
				if(dist < closestDist || !p_closestPlayer)
				{
					if(canSee((*i)->getPosition()))
					{
						p_closestPlayer = *i;
						closestDist = dist;
					}
				}
			}
		}

		if(p_closestPlayer)
		{
			targetPosition = p_closestPlayer->getPosition();
			interest += 2225 - closestDist;
		}

		thinkCounter = random(2, 5);
	}

	if(subType == 0)
	{
		int oldDir = dir;

		if(moveCounter-- <= 0 && fabs(shownDir - dir) < 0.4)
		{
			int r = random(0, 8);
			if(interest >= 10000) r = random(0, 40);

			if(contamination < 50)
			{
				if(random() % 2) r = 0;
			}

			interest /= 2;

			switch(r)
			{
			case 0:
				{
					int d = random(-22, 22) / 10;
					if(d) dir += d, anim += 16;
				}
				break;
			case 1:
			case 2:
			case 3:
				if(!tryToMove(facing)) dir += random(-22, 22) / 10;
				anim += 16;
				break;
			default:
				if(r >= 6 && targetPosition.x != -1)
				{
					// zum Ziel laufen
					Vec2i toTarget = targetPosition - position;
					if(toTarget.x && toTarget.y) toTarget.value[random(0, 1)] = 0;
					int d = dirToInt(toTarget);
					toTarget = intToDir(d);
					if(tryToMove(toTarget))
					{
						dir = d;
						anim += 16;
						interest *= 2;
					}
				}
				break;
			}

			if(position == targetPosition || interest < 10)
			{
				targetPosition = Vec2i(-1, -1);
				interest = 0;
			}

			while(dir < 0) dir += 4, shownDir += 4.0;
			dir %= 4;

			moveCounter = random(4, 7);
		}

		if(anim) anim--;

		double dd = static_cast<double>(dir) - shownDir;
		if(dd > 2.0) shownDir += 4.0;
		else if(dd < -2.0) shownDir -= 4.0;
		shownDir = 0.125 * dir + 0.875 * shownDir;

		if(!soundCounter)
		{
			if(oldDir != dir)
			{
				// Kratz-Sound abspielen
				Engine::inst().playSound("enemy1_turn.ogg", false, 0.1, -100);
				soundCounter = random(15, 55);
			}
		}
		else soundCounter--;

		if(burpCounter)
		{
			burpCounter--;
			if(!burpCounter)
			{
				int s = random(0, 1);
				std::string sound;
				if(s == 0) sound = "enemy1_burp1.ogg";
				else if(s == 1) sound = "enemy1_burp2.ogg";
				Engine::inst().playSound(sound, false, 0.1);

				// Rülpspartikel erzeugen
				ParticleSystem* p_particleSystem = level.getParticleSystem();
				ParticleSystem::Particle p;
				for(int i = 0; i < 10; i++)
				{
					p.lifetime = random(50, 75);
					p.damping = 0.99f;
					p.gravity = random(-0.005f, -0.02f);
					p.positionOnTexture = Vec2b(96, 32);
					p.sizeOnTexture = Vec2b(16, 16);
					p.position = position * 16 + Vec2i(8 + random(-4, 4), 6);
					p.velocity = Vec2d(random(-0.5, 0.5), random(-1.0, -0.5));
					p.color = Vec4d(random(0.8, 1.0), random(0.8, 1.0), random(0.8, 1.0), 0.25);
					p.deltaColor = Vec4d(0.0, 0.0, 0.0, -p.color.a / p.lifetime);
					p.rotation = random(-0.5f, 0.5f);
					p.deltaRotation = random(-0.05f, 0.05f);
					p.size = random(0.2f, 1.0f);
					p.deltaSize = random(0.0f, 0.01f);
					p_particleSystem->addParticle(p);
				}
			}
		}
	}
	else if(subType == 1)
	{
		if(random() % 2) anim++;

		if(moveCounter-- <= 0)
		{
			int r = random(0, 1);
			if(interest > 6000) r = random(0, 50);

			if(contamination < 50)
			{
				if(random() % 2) r = 0;
			}

			interest /= 2;

			switch(r)
			{
			case 0:
				tryToMove(intToDir(random(0, 4)));
				break;
			default:
				if(targetPosition.x != -1)
				{
					// zum Ziel laufen
					Vec2i toTarget = targetPosition - position;
					if(toTarget.x && toTarget.y) toTarget.value[random(0, 1)] = 0;
					int d = dirToInt(toTarget);
					toTarget = intToDir(d);
					if(tryToMove(toTarget)) interest *= 2;
				}
				else
				{
					// Wo ist die Spur am heißesten?
					int bestDir = 0;
					uint bestTrace = 0;
					for(int dir = 0; dir < 4; dir++)
					{
						uint trace = level.getAITrace(position + intToDir(dir));
						if(trace > bestTrace)
						{
							bestTrace = trace;
							bestDir = dir;
						}
					}

					if(bestTrace)
					{
						Vec2i bestDirV = intToDir(bestDir);
						if(!tryToMove(bestDirV))
						{
							// Das ging nicht. Ist da ein anderer Gegner?
							bool reduceTrace = true;
							Object* p_obj = level.getFrontObjectAt(position + bestDirV);
							if(p_obj)
							{
								// Wenn da ein anderer Gegner ist, ist es egal.
								if(p_obj->getType() == "Enemy") reduceTrace = false;
							}

							if(reduceTrace)
							{
								// Die Spur dort etwas uninteressanter machen!
								level.setAITrace(position + bestDirV, bestTrace / 2);
							}
						}
						else
						{
							if(bestTrace > 850) interest = 160000;
							else if(bestTrace > 100) interest = 20000;
						}
					}
				}
				break;
			}

			if(position == targetPosition || interest < 10)
			{
				targetPosition = Vec2i(-1, -1);
				interest = 0;
			}

			moveCounter = random(4, 7);
		}

		if(height == 0.0)
		{
			if(!(random() % 25))
			{
				vy = random(40.0, 80.0);
				height = 0.5;
			}
		}
		else
		{
			height += 0.02 * vy;
			vy -= 0.02 * 400.0;

			if(height < 0.5)
			{
				height = 0.0;
				vy = 0.0;
			}
		}

		int pr = 700;
		if(interest >= 10000) pr = 350;
		if(!(random() % pr))
		{
			// Lachen abspielen
			Engine::inst().playSound("enemy2_laugh.ogg", false, 0.15, -100);
		}

		if(interest >= 40000)
		{
			if(!(random() % 200))
			{
				// Knurren abspielen
				Engine::inst().playSound("enemy2_growl.ogg", false, 0.15, -100);
			}
		}

		if(interest >= 10000)
		{
			// Feuer
			ParticleSystem* p_particleSystem = level.getParticleSystem();
			ParticleSystem* p_fireParticleSystem = level.getFireParticleSystem();
			ParticleSystem::Particle p;
			p.lifetime = random(40, 50);
			p.damping = 0.9f;
			p.gravity = -0.04f;
			p.positionOnTexture = Vec2b(32, 0);
			p.sizeOnTexture = Vec2b(16, 16);
			const double r = random(0.0, 6.283);
			const Vec2d vr(sin(r), cos(r));
			p.position = position * 16 + Vec2d(7.5, 7.5 - height) + 7.5 * vr;
			p.velocity = vr;
			p.color = Vec4d(random(0.5, 1.0), random(0.8, 1.0), random(0.0, 0.25), random(0.2, 0.4));
			const double dc = -1.5 / (p.lifetime + random(-25, 25));
			p.deltaColor = Vec4d(dc, dc, dc, -p.color.a / p.lifetime);
			p.rotation = random(0.0f, 10.0f);
			p.deltaRotation = random(-0.1f, 0.1f);
			p.size = random(0.5f, 0.9f);
			p.deltaSize = random(0.0075f, 0.015f);
			if(random() % 2) p_particleSystem->addParticle(p);
			else p_fireParticleSystem->addParticle(p);
		}
	}

	if(eatCounter) eatCounter--;
}