• 14
• 12
• 9
• 10
• 13
• ### Similar Content

• By elect
Hi,
ok, so, we are having problems with our current mirror reflection implementation.
At the moment we are doing it very simple, so for the i-th frame, we calculate the reflection vectors given the viewPoint and some predefined points on the mirror surface (position and normal).
Then, using the least squared algorithm, we find the point that has the minimum distance from all these reflections vectors. This is going to be our virtual viewPoint (with the right orientation).
After that, we render offscreen to a texture by setting the OpenGL camera on the virtual viewPoint.
And finally we use the rendered texture on the mirror surface.
So far this has always been fine, but now we are having some more strong constraints on accuracy.
What are our best options given that:
- we have a dynamic scene, the mirror and parts of the scene can change continuously from frame to frame
- we have about 3k points (with normals) per mirror, calculated offline using some cad program (such as Catia)
- all the mirror are always perfectly spherical (with different radius vertically and horizontally) and they are always convex
- a scene can have up to 10 mirror
- it should be fast enough also for vr (Htc Vive) on fastest gpus (only desktops)

Looking around, some papers talk about calculating some caustic surface derivation offline, but I don't know if this suits my case
Also, another paper, used some acceleration structures to detect the intersection between the reflection vectors and the scene, and then adjust the corresponding texture coordinate. This looks the most accurate but also very heavy from a computational point of view.

Other than that, I couldn't find anything updated/exhaustive around, can you help me?

• Hello all,
I am currently working on a game engine for use with my game development that I would like to be as flexible as possible.  As such the exact requirements for how things should work can't be nailed down to a specific implementation and I am looking for, at least now, a default good average case scenario design.
Here is what I have implemented:
Deferred rendering using OpenGL Arbitrary number of lights and shadow mapping Each rendered object, as defined by a set of geometry, textures, animation data, and a model matrix is rendered with its own draw call Skeletal animations implemented on the GPU.   Model matrix transformation implemented on the GPU Frustum and octree culling for optimization Here are my questions and concerns:
Doing the skeletal animation on the GPU, currently, requires doing the skinning for each object multiple times per frame: once for the initial geometry rendering and once for the shadow map rendering for each light for which it is not culled.  This seems very inefficient.  Is there a way to do skeletal animation on the GPU only once across these render calls? Without doing the model matrix transformation on the CPU, I fail to see how I can easily batch objects with the same textures and shaders in a single draw call without passing a ton of matrix data to the GPU (an array of model matrices then an index for each vertex into that array for transformation purposes?) If I do the matrix transformations on the CPU, It seems I can't really do the skinning on the GPU as the pre-transformed vertexes will wreck havoc with the calculations, so this seems not viable unless I am missing something Overall it seems like simplest solution is to just do all of the vertex manipulation on the CPU and pass the pre-transformed data to the GPU, using vertex shaders that do basically nothing.  This doesn't seem the most efficient use of the graphics hardware, but could potentially reduce the number of draw calls needed.

Really, I am looking for some advice on how to proceed with this, how something like this is typically handled.  Are the multiple draw calls and skinning calculations not a huge deal?  I would LIKE to save as much of the CPU's time per frame so it can be tasked with other things, as to keep CPU resources open to the implementation of the engine.  However, that becomes a moot point if the GPU becomes a bottleneck.

