• 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
MartinSmith160

OpenGL
Creating a DirectX 9.0 window class in C++

15 posts in this topic

Hi All

I have read through Advanced2D development by J Harbour in which you create a 2D directX 9.0 game engine. The engine is based around a single window.

I was planning on doing it the following way but im not sure its the correct approach:

[list]
[*]Write a window class that has all the parameters to allow creation of different types and styles of window
[*]Each window will have its own D3D device
[*]Each window will be registered with windows
[*]Each window will have its own rendering portion, so each sprite on its draw command will pass in it's D3D device (like a GC in openGL)
[/list]

This is what I plan to do but im not sure about handling the rendering properly. I also can never know how many windows a user could create so I am going to add them to a vector and then iterate over each whilst processing. I haven't really thought about sound yet.

My question is, is there anything blindingly I have missed out or really need to think about before I start this.

Thanks guys,

All the best,
Martin
0

Share this post


Link to post
Share on other sites
That's more or less the approach I use. One note though, you need one unique D3D device per [i]fullscreen [/i]window. If you have multiple non-fullscreen windows, they should share a device. I have a window request a device from a device manager type class at window creation. If it is the first window, a device is created, otherwise the window is given an already created device.
0

Share this post


Link to post
Share on other sites
Thanks turch. Yea each window will have its own device because I want to be able to run both windows in full screen. I'm going to be running my games on a multi monitor system. Thanks for the advice. I guess I will start planning.

Thanks.
0

Share this post


Link to post
Share on other sites
Hi Turch,

Just a quick question, I currently on have one LPD3DXSPRITE which is use as a sprite handler and that is used to draw all the sprites. When I create my sprite handler I have to pass it the LPDIRECT3DDEVICE9

eg D3DXCreateSprite(this->p_device, &this->p_sprite_handler);

My question is, do I now need to create a LPD3DXSPRITE for every window similar to making one LPDIRECT3DDEVICE9 for each window.

Thanks,
Martin
0

Share this post


Link to post
Share on other sites
LPD3DXSPRITE is really nothing more than a regular vertex and index buffer together with some variables, cobbled together into what looks like a D3D interface. So based on that, you can see that the same rules apply for creating sprites as for creatng any other resource - the Create* call is specific to a device and the resource is specific to the device that created it.

Note that D3D9Ex allows for sharing of resources between more than one device, but it's only available on Vista or higher, and comes with a bunch of other restrictions regarding usage and memory pools. I'm not certain if the LPD3DXSPRITE interface exposes this capability for the resources it creates, though.
0

Share this post


Link to post
Share on other sites
Yes you do, and you will also need to duplicate any other device bound objects if you want to use them in either window - vertex buffers, textures, etc will all need to be duplicated.
0

Share this post


Link to post
Share on other sites
Hi Guys

Thanks for you advice. I am having a a few issues with my window creation though. I have created a window wrapper class. I thought it was working because the windows create, are the correct dimensions and positions correctly. BUT when I call CreateWindowEX() it returns a NULL HWND.

Here is my Create function which sets up the window:

[source lang="cpp"]bool ST_Window::Create(HINSTANCE instance, int cmnd)
{
bool returnStatus = true;
appInstance = instance;
cmndLineArgs = cmnd;

wincl.hInstance = appInstance;
wincl.lpszClassName = title;
wincl.lpfnWndProc = WindowProc;
wincl.style = CS_HREDRAW | CS_VREDRAW;
wincl.cbSize = sizeof(WNDCLASSEX);
wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
wincl.lpszMenuName = NULL;
wincl.cbClsExtra = 0; /* No extra bytes after the window class */
wincl.cbWndExtra = 0; /* structure or the window instance */
wincl.hbrBackground = NULL;

/* Register the first windows class, and if it fails quit the program
returning a 1 so that we know where it failed*/
if (!RegisterClassEx (&wincl))
return 1;


hwnd = CreateWindowEx (
0, /* Extended possibilites for variation */
title, /* Classname */
title, /* Title Text */
WS_OVERLAPPEDWINDOW, /* default window */
xPos, /* X position */
yPos, /* Y position */
width, /* The programs width */
height, /* and height in pixels */
0, /* The window is a child-window to desktop */
0, /* No menu */
appInstance, /* Program Instance handler */
0 /* No Window Creation data */
);

DWORD error = GetLastError();

if(!hwnd)
returnStatus = false;

return returnStatus;
}[/source]

