• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
xDarkice

OpenGL
Porting from OpenGL to Directx

30 posts in this topic

Hello,

recently I have been trying to port over the OpenGL interface due to some problems with Intel Graphic chips which have a bad OpenGL driver in Windows. I need help to port a Quad in OpenGL to DirectX. Heres what i have done in OpenGL:

[code] GL.Begin(BeginMode.Quads);
GL.TexCoord2(x1, y1);
GL.Vertex3(rx1, ry1, rect.Z + CGraphics.ZOffset);

GL.TexCoord2(x1, y2);
GL.Vertex3(rx1, ry2, rect.Z + CGraphics.ZOffset);
GL.TexCoord2(x2, y2);
GL.Vertex3(rx2, ry2, rect.Z + CGraphics.ZOffset);
GL.TexCoord2(x2, y1);
GL.Vertex3(rx2, ry1, rect.Z + CGraphics.ZOffset);
GL.End();[/code]

And here is what I am doing for DirectX[code] rx1 = ((rx1 * 2) / ClientSize.Width) -1f;
rx2 = ((rx2 * 2) / ClientSize.Width) - 1f;
ry1 = ((ry1 * 2) / ClientSize.Height) - 1f;
ry2 = ((ry2 * 2) / ClientSize.Height) - 1f;

DataStream stream = _VertexBuffer.Lock(0, 0, LockFlags.None);
stream.WriteRange(new[] {
new TexturedVertex(new Vector3(rx1, ry1, 0), new Vector2(x1, y1)),
new TexturedVertex(new Vector3(rx1, ry2, 0), new Vector2(x1, y2)),
new TexturedVertex(new Vector3(rx2, ry2, 0), new Vector2(x2, y2)),
new TexturedVertex(new Vector3(rx2, ry1, 0), new Vector2(x2, y1)),
});
_VertexBuffer.Unlock();
m_Device.SetTexture(0, _D3DTextures[Texture.index]);
m_Device.SetStreamSource(0, _VertexBuffer, 0, Marshal.SizeOf(typeof(TexturedVertex)));
m_Device.DrawPrimitives(PrimitiveType.TriangleFan, 0, 2);[/code]

Unfortunetely the Textures are mirrored and the alpha Channel is displayed in black. I hope you can help me, I have been trying to get this working for 2 days now =/

Best regards xDarkice
0

Share this post


Link to post
Share on other sites
To mirror the texture, negate the v component of the texture coordinate. D3D and OpenGL consider the "up" direction differently in this case.

To blend with alpha channel, you need to enable the alphablend render state, and set the blend source and destination states accordingly.

As a side note, you don't want to be locking the vertex buffer at each frame if you don't need to. If you have a genuine need to do so, use a vertex buffer with dynamic usage flag specified. Excessive locking can cause stalling because the hardware can't use the buffer for rendering while it is locked to you. Requesting dynamic usage hints the driver to allocate the buffer to a physical memory resource that allows fast write usage at the expense of rendering performance (though choosing the actual allocation strategy is still up to the driver).
1

Share this post


Link to post
Share on other sites
Thanks for your answer! After setting [code] m_Device.SetRenderState(RenderState.AlphaBlendEnable, true);
m_Device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha);
m_Device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha);[/code]
Alpha textures seem to render almost properly. But there are still some black blocks left.

Negating the y cords seems to work for the mirror part but the image is still some of sort of upset down. The main menu texture should be top. The ry1 and ry2 coordinates seem to be incorrect. Am I calculating them wrong? On top of that my Textures seem to be blurry and there might be a part missing[Code] ry1 = ((ry1 * 2) / CSettings.iRenderH) - 1f;
ry2 = ((ry2 * 2) / CSettings.iRenderH) - 1f;[/Code]
I am multiplicating my coordinates by 2 and dividing them by the heigth and substracting 1.

I think I do not need to lock the buffer each frame. What should i initialize my DataStream with? Right now I am using [code]DataStream stream = _VertexBuffer.Lock(0, 0, LockFlags.None);[/code]

The second picture shows how it is rendering in OpenGL. I disabled the background video in DirectX for testing purposes.

Now I just need to find a way to color the textures. But I think I can just add a new Color in my TexturedVertex struct.

Thanks for your help!

EDIT: I got the upside down fixed! I didnt had to negate y1 and y2, but ry1 and y2. But the blurry textures and texts arent fixed yet
EDIT2: The Black Bars seem to appear for a whitespace in a text
0