• Hello!
I would like to introduce Diligent Engine, a project that I've been recently working on. Diligent Engine is a light-weight cross-platform abstraction layer between the application and the platform-specific graphics API. Its main goal is to take advantages of the next-generation APIs such as Direct3D12 and Vulkan, but at the same time provide support for older platforms via Direct3D11, OpenGL and OpenGLES. Diligent Engine exposes common front-end for all supported platforms and provides interoperability with underlying native API. Shader source code converter allows shaders authored in HLSL to be translated to GLSL and used on all platforms. Diligent Engine supports integration with Unity and is designed to be used as a graphics subsystem in a standalone game engine, Unity native plugin or any other 3D application. It is distributed under Apache 2.0 license and is free to use. Full source code is available for download on GitHub.
Features:
True cross-platform Exact same client code for all supported platforms and rendering backends No #if defined(_WIN32) ... #elif defined(LINUX) ... #elif defined(ANDROID) ... No #if defined(D3D11) ... #elif defined(D3D12) ... #elif defined(OPENGL) ... Exact same HLSL shaders run on all platforms and all backends Modular design Components are clearly separated logically and physically and can be used as needed Only take what you need for your project (do not want to keep samples and tutorials in your codebase? Simply remove Samples submodule. Only need core functionality? Use only Core submodule) No 15000 lines-of-code files Clear object-based interface No global states Key graphics features: Automatic shader resource binding designed to leverage the next-generation rendering APIs Multithreaded command buffer generation 50,000 draw calls at 300 fps with D3D12 backend Descriptor, memory and resource state management Modern c++ features to make code fast and reliable The following platforms and low-level APIs are currently supported:
Windows Desktop: Direct3D11, Direct3D12, OpenGL Universal Windows: Direct3D11, Direct3D12 Linux: OpenGL Android: OpenGLES MacOS: OpenGL iOS: OpenGLES API Basics
Initialization
The engine can perform initialization of the API or attach to already existing D3D11/D3D12 device or OpenGL/GLES context. For instance, the following code shows how the engine can be initialized in D3D12 mode:
#include "RenderDeviceFactoryD3D12.h" using namespace Diligent; // ...  GetEngineFactoryD3D12Type GetEngineFactoryD3D12 = nullptr; // Load the dll and import GetEngineFactoryD3D12() function LoadGraphicsEngineD3D12(GetEngineFactoryD3D12); auto *pFactoryD3D11 = GetEngineFactoryD3D12(); EngineD3D12Attribs EngD3D12Attribs; EngD3D12Attribs.CPUDescriptorHeapAllocationSize[0] = 1024; EngD3D12Attribs.CPUDescriptorHeapAllocationSize[1] = 32; EngD3D12Attribs.CPUDescriptorHeapAllocationSize[2] = 16; EngD3D12Attribs.CPUDescriptorHeapAllocationSize[3] = 16; EngD3D12Attribs.NumCommandsToFlushCmdList = 64; RefCntAutoPtr<IRenderDevice> pRenderDevice; RefCntAutoPtr<IDeviceContext> pImmediateContext; SwapChainDesc SwapChainDesc; RefCntAutoPtr<ISwapChain> pSwapChain; pFactoryD3D11->CreateDeviceAndContextsD3D12( EngD3D12Attribs, &pRenderDevice, &pImmediateContext, 0 ); pFactoryD3D11->CreateSwapChainD3D12( pRenderDevice, pImmediateContext, SwapChainDesc, hWnd, &pSwapChain ); Creating Resources
Device resources are created by the render device. The two main resource types are buffers, which represent linear memory, and textures, which use memory layouts optimized for fast filtering. To create a buffer, you need to populate BufferDesc structure and call IRenderDevice::CreateBuffer(). The following code creates a uniform (constant) buffer:
BufferDesc BuffDesc; BufferDesc.Name = "Uniform buffer"; BuffDesc.BindFlags = BIND_UNIFORM_BUFFER; BuffDesc.Usage = USAGE_DYNAMIC; BuffDesc.uiSizeInBytes = sizeof(ShaderConstants); BuffDesc.CPUAccessFlags = CPU_ACCESS_WRITE; m_pDevice->CreateBuffer( BuffDesc, BufferData(), &m_pConstantBuffer ); Similar, to create a texture, populate TextureDesc structure and call IRenderDevice::CreateTexture() as in the following example:
TextureDesc TexDesc; TexDesc.Name = "My texture 2D"; TexDesc.Type = TEXTURE_TYPE_2D; TexDesc.Width = 1024; TexDesc.Height = 1024; TexDesc.Format = TEX_FORMAT_RGBA8_UNORM; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_SHADER_RESOURCE | BIND_RENDER_TARGET | BIND_UNORDERED_ACCESS; TexDesc.Name = "Sample 2D Texture"; m_pRenderDevice->CreateTexture( TexDesc, TextureData(), &m_pTestTex ); Initializing Pipeline State
Diligent Engine follows Direct3D12 style to configure the graphics/compute pipeline. One big Pipelines State Object (PSO) encompasses all required states (all shader stages, input layout description, depth stencil, rasterizer and blend state descriptions etc.)
To create a shader, populate ShaderCreationAttribs structure. An important member is ShaderCreationAttribs::SourceLanguage. The following are valid values for this member:
SHADER_SOURCE_LANGUAGE_DEFAULT  - The shader source format matches the underlying graphics API: HLSL for D3D11 or D3D12 mode, and GLSL for OpenGL and OpenGLES modes. SHADER_SOURCE_LANGUAGE_HLSL  - The shader source is in HLSL. For OpenGL and OpenGLES modes, the source code will be converted to GLSL. See shader converter for details. SHADER_SOURCE_LANGUAGE_GLSL  - The shader source is in GLSL. There is currently no GLSL to HLSL converter. To allow grouping of resources based on the frequency of expected change, Diligent Engine introduces classification of shader variables:
Static variables (SHADER_VARIABLE_TYPE_STATIC) are variables that are expected to be set only once. They may not be changed once a resource is bound to the variable. Such variables are intended to hold global constants such as camera attributes or global light attributes constant buffers. Mutable variables (SHADER_VARIABLE_TYPE_MUTABLE) define resources that are expected to change on a per-material frequency. Examples may include diffuse textures, normal maps etc. Dynamic variables (SHADER_VARIABLE_TYPE_DYNAMIC) are expected to change frequently and randomly. This post describes the resource binding model in Diligent Engine.
The following is an example of shader initialization:
To create a pipeline state object, define instance of PipelineStateDesc structure. The structure defines the pipeline specifics such as if the pipeline is a compute pipeline, number and format of render targets as well as depth-stencil format:
// This is a graphics pipeline PSODesc.IsComputePipeline = false; PSODesc.GraphicsPipeline.NumRenderTargets = 1; PSODesc.GraphicsPipeline.RTVFormats[0] = TEX_FORMAT_RGBA8_UNORM_SRGB; PSODesc.GraphicsPipeline.DSVFormat = TEX_FORMAT_D32_FLOAT; The structure also defines depth-stencil, rasterizer, blend state, input layout and other parameters. For instance, rasterizer state can be defined as in the code snippet below:
// Init rasterizer state RasterizerStateDesc &RasterizerDesc = PSODesc.GraphicsPipeline.RasterizerDesc; RasterizerDesc.FillMode = FILL_MODE_SOLID; RasterizerDesc.CullMode = CULL_MODE_NONE; RasterizerDesc.FrontCounterClockwise = True; RasterizerDesc.ScissorEnable = True; //RSDesc.MultisampleEnable = false; // do not allow msaa (fonts would be degraded) RasterizerDesc.AntialiasedLineEnable = False; When all fields are populated, call IRenderDevice::CreatePipelineState() to create the PSO:
Shader resource binding in Diligent Engine is based on grouping variables in 3 different groups (static, mutable and dynamic). Static variables are variables that are expected to be set only once. They may not be changed once a resource is bound to the variable. Such variables are intended to hold global constants such as camera attributes or global light attributes constant buffers. They are bound directly to the shader object:

m_pPSO->CreateShaderResourceBinding(&m_pSRB); Dynamic and mutable resources are then bound through SRB object:
m_pSRB->GetVariable(SHADER_TYPE_VERTEX, "tex2DDiffuse")->Set(pDiffuseTexSRV); m_pSRB->GetVariable(SHADER_TYPE_VERTEX, "cbRandomAttribs")->Set(pRandomAttrsCB); The difference between mutable and dynamic resources is that mutable ones can only be set once for every instance of a shader resource binding. Dynamic resources can be set multiple times. It is important to properly set the variable type as this may affect performance. Static variables are generally most efficient, followed by mutable. Dynamic variables are most expensive from performance point of view. This post explains shader resource binding in more details.
Setting the Pipeline State and Invoking Draw Command
Before any draw command can be invoked, all required vertex and index buffers as well as the pipeline state should be bound to the device context:
// Clear render target const float zero[4] = {0, 0, 0, 0}; m_pContext->ClearRenderTarget(nullptr, zero); // Set vertex and index buffers IBuffer *buffer[] = {m_pVertexBuffer}; Uint32 offsets[] = {0}; Uint32 strides[] = {sizeof(MyVertex)}; m_pContext->SetVertexBuffers(0, 1, buffer, strides, offsets, SET_VERTEX_BUFFERS_FLAG_RESET); m_pContext->SetIndexBuffer(m_pIndexBuffer, 0); m_pContext->SetPipelineState(m_pPSO); Also, all shader resources must be committed to the device context:
m_pContext->CommitShaderResources(m_pSRB, COMMIT_SHADER_RESOURCES_FLAG_TRANSITION_RESOURCES); When all required states and resources are bound, IDeviceContext::Draw() can be used to execute draw command or IDeviceContext::DispatchCompute() can be used to execute compute command. Note that for a draw command, graphics pipeline must be bound, and for dispatch command, compute pipeline must be bound. Draw() takes DrawAttribs structure as an argument. The structure members define all attributes required to perform the command (primitive topology, number of vertices or indices, if draw call is indexed or not, if draw call is instanced or not, if draw call is indirect or not, etc.). For example:
DrawAttribs attrs; attrs.IsIndexed = true; attrs.IndexType = VT_UINT16; attrs.NumIndices = 36; attrs.Topology = PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; pContext->Draw(attrs); Tutorials and Samples
The GitHub repository contains a number of tutorials and sample applications that demonstrate the API usage.