Also here is my windows procedure, each object will have this but its a static function:

[source lang="java"]LRESULT CALLBACK ST_Window::WindowProc(HWND p_hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message) /* handle the messages */
{
case WM_DESTROY:
PostQuitMessage (0); /* send a WM_QUIT to the message queue */
break;
default: /* for messages that we don't deal with */
return DefWindowProc (p_hwnd, message, wParam, lParam);
}

//return 0;
}[/source]

Its really strange because the windows create but no handle is returned. Also I call GetLastError() and it returns 0. I cant setup up and DirectX without the HWNDs so im screwed. Any help would be awesome.

Thanks so much guys,

All the best,
Martin
0

Share this post


Link to post
Share on other sites
I ran that function in a default windows project and it returned a HWND. Post more code so we can see what's going on around it.

Are you sure the window that is created, is created by that code? You don't call [url="http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx"]ShowWindow[/url] anywhere, and if you just create the window without calling that it won't actually show up.
0

Share this post


Link to post
Share on other sites
Hi Turch

Thats the create function of my window wrapper class. I have a winmain that calls ShowWindow() after its created. The window does show up so thats not the problem.

Here is my winmain code:

[source lang="cpp"]#pragma once

#include "ST_Window.h"

int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nFunsterStil)

{
MSG messages; /* Here messages to the application are saved. This is shared in this example */

ST_Window window1("Window1", 0,0,800,600);
ST_Window window2("Window2", 1000,0,800,600);

window1.Create(hThisInstance,nFunsterStil);
window2.Create(hThisInstance,nFunsterStil);

window1.ShowThisWindow();
window2.ShowThisWindow();

while(true)
{
while (PeekMessage (&messages, NULL, 0, 0, PM_REMOVE))
{
/* Translates Messages from GetMessage Function */
TranslateMessage(&messages);
/* Dipatches Messages */
DispatchMessage(&messages);
}

//UPDATE ENGINE

}
return messages.wParam;
}[/source]

I dont need to use the windows messaging so I dont mind that messages are shared between windows with the static WinProc. Its really strange, sometimes I get a HWND ok (Normally after a rebuild) but then after that i just get [unused] = ??? as the value.

I cant tell how great full I am for you help, im really stuck on this at the minute.

All the best,
Martin
0

Share this post


Link to post
Share on other sites
ShowWindow takes a HWND, so if the window shows up you must be passing a valid HWND. Where do you try to return the HWND that doesn't work? Post that code.

Also, post the [color="#000000"]ST_Window[/color] constructor and ShowThisWindow functions.
0

Share this post


Link to post
Share on other sites
Hi Turch

Im getting the HWND later when I want to create the directX device for the window. Basically I pass the window into the device manager and it creates a device and gives it to the window. I took that code out to make it cleaner to read. That code isnt working yet either but I thought it was due to having an invalid HWND. Could it be that the debugger is just showing me the wrong value?

Here is the ST_Window constructors:

[source lang="cpp"]ST_Window::ST_Window()
{
appInstance = 0;
hwnd = 0;
title = "DefaultWindow";
xPos = 0;
yPos = 0;
width = 800;
height = 600;
isFullScreen = false;
cmndLineArgs = 0;

window_device = 0;
window_backbuffer = 0;
window_sprite_handler = 0;
window_ambient_color = D3DCOLOR_RGBA(255,255,255,0);
}[/source]
[source lang="cpp"]ST_Window::ST_Window(char *title, int x, int y, int width, int height)
{
appInstance = 0;
hwnd = 0;
this->title = title;
xPos = x;
yPos = y;
this->width = width;
this->height = height;
isFullScreen = false;
cmndLineArgs = 0;

window_device = 0;
window_backbuffer = 0;
window_sprite_handler = 0;
window_ambient_color = D3DCOLOR_XRGB(255,255,255);
}[/source]

Here is the ShowThisWindow() function ( It basically just calls the windows functions but uses the stored HWND)

