# OpenGL bit of a conversion problem

## Recommended Posts

i have recntly bought a few tutorials from www.gametutorials.com i am currently trying to convert the c++ direct3d water tutorial to vb.net , i have been trying for ages and can seem to find the problem , i have converted the code over word for word and still dosent work, so below i have posted the c++ and vb.net and i would be very gratefull if somebody could have a look at them and maybe point out some mistakes that i have made. c++ version water.h
#include "d3d_obj.h"
#include "d3d_texture.h"

/////////////
// Macros //
///////////

#define DEG2RAD(x) (x * (D3DX_PI / 180.0f)) // Converts degrees to radians
#define RAD2DEG(x) (x * (180.0f / D3DX_PI)) // Converts radians to degrees

#define F2I(x) ( (int)((x) + 0.5f) ) // Converts a float to int with proper rounding

////////////////
// Constants //
//////////////

const int kWaterTesselation = 32; // Number of rows X cols of tessellated quads in water
const int kWaveTableSize = 36; // Number of entries in the wave table

const float kWaterForce = 1.0f / 25.0f; // Controls the "choppiness" of the water (Range is 0.0f - 1.0f)
// 0.0f == Water is still
// 1.0f == Water is VERY choppy (so choppy it looks very bad)
const float kWaterWid = 30.0f; // Width of water (along X-axis)
const float kWaterHgt = 30.0f; // Height of water (along Z-axis)

class CWater
{
public:

CWater(); // Constructor

bool init(); // Initialize the water object
void process(); // Process the water object (apply sin() wave to Y value of verts)
void render(); // Render the water

~CWater(); // Deconstructor

private:

bool createGeometery(float width, float height, int tesselation);

CD3DTexture mTexture;
SVertex *mVerts;
WORD *mIndices;

int mVertCount;
int mIndexCount;
int mTesselation;

float mWaveTable[kWaveTableSize];
};

#endif


water.cpp

#include "water.h"

const CPos kWaterCen(0.0f, 0.0f, 0.0f); // Water is always centered at (0,0,0)

// Helper function for determining if a float is less than or equal to
// another float
inline bool ToleranceLE(float a, float b, float tolerance = 0.001f)
{
return ((a - tolerance) <= b);
}

// Constructor
CWater::CWater()
{
memset(mWaveTable, 0, sizeof(mWaveTable));

mVerts = NULL;
mIndices = NULL;

mVertCount = 0;
mIndexCount = 0;
mTesselation = 0;

// "texture" gets initialized by it's constructor
}

// Init the water object, returns true on success, false otherwise
bool CWater::init()
{
// Fill the wave table
float angInc = 360.0f / (float)kWaveTableSize;
float angle = 0.0f;

// Fill in the table with values of the sine function
for(int i = 0; i < kWaveTableSize; ++i)
{
angle += angInc;
}

if(!createGeometery(kWaterWid, kWaterHgt, kWaterTesselation))
return false;

}

// Process the water every frame
void CWater::process()
{
static int startIndex = 0;

int waveIndex = startIndex;
int vertIndex = 0;

// Loop through all rows of triangles
for(int i = 0; i <= mTesselation; ++i)
{
// Loop through all the columns of triangles
for(int j = 0; j <= mTesselation; ++j, ++vertIndex)
{
// Perturb each vertex
mVerts[vertIndex].y += mWaveTable[waveIndex] * kWaterForce;

if(++waveIndex == kWaveTableSize)
waveIndex = 0;
}

}

// Keep cycling thorough the mWaveTable
if(++startIndex == kWaveTableSize)
startIndex = 0;
}

// Render the water object as a triangle strip
void CWater::render()
{
bool b = g3D->setAlphaBlendMode(true); // Turn on alpha blending

mTexture.select(); // Select the water texture
g3D->render(mVerts, mVertCount, mIndices, mIndexCount); // Render the tessellated quad

g3D->setAlphaBlendMode(false); // Turn off alpha blending
}

