void NotPassableTerrain::HeihghtmapUpdated(const DAVA::Rect &forRect)
{
    EditorLandscape::HeihghtmapUpdated(forRect);
    
    AABBox3 boundingBox = nestedLandscape->GetBoundingBox();
    Vector3 landSize = boundingBox.max - boundingBox.min;

    float32 angleCellDistance = landSize.x / (float32)(heightmap->Size() - 1);
    float32 angleHeightDelta = landSize.z / (float32)(Heightmap::MAX_VALUE - 1);
    float32 tanCoef = angleHeightDelta / angleCellDistance;
 
    Texture *notPassableMap = notPassableMapSprite->GetTexture();
    float32 dx = (float32)notPassableMap->GetWidth() / (float32)(heightmap->Size() - 1);
    
    RenderManager::Instance()->LockNonMain();
    RenderManager::Instance()->SetRenderTarget(notPassableMapSprite);

    Rect drawRect(forRect.x * dx, forRect.y * dx, (forRect.dx - 1)* dx, (forRect.dy - 1) * dx);
    RenderManager::Instance()->ClipPush();
    RenderManager::Instance()->ClipRect(drawRect);

    DrawFullTiledTexture(notPassableMap, drawRect);
    
    int32 lastY = (int32)(forRect.y + forRect.dy);
    int32 lastX = (int32)(forRect.x + forRect.dx);
    for (int32 y = (int32)forRect.y; y < lastY; ++y)
    {
        int32 yOffset = y * heightmap->Size();
        for (int32 x = (int32)forRect.x; x < lastX; ++x)
        {
            uint16 currentPoint = heightmap->Data()[yOffset + x];
            uint16 rightPoint = heightmap->Data()[yOffset + x + 1];
            uint16 bottomPoint = heightmap->Data()[yOffset + x + heightmap->Size()];
            
            uint16 deltaRight = (uint16)abs((int32)currentPoint - (int32)rightPoint);
            uint16 deltaBottom = (uint16)abs((int32)currentPoint - (int32)bottomPoint);
            
            float32 tanRight = (float32)deltaRight * tanCoef;
            float32 tanBottom = (float32)deltaBottom * tanCoef;
            
            float32 ydx = y * dx;
            float32 xdx = x * dx;

            RenderManager* renderManager = RenderManager::Instance();
            RenderHelper* renderHelper = RenderHelper::Instance();
            
            Color color;

            if(PickColor(tanRight, color))
            {
                renderManager->SetColor(color);
                renderHelper->DrawLine(Vector2(xdx, ydx), Vector2((xdx + dx), ydx));
            }
            
            if(PickColor(tanBottom, color))
            {
                renderManager->SetColor(color);
                renderHelper->DrawLine(Vector2(xdx, ydx), Vector2(xdx, (ydx + dx)));
            }
            
        }
    }

    RenderManager::Instance()->ResetColor();
    
    RenderManager::Instance()->ClipPop();
    
    RenderManager::Instance()->RestoreRenderTarget();
    RenderManager::Instance()->UnlockNonMain();
}
Example #2
0
//----------------------------------------------------------------------------//
void OgreRenderer::destroyTexture(Texture& texture)
{
    destroyTexture(texture.getName());
}
Example #3
0
void RenderTextureTarget::addColorAttachment(const Texture& texture)
{
	glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer);
	glFramebufferTexture(GL_FRAMEBUFFER, toGlFrameBufferAttachment(FrameBufferAttachment_Color) + m_colorAttachmentCount, texture._getGlTextureId(), 0);
	++m_colorAttachmentCount;

	std::vector<GLenum> buffers;
	for (int i = 0; i < m_colorAttachmentCount; ++i)
	{
		buffers.push_back(GL_COLOR_ATTACHMENT0_EXT + i);
	}
	assert(!buffers.empty());
	glDrawBuffers(m_colorAttachmentCount, &buffers[0]);
}
Example #4
0
void wgd::Font::bind() {
	if (m_needsbuild) buildFont();
	m_needsbuild = false;
	Texture *tex = texture();
	if (tex != 0) tex->bind();
}
Example #5
0
void wgd::Font::buildFont() {

	//Delete any existing font display lists
	//if (m_base != 0xFFFFFFFF)
	//	destroyFont();

	//Create new GL display lists for this font
	//m_base = glGenLists(96);

	Texture *tex;
		//Make a texture for it
	if (get(ix::texture) == Null) {
		tex = new Texture();
		tex->compress(false);
		tex->nearest(true);
		if (size() < 32) {
			tex->width(256);
			tex->height(256);
		} else {
			tex->width(512);
			tex->height(512);
		}
		texture(tex);
		//Processor::processAll();
		tex->make(RGBA);
		//Processor::processAll();
	} else {
		tex = texture();
		if (!tex->isLoaded()) {
			tex->compress(false);
			tex->nearest(true);
			if (size() < 32) {
				tex->width(256);
				tex->height(256);
			} else {
				tex->width(512);
				tex->height(512);
			}
			tex->make(RGBA);
		}
	}
	
	if (tex == 0) return;
	
	#ifdef WIN32
	HFONT font;
	HFONT oldfont;
	
	#ifdef UNICODE
	int wLen = name().size() + 1;
	wchar_t *wFont = new wchar_t[wLen];
	mbstowcs(wFont, name(), wLen);
	#else
	char *wFont = strdup(name());
	#endif
	
	
	//Ask windows for a font
	font = CreateFont(	-size(),//Height
				0,	//Width
				0,	//Angle
				0,	//Orientation
				(bold()) ? FW_BOLD : FW_REGULAR,//Weight
				FALSE,	//Italic
				FALSE,	//UNDERLINE
				FALSE,	//Strikeout
				ANSI_CHARSET,
				OUT_TT_PRECIS,
				CLIP_DEFAULT_PRECIS,
				ANTIALIASED_QUALITY,
				FF_DONTCARE | DEFAULT_PITCH,
				wFont);	//Font name

	HDC memDC = CreateCompatibleDC(wgd::window->getHDC());
	//Select this new font and save the current one.
	oldfont = (HFONT)SelectObject(memDC, font);
	//Get windows to generate display lists for this font
	//wglUseFontBitmaps(memDC, 32, 96, m_base);

	HBITMAP bmp = CreateCompatibleBitmap(memDC, tex->width(),tex->height());
	HBITMAP oldbmp = (HBITMAP)SelectObject(memDC, bmp);
	
	char letter = '@';
	int x = 0;
	int y = 0;// size();
	int w;
	int h;
	//GetCharWidth(memDC, letter, letter, &w);
	TEXTMETRIC tmet;
	GetTextMetrics(memDC, &tmet);
	SetTextColor(memDC, 0x00FFFFFF);
	SetBkColor(memDC, 0x00000000);

	w = tmet.tmAveCharWidth;
	h = tmet.tmHeight;
	//width(w);
	//height(h);

	for (int i=32; i<128; i++) {
		//if (i >= 65 && i <= 90)
		//	letter = i+33;
		//else
		letter = i;
		GetCharWidth(memDC, letter, letter, &w);
		
		#ifdef UNICODE
		wchar_t *wbuf = new wchar_t[2];
		mbstowcs(wbuf, &letter, 2);
		TextOut(memDC, x, y, (LPCWSTR)wbuf, 1);
		#else
		TextOut(memDC, x, y, &letter, 1);
		#endif

		m_cdata[i].width = w;
		m_cdata[i].x = x;
		m_cdata[i].y = y;
		m_cdata[i].height = h;

		x += w;
		if (x+w > tex->width()) {
			y += h;
			x = 0;
		}
	};

	BITMAPINFO binfo;
	binfo.bmiHeader.biSize = sizeof(binfo);
	binfo.bmiHeader.biWidth = tex->width();
	binfo.bmiHeader.biHeight = -tex->height();
	binfo.bmiHeader.biPlanes = 1;
	binfo.bmiHeader.biBitCount = 32;
	binfo.bmiHeader.biCompression = BI_RGB;
	binfo.bmiHeader.biSizeImage = 0;
	colour4i *data = new colour4i[tex->width()*tex->height()];
	GetDIBits(memDC, bmp, 0, tex->width(), data, &binfo, DIB_RGB_COLORS);

	for (int i=0; i<tex->width()*tex->height(); i++) {
		if (data[i].r != 0 || data[i].g != 0 || data[i].b != 0)
			data[i].a = 255;
		//data[i].r = 255;
	}

	if (!tex->setPixels(0,0,tex->width(),tex->height(), data)) {
		std::cout << "Failed to set font pixels\n";
	}

	delete [] data;

	//Restore the previous font.
	SelectObject(memDC, oldfont);
	SelectObject(memDC, oldbmp);

	DeleteObject(bmp);
	DeleteObject(font);
	DeleteDC(memDC);
	#endif

	#ifdef LINUX
	XFontStruct *font;

	//Linux needs a font string so create it
	char *fstring = new char[1000];
	sprintf(fstring,"-*-%s-%s-r-*-*-*-%i-75-75-*-*-*-*", (const char*)name(), ((bold()) ? "bold" : "medium"), size()*10);
	//std::cout << "Font String: " << fstring << std::endl;

	//Ask X to find and then load this font if it exists.
	font = XLoadQueryFont(wgd::window->getXDisplay(), fstring);
			//"-*-helvetica-bold-r-normal--24-*-*-*-p-*-iso8859-1");
	delete [] fstring;

	//Font did not exist so load the default font which surely will exist
	if (font == NULL) {
		font = XLoadQueryFont(wgd::window->getXDisplay(), "fixed");
		std::cout << "Unable to load correct font.\n";
	}

	//Ask glX to create display lists using this X font.
	//glXUseXFont(font->fid, 32, 96, m_base);

	unsigned long valuemask = 0;
	XGCValues values;
	Pixmap pix = XCreatePixmap(wgd::window->getXDisplay(), wgd::window->getXWindow(), tex->width(), tex->height(), 32);
	GC gc = XCreateGC(wgd::window->getXDisplay(), pix, valuemask, &values);
	XSetFont(wgd::window->getXDisplay(), gc, font->fid);
	XSetForeground(wgd::window->getXDisplay(), gc, BlackPixel(wgd::window->getXDisplay(), wgd::window->getXScreen()));
	XFillRectangle(wgd::window->getXDisplay(), pix, gc, 0, 0, tex->width(), tex->height());
	XSetForeground(wgd::window->getXDisplay(), gc, WhitePixel(wgd::window->getXDisplay(), wgd::window->getXScreen()));


	char letter = '@';
	int x = 0;
	int h = font->max_bounds.ascent + font->max_bounds.descent;
	int y = font->max_bounds.ascent;
	int w = XTextWidth(font, &letter, 1);
	
	std::cout << "Font height = " << h << "\n";
	//width(w);
	//height(size());
	
	//XCharStruct charinfo;

	for (int i=32; i<128; i++) {
		letter = i;
		w = XTextWidth(font, &letter, 1);
		//XTextExtents(font, &letter, 1, 0, 0, 0, &charinfo);
		
		XDrawString(wgd::window->getXDisplay(), pix, gc, x, y, &letter, 1);

		m_cdata[i].width = w;
		m_cdata[i].height = h;
		m_cdata[i].x = x;
		m_cdata[i].y = y-font->max_bounds.ascent;

		x += w;
		if (x+w >= tex->width()) {
			y += h;
			x = 0;
		}
	};

	XImage *img = XGetImage(wgd::window->getXDisplay(), pix, 0, 0, tex->width(), tex->height(), AllPlanes, ZPixmap);

	//wgd::cout << "Image bits: " << img->depth << "\n";

	colour4i *data = (colour4i*)img->data;
	for (int i=0; i<tex->width()*tex->height(); i++) {
		if (data[i].r != 0 || data[i].g != 0 || data[i].b != 0)
			data[i].a = 255;
		data[i].r = 255;
		data[i].g = 255;
		data[i].b = 255;
	}

	if (img == 0) {
		std::cout << "No font image\n";
	} else if (img->data == 0) {
		std::cout << "No font image data\n";
	} else {
		if (!tex->setPixels(0,0,tex->width(),tex->height(), data)) {
			std::cout << "Failed to set font pixels\n";
		}
	}

	XFreePixmap(wgd::window->getXDisplay(), pix);
	XFreeGC(wgd::window->getXDisplay(), gc);

	XFreeFont(wgd::window->getXDisplay(), font);
	#endif
}
Example #6
0
	void OGLESTexture3D::CopyToSubTexture3D(Texture& target,
			uint32_t dst_array_index, uint32_t dst_level, uint32_t dst_x_offset, uint32_t dst_y_offset, uint32_t dst_z_offset, uint32_t dst_width, uint32_t dst_height, uint32_t dst_depth,
			uint32_t src_array_index, uint32_t src_level, uint32_t src_x_offset, uint32_t src_y_offset, uint32_t src_z_offset, uint32_t src_width, uint32_t src_height, uint32_t src_depth)
	{
		KFL_UNUSED(dst_depth);

		BOOST_ASSERT(type_ == target.Type());
		BOOST_ASSERT(0 == src_array_index);
		BOOST_ASSERT(0 == dst_array_index);

		if ((src_width == dst_width) && (src_height == dst_height) && (src_depth == dst_depth) && (format_ == target.Format()))
		{
			if (IsCompressedFormat(format_))
			{
				BOOST_ASSERT((0 == (src_x_offset & 0x3)) && (0 == (src_y_offset & 0x3)));
				BOOST_ASSERT((0 == (dst_x_offset & 0x3)) && (0 == (dst_y_offset & 0x3)));
				BOOST_ASSERT((0 == (src_width & 0x3)) && (0 == (src_height & 0x3)));
				BOOST_ASSERT((0 == (dst_width & 0x3)) && (0 == (dst_height & 0x3)));

				for (uint32_t z = 0; z < src_depth; ++ z)
				{
					Texture::Mapper mapper_src(*this, src_array_index, src_level, TMA_Read_Only,
						src_x_offset, src_y_offset, src_z_offset + z, src_width, src_height, 1);
					Texture::Mapper mapper_dst(target, dst_array_index, dst_level, TMA_Write_Only,
						dst_x_offset, dst_y_offset, dst_z_offset + z, dst_width, dst_height, 1);

					uint32_t const block_size = NumFormatBytes(format_) * 4;
					uint8_t const * s = mapper_src.Pointer<uint8_t>();
					uint8_t* d = mapper_dst.Pointer<uint8_t>();
					for (uint32_t y = 0; y < src_height; y += 4)
					{
						std::memcpy(d, s, src_width / 4 * block_size);

						s += mapper_src.RowPitch();
						d += mapper_dst.RowPitch();
					}
				}
			}
			else
			{
				for (uint32_t z = 0; z < src_depth; ++ z)
				{
					size_t const format_size = NumFormatBytes(format_);

					Texture::Mapper mapper_src(*this, src_array_index, src_level, TMA_Read_Only,
						src_x_offset, src_y_offset, src_z_offset + z, src_width, src_height, 1);
					Texture::Mapper mapper_dst(target, dst_array_index, dst_level, TMA_Write_Only,
						dst_x_offset, dst_y_offset, dst_z_offset + z, dst_width, dst_height, 1);
					uint8_t const * s = mapper_src.Pointer<uint8_t>();
					uint8_t* d = mapper_dst.Pointer<uint8_t>();
					for (uint32_t y = 0; y < src_height; ++ y)
					{
						std::memcpy(d, s, src_width * format_size);

						s += mapper_src.RowPitch();
						d += mapper_dst.RowPitch();
					}
				}
			}
		}
		else
		{
			this->ResizeTexture3D(target, dst_array_index, dst_level, dst_x_offset, dst_y_offset, dst_z_offset, dst_width, dst_height, dst_depth,
				src_array_index, src_level, src_x_offset, src_y_offset, src_z_offset, src_width, src_height, src_depth, true);
		}
	}