AntTweakBar sample demonstrates how to use AntTweakBar library to create simple user interface.

Atmospheric scattering sample is a more advanced example. It demonstrates how Diligent Engine can be used to implement various rendering tasks: loading textures from files, using complex shaders, rendering to textures, using compute shaders and unordered access views, etc.

The repository includes Asteroids performance benchmark based on this demo developed by Intel. It renders 50,000 unique textured asteroids and lets compare performance of D3D11 and D3D12 implementations. Every asteroid is a combination of one of 1000 unique meshes and one of 10 unique textures.

Integration with Unity
Diligent Engine supports integration with Unity through Unity low-level native plugin interface. The engine relies on Native API Interoperability to attach to the graphics API initialized by Unity. After Diligent Engine device and context are created, they can be used us usual to create resources and issue rendering commands. GhostCubePlugin shows an example how Diligent Engine can be used to render a ghost cube only visible as a reflection in a mirror.

• By Yxjmir
I'm trying to load data from a .gltf file into a struct to use to load a .bin file. I don't think there is a problem with how the vertex positions are loaded, but with the indices. This is what I get when drawing with glDrawArrays(GL_LINES, ...):

Also, using glDrawElements gives a similar result. Since it looks like its drawing triangles using the wrong vertices for each face, I'm assuming it needs an index buffer/element buffer. (I'm not sure why there is a line going through part of it, it doesn't look like it belongs to a side, re-exported it without texture coordinates checked, and its not there)
I'm using jsoncpp to load the GLTF file, its format is based on JSON. Here is the gltf struct I'm using, and how I parse the file:
glBindVertexArray(g_pGame->m_VAO);
glDrawElements(GL_LINES, g_pGame->m_indices.size(), GL_UNSIGNED_BYTE, (void*)0); // Only shows with GL_UNSIGNED_BYTE
glDrawArrays(GL_LINES, 0, g_pGame->m_vertexCount);
So, I'm asking what type should I use for the indices? it doesn't seem to be unsigned short, which is what I selected with the Khronos Group Exporter for blender. Also, am I reading part or all of the .bin file wrong?
Test.gltf
Test.bin

• That means how do I use base DirectX or OpenGL api's to make a physics based destruction simulation?
Will it be just smart rendering or something else is required?

# OpenGL OpenGL png transparency

This topic is 1407 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi all,