// Creates a tesselated quad of (width x height) dimensions
// Number of triangles in quad is (tessAmt * tessAmt * 2)
bool CWater::createGeometery(float width, float height, int tessAmt)
{
if(width < 0.0f || height < 0.0f || tessAmt <= 0)
return false;

// Set tesselation amount
mTesselation = tessAmt;

// Calculate vertex count.  We know that we have (tesselation * tesselation * 2) triangles
// with 3 vertices per triangle.  So each row of vertices will contain "number of rows + 1"
// vertices and each column of vertices well contain "number of columns + 1" vertices.  This
// makes the total number of vertices equal the following equation
mVertCount = (mTesselation + 1) * (mTesselation + 1);

// Calculate index count.  We know that we'll have (tesselation * tesselation * 2) triangles
// and we have 3 vertices per triangle, thus the below equation
mIndexCount = mTesselation * mTesselation * 6;

// Allocate space for vertices and indices
mVerts = new SVertex[mVertCount];
mIndices = new WORD[mIndexCount];

if(mVerts == NULL || mIndices == NULL)
return false;

// Get the sub divided width and height of each triangle
float subDivideWid = width * (1.0f / (float)mTesselation);
float subDivideHgt = height * (1.0f / (float)mTesselation);

// Calculate the starting (x,y) and ending (x,y) of the quad
float startX = kWaterCen.x - (width / 2.0f);
float startY = kWaterCen.z - (height / 2.0f);
float endX = kWaterCen.x + (width / 2.0f);
float endY = kWaterCen.z + (height / 2.0f);

float uCoord = 0.0f; // Holds the current trinagle's U coordinate
float vCoord = 1.0f; // Holds the current triangle's V coordinate
float uvInc = 1.0f / (float)mTesselation; // Calculate the amount to add to each UV coordinate

int i = 0; // Index for all of for...loops

// Create all the vertices
for(float y = startY; ToleranceLE(y, endY); y += subDivideHgt)
{
for(float x = startX; ToleranceLE(x, endX); x += subDivideWid, ++i)
{
// Set the value for the current vert
mVerts[i].x = x;
mVerts[i].y = kWaterCen.y;
mVerts[i].z = y;
mVerts[i].u = uCoord;
mVerts[i].v = vCoord;
mVerts[i].color = D3DCOLOR_ARGB(128, 255, 255, 255);

uCoord += uvInc;
}

// Set UV for next row of vertices
uCoord = 0.0f;
vCoord -= uvInc;
}

// Make sure we calculatd the vertex count correctly
assert(mVertCount == i);

int indexValue = 0;
int nextRow = 0;

// Look at this sample 2 x 2 quad to understand the pattern used to fill in the indices
/*
6----7----8		Index count =  24
|\ 	 |\   |		Tesselation = 2
| \  | \  |
|  \ |  \ |		Pattern is:	0, 3, 1
|   \|   \|					1, 3, 4
3----4----5					1, 4, 2
|\ 	 |\   |					2, 4, 5
| \  | \  | 				3, 6, 4
|  \ |  \ |					4, 6, 7
|   \|   \|					4, 7, 5,
0----1----2					5, 7, 8
*/

// Create all the indices
for(i = 0; i < mIndexCount; i += 6)
{
mIndices[i] = indexValue;
mIndices[i + 1] = indexValue + (mTesselation + 1);
mIndices[i + 2] = mIndices[i] + 1;

indexValue++;

mIndices[i + 3] = indexValue;
mIndices[i + 4] = indexValue + mTesselation;
mIndices[i + 5] = mIndices[i + 4] + 1;

if(++nextRow == mTesselation)
{
indexValue++;
nextRow = 0;
}
}

return true;
}

// Free the memory
CWater::~CWater()
{
if(mVerts)
{
delete[] mVerts;
mVerts = NULL;
}

if(mIndices)
{
delete[] mIndices;
mIndices = NULL;
}
}


and here is my vb.net conversion

Public Class RealisticWater

Public Function Deg2Rad(ByVal X As Single) As Single
Return X * (PI / 180.0F) 'convert degrees to radian
End Function

Public Function Rad2Deg(ByVal x As Single) As Single
Return x * (180.0F / PI) 'converts radians to degrees
End Function

Public Function F2I(ByVal x As Single) As Integer
Return CType(x + 0.5F, Integer) 'converts  float to int with proper rounding
End Function

Private Const kWaterTesselation As Single = 32 ' number of row columns of teselation in water
Private Const kWaveTableSize As Single = 36 ' number of entries in the wav table
Private Const kWaterForce As Single = 0.1F / 25.0F ' // Controls the "choppiness" of the water (Range is 0.0f - 1.0f)
'// 0.0f == Water is still
'// 1.0f == Water is VERY choppy (so choppy it looks very bad)
Private Const kWaterWid As Single = 30.0F 'width of water along x axis
Private Const kWaterHgt As Single = 30.0F ' height of water along z axis

#Region "Water Vertex Structure"
Public Structure WVertex
Public x, y, z As Single
Public Color As Integer
Public u, v As Single
Public Const Format As VertexFormats = VertexFormats.Position Or VertexFormats.Diffuse Or (1 << VertexFormats.TextureCountShift)
'Public Const Format As VertexFormats = VertexFormats.Diffuse Or VertexFormats.Position Or (1 << VertexFormats.TextureCountShift)
End Structure
#End Region

Private mTexture As Direct3D.Texture
Private mVerts() As WVertex
Private mIndices() As Integer
Private mVertCount As Integer
Private mIndexCount As Integer
Private mTesselation As Single
Private mWaveTable(kWaveTableSize) As Single
Private kWaterCen As Vector3 = New Vector3(0, 0, 0) 'water is always cenetred at 0.0f
Private Dev As Direct3D.Device