Example #7
0
void FrameBuffer::Init()
{
	glGenFramebuffers(1, &id);
	glBindFramebuffer(GL_FRAMEBUFFER, id);

//	GetGame()->Log(glGetError());

	drawBuffers.clear();
	Texture* tex = nullptr;
	if(textures.size() > 0)
	{
		for(uint i = 0; i < textures.size(); ++i)
		{
			tex = textures[i];
		//	tex->scaleFilter = Texture::ScaleFilter::Linear;
			tex->wrapMode = Texture::WrapMode::Clamp;
		//	tex->mode = GL_TEXTURE_2D_MULTISAMPLE;
			tex->size = uvec2(rect.width, rect.height);
			tex->SetIndex(startIndex+i);
			tex->InitData(0);

			uint32 attachment = startIndex+GL_COLOR_ATTACHMENT0+i;
			GetGame()->Log("Setting up textures for FrameBuffer, tex ", i, " gets attachment ", attachment, ". GL_COLOR_ATTACHMENT0 = ", GL_COLOR_ATTACHMENT0);

			tex->Bind();
			glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, tex->GetMode(), tex->GetId(), 0);

			drawBuffers.push_back(attachment);
		}
	}

	if(hasDepth)
	{
	/*	glGenRenderbuffers(1, &depthBuffer);
		glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer);
		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, rect.width, rect.height);
		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthBuffer);
	*/
		if(depthTexture)
		{
		//	depthTexture->SetFormat(Texture::Format::Depth32F_Stencil8, Texture::Format::Depth);
			depthTexture->SetFormat(Texture::Format::Depth32F, Texture::Format::Depth);
			depthTexture->wrapMode = Texture::WrapMode::Clamp;
			depthTexture->dataType = Texture::DataType::Float;
			depthTexture->size = uvec2(rect.width, rect.height);
			depthTexture->SetIndex(startIndex+textures.size());
			depthTexture->InitData(0);

			depthTexture->Bind();
			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, depthTexture->GetMode(), depthTexture->GetId(), 0);

			GetGame()->Log(glGetError());
		}
	}

	DrawBuffers();

	BeginRender();

	Unbind();
}
Example #8
0
//----------------------------------------------------------------------------//
void OpenGLRendererBase::destroyTexture(Texture& texture)
{
    destroyTexture(texture.getName());
}
Example #9
0
bool Image::toTexture(Texture& texture) const
{
    return texture.load((byte*)&_pixels.front(), _width, _height);
}
Example #10
0
void mainLevel(RenderWindow &window)
{
	//>>>>>>>>>>>>>>>---Level---<<<<<<<<<<<<<<<<<<<<<<<<<<<
	 Level lvl;
	 lvl.LoadFromFile("map.tmx");

	//>>>>>>>>>>>>>>>>---Load basic image for level1----<<<<<<<<<<<<<<<<<
	Texture texture;
	texture.loadFromFile("images/level1empty.jpg");
	Sprite level(texture);

	Texture texture2; 
	texture2.loadFromFile("images/levelShad.png");
	Sprite level2(texture2);

	Texture texture3;
	texture3.loadFromFile("images/level12.png");
	Sprite level3(texture3);
	//>>>>>>>>>>>>>>>>---Music---<<<<<<<<<<<<<<<<<<<<<<<<<<
	 Music mainSong;
	 Music skyrim, muse, bathMus;
	 bathMus.openFromFile("music/bath.ogg");
	 Object mus = lvl.GetObject("muse");
	 muse.openFromFile("music/synd.ogg"); muse.setVolume(100);
	 skyrim.openFromFile("music/skyrim.ogg"); skyrim.setVolume(100);
	 mainSong.openFromFile("music/level1.ogg");
	 mainSong.play();
	 mainSong.setLoop(true);
	 mainSong.setVolume(75);

	 //>>>>>>>>>>>>>>>>---Create a cat---<<<<<<<<<<<<<<<<<<<
	 Object player = lvl.GetObject("cat");
	 Object fish = lvl.GetObject("fish");
	 Object mo = lvl.GetObject("mouse");
	 Object ob = lvl.GetObject("catPlace");


	 Player cat("cat.png", lvl, 68, 429, 60, 120, player.rect.left,  player.rect.top, ELSE);
	 
	 Clock clock;
	 Clock gameTimeClock;
	 int sinkCnt = 0;

	 //>>>>>>>>>>>>>>>>---Sounds----<<<<<<<<<<<<<<<<<<<
	SoundBuffer buf1, buf2;
	buf1.loadFromFile("music/meow1.ogg");
	buf2.loadFromFile("music/meow2.ogg");
	Sound meow1, meow2;
	meow1.setBuffer(buf1);
	meow2.setBuffer(buf2);

	SoundBuffer buf, buf3;
	buf.loadFromFile("music/steklo.ogg");
	buf3.loadFromFile("music/mouse.ogg");
	Sound glass; Sound mouseS;
	glass.setBuffer(buf); glass.setVolume(100);
	mouseS.setBuffer(buf3);
	
	 //Objects
	 Furniture posters("tayles1.png",  160, 660, 210, 250, 280, 215, POSTERS);
	 Furniture bed("tayles1.png", 420, 80, 280, 310, 250, 440, ELSE); 
	 Furniture toys("tayles1.png", 120, 470, 180, 150, 220, 545, TOYS);
	 Furniture upShelf("tayles1.png", 700, 652.5, 120, 97.5, 350, 83, SHELF);
	 Furniture cabinet("tayles1.png", 75, 40, 250, 350, 605, 305, CABINET); 
	 Furniture mop("tayles1.png", 515, 785, 165, 241, 587, 385, MOP); 
	 Furniture flower("tayles1.png",780, 65, 170, 330, 147, 285, ELSE);
	 Furniture ball("tayles1.png", 905, 615, 40, 55, 357, 190, BALL); 
	 Furniture books("tayles1.png", 860, 735, 125, 80, 290, 187, BOOKS); 
	 Furniture brokenBall("tayles1.png",920, 540, 90, 42, 430, 430, ELSE); 
	 Furniture key("tayles1.png", 1, 1, 25, 25, 430, 425, KEY);
	 Furniture cabinetEnd("cabinet.png", 20, 50, 270, 350, 590, 290, ELSE); 
	 Furniture girl("girlHair.png", 1,1, 96, 45, 1075, 350, ELSE);
	 
	 Furniture door("tayles2.png", 0, 560, 80, 340, 870, 350, ELSE);
	 Furniture puddle("tayles1.png",789, 1000, 204, 75, 1057, 559, ELSE);
	 Furniture brokenLight("tayles2.png", 10, 110, 50, 70, 795, 430, ELSE);
	 Furniture light("tayles2.png", 20, 20, 35, 70, 220, 565, ELSE);
	 Furniture bath("tayles2.png", 80, 50, 320, 380, 1010, 330, BATH);
	 Furniture openBath("bathr.png", 264, 79, 339, 369, 1015, 315, ELSE);
	 Furniture carpet("tayles2.png", 100, 500, 100, 140, 870, 530, ELSE);
	 Furniture mirror("tayles2.png", 90, 700, 110, 290, 1200, 300, ELSE);
	 Furniture sink("tayles2.png", 290, 440, 150, 240, 1190, 450, SINK);
	 Furniture sinkWater("bathr.png", 22, 180, 197, 427, 1200, 540, ELSE);
	 Furniture mou("mouse.png",  2, 21, 32, 25, mo.rect.left, mo.rect.top, ELSE);
	 
	 
	 std::list<Furniture> fList;
	 std::list<Furniture>::iterator it;
	 fList.push_back(posters);
	 fList.push_back(toys);
	 fList.push_back(upShelf);
	 fList.push_back(cabinet);
	 fList.push_back(mop);
	 fList.push_back(ball);
	 fList.push_back(books);
	 fList.push_back(key);
	 fList.push_back(puddle);
	 fList.push_back(brokenLight);
	 fList.push_back(bath);
	 fList.push_back(sink);
	 for(it = fList.begin(); it != fList.end(); it++){
		 it->setSub((void *)&it, writeMess);
	 }

	 int cntMeow = 1, cntGame = 0, click = 0, clickBath = 1, clickSink = 1;
	 bath.isPlayed = true;
	 sink.isPlayed = true;


	  while (window.isOpen())
    {
		
		float time = clock.getElapsedTime().asMicroseconds();
		float sinkTime = gameTimeClock.getElapsedTime().asSeconds();
		if(clickSink < 2)
			gameTimeClock.restart();
		clock.restart();
		time = time/500;
		Vector2i pos = Mouse::getPosition(window);
		
		Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();

			if (event.type == Event::MouseButtonPressed)
				if (event.key.code == Mouse::Left){

					if (fish.rect.contains(pos.x, pos.y) && key.isPlayed == true){
						mainSong.stop();
						finish();
						window.close();
					}
					if (cat.sprite.getGlobalBounds().contains(pos.x, pos.y))
					{
						cntMeow++;
						if(cntMeow == 5)
						{
							meow2.play();
							cntMeow = 0;
						}
						else
							meow1.play();
					}
					 
					toys.trueMove(pos);
					if(light.isPlayed == false) light.trueMove(pos);
					if(ball.isPlayed == true && books.isPlayed == true) key.trueMove(pos);
					if(puddle.isPlayed == true) mop.trueMove(pos);
					click = light.clickedThings(pos);
					clickBath = bath.clickedThings(pos);
					clickSink = sink.clickedThings(pos);


					if (upShelf.sprite.getGlobalBounds().contains(pos.x, pos.y)){
						skyrim.play();
					}
					if (mus.rect.contains(pos.x, pos.y)){
						muse.play();
					}
					if (girl.sprite.getGlobalBounds().contains(pos.x, pos.y) && cat.room == 2){
						mainSong.pause();
						gameOver();
						mainSong.play();
					}
					if(mou.isPlayed == false)
						{
							if (mou.sprite.getGlobalBounds().contains(pos.x, pos.y))
							{
								mainSong.pause();
								mouseS.play();
								//gameRunning();
								mou.isPlayed = true;
								mainSong.play();
							}
						}

						if(books.isPlayed == false)
						{
							if (books.sprite.getGlobalBounds().contains(pos.x, pos.y))
							{
								mainSong.pause();
								MiniGame_Books();
								books.isPlayed = true;
								mainSong.play();
							}
						}
				}
					
			if (event.type == Event::MouseButtonReleased)
				if (event.key.code == Mouse::Left){
					toys.isMove = false;
					key.isMove = false;
					if(light.isPlayed == false) light.isMove = false;
					 mop.isMove = false;
				}
		}
		if(sinkTime > 5 && clickSink == 2) puddle.isPlayed = true;

		if(clickBath == 2 && cat.room == 2)
			bathMus.play();

		if(click == -1){}
		else if(click == 1 || click == 2)
			cat.room = click;
		toys.intersect("toys",lvl); toys.move(pos); 
		if(mop.isPlayed == false)
		{
			mop.intersect("mop", lvl);
			mop.move(pos);
		}
		if(light.isPlayed == false) 
		{
			light.intersect("light", lvl);
			light.move(pos);
		}
		if(ball.isPlayed == true && books.isPlayed == true){
			if(mop.isPlayed == true)
				key.intersect("key", lvl);
			if(key.isPlayed == false)
				key.move(pos);
		}
		if(ball.isPlayed == false && books.isPlayed == true){
			if(cat.sprite.getGlobalBounds().intersects(ob.rect))
			{
				if(cntMeow == 0)
				{
					ball.falling(event, window, pos, lvl, time);
					glass.play();
					ball.isPlayed = true;
					ball.intersect("ball", lvl);
				}
			}
		}
        
      
		cat.Update(time);

		window.clear(Color::Black);
		lvl.Draw(window);
		if(cat.room == 0)
			window.draw(level);
		if(cat.room == 1)
			window.draw(level2); 
		if(cat.room == 2)
			window.draw(level3);
			
		window.draw(posters.sprite);
		window.draw(bed.sprite);
		if(key.isPlayed == true)
			window.draw(cabinetEnd.sprite);
		else
			window.draw(cabinet.sprite);
		window.draw(upShelf.sprite);
		window.draw(flower.sprite);
		if(ball.isPlayed == false)
			window.draw(ball.sprite);
		else
		{
			window.draw(brokenBall.sprite);
			window.draw(key.sprite);
		}
		window.draw(books.sprite);

		
		if(mou.isPlayed == false){
			window.draw(mou.sprite);
		}
		else
			window.draw(light.sprite);
		window.draw(toys.sprite);


		if(cat.room == 2){
				
			 if(clickBath == 2){
				window.draw(girl.sprite);
				window.draw(openBath.sprite);
			 }
			 else
				 window.draw(bath.sprite);
			window.draw(mirror.sprite);

			 if(clickSink == 2)
				window.draw(sinkWater.sprite);
			 else
				 window.draw(sink.sprite);

			 if(puddle.isPlayed == true && mop.isPlayed == false)
				window.draw(puddle.sprite);
		}

		if(cat.room == 1 || cat.room == 2){
			if(light.isPlayed == false)
			window.draw(brokenLight.sprite);
			window.draw(carpet.sprite);
			window.draw(door.sprite);
		}
		if(mop.isPlayed == false)
			window.draw(mop.sprite);
		window.draw(cat.sprite);

		for(it = fList.begin(); it != fList.end(); it++)
			{
				if(it->sprite.getGlobalBounds().contains(pos.x, pos.y))
				{
					if(it->f.cb_fn != NULL)
					{
						cb_fn fn;
						fn = (cb_fn)it->f.cb_fn;
						fn(&window, it->type, &pos);
					}
				}
			}
		
		window.display();
    }

}
Example #11
0
void TextureStore::TileSwapper::load(const TileKey& key, TileRecord& record)
{
    // Fetch the texture container.
    const TextureContainer& textures =
        key.m_assembly_uid == UniqueID(~0)
            ? m_scene.textures()
            : m_assemblies[key.m_assembly_uid]->textures();

    // Fetch the texture.
    Texture* texture = textures.get_by_uid(key.m_texture_uid);

    if (m_params.m_track_tile_loading)
    {
        RENDERER_LOG_DEBUG(
            "loading tile (" FMT_SIZE_T ", " FMT_SIZE_T ") "
            "from texture \"%s\"...",
            key.get_tile_x(),
            key.get_tile_y(),
            texture->get_name());
    }

    // Load the tile.
    record.m_tile = texture->load_tile(key.get_tile_x(), key.get_tile_y());
    record.m_owners = 0;

    // Convert the tile to the linear RGB color space.
    switch (texture->get_color_space())
    {
      case ColorSpaceLinearRGB:
        break;

      case ColorSpaceSRGB:
        convert_tile_srgb_to_linear_rgb(*record.m_tile);
        break;

      case ColorSpaceCIEXYZ:
        convert_tile_ciexyz_to_linear_rgb(*record.m_tile);
        break;

      assert_otherwise;
    }

    // Track the amount of memory used by the tile cache.
    m_memory_size += record.m_tile->get_memory_size();
    m_peak_memory_size = max(m_peak_memory_size, m_memory_size);

    if (m_params.m_track_store_size)
    {
        if (m_memory_size > m_params.m_memory_limit)
        {
            RENDERER_LOG_DEBUG(
                "texture store size is %s, exceeding capacity %s by %s",
                pretty_size(m_memory_size).c_str(),
                pretty_size(m_params.m_memory_limit).c_str(),
                pretty_size(m_memory_size - m_params.m_memory_limit).c_str());
        }
        else
        {
            RENDERER_LOG_DEBUG(
                "texture store size is %s, below capacity %s by %s",
                pretty_size(m_memory_size).c_str(),
                pretty_size(m_params.m_memory_limit).c_str(),
                pretty_size(m_params.m_memory_limit - m_memory_size).c_str());
        }
    }
}
Example #12
0
File: main.cpp Project: Ladicle/FPS
UINT MainLoop(WindowManager *winmgr)
{
	//window setting
	Window window;
	winmgr->RegisterWindow(&window);
	ARSG g(window.hWnd, WINDOW_WIDTH, WINDOW_HEIGHT, true);
	ARSI *keyIn = window.GetInputHandler();
	ARSS s;
	Sound bgm, badend, atk;
	s.CreateSoundBuffer(&atk, L"../sound/atk.wav");
	s.CreateSoundBuffer(&bgm, L"../sound/bgm.wav");
	s.CreateSoundBuffer(&badend, L"../sound/fadein.wav");

	//Texture
	Texture board;
	Texture bg;
	Texture mask;
	Texture gameover;
	Texture clear;

	//BitPlane
	BitPlane source;
	BitPlane stored;
	BitPlane hitArea;
	BitPlane bitmask;

	//Light
	Light light;
	g.CreateLight(&light);
	light.SetLightIntensity(10);

	//Camera
	ARSD d;
	d.Init();
	d.AttachCam(0);
	d.BindBitPlane(&source);
	d.StartGraph();
	while (!source.GetPointer());
	source.GetSize(&sizex, &sizey, &depth);
	source.CopyTo(&stored);

	//background
	g.CreateTexture(&bg, L"../img/bgbg.jpg");
	bg.SetDrawMode(true);
	g.CreateTexture(&mask, L"../img/mask.jpg");
	mask.SetDrawMode(true);
	mask.GetBitData(&bitmask);
	g.CreateTexture(&board, sizex, sizey);
	board.SetDrawMode(true);
	Mesh f;
	g.CreateMesh(&f, L"../model/f4.x");
	float scale=25.0f;
	f.SetScale(scale, scale, scale, GL_ABSOLUTE);
	f.SetPosition(45.0f, -4.0f, 65.0f, GL_ABSOLUTE);
	f.SetRotationY(1.57f);
	g.CreateTexture(&gameover, L"../img/gameover.jpg");
	gameover.SetDrawMode(true);
	g.CreateTexture(&clear, L"../img/clear.PNG");
	gameover.SetDrawMode(true);

	//gun
	Gun gun(&g, &s, L"gun2.x", L"../sound/gun2.wav");
	gun.DefaultPosition(0.0f, -1.2f, -17.0f);
	gun.SetRotation(-0.1f, 3.14f, 0.0f, GL_ROTXYZ, GL_ABSOLUTE);

	//enemy
	int i, j;
	Batman bats[BAT];
	for(i=0,j=-1; i<BAT; ++i,j*=-1){
		new(bats+i)Batman(j*3.0f, 5.0f, 25.0f, j*-1*0.02f, -0.03f, -0.25f, j*-1*0.04f);
		bats[i].setting(&g, L"../model/bat.x");
	}
	Bone bons[BONE];
	for(i=0; i<BONE; ++i){
		new(bons+i)Bone(i*2, -4.8f, 20.0f, 0.0f, 0.01f, -0.25f);
		bons[i].setting(&g, L"../model/bone.x");
	}
	Boss boss(0.0f, -8.0f, 5.0f);
	boss.setSize(3.0f);
	boss.setting(&g, L"../model/teki.x");

	//add
	g.RegisterLight(&light);
	g.RegisterShape(&bg);
	g.RegisterShape(&f);
	for(i=0; i<BAT; ++i)
		g.RegisterShape(&bats[i]);
	g.RegisterShape(&board);
	g.RegisterShape(&gun);
	Effect e(&g);
	Player p(&g);

	enum {START, BAD, SCARLE, ARMER, BOSS, GAMEOVER, END};
	int state = START;
	unsigned int cnt=0;
	j=0;
	bgm.Play(true);
	while (!winmgr->WaitingForTermination()){
		if (keyIn->GetKeyTrig('A'))
			source.CopyTo(&stored);
		if (keyIn->GetKeyTrig('Q')) break;
		
		subtract_maskf(&bitmask, &hitArea,&stored,&source,0x50505050);
		gun.move(&hitArea);

		switch(state){
		case START:
			if(cnt==20){
				cnt=0;
				state=BAD;
			}
			break;
		case BAD:
			if(cnt<400)
				f.SetPosition(-0.004f, 0.0f, -0.05f, GL_RELATIVE);
			else if(cnt<410)
				f.SetPosition(-0.01f, 0.0f, -0.15f, GL_RELATIVE);
			else if(cnt<420){
				f.SetRotationY(-0.157f);
				f.SetPosition(-9.0f, 0.0f, -1.7f, GL_RELATIVE);
			}else if(cnt<565){
				f.SetRotationY(-0.001f);
				f.SetPosition(-0.04f, 0.0f, -0.14f, GL_RELATIVE);
			}else if(cnt<745){
				f.SetRotationY(0.001f);
				f.SetPosition(0.0f, 0.0f, -0.15f, GL_RELATIVE);
			}else if(cnt<770){
				f.SetRotationY(0.052f);
				f.SetPosition(1.5f, 0.0f, 0.72f, GL_RELATIVE);
			}else if(cnt==771){
				cnt=0;
				j=0;
				state=SCARLE;
				for(i=0; i<BONE; ++i)
					g.RegisterShape(&bons[i]);
				e.reSet();
			}
			break;
		case SCARLE:
			if(cnt<45){
				f.SetPosition(0.0f, 0.0f, 0.31f, GL_RELATIVE);
			}else if(cnt == 201){
				cnt=0;
				j=0;
				state=ARMER;
				for(i=0; i<BONE; ++i)
					g.UnregisterShape(&bons[i]);
					
			}
			break;

		case ARMER:
			if(cnt<20){
				f.SetRotationY(0.055f);
				f.SetPosition(1.5f, 0.0f, 0.72f, GL_RELATIVE);
			}else if(cnt<100){
				f.SetRotationY(0.005f);
				f.SetPosition(0.12f, 0.0f, -0.16f, GL_RELATIVE);
			}else if(cnt<210){
				f.SetPosition(0.0f, 0.0f, -0.175f, GL_RELATIVE);
			}else if(cnt<220){
				f.SetRotationY(-0.055f);
				f.SetPosition(-0.1f, 0.0f, -0.2f, GL_RELATIVE);
			}else if(cnt<370){
				f.SetRotationY(0.003f);
				f.SetPosition(0.0f, 0.0f, -0.12f, GL_RELATIVE);
			}
			if(p.getWin()){
				state=BOSS;
			}
			if(cnt==360){
				g.RegisterShape(&boss);
				e.reSet();
			}
			if(cnt>370){
				boss.move(&p, &e, &atk);
				boss.hitCheck(&gun, &e, &p);
			}
			break;
		case BOSS:
			bgm.Stop();
			g.RegisterShape(&clear);
			state=END;
			break;
		case GAMEOVER:
			bgm.Stop();
			badend.Play();
			g.RegisterShape(&gameover);
			state=END;
			break;
		default:
				break;
		}

		if(state==START || state==BAD){
			if(j<BAT && cnt%61==0)
				++j;
			for(i=0; i<j; ++i){
				bats[i].move(&p, &e, &atk);
				bats[i].hitCheck(&gun, &e);
			}
		}
		
		if(state==SCARLE){
			if(j<BONE && cnt%61==0)
				++j;
			for(i=0; i<j; ++i){
				bons[i].move(&p, &e, &atk);
				bons[i].hitCheck(&gun, &e);
			}
		}
		
		e.addEffect();
		if(p.checkHP())
			state=GAMEOVER;
		board.SetBitData(&hitArea);
		g.Draw();
		++cnt;
	}
	d.StopGraph();
	return 0;
}
Example #13
0
void GameWorldPanel::render(Renderer &renderer)
{
	assert(this->getGameState()->gameDataIsActive());

	// Clear full screen.
	renderer.clearNative();
	renderer.clearOriginal();

	// Draw game world onto the native frame buffer. The game world buffer
	// might not completely fill up the native buffer (bottom corners), so 
	// clearing the native buffer beforehand is still necessary.
	renderer.renderWorld();

	// Set screen palette.
	auto &textureManager = this->getGameState()->getTextureManager();
	textureManager.setPalette(PaletteFile::fromName(PaletteName::Default));

	// Set original frame buffer blending to true.
	renderer.useTransparencyBlending(true);

	// Draw game world interface.
	const auto &gameInterface = textureManager.getTexture(
		TextureFile::fromName(TextureName::GameWorldInterface));
	renderer.drawToOriginal(gameInterface.get(), 0, 
		Renderer::ORIGINAL_HEIGHT - gameInterface.getHeight());

	// Draw player portrait.
	const auto &player = this->getGameState()->getGameData()->getPlayer();
	const auto &headsFilename = PortraitFile::getHeads(
		player.getGenderName(), player.getRaceName(), true);
	const auto &portrait = textureManager.getTextures(headsFilename)
		.at(player.getPortraitID());
	const auto &status = textureManager.getTextures(
		TextureFile::fromName(TextureName::StatusGradients)).at(0);
	renderer.drawToOriginal(status.get(), 14, 166);
	renderer.drawToOriginal(portrait.get(), 14, 166);

	// Draw compass slider (the actual headings). +X is north, +Z is east.
	// Should do some sin() and cos() functions to get the pixel offset.
	auto *compassSlider = textureManager.getSurface(
		TextureFile::fromName(TextureName::CompassSlider));

	Texture compassSliderSegment = [&renderer, &compassSlider]()
	{
		SDL_Surface *segmentTemp = Surface::createSurfaceWithFormat(32, 7,
			Renderer::DEFAULT_BPP, Renderer::DEFAULT_PIXELFORMAT);

		SDL_Rect clipRect;
		clipRect.x = 60; // Arbitrary offset until compass rotation works.
		clipRect.y = 0;
		clipRect.w = segmentTemp->w;
		clipRect.h = segmentTemp->h;

		SDL_BlitSurface(compassSlider, &clipRect, segmentTemp, nullptr);

		SDL_Texture *segment = renderer.createTextureFromSurface(segmentTemp);
		SDL_FreeSurface(segmentTemp);

		return Texture(segment);
	}();

	renderer.drawToOriginal(compassSliderSegment.get(),
		(Renderer::ORIGINAL_WIDTH / 2) - (compassSliderSegment.getWidth() / 2),
		compassSliderSegment.getHeight());

	// Draw compass frame over the headings.
	const auto &compassFrame = textureManager.getTexture(
		TextureFile::fromName(TextureName::CompassFrame));
	renderer.drawToOriginal(compassFrame.get(),
		(Renderer::ORIGINAL_WIDTH / 2) - (compassFrame.getWidth() / 2), 0);

	// If the player's class can't use magic, show the darkened spell icon.
	if (!player.getCharacterClass().canCastMagic())
	{
		const auto &nonMagicIcon = textureManager.getTexture(
			TextureFile::fromName(TextureName::NoSpell));
		renderer.drawToOriginal(nonMagicIcon.get(), 91, 177);
	}

	// Draw text: player name.
	renderer.drawToOriginal(this->playerNameTextBox->getTexture(),
		this->playerNameTextBox->getX(), this->playerNameTextBox->getY());

	// Scale the original frame buffer onto the native one.
	// This shouldn't be done for the game world interface because it needs to
	// clamp to the screen edges, not the letterbox edges. 
	// Fix this eventually... again.
	renderer.drawOriginalToNative();

	// Draw cursor, depending on its position on the screen.
	const Int2 mousePosition = this->getMousePosition();

	const Texture &cursor = [this, &mousePosition, &textureManager]()
		-> const Texture& // Interesting how this return type isn't deduced in MSVC.
	{
		// See which arrow cursor region the native mouse is in.
		for (int i = 0; i < this->nativeCursorRegions.size(); ++i)
		{
			if (this->nativeCursorRegions.at(i)->contains(mousePosition))
			{
				return textureManager.getTextures(
					TextureFile::fromName(TextureName::ArrowCursors)).at(i);
			}
		}

		// If not in any of the arrow regions, use the default sword cursor.
		return textureManager.getTexture(
			TextureFile::fromName(TextureName::SwordCursor));
	}();

	renderer.drawToNative(cursor.get(), mousePosition.getX(), mousePosition.getY(),
		static_cast<int>(cursor.getWidth() * this->getCursorScale()),
		static_cast<int>(cursor.getHeight() * this->getCursorScale()));

	// Set the transparency blending back to normal (off).
	renderer.useTransparencyBlending(false);
}
Example #14
0
void SceneManagerDungeon::SpawnEnemy(MapEventEnemy* event, Enums::EnemyTypes type, float x, float y)
{
    sf::Sprite sprite;
    Texture* tex;
    switch(type)
    {
    case Enums::EnemyDefault:
    case Enums::EnemyChest:
        tex = TextureList::getTexture(TextureList::EnemySpriteSheet);
        break;
    case Enums::EnemyBoss:
        tex = TextureList::getTexture(TextureList::BossSpriteSheet);
    }
    sprite.setTexture(*tex);
    sprite.setTextureRect(sf::IntRect(0,0,32,32));
    Node* enemy = new AnimatedNode(&sprite, tex->GetNumberAnimationSteps());
    switch(type)
    {
    case Enums::EnemyDefault:
    case Enums::EnemyChest:
        enemy->setBoundingBox(sf::FloatRect(4.0f,16.0f,20.0f,16.0f));
        break;
    case Enums::EnemyBoss:
        enemy->setBoundingBox(sf::FloatRect(0.0f,0.0f,32.0f,32.0f));
    }
    m_eventLayer->addChild(enemy);

    sf::Transform enemyTransform;
    //Place Enemy at Position
    enemyTransform.translate(x, y);
    enemy->setTransform(enemyTransform);

    std::vector<Entity*>* enemies = new std::vector<Entity*>();

    Entity* e;
    switch(type)
    {
    case Enums::EnemyDefault:
        for(int i = 0; i < m_dungeonConfig->GetNrEnemies(); i++)
        {
            e = m_dungeonConfig->GetDungeonEnemy(m_lvlId);
            e->SetTeamId(1);
            enemies->push_back(e);
        }
        break;
    case Enums::EnemyBoss:
        {
            int nrAdds = 0;
            for(; nrAdds < m_dungeonConfig->GetNrBossAdds() / 2; nrAdds++)
            {
                e = m_dungeonConfig->GetDungeonEnemy(m_lvlId);
                e->SetTeamId(1);
                enemies->push_back(e);
            }
            e = m_dungeonConfig->GetDungeonBoss(m_lvlId);
            e->SetTeamId(1);
            enemies->push_back(e);
            for(; nrAdds < m_dungeonConfig->GetNrBossAdds(); nrAdds++)
            {
                e = m_dungeonConfig->GetDungeonEnemy(m_lvlId);
                e->SetTeamId(1);
                enemies->push_back(e);
            }
        }
        break;
    case Enums::EnemyChest:
        for(int i = 0; i < m_dungeonConfig->GetNrEnemies() + 1; i++)
        {
            e = m_dungeonConfig->GetDungeonEnemy(m_lvlId + 2);
            e->SetTeamId(1);
            enemies->push_back(e);
        }
        break;
    }

    event->Init(&m_map, enemy, enemies);
}
Example #15
0
Texture create_texture_from_image(const ImagePtr& the_img, bool mipmap,
                                  bool compress, GLfloat anisotropic_filter_lvl)
{
    Texture ret;
    
    if(!the_img){ return ret; }
    GLenum format = 0, internal_format = 0;
    
    switch(the_img->bytes_per_pixel)
    {
#ifdef KINSKI_GLES
        case 1:
            internal_format = format = GL_LUMINANCE;
            break;
        case 2:
            internal_format = format = GL_LUMINANCE_ALPHA;
            break;
        case 3:
            internal_format = format = GL_RGB;
            // needs precompressed image and call to glCompressedTexImage2D
            //                internal_format = compress ? GL_ETC1_RGB8_OES : GL_RGB;
            break;
        case 4:
            internal_format = format = GL_RGBA;
        default:
            break;
#else
        case 1:
            format = GL_RED;
            internal_format = compress? GL_COMPRESSED_RED_RGTC1 : GL_RGBA;
            break;
        case 2:
            format = GL_RG;
            internal_format = compress? GL_COMPRESSED_RG_RGTC2 : GL_RGBA;
            break;
        case 3:
            format = GL_RGB;
            internal_format = compress? GL_COMPRESSED_RGB_S3TC_DXT1_EXT : GL_RGBA;
            break;
        case 4:
            format = GL_RGBA;
            internal_format = compress? GL_COMPRESSED_RGBA_S3TC_DXT5_EXT : GL_RGBA;
        default:
            break;
#endif
    }
    Texture::Format fmt;
    fmt.set_internal_format(internal_format);
    
    if(mipmap)
    {
        fmt.set_mipmapping();
        fmt.set_min_filter(GL_LINEAR_MIPMAP_NEAREST);
    }
    uint8_t *data = the_img->data;
    
#if !defined(KINSKI_GLES)
    gl::Buffer pixel_buf;
    pixel_buf.set_data(the_img->data, the_img->num_bytes());
    pixel_buf.bind(GL_PIXEL_UNPACK_BUFFER);
    data = nullptr;
#endif
    ret = Texture(data, format, the_img->width, the_img->height, fmt);
    ret.set_flipped();
    KINSKI_CHECK_GL_ERRORS();
    
    ret.set_anisotropic_filter(anisotropic_filter_lvl);
    return ret;
}
Example #16
0
void DXShader::BindTexture( Texture& text ) const 
{
	// set the texture in the shader
	AdapterController::Get()->GetDeviceContext().dx->PSSetShaderResources( 0, 1, &text.GetTextureId().dx );
}
Example #17
0
//----------------------------------------------------------------------------//
void Direct3D10Renderer::destroyTexture(Texture& texture)
{
    destroyTexture(texture.getName());
}
Example #18
0
void setup_and_render()
{

	Image img(WIDTH, HEIGHT);
	img.addRef();

	//Set up the scene
	GeometryGroup scene;

	// load scene
	LWObject objects;
	objects.read("models/cube.obj", true);
	objects.addReferencesToScene(scene.primitives);	
	scene.rebuildIndex();
	
	//apply custom shaders
	BumpTexturePhongShader as;
	as.addRef();
	Image  grass;
	grass.addRef();
	grass.readPNG("models/mat.png");
	Texture textureGrass;
	textureGrass.addRef();
	textureGrass.image = &grass;
	as.diffTexture = &textureGrass;
	as.amibientTexture = &textureGrass;
	as.specularCoef = float4::rep(0);
	as.specularExponent = 10000.f;
	as.transparency = float4::rep(0.9);
	FractalLandscape f(Point(-4419,-8000,-569), Point(3581,0, -569),9, 0.1, &as, 5.0f);
	f.addReferencesToScene(scene.primitives);
	scene.rebuildIndex();
	
	// my phong
	RRPhongShader glass;
	glass.n1 = 1.0f;
	glass.n2 = 1.5f;
	glass.diffuseCoef = float4(0.1, 0.1, 0.1, 0);
	glass.ambientCoef = glass.diffuseCoef;
	glass.specularCoef = float4::rep(0.9);
	glass.specularExponent = 10000;
	glass.transparency = float4::rep(0.9);
	glass.addRef();
	Sphere sphere(Point(-78,1318,40), 25, &glass);;
	scene.primitives.push_back(&sphere);
	scene.rebuildIndex();	
	objects.materials[objects.materialMap["Glass"]].shader = &glass;

	
	//sample shader for noise
	ProceduralPhongShader skyShader;
	skyShader.addRef();
	CloudTexture nt;
	nt.addRef();
	skyShader.amibientNoiseTexture = &nt;
	skyShader.diffuseCoef = float4::rep(0.0f);
	skyShader.specularCoef = float4::rep(0.0f);

// 	float w = skyShader.amibientNoiseTexture->perlin->width;
 objects.materials[objects.materialMap["Sky"]].shader = &skyShader;

	//Set up the cameras
	PerspectiveCamera cam1(Point(-23, 1483, 30 ), forwardForCamera((0.0)*PI/180.0), Vector(0, 0, 1), 45,
		std::make_pair(img.width(), img.height()));
	
	cam1.addRef();

	//Set up the integrator
	IntegratorImpl integrator;
	integrator.addRef();
	integrator.scene = &scene;

	PointLightSource pls3;

	pls3.falloff = float4(0, 0, 1, 0);

	pls3.intensity  = float4::rep(0.9f);
	pls3.position = Point(299.5, 99, 518);
	integrator.lightSources.push_back(pls3);

// 	PointLightSource pls4;
// 
// 	pls4.falloff = float4(0, 0, 1, 0);
// 
// 	pls4.intensity  = float4::rep(0.9f);
// 	pls4.position = Point(1289.5, 99, 518);
// 	integrator.lightSources.push_back(pls4);
	
	areaLightSource(integrator, 0.9, 2, Point(-1180, -3860, -1718), 1000);
	integrator.ambientLight = float4::rep(0.1f);

	StratifiedSampler samp;
	samp.addRef();
 	samp.samplesX = 3;
	samp.samplesY = 3;

	//Render
	Renderer r;
	r.integrator = &integrator;
	r.target = &img;
	r.sampler = &samp;

	r.camera = &cam1;
	r.render();
	img.writePNG("result.png");
	
}
Example #19
0
        Texture* TextureManager::addTexture( const std::string& filename )
        {
            Texture* ret = nullptr;

            FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
            FIBITMAP* dib = nullptr; // TODO This name is nonsense, change it

            // Find format from file signature
            fif = FreeImage_GetFileType( filename.c_str(), 0 );

            if ( FIF_UNKNOWN == fif )
            {
                // Find format from file extension
                fif = FreeImage_GetFIFFromFilename( filename.c_str() );
            }

            if ( FIF_UNKNOWN == fif )
            {
                // Still unknown
                std::string error = "Cannot determine " + filename + " image format.";
                LOG( logERROR ) << error;
                CORE_ASSERT( 0, error.c_str() );

                return nullptr;
            }

            if ( FreeImage_FIFSupportsReading( fif ) )
            {
                dib = FreeImage_Load( fif, filename.c_str() );
            }

            std::string error = "Something went wrong while trying to load " + filename + ".";
            //CORE_ASSERT(dib, error.c_str());

            if ( nullptr == dib )
            {
                LOG( logERROR ) << error;
                return nullptr;
            }

            ret = new Texture( filename, GL_TEXTURE_2D );
            unsigned char* data = FreeImage_GetBits( dib );

            int bpp = FreeImage_GetBPP( dib );
            int format = ( bpp == 24 ? GL_BGR : 0 ); // TODO Handle other formats
            int internal = ( bpp == 24 ? GL_RGB : 0 ); // TODO Handle other formats
            int w = FreeImage_GetWidth( dib );
            int h = FreeImage_GetHeight( dib );

            // FIXME(Charly): Use VLOG instead of the check
            if ( m_verbose )
            {
                LOG( logINFO ) << "Image stats (" << filename << ") :\n"
                               << "\tBPP    : 0x" << std::hex << bpp << std::dec << std::endl
                               << "\tFormat : 0x" << std::hex << format << std::dec << std::endl
                               << "\tSize   : " << w << ", " << h;
            }


            CORE_ASSERT( data, "Data is null" );

            ret->initGL( internal, w, h, format, GL_UNSIGNED_BYTE, data );
            ret->genMipmap( GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR );

            m_textures.insert( TexturePair( filename, ret ) );

            FreeImage_Unload( dib );

            return ret;
        }