[source lang="cpp"]bool ST_Window::ShowThisWindow()
{
return ShowWindow(hwnd, cmndLineArgs);
}[/source]

Here is My DeviceManager class code:

[source lang="cpp"]#include "ST_DeviceManager.h"

ST_DeviceManager::ST_DeviceManager()
{
deviceCount = 0;
devices.clear();
this->d3d = NULL;
}

ST_DeviceManager::~ST_DeviceManager()
{
for(int i = 0; i < devices.size(); i++)
{
devices[i]->Release();
}

d3d->Release();
}

void ST_DeviceManager::CreateDevice(ST_Window &targetWindow)
{
if (this->d3d == NULL)
{
this->d3d = Direct3DCreate9(D3D_SDK_VERSION);
}

RECT clientWindowRect;
GetClientRect(targetWindow.GetHWND(),&clientWindowRect);

//get system desktop color depth
D3DDISPLAYMODE dm;
LPDIRECT3DDEVICE9 newDevice;
LPDIRECT3DSURFACE9 newbackbuffer;
LPD3DXSPRITE new_sprite_handler;

this->d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &dm);

//set configuration options for Direct3D
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = targetWindow.IsFullScreen();
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
d3dpp.BackBufferFormat = dm.Format;
d3dpp.BackBufferCount = 1;
d3dpp.BackBufferWidth = clientWindowRect.right;
d3dpp.BackBufferHeight = clientWindowRect.bottom;
d3dpp.hDeviceWindow = targetWindow.GetHWND();

//create Direct3D device
this->d3d->CreateDevice(
D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
targetWindow.GetHWND(),
D3DCREATE_HARDWARE_VERTEXPROCESSING,
&d3dpp,
&newDevice);

//TODO NEED TO ADD CLEAR SCREEN

newDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &newbackbuffer);

newDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
newDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
newDevice->SetRenderState(D3DRS_LIGHTING, true);
newDevice->SetRenderState(D3DRS_AMBIENT,targetWindow.GetWindowAmbientColor());

D3DSURFACE_DESC bb_desc;
newbackbuffer->GetDesc(&bb_desc);

//SET DEFAULT MATERIAL
D3DMATERIAL9 mat;
memset(&mat, 0, sizeof(mat));
mat.Diffuse.r = mat.Ambient.r = 1.0f;
mat.Diffuse.g = mat.Ambient.g = 1.0f;
mat.Diffuse.b = mat.Ambient.b = 1.0f;
mat.Diffuse.a = mat.Ambient.a = 1.0f;
newDevice->SetMaterial(&mat);

targetWindow.SetWindowDevice(newDevice);
targetWindow.SetWindowBackBuffer(newbackbuffer);

newDevice = 0;
newbackbuffer = 0;
new_sprite_handler = 0;
}[/source]

Its very simplistic at this stage, I just wanted to get it working fundamentally. The DeviceManager::CreateDevice() is called after the window is created.

Sorry to bombard you with code. Basically if I call the CreateDevice() function my screen flashes black and the app locks up so I know something is majorly wrong but I thought its was not having a valid HWND. I stepped through the code for the CreateDevice() function and it locks up after this->d3d->CreateDevice() is called.

Thanks again for your help dude.
[img]C:\Users\stormoffice\Desktop\HWND_Problem.png[/img]
0

Share this post


Link to post
Share on other sites
Holy Shit, I made such a stupid error.