Public Function ToleranceLE(ByVal a As Single, ByVal b As Single, Optional ByVal tolerance As Single = 0.001F) As Boolean
Return ((a - tolerance) <= b)
End Function

'// Constructor
Public Sub New(ByVal Device As Direct3D.Device, ByVal TexturePath As String)
Dev = Device
mVerts = Nothing
mIndices = Nothing
mVertCount = 0
mIndexCount = 0
mTesselation = 0
Init(TexturePath)
End Sub

'// Init the water object, returns true on success, false otherwise
Private Sub Init(ByVal TexturePath As String)
'// Fill the wave table
Dim anginc As Single = 360.0F / CType(kWaveTableSize, Single)
Dim angle As Single = 0.0F
Dim I As Integer

'// Fill in the table with values of the sine function
For I = 0 To kWaveTableSize - 1
angle += anginc
Next

CreateGeometery(kWaterWid, kWaterHgt, kWaterTesselation)

End Sub

'// Process the water every frame
Public Sub Process()
Static startIndex As Integer = 0
Dim waveIndex As Integer = startIndex
Dim vertIndex As Integer = 0
Dim i As Integer
Dim j As Integer

'// Loop through all rows of triangles
For i = 0 To mTesselation '- 1
'// Loop through all the columns of triangles
For j = 0 To mTesselation
'// Perturb each vertex
mVerts(vertIndex).y += mWaveTable(waveIndex) * kWaterForce
waveIndex = 0
End If
Next
Next

'// Keep cycling thorough the mWaveTable
startIndex = 0
End If
End Sub

Public Sub Process2()
Static startindex As Integer
Dim waveindex As Integer = startindex
Dim vertindex As Integer
Dim i As Integer
Dim j As Integer
'// Loop through all rows of triangles
For i = 0 To mTesselation
'// Loop through all the columns of triangles
For j = 0 To mTesselation
'// Perturb each vertex
mVerts(vertindex).y += mWaveTable(waveIndex) * kWaterForce
vertindex += 1
waveindex += 1
If waveindex = kWaveTableSize Then
waveindex = 0
End If
Next
Next
'// Keep cycling thorough the mWaveTable
startindex += 1
If startindex = kWaveTableSize Then
startindex = 0
End If
End Sub

'// Render the water object as a triangle strip
Public Sub Render()
Dev.RenderState.AlphaBlendEnable = True
Dev.RenderState.Lighting = False
Dev.VertexFormat = WVertex.Format
Dev.SetTexture(0, mTexture)
Dev.RenderState.CullMode = Cull.None
Dev.DrawIndexedUserPrimitives(PrimitiveType.TriangleStrip, 0, mIndexCount, mIndexCount / 3, mIndices, False, mVerts)
Dev.RenderState.Lighting = True
Dev.RenderState.AlphaBlendEnable = False
End Sub

'// Creates a tesselated quad of (width x height) dimensions
'// Number of triangles in quad is (tessAmt * tessAmt * 2)
Public Function createGeometery(ByVal width As Single, ByVal height As Single, ByVal tessAmt As Single) As Boolean

If width < 0.0F Or height < 0.0F Or tessAmt <= 0 Then Return False

'Set tesselation amount
mTesselation = tessAmt

' Calculate vertex count.  We know that we have (tesselation * tesselation * 2) triangles
' with 3 vertices per triangle.  So each row of vertices will contain "number of rows + 1"
' vertices and each column of vertices well contain "number of columns + 1" vertices.  This
' makes the total number of vertices equal the following equation
mVertCount = (mTesselation + 1) * (mTesselation + 1)

' Calculate index count.  We know that we'll have (tesselation * tesselation * 2) triangles
' and we have 3 vertices per triangle, thus the below equation
mIndexCount = mTesselation * mTesselation * 6

' Allocate space for vertices and indices
ReDim mVerts(mVertCount)
ReDim mIndices(mIndexCount)

'not sure how this could ever be true given the two lines above
'if mVerts = NULL or  mIndices == NULL Then Return False

' Get the sub divided width and height of each triangle
Dim subDivideWid As Single = width * (1 / mTesselation)
Dim subDivideHgt As Single = height * (1 / mTesselation)

Dim startx As Single
Dim starty As Single
Dim endx As Single
Dim endy As Single
Dim ucoord As Single
Dim vcoord As Single
Dim uvinc As Single

' Calculate the starting (x,y) and ending (x,y) of the quad
startx = kWaterCen.X - (width / 2.0F)
starty = kWaterCen.Z - (height / 2.0F)
endx = kWaterCen.X + (width / 2.0F)
endy = kWaterCen.Z + (height / 2.0F)

ucoord = 0.0F ' Holds the current trinagle's U coordinate
vcoord = 1.0F ' Holds the current triangle's V coordinate