Share this post


Link to post
Share on other sites
OpenGL interprets screen-space positions as the centre of the pixel
DirectX interprets screen-space positions as the top-left corner of the pixel
(Or is it the other way round?)

Either way, to stop your textures from blurring, you need to subtract 0.5 from your screen-space positions when changing between OpenGL and DX. This is like shifting them up-left by 0.5 pixels. So they will still fill the same pixels, but it will affect how the texture coordinates are interpolated, and should stop the blurring
0

Share this post


Link to post
Share on other sites
I believe the black bars appear because your text rendering logic actually generates black rectangles with alpha of 1.0 to fill whitespace. Check your code that generates the triangles for the glyphs.
0

Share this post


Link to post
Share on other sites
Regarding locking, only do so when you actually change the text contents. You can't get the DataStream any other way than locking the buffer, nor can you keep the reference to it between frames (because it would keep the resource locked).

You can change the text color by modulating the rgb of the texture with a constant color factor, instead of locking the buffer. In fixed function pipeline, this is achieved by setting appropriate texture stage states, and in a pixel shader the operation is a single multiplication.
0

Share this post


Link to post
Share on other sites
I think the black bars appear because texture transparency is not drawn properly. For example my main menu bar should be drawn a little bit transparent like in the openGL pickture I included above.
My DrawGlyph function does render a transparent texture at whitespaces. This shouldnt be the problem because it is working in OpenGL aswell.

EDIT: I am providing my AddTexture and DrawTexture function:

[code] public STexture AddTexture(Bitmap bmp, string TexturePath)
{
STexture texture = new STexture(-1);
if (bmp.Height == 0 || bmp.Width == 0)
return texture;
int MaxSize;
switch (CConfig.TextureQuality)
{
case ETextureQuality.TR_CONFIG_TEXTURE_LOWEST:
MaxSize = 128;
break;
case ETextureQuality.TR_CONFIG_TEXTURE_LOW:
MaxSize = 256;
break;
case ETextureQuality.TR_CONFIG_TEXTURE_MEDIUM:
MaxSize = 512;
break;
case ETextureQuality.TR_CONFIG_TEXTURE_HIGH:
MaxSize = 1024;
break;
case ETextureQuality.TR_CONFIG_TEXTURE_HIGHEST:
MaxSize = 2048;
break;
default:
MaxSize = 512;
break;
}

int w = bmp.Width;
int h = bmp.Height;

if (h >= w && w > MaxSize)
{
h = (int)Math.Round((float)MaxSize / bmp.Width * bmp.Height);
w = MaxSize;
}

if (w >= h && h > MaxSize)
{
w = (int)Math.Round((float)MaxSize / bmp.Height * bmp.Width);
h = MaxSize;
}

Bitmap bmp2 = new Bitmap(w, h);
Graphics g = Graphics.FromImage(bmp2);
g.DrawImage(bmp, new Rectangle(0, 0, w, h));
g.Dispose();


texture.width = bmp2.Width;
texture.height = bmp2.Height;
texture.w2 = texture.width;
texture.h2 = texture.height;

texture.width_ratio = texture.width / texture.width;
texture.height_ratio = texture.height / texture.height;

BitmapData bmp_data = bmp2.LockBits(new Rectangle(0, 0, bmp2.Width, bmp2.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (MemoryStream stream = new MemoryStream())
{
bmp2.Save(stream, ImageFormat.Bmp);
stream.Position = 0;
//Texture t = Texture.FromStream(m_Device, stream);
Texture t = Texture.FromStream(m_Device, stream, 0, w, h, 0, Usage.None, Format.A8R8G8B8, Pool.Managed, Filter.Default, Filter.Linear, 0);
t.AutoMipGenerationFilter = TextureFilter.Linear;
t.GenerateMipSublevels();
//t = Texture.FromStream(m_Device, stream);
_D3DTextures.Add(t);
}
bmp2.UnlockBits(bmp_data);
bmp2.Dispose();

// Add to Texture List
texture.index = _D3DTextures.Count - 1;
texture.color = new SColorF(1f, 1f, 1f, 1f);
texture.rect = new SRectF(0f, 0f, texture.width, texture.height, 0f);
texture.TexturePath = String.Empty;
_Textures.Add(texture);

return texture;
} [/code]

[code] public void DrawTexture(STexture Texture, SRectF rect, SColorF color, SRectF bounds, bool mirrored)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_D3DTextures.Count > Texture.index))
{
float x1 = (bounds.X - rect.X) / rect.W * Texture.width_ratio;
float x2 = (bounds.X + bounds.W - rect.X) / rect.W * Texture.width_ratio;
float y1 = (bounds.Y - rect.Y) / rect.H * Texture.height_ratio;
float y2 = (bounds.Y + bounds.H - rect.Y) / rect.H * Texture.height_ratio;

if (x1 < 0)
x1 = 0f;

if (x2 > Texture.width_ratio)
x2 = Texture.width_ratio;

if (y1 < 0)
y1 = 0f;

if (y2 > Texture.height_ratio)
y2 = Texture.height_ratio;

float rx1 = rect.X;
float rx2 = rect.X + rect.W;
float ry1 = rect.Y;
float ry2 = rect.Y + rect.H;

if (rx1 < bounds.X)
rx1 = bounds.X;

if (rx2 > bounds.X + bounds.W)
rx2 = bounds.X + bounds.W;

if (ry1 < bounds.Y)
ry1 = bounds.Y;

if (ry2 > bounds.Y + bounds.H)
ry2 = bounds.Y + bounds.H;
rect.Z = 1f;
//y1 = y1*-1;

rx1 = (((rx1-0.5f) * 2) / 1280) - 1f;
rx2 = (((rx2 -0.5f) * 2) / 1280) - 1f;
ry1 = (((ry1-0.5f) * 2) / 720) - 1f;
ry2 = (((ry2-0.5f) * 2) / 720) - 1f;

DataStream stream = _VertexBuffer.Lock(0, 0, LockFlags.None);
Color c = Color.FromArgb((int)(color.A*255), (int)(color.R*255), (int)(color.G*255), (int)(color.B*255));
stream.WriteRange(new[] {
new TexturedColoredVertex(new Vector3(rx1, ry1*-1f, rect.Z + CGraphics.ZOffset), new Vector2(x1, y1), c.ToArgb()),
new TexturedColoredVertex(new Vector3(rx1, ry2*-1f, rect.Z + CGraphics.ZOffset), new Vector2(x1, y2), c.ToArgb()),
new TexturedColoredVertex(new Vector3(rx2, ry2*-1f, rect.Z + CGraphics.ZOffset), new Vector2(x2, y2), c.ToArgb()),
new TexturedColoredVertex(new Vector3(rx2, ry1*-1f, rect.Z + CGraphics.ZOffset), new Vector2(x2, y1), c.ToArgb()),
});
_VertexBuffer.Unlock();
m_Device.VertexDeclaration= TexturedColoredVertex.GetDeclaration(m_Device);
m_Device.SetTexture(0, _D3DTextures[Texture.index]);
m_Device.SetStreamSource(0, _VertexBuffer, 0, Marshal.SizeOf(typeof(TexturedColoredVertex)));
m_Device.DrawPrimitives(PrimitiveType.TriangleFan, 0, 2);
}
}[/code]

I am looking for a way to make textures a bit transparent.
0

Share this post


Link to post
Share on other sites
Ok, thanks for your tip changing from BMP to PNG. This removed the black bars [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img]. Could you please provide a snippet how to not lock the Vertex buffer each frame, because I am not getting it? And i still need the textures to be a bit translucent.
0

Share this post


Link to post
Share on other sites
Simply don't do the lock->write->unlock in the same place where you draw. The buffer update should only be done when you actually want to change its contents, which is usually far more seldom than drawing it.
0

Share this post


Link to post
Share on other sites
And if you want "bit more translucent", you can adjust the alpha levels on the PNG files, or modulate the alpha of the texture by using texture stage states or (again) simple maths in the pixel shader.
1

Share this post


Link to post
Share on other sites
I do not need to adjust the alpha levels, because they should already be in the PNG. In OpenGL those textures are rendered translucent, but in DirectX they arent. Just compare the OpenGL and the DirectX one: In OpenGL you can see the snow falling behind the texture where "Main Menu" is drawn on. In DirectX you cant.
I think I am missing some parameters for alpha Blending, am I?
0

Share this post


Link to post
Share on other sites
If you have alpha blending on, the alpha factor comes from the texture stage setup or the pixel shader. If either outputs alpha of 1.0 (independent of any source textures), the drawn geometry is opaque even though blending is enabled.
1