check line 41 of the [color=#000000][font=Consolas,]ST_DeviceManager::CreateDevice(ST_Window &targetWindow) code. I set [/font][/color][color=#000000][font=Consolas,]d3dpp.Windowed [/font][/color][color=#000000][font=Consolas,]depending on the windows fulscreen status. As of now the isFullscreen variable is aslways false. so d3dpp.windowed was set to false making it try to go fullscreen but its not setup for it. I changed it to be [/font][/color][color=#000000][font=Consolas,]d3dpp.Windowed = !targetWindow.IsFullScreen(); and [/font][/color][color=#000000][font=Consolas,]The windows open and the devices are created correctly.[/font][/color]

[color=#000000][font=Consolas,]The HWND issue still confuses me though. The createDevice function works outs the correct window client area by getting the HWND from the window, but when I look at it in the debugger it still just says unused = ??? [/font][/color]

[color=#000000][font=Consolas,]Very strange.[/font][/color]

[color=#000000][font=Consolas,]Thank you so much for your help and im sorry if its seems like I wasted your time.[/font][/color]

[color=#000000][font=Consolas,]All the best,[/font][/color]
[color=#000000][font=Consolas,]Martin[/font][/color]
0

Share this post


Link to post
Share on other sites
Hah, I actually made the same error when I was testing it a second ago... I set windowed to false thinking it was "fullscreen" - don't worry, the most frustrating and time consuming bugs are the ones where you make a stupid mistake. You gloss over the mistake because you can't [i]possibly [/i]make a mistake so simple [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

Look into [url="http://en.wikipedia.org/wiki/Rubber_duck_debugging"]rubber duck debugging[/url] - whenever I'm searching for a bug and I just can't find it, I call in another dev and start explaining the code to them. They don't do anything or participate or even listen, but the act of explaining it that way forces you to consider those details you overlook because they are so obvious ( if (condition = true) ).

As for the HWND issue, make sure you are compiling and running the debug configuration, not release. If you try debugging a release build, you usually get incorrect data / variable unused / not found / etc. because the compiler doesn't insert debug information and mangles the code quite a bit for optimizations, and thus it can't find the variable.

And just a few more random thoughts:

consider wrapping all your raw directx pointers like so
[code]
typedef CComPtr<IDirect3D9> D3DPtr;
typedef CComPtr<IDirect3DDevice9> D3DDevicePtr;
[/code]

That way, you don't have to call remember when you need to call Release, it will save you tons of time looking for memory leaks. You just use D3DPtr in place of LPDIRECT3D9

You might want to create only one D3DDevice for all (non-fullscreen) windows. Almost everything (textures, vertex buffers, shaders) is device-bound, so if you want to use one texture in two devices, you have to create it twice and keep track of which one belongs to which device. I use something similar to this (pseudocode):

[code]Window::Create(devicemanager)
if (devicemanager.device == null)
m_device = devicemanager.CreateDevice()
else
m_device = devicemanager.device
[/code]

If you want multiple fullscreen windows, however, you have to use multiple devices. But most of the time all you really need multiple windows for is a level editor or other tools, and don't need them to run in fullscreen.
0

Share this post


Link to post
Share on other sites
Thanks Turch

I am running in debug mode for sure. The thing is sometimes it shows the HWND value and sometimes it dosent. BUT it always has a hex value. if it was NULL I would assume the hex value would be like 0x000000 or summin but it has an actual value so maybe its so large that the debugger cant show it. I might be speaking bollocks but it was just a thought.

Thats great advice for the debugging and the DirectX pointers aswell so thanks, I will definitely use that.As far as fullscreen goes, I will always be running two windows both in fullscreen because the games I aim to develop are for a multi monitor platform.

Thanks for all you help dude, you have really helped.
0

Share this post


Link to post
Share on other sites
The debugger recognizes the types of variables and displays them accordingly. There's no variable type that's too large for it. NULL is == (void*)0, so if the debugger says 0x00000000 for a pointer then that's a NULL. You can trust it on this kind of thing. ;)
0

Share this post


Link to post
Share on other sites
Hi Khatharr

Thanks for the input, would you know of a reason then that when I look at my HWND values in the debugger its says 0x000109ba {unused = 0} but the handle still works.

All the best,
Martin.
0

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 mapra99
      Hello

      I am working on a recent project and I have been learning how to code in C# using OpenGL libraries for some graphics. I have achieved some quite interesting things using TAO Framework writing in Console Applications, creating a GLUT Window. But my problem now is that I need to incorporate the Graphics in a Windows Form so I can relate the objects that I render with some .NET Controls.

      To deal with this problem, I have seen in some forums that it's better to use OpenTK instead of TAO Framework, so I can use the glControl that OpenTK libraries offer. However, I haven't found complete articles, tutorials or source codes that help using the glControl or that may insert me into de OpenTK functions. Would somebody please share in this forum some links or files where I can find good documentation about this topic? Or may I use another library different of OpenTK?

      Thanks!
    • 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
  • Popular Now