// Generates the character and texture data for the layer.
bool FontFaceLayer::Initialise(const FontFaceHandle* _handle, FontEffect* _effect, const FontFaceLayer* clone, bool deep_clone)
{
	handle = _handle;
	effect = _effect;
	if (effect != NULL)
	{
		effect->AddReference();
		colour = effect->GetColour();
	}

	const FontGlyphList& glyphs = handle->GetGlyphs();

	// Clone the geometry and textures from the clone layer.
	if (clone != NULL)
	{
		// Copy the cloned layer's characters.
		characters = clone->characters;

		// Copy (and reference) the cloned layer's textures.
		for (size_t i = 0; i < clone->textures.size(); ++i)
			textures.push_back(clone->textures[i]);

		// Request the effect (if we have one) adjust the origins as appropriate.
		if (!deep_clone &&
			effect != NULL)
		{
			for (FontGlyphList::const_iterator i = glyphs.begin(); i != glyphs.end(); ++i)
			{
				const FontGlyph& glyph = *i;

				if (glyph.character >= characters.size())
					continue;

				Character& character = characters[glyph.character];

				Vector2i glyph_origin(Math::RealToInteger(character.origin.x), Math::RealToInteger(character.origin.y));
				Vector2i glyph_dimensions(Math::RealToInteger(character.dimensions.x), Math::RealToInteger(character.dimensions.y));

				if (effect->GetGlyphMetrics(glyph_origin, glyph_dimensions, glyph))
				{
					character.origin.x = (float) glyph_origin.x;
					character.origin.y = (float) glyph_origin.y;
				}
				else
					character.texture_index = -1;
			}
		}
	}
	else
	{
		// Initialise the texture layout for the glyphs.
		characters.resize(glyphs.size(), Character());
		for (FontGlyphList::const_iterator i = glyphs.begin(); i != glyphs.end(); ++i)
		{
			const FontGlyph& glyph = *i;

			Vector2i glyph_origin(0, 0);
			Vector2i glyph_dimensions = glyph.bitmap_dimensions;

			// Adjust glyph origin / dimensions for the font effect.
			if (effect != NULL)
			{
				if (!effect->GetGlyphMetrics(glyph_origin, glyph_dimensions, glyph))
					continue;
			}

			Character character;
			character.origin = Vector2f((float) (glyph_origin.x + glyph.bearing.x), (float) (glyph_origin.y - glyph.bearing.y));
			character.dimensions = Vector2f((float) glyph_dimensions.x - glyph_origin.x, (float) glyph_dimensions.y - glyph_origin.y);
			characters[glyph.character] = character;

			// Add the character's dimensions into the texture layout engine.
			texture_layout.AddRectangle(glyph.character, glyph_dimensions - glyph_origin);
		}

		// Generate the texture layout; this will position the glyph rectangles efficiently and
		// allocate the texture data ready for writing.
		if (!texture_layout.GenerateLayout(512))
			return false;


		// Iterate over each rectangle in the layout, copying the glyph data into the rectangle as
		// appropriate and generating geometry.
		for (int i = 0; i < texture_layout.GetNumRectangles(); ++i)
		{
			TextureLayoutRectangle& rectangle = texture_layout.GetRectangle(i);
			const TextureLayoutTexture& texture = texture_layout.GetTexture(rectangle.GetTextureIndex());
			Character& character = characters[(word) rectangle.GetId()];

			// Set the character's texture index.
			character.texture_index = rectangle.GetTextureIndex();

			// Generate the character's texture coordinates.
			character.texcoords[0].x = float(rectangle.GetPosition().x) / float(texture.GetDimensions().x);
			character.texcoords[0].y = float(rectangle.GetPosition().y) / float(texture.GetDimensions().y);
			character.texcoords[1].x = float(rectangle.GetPosition().x + rectangle.GetDimensions().x) / float(texture.GetDimensions().x);
			character.texcoords[1].y = float(rectangle.GetPosition().y + rectangle.GetDimensions().y) / float(texture.GetDimensions().y);
		}


		// Generate the textures.
		for (int i = 0; i < texture_layout.GetNumTextures(); ++i)
		{
			Texture texture;
			if (!texture.Load(String(64, "?font::%p/%p/%d", handle, effect, i)))
				return false;

			textures.push_back(texture);
		}
	}


	return true;
}
VirtualKeyboard::VirtualKeyboard(Vec2f _position)
{
	Font  mFont	= Font( loadFile(getAssetPath("fonts/Helvetica Neue Light.ttf")), 32 );

	Texture backspaceBtnTex	= Texture(loadImage(loadAsset("keyboard/backBtn.png")));
	Texture _simple		    = Texture(loadImage(loadAsset("keyboard/_simpleBtn.png")));	
	Texture sendBtnTex		= Texture(loadImage(loadAsset("keyboard/send.png")));
			shiftTex1		= Texture(loadImage(loadAsset("keyboard/shift.png")));
			shiftTex0		= Texture(loadImage(loadAsset("keyboard/shift0.png")));
	Texture spaceBtnTex		= Texture(loadImage(loadAsset("keyboard/k3.png")));
	changeKeyboardTex1		= Texture(loadImage(loadAsset("keyboard/k2.png")));
	
	Vec2f shift_Y= Vec2f::zero();
	float _width = 86.0f;
	
	lineOffset1 = Vec2f::zero();
	lineOffset2 = Vec2f(65.0f, 92.0f);
	lineOffset3 = Vec2f(105.0f, 2*92.0f);
	lineOffset4 = Vec2f(150.0f, 3*92.0f);
	lineOffset5 = Vec2f(194.0f, 4*92.0f);
	
	for (auto i = 0; i < lineLength1; i++)
	{
		Button *btn = new Button(_simple, mFont, to_string(i));
		btn->setScreenField(lineOffset1 + Vec2f(i * (_xOffset1 + _width), 0.0f) + shift_Y);		
		buttonsMainKeyboard.push_back(btn);
		buttonsSecondKeyboard.push_back(btn);
	}

	shift = new Button(shiftTex0, mFont, SHIFT_KEY, false);
	shift->setScreenField(lineOffset4 - Vec2f(100.0f, 0.0f) + shift_Y);
	buttonsMainKeyboard.push_back(shift);
	
	Button *backspaceBtn = new Button(backspaceBtnTex, mFont, BACK_KEY, false);
	backspaceBtn->setScreenField(lineOffset1 + Vec2f(10.0f * (_xOffset1 + _width),0.0f) + shift_Y);	
	buttonsMainKeyboard.push_back(backspaceBtn);
	buttonsSecondKeyboard.push_back( backspaceBtn );

	for (size_t i = 0, ilen = secondLineCharacters->size(); i < 10; i++)
	{
		Button *btn = new Button(_simple, mFont, secondLineCharacters[i]);
		btn->setScreenField(lineOffset2 + Vec2f(i * (_xOffset2 + _width), 0.0f) + shift_Y);		
		buttonsMainKeyboard.push_back( btn );
	}

	for (size_t i = 0, ilen = secondLineCharacters2->size(); i < 10; i++)
	{
		Button *btn = new Button(_simple, mFont, secondLineCharacters2[i]);
		btn->setScreenField(lineOffset2 + Vec2f(i * (_xOffset2 + _width), 0.0f) + shift_Y);		
		buttonsSecondKeyboard.push_back( btn );
	}

	for (size_t i = 0, ilen = thirdLineCharacters->size(); i < 10; i++)
	{
		Button *btn = new Button(_simple, mFont, thirdLineCharacters[i]);
		btn->setScreenField(lineOffset3 + Vec2f(i * (_xOffset3 + _width), 0.0f) + shift_Y);		
		buttonsMainKeyboard.push_back( btn );
	}

	for (size_t i = 0, ilen = thirdLineCharacters2->size(); i < 10; i++)
	{
		Button *btn = new Button(_simple, mFont, thirdLineCharacters2[i]);
		btn->setScreenField(lineOffset3 + Vec2f(i * (_xOffset3 + _width), 0.0f) + shift_Y);		
		buttonsSecondKeyboard.push_back( btn );
	}

	for (size_t i = 0, ilen = fourthLineCharacters->size(); i < 9; i++)
	{
		Button *btn = new Button(_simple, mFont, fourthLineCharacters[i]);
		btn->setScreenField(lineOffset4 + Vec2f(i * (_xOffset4 + _width), 0.0f) + shift_Y);		
		buttonsMainKeyboard.push_back( btn );
	}

	for (size_t i = 0, ilen = fourthLineCharacters2->size(); i < 10; i++)
	{
		Button *btn = new Button(_simple, mFont, fourthLineCharacters2[i]);
		btn->setScreenField(lineOffset4 + Vec2f(i * (_xOffset4 + _width), 0.0f) + shift_Y - Vec2f(_xOffset4 + _width, 0.0f));		
		buttonsSecondKeyboard.push_back( btn );
	}

	changeKeyboardBtn = new Button(changeKeyboardTex1, mFont, SPECIAL_SYMBOLS_KEY);
	changeKeyboardBtn->setScreenField(lineOffset5 + Vec2f(0.0f * (_xOffset5 + _width) - 170.0f, 0.0f) + shift_Y);	
	buttonsMainKeyboard.push_back(changeKeyboardBtn);
	buttonsSecondKeyboard.push_back(changeKeyboardBtn);

	Button *dogBtn = new Button(_simple, mFont, SOBAKA_KEY);
	dogBtn->setScreenField(lineOffset5 + Vec2f(0.0f * (_xOffset5 + _width), 0.0f) + shift_Y);	
	buttonsMainKeyboard.push_back(dogBtn);
	buttonsSecondKeyboard.push_back(dogBtn);

	Button *spaceBtn = new Button(spaceBtnTex, mFont, SPACE_KEY, false);
	spaceBtn->setScreenField(lineOffset5 + Vec2f(_xOffset5 + _width, 0.0f) + shift_Y);	
	buttonsMainKeyboard.push_back(spaceBtn);
	buttonsSecondKeyboard.push_back( spaceBtn );
	 
	Button *sendBtn = new Button(sendBtnTex, mFont, SEND_KEY, false);
	Vec2f pos = lineOffset5 + Vec2f(_xOffset5  + _width, 0.0f) + shift_Y;
	sendBtn->setScreenField(pos+ Vec2f(_xOffset5 + spaceBtnTex.getWidth(), 0.0f));	
	buttonsMainKeyboard.push_back(sendBtn);
	buttonsSecondKeyboard.push_back(sendBtn);
	
	position = _position;
	show();
}
glm::ivec2 TextureManager::getGeometria(const unsigned int &_serial) {

	Texture *pTex = getTexture(_serial);
	return pTex != nullptr ? glm::ivec2( pTex->getWidth(), pTex->getHeight()) : glm::ivec2(640,480);

}
Example #23
0
void wgd::Font::unbind() {
	Texture *tex = texture();
	if (tex != 0) tex->unbind();
}
void TextureManager::bind(const unsigned int &_serial) {

	Texture *pTex = getTexture(_serial);
	pTex->apply();

}
Example #25
0
int main()
{
    RenderWindow window(VideoMode(640, 480), "Lesson 6. kychka-pc.ru");



    Texture herotexture;
    herotexture.loadFromFile("images/heroes.png");

    Sprite herosprite;
    herosprite.setTexture(herotexture);
    herosprite.setTextureRect(IntRect(0, 192, 96, 96));
    herosprite.setPosition(0,0);


    Clock clock;

    float nowImage=0;

    while (window.isOpen())
    {

        float time = clock.getElapsedTime().asMicroseconds();
        clock.restart();
        time = time/800;
        Event event;

        nowImage+=0.005*time;
        if(nowImage>=3)
            nowImage-=3;
        while (window.pollEvent(event))
        {
            if (event.type == Event::Closed)
                window.close();
        }

        if ((Keyboard::isKeyPressed(Keyboard::Left) || (Keyboard::isKeyPressed(Keyboard::A))))
        {
            herosprite.move(-0.1*time, 0);
            herosprite.setTextureRect(IntRect((int)(nowImage)*96,96, 96, 96));
        }
        if ((Keyboard::isKeyPressed(Keyboard::Right) || (Keyboard::isKeyPressed(Keyboard::D))))
        {
            herosprite.move(0.1*time, 0);
            herosprite.setTextureRect(IntRect((int)(nowImage)*96, 192, 96, 96));
        }
        if ((Keyboard::isKeyPressed(Keyboard::Up) || (Keyboard::isKeyPressed(Keyboard::W))))
        {
            herosprite.move(0, -0.1*time);
            herosprite.setTextureRect(IntRect((int)(nowImage)*96,288, 96, 96));
        }
        if ((Keyboard::isKeyPressed(Keyboard::Down) || (Keyboard::isKeyPressed(Keyboard::S))))
        {
            herosprite.move(0, 0.1*time);
            herosprite.setTextureRect(IntRect((int)(nowImage)*96,0, 96, 96));
        }


        window.clear();
        window.draw(herosprite);
        window.display();
    }

    return 0;
}
Example #26
0
/**
 * This function is called when one of the mission's UFOs arrives at it's current destination.
 * It takes care of sending the UFO to the next waypoint, landing UFOs and
 * marking them for removal as required. It must set the game data in a way that the rest of the code
 * understands what to do.
 * @param ufo The UFO that reached it's waypoint.
 * @param engine The game engine, required to get access to game data and game rules.
 * @param globe The earth globe, required to get access to land checks.
 */