This is my first post here (so go easy on me . I have spent the better part of a week attempting to properly load a png image,bind it to a texture, set it to an object and have the transparent layer stay transparent while rendering the rest of the sprite(like a decal would appear, or a billboarded sprite). I've searched this forum rather thoroughly, but every solution I've found has seemed not to work for me. Any help would be genuinely and greatly appreciated As I'm uncertain where I'm going wrong, I'm uncertain what information you may need, but I'll try to include the essentials, an image of the semi-transparent sprite is included.

To the best of my knowledge, the png file(created in gimp) does contain the alpha layer and was saved correctly.

Am I failing to set the OpenGL Alpha layer correctly, or perhaps calling the BlendFunc in the wrong location? Perhaps I'm misunderstanding the BlendFunc. (I'm getting my information here:https://www.opengl.org/archives/resources/faq/technical/transparency.htm).

Things:

I'm using c++, codeblocks, Ubuntu 14.04, glfw3,  freeImage (and a little loader found on this forum for png files, included in the code below), nvidia 560 ti,

When i set :

glEnable(GL_BLEND);

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

nothing is rendered at all. Though, if I set :

glEnable(GL_BLEND);

glBlendFunc(GL_ONE, GL_ONE);

things actually appear to display correctly, however, while the transparent layer is completely transparent, the rest of the sprite appears semi-transparent as well.

I've attempted to display the sprite using GL_DECAL, as well as trying to set the alpha_state and have ended up with similar results. Either nothing is displayed at all, the transparent layer is displayed as completely black, or this state, where it is semi-transparent. I've tried calling the glEnable and glBlendFunc in various places. The one thing I can't seem to successfully code is having the sprite display without the background and not be semi-transparent itself.

I should note as well that if I change the Fragment shader color value to vec4 (it's currently set to a vec3) and include an alpha color (set to anything between 0.1 and 1) the glBLendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA) will display the sprite, but (perhaps predictably) the entire sprite is semi-transparent, though the transparent layer of the sprite appears to be black(just slightly transparent) and, thus, not set correctly.

Here is (what i think would be) the relevant code:

Main:

#include "Main.h"

int main()
{
glEnable(GL_TEXTURE_2D);

if(!glfwInit())
{
fprintf( stderr, "Failed to initialize glfw\n");
return -1;
}
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

window = glfwCreateWindow(1920, 1080, "OpenGL is an ******", NULL, NULL);

if(window == NULL)
{
fprintf(stderr, "Failed to open GLFW window.");
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);

glewExperimental = true;
if(glewInit() != GLEW_OK)
{
fprintf(stderr, "Failled to initialize GLEW\n");
return -1;
}

glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);

glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_CULL_FACE);

Object Obj2("background.png","plane5.obj");
Object Obj1("tree.png","tree3.obj");

do
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(Obj1.programID);

Obj2.Render();
Obj1.Render();

glfwSwapBuffers(window);
glfwPollEvents();
}
while(glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
glfwWindowShouldClose(window) == 0);

Obj1.CleanUp();
Obj2.CleanUp();

glfwTerminate();

return 0;
}



Object:

#include "Object.h"

Object::Object(const char* textureHere, const char* objHere) {

VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);

MatrixID = glGetUniformLocation(programID, "MVP");
ViewMatrixID = glGetUniformLocation(programID, "V");
ModelMatrixID = glGetUniformLocation(programID, "M");
PlaneMatrixID = glGetUniformLocation(programID, "P");

res = loadOBJ(objHere, vertices, uvs, normals);

glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);

glGenBuffers(1, &uvbuffer);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(glm::vec2), &uvs[0], GL_STATIC_DRAW);

glGenBuffers(1, &normalbuffer);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW);

glUseProgram(programID);
LightID = glGetUniformLocation(programID, "LightPosition_worldspace");
}

Object::Object(const Object& orig) {
}

Object::~Object() {
}

void Object::Render()
{
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);

computeMatricesFromInputs();
glm::mat4 ProjectionMatrix = getProjectionMatrix();
glm::mat4 ViewMatrix = getViewMatrix();
glm::mat4 ModelMatrix = glm::mat4(1.0);
glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix;

glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix[0][0]);
glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]);

glm::vec3 lightPos = glm::vec3(4,4,4);
glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z);

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, Texture);

glUniform1i(TextureID, 0);

glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
0,              //attribute
3,              //size
GL_FLOAT,       //type
GL_FALSE,       //normalized?
0,              //stride...whateverthehell that is
(void*)0        //array buffer offset
);

// 2nd attribute buffer : uvs
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glVertexAttribPointer(
1,                                // attribute.
2,                                // size : u + v = 2
GL_FLOAT,                         // type
GL_FALSE,                         // normalized?
0,                                // stride
(void*)0                          // array buffer offset
);

//3rd attribute normals
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glVertexAttribPointer(
2,              //attribute
3,              //size
GL_FLOAT,        //type)
GL_FALSE,       //normalized?
0,              //stride
(void*)0        //array buffer offset

);
glDrawArrays(GL_TRIANGLES, 0, vertices.size() );

glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
}

void Object::CleanUp()
{
glDeleteBuffers(1, &vertexbuffer);
glDeleteBuffers(1, &uvbuffer);
glDeleteBuffers(2, &normalbuffer);
glDeleteProgram(programID);
glDeleteTextures(1, &TextureID);
glDeleteVertexArrays(1, &VertexArrayID);
}