Share this post


Link to post
Share on other sites
Ok i got alpha working now. Now I am stuck at creating a texture out of a byte[], height and width is given. I am doing this:

[code] Texture t = new Texture(m_Device, W, H, 0, Usage.Dynamic, Format.A8R8G8B8, Pool.Default);
DataRectangle rect = t.LockRectangle(0, LockFlags.None);
rect.Data.WriteRange(Data);
t.UnlockRectangle(0); [/code]
But i am not getting the result I want on screen. I need this to play a video, decoded by Acinerella, so creating a Bitmap out of the byte[] would not be a good idea due to the bad performance.
0

Share this post


Link to post
Share on other sites
It looks like the pitch of the data is incorrect.

D3D textures have a "pitch" that is the number of bytes per line. It may or may not be equal to width * bytes per pixel, and you should not assume that it is.

The actual visible pixels are guaranteed to be at the beginning of the scanline (regardless of the pitch) so the most robust way to copy an image to a texture is to copy the data one line at a time, and shift the destination pointer by the pitch after each line until all the lines are copied. I don't know how to do this in SlimDX, though - I'm a native D3D user.

Also check that the source and destination formats are same (or at least have the same bit count per pixel).
1

Share this post


Link to post
Share on other sites
Also, do not create the texture each frame. This is very detrimental to performance. Instead, keep the texture reference in your code after you've created it, and merely update it when you want to change the contents.
0

Share this post


Link to post
Share on other sites
I am not recreating the texture each frame. I keep all textures stored in a List and they can be updated using my UpdateTexture methods. The textures are drawn in my DrawTexture methods.

Your post really helped me out. Instead of writing the data directly into the stream i am now doing this which works like a charm:

[code] DataRectangle rect = t.LockRectangle(0, LockFlags.None);
for(int i = 0; i < Data.Length;) {
rect.Data.Write(Data, i, 4 * W);
i+= 4*W;
rect.Data.Position = rect.Data.Position - 4 * W;
rect.Data.Position += rect.Pitch;
}
t.UnlockRectangle(0);[/code]

The hopefully last minor bugs are that [s]my z-position isnt applied correctly [/s]and the textures are still a bit blurry.
The small album art should be rendered over the big one. It is working fine in OpenGL, but z-Positions can go beyond 1.0f in OpenGL. If I draw my z-Positions with values over 1f they wont show up. I am currently setting any positions over 1f to 1f which creates this bug i think.
The other thing is that the textures are not that good as in OpenGL. I experimented with some TextureFilters ending up using a linear filter, which is still not too fine. In OpenGL i am using MipMaps to have smooth textures. Can I do the same in DirectX?

EDIT: Fixed z-Positions, still need to examine why the textures are a bit blurry though I am shifting the Pixels by 0.5
0

Share this post


Link to post
Share on other sites
You can use mipmaps in D3D too.

In the image attached to your last post, it seems that there is not a 1:1 size correspondence between the source and target. If this is intented, be sure to enable minification, magnification and mip filtering. For mip mapping, you need to allocate and fill the mip levels (I believe there is a D3DX helper function for filling them).
0

Share this post


Link to post
Share on other sites
Regarding the z range, you can control it by using the viewport of the device. The viewport structure represents a mapping between physical and logical dimensions of rendering.

The default viewport has a z-range of 0...1, as you noticed.
0

Share this post


Link to post
Could this issue also be caused because I am not using textures with sizes of a power of two? The Sizes are not the same, they need to get scaled. For instance covers of any size can be used and they need to get scaled to fit. Could my calculation of the positions be too inaccurate? I need to scale the positions down to values from 0 to 1. In OpenGL I was able to specify screen positions. Is there a setting to do this in D3D aswell?

Edit: I got it smooth now. But I am now getting small bars. After setting [code]m_Device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Linear);
m_Device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Linear);
m_Device.SetSamplerState(0, SamplerState.MipFilter, TextureFilter.Linear);[/code] I do not get the Previewvideo anymore and these small bars are appearing. Any ideas?

Edit2: [code]m_Device.SetSamplerState(0, SamplerState.MipFilter, TextureFilter.Linear);[/code] is definetely the line which is breaking the video. Could this be due to I am not filling the video's mipmaps? This is how I am adding a new texture for a video:

[code] public STexture AddTexture(int W, int H, ref byte[] Data)
{
STexture texture = new STexture(-1);
texture.width = W;
texture.height = H;
texture.w2 = texture.width;
texture.h2 = texture.height;
texture.width_ratio = texture.width / texture.w2;
texture.height_ratio = texture.height / texture.h2;
Texture t = new Texture(m_Device, W, H, 0, Usage.Dynamic, Format.A8R8G8B8, Pool.Default);
DataRectangle rect = t.LockRectangle(0, LockFlags.None);
for(int i = 0; i < Data.Length;) {
rect.Data.Write(Data, i, 4 * W);
i+= 4*W;
rect.Data.Position = rect.Data.Position - 4 * W;
rect.Data.Position += rect.Pitch;
}
t.UnlockRectangle(0);
_D3DTextures.Add(t);
texture.index = _D3DTextures.Count - 1;
texture.color = new SColorF(1f, 1f, 1f, 1f);
texture.rect = new SRectF(0f, 0f, texture.width, texture.height, 0f);
texture.TexturePath = String.Empty;
_Textures.Add(texture);
return texture;
}
[/code]

And this is how I am updating this:

[code] public bool UpdateTexture(ref STexture Texture, ref byte[] Data)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_D3DTextures.Count > Texture.index))
{
DataRectangle rect = _D3DTextures[Texture.index].LockRectangle(0, LockFlags.None);
for (int i = 0; i < rect.Data.Length; )
{
if (rect.Data.Length - rect.Data.Position > 4 * (int)Texture.width)
{
rect.Data.Write(Data, i, 4 * (int)Texture.width);
i += 4 * (int)Texture.width;
rect.Data.Position = rect.Data.Position - 4 * (int)Texture.width;
rect.Data.Position += rect.Pitch;
}
else
break;
}
rect.Data.Position = 0;
_D3DTextures[Texture.index].UnlockRectangle(0);
}
return true;
}
[/code]

I do not need to use MipMaps for videos due to performance reasons, can I disable MipMaps for single textures only?
0

Share this post


Link to post
Share on other sites
Yes, you can disable/enable mip lookup between every draw call. Each draw call uses the state that happens to be set before it.
0

Share this post


Link to post
Share on other sites
Ok, I got this now. Can I force DirectX to use screen positions instead of values from 0 to 1 to set the Z-Positions and the vertexpositions much more precisely?

I think there could be some 'fighting' between the values when they are too near together. In OpenGL I can do this. Ideas?

Edit: I am trying to use this [code]Matrix.OrthoLH(Screenwidth, Screenheight, zNear, zFar); [/code] This works, but if I am using screenpositions now for drawing, the textures are shifted to the mid of the screen. Basically, position 0,0 is the center of the screen, but I want it to be at the top left.
0

Share this post