void AlienMission::ufoReachedWaypoint(Ufo &ufo, Game &engine, const Globe &globe)
{
	const Ruleset &rules = *engine.getRuleset();
	SavedGame &game = *engine.getSavedGame();
	const size_t curWaypoint = ufo.getTrajectoryPoint();
	const size_t nextWaypoint = curWaypoint + 1;
	const UfoTrajectory &trajectory = ufo.getTrajectory();
	int waveNumber = _nextWave - 1;
	if (waveNumber < 0)
	{
		waveNumber = _rule.getWaveCount() - 1;
	}

	const MissionWave &wave = _rule.getWave(waveNumber);
	if (nextWaypoint >= trajectory.getWaypointCount())
	{
		ufo.setDetected(false);
		ufo.setStatus(Ufo::DESTROYED);
		return;
	}
	ufo.setAltitude(trajectory.getAltitude(nextWaypoint));
	ufo.setTrajectoryPoint(nextWaypoint);
	const RuleRegion &regionRules = *rules.getRegion(_region);
	std::pair<double, double> pos = getWaypoint(trajectory, nextWaypoint, globe, regionRules);

	Waypoint *wp = new Waypoint();
	wp->setLongitude(pos.first);
	wp->setLatitude(pos.second);
	ufo.setDestination(wp);
	if (ufo.getAltitude() != "STR_GROUND")
	{
		if (ufo.getLandId() != 0)
		{
			ufo.setLandId(0);
		}
		// Set next waypoint.
		ufo.setSpeed((int)(ufo.getRules()->getMaxSpeed() * trajectory.getSpeedPercentage(nextWaypoint)));
	}
	else
	{
		// UFO landed.
		if (wave.objective && trajectory.getZone(curWaypoint) == (size_t)(_rule.getSpawnZone()))
		{
			// Remove UFO, replace with MissionSite.
			addScore(ufo.getLongitude(), ufo.getLatitude(), game);
			ufo.setStatus(Ufo::DESTROYED);

			MissionArea area = regionRules.getMissionPoint(trajectory.getZone(curWaypoint), &ufo);
			Texture *texture = rules.getGlobe()->getTexture(area.texture);
			AlienDeployment *deployment = rules.getDeployment(texture->getDeployment());
			
			MissionSite *missionSite = new MissionSite(&_rule, deployment);
			missionSite->setLongitude(ufo.getLongitude());
			missionSite->setLatitude(ufo.getLatitude());
			missionSite->setId(game.getId(deployment->getMarkerName()));
			missionSite->setSecondsRemaining(RNG::generate(deployment->getDurationMin(), deployment->getDurationMax()) * 3600);
			missionSite->setAlienRace(_race);
			missionSite->setTexture(area.texture);
			missionSite->setCity(area.name);
			game.getMissionSites()->push_back(missionSite);
			for (std::vector<Target*>::iterator t = ufo.getFollowers()->begin(); t != ufo.getFollowers()->end();)
			{
				Craft* c = dynamic_cast<Craft*>(*t);
				if (c && c->getNumSoldiers() != 0)
				{
					c->setDestination(missionSite);
					t = ufo.getFollowers()->begin();
				}
				else
				{
					++t;
				}
			}
		}
		else if (trajectory.getID() == "__RETALIATION_ASSAULT_RUN")
		{
			// Ignore what the trajectory might say, this is a base assault.
			// Remove UFO, replace with Base defense.
			ufo.setDetected(false);
			std::vector<Base *>::const_iterator found =
			    std::find_if (game.getBases()->begin(), game.getBases()->end(),
					 MatchBaseCoordinates(ufo.getLongitude(), ufo.getLatitude()));
			if (found == game.getBases()->end())
			{
				ufo.setStatus(Ufo::DESTROYED);
				// Only spawn mission if the base is still there.
				return;
			}
			ufo.setDestination(*found);
		}
		else
		{
			// Set timer for UFO on the ground.
			ufo.setSecondsRemaining(trajectory.groundTimer()*5);
			if (ufo.getDetected() && ufo.getLandId() == 0)
			{
				ufo.setLandId(engine.getSavedGame()->getId("STR_LANDING_SITE"));
			}
		}
	}
}
  MyApp() {

    // Load a .jpg file
    //
    const char *filename = "../../share/images/tiny.jpg";

    if (image.load(filename)) {
      printf("Read image from %s\n", filename);
    } else {
      printf("Failed to read image from %s!  Quitting.\n", filename);
      exit(-1);
    }

    // Here we copy the pixels from the image to the texture
    texture.allocate(image.array());

    // Don't bother trying to print the image or the image's array directly
    // using C++ syntax.  This won't work:
    //
    //cout << "Image " << image << endl;
    //cout << "   Array: " << image.array() << endl;

    // Make a reference to our image's array so we can just say "array" instead
    // of "image.array()":
    //
    Array& array(image.array());

    // The "components" of the array are like "planes" in Jitter: the number of
    // data elements in each cell.  In our case three components would
    // represent R, G, B.
    //
    cout << "array has " << (int) array.components() << " components" << endl;

    // Each of these data elements is represented by the same numeric type:
    //
    cout << "Array's type (as enum) is " << array.type() << endl;

    // But that type is represented as an enum (see al_Array.h), so if you want
    // to read it use this function:
    //
    printf("Array's type (human readable) is %s\n", allo_type_name(array.type()));

    // The array itself also has a print method:
    //
    cout << "Array.print: "  << endl << "   ";
    array.print();    


    // Code below assumes this type is 8-bit unsigned integer, so this line
    // guarantees that's the case, or else crashes the program if not:
    //
    assert(array.type() == AlloUInt8Ty);

    // AlloCore's image class provides a type for an RGBA pixel, which is of
    // course templated on the numeric type used to represent each value in the
    // pixel.  Since templating happens at compile time we can't just ask the
    // array at runtime what type to put in here (hence the "assert" above):
    //
    Image::RGBAPix<uint8_t> pixel;

    // Loop through all the pixels.  Note that the columns go from left to
    // right and the rows go from bottom to top.  (So the "row" and "column"
    // are like X and Y coordinates on the Cartesian plane, with the entire
    // image living in the quadrant with positive X and positive Y --- in other
    // words the origin is in the lower left of the image.)
    //
    cout << "Display ALL the pixels !!! " << endl;

    for (size_t row = 0; row < array.height(); ++row) {
      for (size_t col = 0; col < array.width(); ++col) {

        // read the pixel at (row, col) and print
        //
        //array.read(&pixel, row, col);
        array.read(&pixel, col, row);
        cout << "image[" << row << "," << col << "]=" <<
        (int)pixel.r << "," << (int)pixel.g << "," << (int)pixel.b << endl;
      }
    }
  }