{
FREE_IMAGE_FORMAT formato =
FreeImage_GetFileType(imageName,0);

FIBITMAP* temp = imagen;

imagen = FreeImage_ConvertTo32Bits(imagen);

int w = FreeImage_GetWidth(imagen);
int h = FreeImage_GetHeight(imagen);

GLubyte* textura = new GLubyte[4*w*h];
char* pixels = (char*)FreeImage_GetBits(imagen);

for(int j= 0; j<w*h; j++){
textura[j*4+0]= pixels[j*4+2];
textura[j*4+1]= pixels[j*4+1];
textura[j*4+2]= pixels[j*4+0];
textura[j*4+3]= pixels[j*4+3];
}
GLuint TextureID;
glGenTextures(1, &TextureID);
glBindTexture(GL_TEXTURE_2D, TextureID);
if(FreeImage_GetBPP(imagen) == 24)
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA, w, h, 0,
GL_RGB,GL_UNSIGNED_BYTE,(GLvoid*)textura );
else if(FreeImage_GetBPP(imagen) == 32)
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA, w, h, 0,
GL_RGBA,GL_UNSIGNED_BYTE,(GLvoid*)textura );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

return TextureID;
}



Let me know if you need any more relevant information. And, my apologies for posting yet another png transparency thread. I'm out of ideas, so create yet another thread on this out of simple desperation. The solution on almost every thread appears to be to simply set glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);, which results in nothing being displayed at all.

Thank you in advance for any assistance,

Edited by Misantes

##### Share on other sites

FREE_IMAGE_FORMAT formato =
FreeImage_GetFileType(imageName,0);

FIBITMAP* temp = imagen;

imagen = FreeImage_ConvertTo32Bits(imagen);

If your .png is authored and is loaded correctly, then it should already be a 32 bit image. I wonder if it's only 24-bit and FreeImage_ConvertTo32Bits is adding an empty alpha channel for you.

Also, could you post your fragment shader, please? The line "I should note as well that if I change the Fragment shader color value to vec4 (it's currently set to a vec3) and include an alpha color (set to anything between 0.1 and 1)" sounds a bit wrong, you probably should be dealing with vec4s when you're manipulating rgba colours.

I suppose that to narrow down whether it's a image loading or a rendering problem, you could experiment by modifying the "textura[j*4+3]= pixels[j*4+3];" line to "textura[j*4+3]= 128;" and see if that gives you a semi-transparent image. If so, then you know it's your image loading, otherwise it's your rendeiring. (Actually maybe it's textura[j*4+0] which represents alpha, I can never remember which order these things are supposed to be)

##### Share on other sites

Hey, thank you so much for the response.

#version 330 core

// Interpolated values from the vertex shaders
in vec2 UV;
in vec3 Position_worldspace;
in vec3 Normal_cameraspace;
in vec3 EyeDirection_cameraspace;
in vec3 LightDirection_cameraspace;

// Ouput data
out vec3 color;

// Values that stay constant for the whole mesh.
uniform sampler2D myTextureSampler;
uniform mat4 MV;
uniform vec3 LightPosition_worldspace;

void main(){

// Light emission properties
// You probably want to put them as uniforms
vec3 LightColor = vec3(1,1,1);
float LightPower = 50.0f;

// Material properties
vec3 MaterialDiffuseColor = texture2D( myTextureSampler, UV ).rgb;
vec3 MaterialAmbientColor = vec3(0.5,0.5,0.5) * MaterialDiffuseColor;
vec3 MaterialSpecularColor = vec3(0.3,0.3,0.3);

// Distance to the light
float distance = length( LightPosition_worldspace - Position_worldspace );

// Normal of the computed fragment, in camera space
vec3 n = normalize( Normal_cameraspace );
// Direction of the light (from the fragment to the light)
vec3 l = normalize( LightDirection_cameraspace );
// Cosine of the angle between the normal and the light direction,
// clamped above 0
//  - light is at the vertical of the triangle -> 1
//  - light is perpendicular to the triangle -> 0
//  - light is behind the triangle -> 0
float cosTheta = clamp( dot( n,l ), 0,1 );

// Eye vector (towards the camera)
vec3 E = normalize(EyeDirection_cameraspace);
// Direction in which the triangle reflects the light
vec3 R = reflect(-l,n);
// Cosine of the angle between the Eye vector and the Reflect vector,
// clamped to 0
//  - Looking into the reflection -> 1
//  - Looking elsewhere -> < 1
float cosAlpha = clamp( dot( E,R ), 0,1 );

color.rgb =
// Ambient : simulates indirect lighting
MaterialAmbientColor +
// Diffuse : "color" of the object
MaterialDiffuseColor * LightColor * LightPower * cosTheta / (distance*distance) +
// Specular : reflective highlight, like a mirror
MaterialSpecularColor * LightColor * LightPower * pow(cosAlpha,5) / (distance*distance);
//color.a = 0.3;
}