uvinc = 1.0F / mTesselation ' Calculate the amount to add to each UV coordinate

Dim i As Integer = 0 ' Index for all of for...loops
Dim y As Single
Dim x As Single

' Create all the vertices
For y = starty To ToleranceLE(y, endy) Step subDivideHgt
For x = startx To ToleranceLE(x, endx) Step subDivideWid

' Set the value for the current vert
mVerts(i).x = x
mVerts(i).y = kWaterCen.Y
mVerts(i).z = y
mVerts(i).u = ucoord
mVerts(i).v = vcoord
mVerts(i).Color = Color.FromArgb(128, 255, 255, 255).ToArgb

ucoord += uvinc

i += 1

Next x

' Set UV for next row of vertices
ucoord = 0.0F
vcoord -= uvinc

Next y

' Make sure we calculatd the vertex count correctly
'If mVertCount <> i Then Throw New Exception("Vertex count does not equal " & i.ToString)

Dim indexValue As Integer = 0
Dim nextRow As Integer = 0

' Look at this sample 2 x 2 quad to understand the pattern used to fill in the indices
'6----7----8      Index count =  24
'|\     |\   |      Tesselation = 2
'| \  | \  |
'|  \ |  \ |      Pattern is:   0, 3, 1
'|   \|   \|               1, 3, 4
'3----4----5               1, 4, 2
'|\     |\   |               2, 4, 5
'| \  | \  |             3, 6, 4
'|  \ |  \ |               4, 6, 7
'|   \|   \|               4, 7, 5,
'0----1----2               5, 7, 8

' Create all the indices
For i = 0 To mIndexCount - 1 Step 6

mIndices(i) = indexValue
mIndices(i + 1) = indexValue + mTesselation + 1
mIndices(i + 2) = mIndices(i) + 1

indexValue += 1

mIndices(i + 3) = indexValue
mIndices(i + 4) = indexValue + mTesselation
mIndices(i + 5) = mIndices(i + 4) + 1

nextRow += 1

If nextRow = mTesselation Then
indexValue += 1
nextRow = 0
End If

Next i

Return True
End Function

Public Sub Dispose()
Erase mVerts
Erase mIndices
End Sub

End Class


plase any help will be very helpfull ive been trying for ages to get this working and i cant seem to see anything wrong. sorry i though i used the code tags already, i know im really sorry about all the code but the prob is i have gone trough it loadz of times and icant find the prob. the prob is it dosent render properly, but from what i can see its the vertice generation that causes the prob, i just for the life of me figure it out. and im not convberting opengl to MDX, its c++ MDX to vb.net MDX, which i have done loadz of times and should be almost identical, but i cant seem to find the problem. [Edited by - tuvd on May 17, 2006 6:25:36 AM]

##### Share on other sites

Also, alot of people that answer questions on these forums don't really have time to go through a whole bunch of code like that. A simple question with regards to conversion might be something like how do I convert ID3DXSprite to MDX or what is the MDX equavalent.

Stay cool.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628337
• Total Posts
2982156
• ### Similar Content

• Hi, New here.
I need some help. My fiance and I like to play this mobile game online that goes by real time. Her and I are always working but when we have free time we like to play this game. We don't always got time throughout the day to Queue Buildings, troops, Upgrades....etc....
I was told to look into DLL Injection and OpenGL/DirectX Hooking. Is this true? Is this what I need to learn?
How do I read the Android files, or modify the files, or get the in-game tags/variables for the game I want?
Any assistance on this would be most appreciated. I been everywhere and seems no one knows or is to lazy to help me out. It would be nice to have assistance for once. I don't know what I need to learn.
So links of topics I need to learn within the comment section would be SOOOOO.....Helpful. Anything to just get me started.
Thanks,
Dejay Hextrix
• By mellinoe
Hi all,
First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
• By aejt
I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
I have these classes:
For GPU resources:
Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).
And my plan is to define everything into these XML documents to abstract away files:
Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
Factory classes for resources:
For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
Factory classes for assets:
Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).

Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
Thanks!
• By nedondev
I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
Thanks.

• So I've recently started learning some GLSL and now I'm toying with a POM shader. I'm trying to optimize it and notice that it starts having issues at high texture sizes, especially with self-shadowing.
Now I know POM is expensive either way, but would pulling the heightmap out of the normalmap alpha channel and in it's own 8bit texture make doing all those dozens of texture fetches more cheap? Or is everything in the cache aligned to 32bit anyway? I haven't implemented texture compression yet, I think that would help? But regardless, should there be a performance boost from decoupling the heightmap? I could also keep it in a lower resolution than the normalmap if that would improve performance.
Any help is much appreciated, please keep in mind I'm somewhat of a newbie. Thanks!

• 9
• 24
• 9
• 9
• 13