Example #28
0
void TutorialStage::drawMark()
{
    SDL_RenderClear(gRenderer);

    string markStr;
    ostringstream sstream;
    // change float to string && cut after two decimal numbers
    sstream << _mark;
    markStr = sstream.str();
    Texture* markText = new Texture("font/font.ttf", "Your Mark", { 0x00, 0x00, 0x00, 0xFF }, 64);
    
    SDL_Rect markTextDest = { SCREEN_WIDTH / 2 - markText->getWidth() / 2,
                            SCREEN_HEIGHT / 2 - 300, 
                            markText->getWidth(), 
                            markText->getHeight()
                        };
    //printf("position:(%d,%d,%d,%d)\n", position.x, position.y, position.w, position.h);
//    Texture* markText = new Texture()
    Texture* scoreBg = new Texture("img/score_bg.jpg");
    SDL_Rect screenRect = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT };
    scoreBg->render(NULL, &screenRect);
    cout << "render score BG finished" << endl;
    markText->render(NULL, &markTextDest);
    cout << "render score text finished " << endl;
    delete markText;
    markText = new Texture("font/font.ttf", markStr, { 0x00, 0x00, 0x00, 0xFF }, 64);
    
    markTextDest = { SCREEN_WIDTH / 2 - markText->getWidth() / 2,
                            SCREEN_HEIGHT / 2 - 300 + markText->getHeight(), 
                            markText->getWidth(), 
                            markText->getHeight()
                        };

    markText->render(NULL, &markTextDest);
    SDL_RenderPresent(gRenderer);
    SDL_Event e;
    bool quit = false;
    while (!quit){

        while (SDL_PollEvent(&e) != 0)
        {
            if (e.type == SDL_QUIT)
            {
                quit = true;
            }
            else if (e.type == SDL_KEYDOWN)
            {
                if (e.key.keysym.sym == SDLK_q)
                {
                    quit = true;
                }
            }
        }
    }

}
Example #29
0
    void Text::UpdateText(const std::string &text,const Vec4 &color)
    {
        if (this->text!=text)
        {
            this->text = text;

            if (Initialized)
            {
                geometry->Dispose();
                geometry->index.clear();
                geometry->tVertex.clear();
                geometry->tNormal.clear();
                geometry->tTexcoord.clear();
            }
            
            Initialized = true;

            f32 width = 0.0f;
            f32 height = 0.0f;

            f32 offsetX = 0;
            f32 offsetY = 0;

            uint32 quads = 0;
            f32 lineSize = 0.0f;

            for (uint32 i = 0;i<text.size();i++)
            {
                switch(text[i])
                {
                    case '\n':
                        // Build Quads in the bottom
                        offsetY-=lineSize*1.5f;
                        offsetX = 0.0f;
                    break;
                    case ' ':
                        offsetX+=font->GetFontSize()/2;
                    break;
                    default:

                        glyph_properties glp = font->GetGlyphs()[text[i]];
                        width = glp.size.x;
                        height = glp.size.y;
                        // Build Quads to the right
                        f32 w2 = width; f32 h2 = height;

                        if (height + glp.offset.y >lineSize) lineSize = height + glp.offset.y;

                        Vec3 a = Vec3(offsetX,      offsetY-glp.offset.y        ,0);
                        Vec3 b = Vec3(w2+offsetX,   offsetY-glp.offset.y        ,0);
                        Vec3 c = Vec3(w2+offsetX,   h2+offsetY-glp.offset.y     ,0);
                        Vec3 d = Vec3(offsetX,      h2+offsetY-glp.offset.y     ,0);

                        // Apply Dimensions
                        a.x = charWidth * a.x / font->GetFontSize();
                        a.y = charHeight * a.y / font->GetFontSize();

                        b.x = charWidth * b.x / font->GetFontSize();
                        b.y = charHeight * b.y / font->GetFontSize();

                        c.x = charWidth * c.x / font->GetFontSize();
                        c.y = charHeight * c.y / font->GetFontSize();

                        d.x = charWidth * d.x / font->GetFontSize();
                        d.y = charHeight * d.y / font->GetFontSize();

                        Vec3 normal = Vec3(color.x,color.y,color.z);

                        geometry->tVertex.push_back(a);   geometry->tNormal.push_back(normal);
                        geometry->tVertex.push_back(b);   geometry->tNormal.push_back(normal);
                        geometry->tVertex.push_back(c);   geometry->tNormal.push_back(normal);
                        geometry->tVertex.push_back(d);   geometry->tNormal.push_back(normal);

                        Texture* t = font->GetTexture();
                        geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x,glp.startingPoint.y + glp.size.y/(f32)t->GetHeight()));
                        geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x + glp.size.x/(f32)t->GetWidth(),glp.startingPoint.y + glp.size.y/(f32)t->GetHeight()));
                        geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x + glp.size.x/(f32)t->GetWidth(),glp.startingPoint.y));
                        geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x,glp.startingPoint.y));

                        geometry->index.push_back(quads*4+0);
                        geometry->index.push_back(quads*4+1);
                        geometry->index.push_back(quads*4+2);
                        geometry->index.push_back(quads*4+2);
                        geometry->index.push_back(quads*4+3);
                        geometry->index.push_back(quads*4+0);

                        offsetX+=width + glp.offset.x;
                        quads++;

                    break;
                }
            }

            // Build and Send Buffers
            Build();
        }
    }