As I'm new to OpenGL and haven't gotten around to writing my own shaders yet, I used the shader from the tutorials on http://www.opengl-tutorial.org/, so it's entirely possible it's not suitable for what I'm trying to do as its just a simple example shader. I've left in the commented out line //color.a = 0.3; My previous comment was about trying to change  "out vec3 color;" to "out vec4 color" and adding the "color.a = 0.3" at the bottom. Again, when I do that, it sill appears semi-transparent, but the transparent layer appears as a semi-transparent black instead of being completely transparent (which kind of makes sense, i think, as I'm then having the shader make everything it renders semi-transparent..If I'm following how shaders work at all).

If I change textura[j*4+3]= pixels[j*4+3];" line to "textura[j*4+3]= 128; I do still end up with a semi-transparent image(it is the pixels[j*4+3] and not pixels[j*4+3] as that line appears to be the red value).

As I mentioned, the LoadImage function I got on this forum, but it seemed to work so I ran with it. It looks as though the convert function is just there to make sure the image ends up as 32 bits. However, If I comment out that line (as well as the one above and below), the image still appears semi-transparent.

FREE_IMAGE_FORMAT formato =
FreeImage_GetFileType(imageName,0);

//FIBITMAP* temp = imagen;

//imagen = FreeImage_ConvertTo32Bits(imagen);
//FreeImage_Unload(temp); 

I also tried commenting out

/*if(FreeImage_GetBPP(imagen) == 24)
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA, w, h, 0,
GL_RGB,GL_UNSIGNED_BYTE,(GLvoid*)textura );
else if(FreeImage_GetBPP(imagen) == 32)*/


and it appears to have no effect either. I also tried changing the above code(still with the "FreeImage_ConvertTo32Bits" function commented out)  to:

if(FreeImage_GetBPP(imagen) == 24)
{
std::cout<<"This is 24 bits, dummy."<<std::endl;
}

else if(FreeImage_GetBPP(imagen) == 32)
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA, w, h, 0,
GL_RGBA,GL_UNSIGNED_BYTE,(GLvoid*)textura );


and it appears to be loading the image as 32 bits when it runs (as the image still appears semi-transparent, and the console doesn't return the error).

I tried all of those changes with glBlendFunc set to both(GL_ONE, GL_ONE) and glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA).

Do you still think it may be the LoadImage Function, or does the shader maybe look problematic?

Thanks again for your help, I truly appreciate it! This has been one of those bang-my-head-against-the-desk problems for a week now . I'm trying to take a game I've made in 2D to a 3D environment with billboarding to give it a bit more depth. So, this is pretty much my first foray into OpenGL, other than some tinkering with it here and there. So, I'm not completely new, but new enough that i'm going to look stupid when we figure this out

Also, for reference, here is what it looks like with the shader changed to vec4 and color.a set to 0.3 and glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA).

and with color set to "color.a = 1.0;

When it is set to 1.0 it seems to be more of the typical problem where  the PNG is just displaying the transparency as black.

Edited by Misantes

##### Share on other sites

Hello Misantes, It seems to me that the shader you have there doesn't account for any change in alpha from the texture.
when you converted your vec3 color to a vec4 and inserted 0.3 into the alpha channel you essentially made every pixel be the same amount of transparency regardless of the texture.

To get this working and using your textures transparency you will need to change it to a vec4 but instead use the alpha channel from your texture sampler.

The easiest fix I can see is to just replace the line:

vec3 MaterialDiffuseColor = texture2D( myTextureSampler, UV ).rgb;

with

vec4 MaterialDiffuseColor = texture2D( myTextureSampler, UV );

you will then need to put .rgb on the end of anywhere you have you MaterialDiffuseColor.

Then replace your color.a = 0.3; with color.a = MaterialDiffuseColor.a;

I hope that makes sense, and if you would like for me to explain further why this needs to be done just ask :)

##### Share on other sites
#version 330 core

// Interpolated values from the vertex shaders
in vec2 UV;
in vec3 Position_worldspace;
in vec3 Normal_cameraspace;
in vec3 EyeDirection_cameraspace;
in vec3 LightDirection_cameraspace;

// Ouput data
out vec4 color;

// Values that stay constant for the whole mesh.
uniform sampler2D myTextureSampler;
uniform mat4 MV;
uniform vec3 LightPosition_worldspace;