Link to post
Share on other sites
You could make a matrix that scales and biases coordinates from 0...screenwidth and 0...screenheight to -1...1. This is very simple math.
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Similar Content

    • By Solid_Spy
      Hello, I have been working on SH Irradiance map rendering, and I have been using a GLSL pixel shader to render SH irradiance to 2D irradiance maps for my static objects. I already have it working with 9 3D textures so far for the first 9 SH functions.
      In my GLSL shader, I have to send in 9 SH Coefficient 3D Texures that use RGBA8 as a pixel format. RGB being used for the coefficients for red, green, and blue, and the A for checking if the voxel is in use (for the 3D texture solidification shader to prevent bleeding).
      My problem is, I want to knock this number of textures down to something like 4 or 5. Getting even lower would be a godsend. This is because I eventually plan on adding more SH Coefficient 3D Textures for other parts of the game map (such as inside rooms, as opposed to the outside), to circumvent irradiance probe bleeding between rooms separated by walls. I don't want to reach the 32 texture limit too soon. Also, I figure that it would be a LOT faster.
      Is there a way I could, say, store 2 sets of SH Coefficients for 2 SH functions inside a texture with RGBA16 pixels? If so, how would I extract them from inside GLSL? Let me know if you have any suggestions ^^.
    • By KarimIO
      EDIT: I thought this was restricted to Attribute-Created GL contexts, but it isn't, so I rewrote the post.
      Hey guys, whenever I call SwapBuffers(hDC), I get a crash, and I get a "Too many posts were made to a semaphore." from Windows as I call SwapBuffers. What could be the cause of this?
      Update: No crash occurs if I don't draw, just clear and swap.
      static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 32, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 24, // 24Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(hDC = GetDC(windowHandle))) return false; unsigned int PixelFormat; if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) return false; if (!SetPixelFormat(hDC, PixelFormat, &pfd)) return false; hRC = wglCreateContext(hDC); if (!hRC) { std::cout << "wglCreateContext Failed!\n"; return false; } if (wglMakeCurrent(hDC, hRC) == NULL) { std::cout << "Make Context Current Second Failed!\n"; return false; } ... // OGL Buffer Initialization glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glUseProgram(myprogram); glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (void *)indexStart); SwapBuffers(GetDC(window_handle));  
    • By Tchom
      Hey devs!
       
      I've been working on a OpenGL ES 2.0 android engine and I have begun implementing some simple (point) lighting. I had something fairly simple working, so I tried to get fancy and added color-tinting light. And it works great... with only one or two lights. Any more than that, the application drops about 15 frames per light added (my ideal is at least 4 or 5). I know implementing lighting is expensive, I just didn't think it was that expensive. I'm fairly new to the world of OpenGL and GLSL, so there is a good chance I've written some crappy shader code. If anyone had any feedback or tips on how I can optimize this code, please let me know.
       
      Vertex Shader
      uniform mat4 u_MVPMatrix; uniform mat4 u_MVMatrix; attribute vec4 a_Position; attribute vec3 a_Normal; attribute vec2 a_TexCoordinate; varying vec3 v_Position; varying vec3 v_Normal; varying vec2 v_TexCoordinate; void main() { v_Position = vec3(u_MVMatrix * a_Position); v_TexCoordinate = a_TexCoordinate; v_Normal = vec3(u_MVMatrix * vec4(a_Normal, 0.0)); gl_Position = u_MVPMatrix * a_Position; } Fragment Shader
      precision mediump float; uniform vec4 u_LightPos["+numLights+"]; uniform vec4 u_LightColours["+numLights+"]; uniform float u_LightPower["+numLights+"]; uniform sampler2D u_Texture; varying vec3 v_Position; varying vec3 v_Normal; varying vec2 v_TexCoordinate; void main() { gl_FragColor = (texture2D(u_Texture, v_TexCoordinate)); float diffuse = 0.0; vec4 colourSum = vec4(1.0); for (int i = 0; i < "+numLights+"; i++) { vec3 toPointLight = vec3(u_LightPos[i]); float distance = length(toPointLight - v_Position); vec3 lightVector = normalize(toPointLight - v_Position); float diffuseDiff = 0.0; // The diffuse difference contributed from current light diffuseDiff = max(dot(v_Normal, lightVector), 0.0); diffuseDiff = diffuseDiff * (1.0 / (1.0 + ((1.0-u_LightPower[i])* distance * distance))); //Determine attenuatio diffuse += diffuseDiff; gl_FragColor.rgb *= vec3(1.0) / ((vec3(1.0) + ((vec3(1.0) - vec3(u_LightColours[i]))*diffuseDiff))); //The expensive part } diffuse += 0.1; //Add ambient light gl_FragColor.rgb *= diffuse; } Am I making any rookie mistakes? Or am I just being unrealistic about what I can do? Thanks in advance
    • By yahiko00
      Hi,
      Not sure to post at the right place, if not, please forgive me...
      For a game project I am working on, I would like to implement a 2D starfield as a background.
      I do not want to deal with static tiles, since I plan to slowly animate the starfield. So, I am trying to figure out how to generate a random starfield for the entire map.
      I feel that using a uniform distribution for the stars will not do the trick. Instead I would like something similar to the screenshot below, taken from the game Star Wars: Empire At War (all credits to Lucasfilm, Disney, and so on...).

      Is there someone who could have an idea of a distribution which could result in such a starfield?
      Any insight would be appreciated
    • By afraidofdark
      I have just noticed that, in quake 3 and half - life, dynamic models are effected from light map. For example in dark areas, gun that player holds seems darker. How did they achieve this effect ? I can use image based lighting techniques however (Like placing an environment probe and using it for reflections and ambient lighting), this tech wasn't used in games back then, so there must be a simpler method to do this.
      Here is a link that shows how modern engines does it. Indirect Lighting Cache It would be nice if you know a paper that explains this technique. Can I apply this to quake 3' s light map generator and bsp format ?
  • Popular Now