Example #30
0
int main(int argc, char** argv)
{
	RenderWindow window(sf::VideoMode(W_WIDTH,W_HEIGHT),"Hello",sf::Style::Close);
		
	View view{ FloatRect{0,0,V_WIDTH,V_HEIGHT} };
	View defaultView = View{ FloatRect{ 0,0, 1600, 1200 } };

	//window.setView(view);

	Physics physics{ {0.f, 9.8f}, 10.f };

	//LightMap lights{view};
	LightMap lights{ defaultView };

	auto playerLight = lights.createLight("../assets/lightmask.png", 400, 370, 3.f);

	//lights.createLight("../assets/lightmask.png", 200, 100, 3.f);

	Clock clock;

	physics.spawnStaticBox(40.f, 60.f, 800.f, 40.f);
	physics.spawnStaticBox(80.f, 110.f, 800.f, 40.f);
	
	auto pPlayerBody = physics.spawnDynamicCircle(3.f, 400.f, 0.f);
	
	Texture tex;
	tex.loadFromFile("../assets/tile.png");
	tex.setSmooth(true);

	Shader blendShader;

	if (!blendShader.loadFromFile("../src/test.frag", Shader::Fragment))
		std::cout << "Failed to load blend fragment shader" << std::endl;

	Texture playerTex;
	playerTex.loadFromFile("../assets/player.png");
	playerTex.setSmooth(true);

	sf::Event ev;

	Texture worldTex;
	worldTex.create(W_WIDTH, W_HEIGHT);
	Sprite displaySprite;

	Font font;
	font.loadFromFile("../assets/kenney_bold.ttf");

	Text framerate;
	framerate.setFont(font);
	framerate.setCharacterSize(40);
	framerate.setPosition(1100, 200);
	framerate.setColor(sf::Color::White);

	while (window.isOpen())
	{
		while (window.pollEvent(ev))
		{
			if (ev.type == Event::Closed)
			{
				window.close();
			}

			if (ev.type == Event::KeyPressed)
			{
				if (ev.key.code == sf::Keyboard::Left)
				{	
					if (pPlayerBody->GetLinearVelocity().x - (MS_X / 100) > -(2 * MS_X / 100))
						pPlayerBody->ApplyForceToCenter({-MS_X, 0.f},true);
					else
						pPlayerBody->ApplyForceToCenter({ -(2 * MS_X / 100) - pPlayerBody->GetLinearVelocity().x , 0.f }, true);
				}

				if (ev.key.code == sf::Keyboard::Right)
				{
					if (pPlayerBody->GetLinearVelocity().x + (MS_X / 100) < (2 * MS_X / 100))
						pPlayerBody->ApplyForceToCenter({ MS_X, 0.f }, true);
					else
						pPlayerBody->ApplyForceToCenter({ (2 * MS_X / 100) - pPlayerBody->GetLinearVelocity().x , 0.f }, true);
				}

				if (ev.key.code == sf::Keyboard::Space)
				{
					if (pPlayerBody->GetLinearVelocity().y + (MS_X / 100)  < (2 * MS_X / 100))
						pPlayerBody->ApplyForceToCenter({ 0.f, -MS_X * 2 }, true);
					//else
						//pPlayerBody->ApplyForceToCenter({ 0.f, (3 * MS_X / 100) - pPlayerBody->GetLinearVelocity().y }, true);
				}
			}

			if (ev.type == Event::JoystickButtonPressed)
			{
				std::cout << ev.joystickButton.button << std::endl;
			}

			if (ev.type == Event::JoystickMoved)
			{
				std::cout << ev.joystickMove.axis << std::endl;
			}
		}

		physics.step(1.f / 30.f);
		
		window.clear();

		auto playerPos = pPlayerBody->GetPosition();
		view.setCenter(SCALE * playerPos.x, SCALE * playerPos.y);
		//window.setView(view);

		auto lightSize = playerLight->getSprite().getTexture()->getSize();

		// 3.f is the player body radius
		playerLight->setPosition(
			playerPos.x * SCALE - lightSize.x - 3.f * SCALE * 2
			, playerPos.y * SCALE - lightSize.y - 3.f * SCALE * 2);

		auto bodyIt = physics.getBodyList();

		//lights.updateView(view);
		lights.render();

		while (bodyIt != nullptr)
		{
			auto pos = bodyIt->GetPosition();

			if (bodyIt->GetType() == b2_dynamicBody)
			{
				CircleShape sprite;
							
				sprite.setTexture(&playerTex);

				auto playerShape = *(b2CircleShape*)(bodyIt->GetFixtureList()->GetShape());

				sprite.setRadius(playerShape.m_radius * SCALE);
				
				sprite.setOrigin(playerShape.m_radius * SCALE, playerShape.m_radius * SCALE);
				
				sprite.setPosition(SCALE * pos.x, SCALE * pos.y);

				sprite.setRotation(bodyIt->GetAngle() * 180 / b2_pi);
				
				window.draw(sprite);
			}

			else // ground
			{
				RectangleShape sprite;
				
				sprite.setSize({800.f, 40.f});
				
				sprite.setOrigin(400, 20);

				sprite.setPosition(pos.x * SCALE, pos.y * SCALE);

				sprite.setRotation(bodyIt->GetAngle() * 180 / b2_pi);

				sprite.setTexture(&tex);

				window.draw(sprite);
			}
			
			bodyIt = bodyIt->GetNext();
		}

		window.draw(Sprite{ lights.getLightMapTexture() }, BlendMultiply);

		float frameTime = 1.f / clock.getElapsedTime().asSeconds();
		clock.restart();
		framerate.setString(std::to_string((int)frameTime) + " fps");

		window.draw(framerate);

		window.display();
	}
}