void main(){

// Light emission properties
// You probably want to put them as uniforms
vec3 LightColor = vec3(1,1,1);
float LightPower = 50.0f;

// Material properties
vec4 MaterialDiffuseColor = texture2D( myTextureSampler, UV );
vec3 MaterialAmbientColor = vec3(0.5,0.5,0.5) * MaterialDiffuseColor;
vec3 MaterialSpecularColor = vec3(0.3,0.3,0.3);

// Distance to the light
float distance = length( LightPosition_worldspace - Position_worldspace );

// Normal of the computed fragment, in camera space
vec3 n = normalize( Normal_cameraspace );
// Direction of the light (from the fragment to the light)
vec3 l = normalize( LightDirection_cameraspace );
// Cosine of the angle between the normal and the light direction,
// clamped above 0
//  - light is at the vertical of the triangle -> 1
//  - light is perpendicular to the triangle -> 0
//  - light is behind the triangle -> 0
float cosTheta = clamp( dot( n,l ), 0,1 );

// Eye vector (towards the camera)
vec3 E = normalize(EyeDirection_cameraspace);
// Direction in which the triangle reflects the light
vec3 R = reflect(-l,n);
// Cosine of the angle between the Eye vector and the Reflect vector,
// clamped to 0
//  - Looking into the reflection -> 1
//  - Looking elsewhere -> < 1
float cosAlpha = clamp( dot( E,R ), 0,1 );

color.rgb =
// Ambient : simulates indirect lighting
MaterialAmbientColor +
// Diffuse : "color" of the object
MaterialDiffuseColor.rgb * LightColor * LightPower * cosTheta / (distance*distance) +
// Specular : reflective highlight, like a mirror
MaterialSpecularColor * LightColor * LightPower * pow(cosAlpha,5) / (distance*distance);
color.a = MaterialDiffuseColor.a;
} 

Hm, That results in an error:

0(28) : error C7011: implicit cast from "vec4" to "vec3"

And, I would welcome any explanation, but don't feel obligated as my knowledge of shaders is pretty limited still.
Also, thanks for the help

Shader now looks like the above.

Edit* nevermind, i fixed the error (it's 330am for me >,<), it now runs, but it is still showing up as semi-transparent.

Edit#2*
I changed the glBlendFunc to glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) and it now shows up perfectly!
Thanks so much to both you and C0lumbo! You've both been a giant help

See, I knew I'd look stupid Time to go read up on shaders  I'd still love a quick explanation if you have a moment though. I feel like I almost understand, but the concept is eluding me a little (a lot). I'm happy to do my own homework, usually, but sometimes I quick explanation can set me in the right direction to understanding it.

Cheers, and thanks again to both of you.

(and to anyone reading this later, no laughing at the art, It's just placeholder an artist-friend comes through with the finished sprites. I can't draw :))
Edited by Misantes

##### Share on other sites

No problem, it would have taken you a lot of work to figure that out considering you don't know much about shaders.

When using the texture2D function it samples a value from the texture that you have assigned to the shader. This combined with other values coming from light sources and the other material properties give you your final output colour. Without having an alpha channel it must force the alpha channel to be 1.0f making them opaque;

Shaders are great to play with and you can make some pretty cool effects. I would suggest checking out www.open.gl for some pretty decent tutorials into the basics of openGL and shaders.

##### Share on other sites

Just an FYI, your are using texture2D which has been deprecated since GLSL 1.30. You should just use texture instead, which overloads based on the sampler type.

##### Share on other sites

No problem, it would have taken you a lot of work to figure that out considering you don't know much about shaders.

When using the texture2D function it samples a value from the texture that you have assigned to the shader. This combined with other values coming from light sources and the other material properties give you your final output colour. Without having an alpha channel it must force the alpha channel to be 1.0f making them opaque;

Shaders are great to play with and you can make some pretty cool effects. I would suggest checking out www.open.gl for some pretty decent tutorials into the basics of openGL and shaders.

Yes, I have a feeling I would have been stuck on that for a very long time(well, longer than it already has).

And, thank you for the tutorial link.

Just an FYI, your are using texture2D which has been deprecated since GLSL 1.30. You should just use texture instead, which overloads based on the sampler type.

And thank you too. I seem to have had the damndest time finding any books/tutorials that aren't out of date. I'll check out the tutorial links above, and thanks again to everyone.