C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – SDL_TTF绘制垃圾大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
前几天我问了一个关于使用SDL渲染TTF字体的问题,并指向SDL_TTFL我尝试过使用SDL_TTF库,但是我得到的只是屏幕上的垃圾

我已经包含了我的着色器,这对于这个程序非常简单,还有我用来将文本加载到表面并将其绑定到纹理的剪切.我根本不想在这里做任何疯狂的事情.你能看到我做错了什么吗?我真的不太确定如何调试着色器等.

片段着色器(frag.glsl):

#version 330
in vec2 texCoord;
in vec4 fragColor;

out vec3 finalColor;

uniform sampler2D myTextureSampler;
void main() {
    finalColor = texture( myTextureSampler,texCoord ).rgb;
}

顶点着色器(vert.glsl)

#version 330

in vec3 vert;
in vec4 color;
in vec2 texcoord;

out vec4 fragColor;
out vec2 texCoord;

void main() {
    fragColor = color;
    gl_Position = vec4(vert,1);
    texCoord = texcoord;
}

字体加载(loadFont.cpp)

//Initialise TTF
if( TTF_Init() == -1 )
    throw std::runtime_error("SDL_TTF Failed to initialise.");

//Load the texture
font = TTF_OpenFont( filePath.c_str(),12 );
if(!font)
    throw std::runtime_error("Couldn't load: "+ filePath);

TTF_SetFontStyle(font,TTF_STYLE_NORMAL);

surface = TTF_RenderUTF8_Blended(font,"Hello",this->textColor);
Uint8 colors = surface->format->BytesPerPixel;
int texture_format;
if (colors == 4) {   // alpha
    if (surface->format->Rmask == 0x000000ff)
        texture_format = GL_RGBA;
    else
        texture_format = GL_BGRA;
} else {             // no alpha
    if (surface->format->Rmask == 0x000000ff)
        texture_format = GL_RGB;
    else
        texture_format = GL_BGR;
}
glGentextures(1,&texturE);
glBindTexture(GL_TEXTURE_2D,texturE);

glTexImage2D(GL_TEXTURE_2D,colors,surface->w,surface->h,texture_format,GL_UNSIGNED_BYTE,surface->pixels);
SDL_FreeSurface(surfacE);

顶点属性设置

GLfloat vertices[] = {
    //X    Y      Z     R     G     B     A     U    V
    -1.0f,-1.0f,0.0f,1.0f,0.5f,0.f,1.f,-0.4f,0.f

};


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

glGenBuffers(1,&_vbo);
glBindBuffer(GL_ARRAY_BUFFER,_vbo);
glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_STATIC_DRAW);

glEnabLevertexAttribArray(program->attrib("vert"));
glVertexAttribPointer(program->attrib("vert"),3,GL_FLOAT,GL_falSE,9*sizeof(GLfloat),null);

glEnabLevertexAttribArray(program->attrib("color"));
glVertexAttribPointer(program->attrib("color"),4,GL_TRUE,(const GLvoid*)(3 * sizeof(GLfloat)));

glEnabLevertexAttribArray(program->attrib("texcoord"));
glVertexAttribPointer(program->attrib("texcoord"),2,(const GLvoid*)(7 * sizeof(GLfloat)));

我根据下面的评论附加了我用于顶点属性代码.

编辑:
一个删除回复中,有人询问SDL_TTF是返回3个还是4个频道.它正在返回BGRA图像.我已经尝试将片段着色器更改为

片段着色器

#version 330
in vec2 texCoord;
in vec4 fragColor;

out vec4 finalColor;

uniform sampler2D myTextureSampler;
void main() {
    finalColor = texture( myTextureSampler,texCoord ).rgba;
}

注意vec4,并使用rgba而不是rgb.这只会导致黑色矩形.
我还尝试使用SDL_LoadBMP()生成表面,它给出了完全相同的结果.

解决方法

你的来电

glTexImage2D(GL_TEXTURE_2D,颜色,表面 – > w,表面 – > h,
texture_format,surface-> pixels);

是个问题.

第三个参数错了:

http://www.opengl.org/sdk/docs/man/xhtml/glTexImage2D.xml

internalFormat

Specifies the number of color components in the texture.
                Must be one of basE internal formats given in Table 1,one of the sized internal formats given in Table 2,or one
                of the compressed internal formats given in Table 3,below.

我怀疑你想要你的GL_RGBA(或者你想让opengl存储你的纹理的格式)

编辑:

我现在只看到它,但你在片段着色器中只使用了3个通道.混合功能要求您使用4个通道,否则Alpha通道将被搞砸.

我认为你的“主要”问题在于其他地方,因为这应该只是使整个表面的颜色保持不变. (不是你看到的“垃圾”)

我很快写了这个程序,主要做你做的事情.我认为它会比我的存储库更有帮助,因为它直截了当.

#include <GL/glew.h>

#include <SDL2/SDl.h>
#include <SDL2/SDL_opengl.h>
#include <SDL2/SDL_ttf.h>

#include <String>
#include <iostream>

using namespace std;

SDL_Window *window = NULL;
SDL_GLContext context = NULL;
TTF_Font* font = NULL;
SDL_Surface* surface = NULL;

//OpenGL Objects
GLuint vao;
GLuint vbo;
GLuint texture;

//Shader Objects
GLuint program;
GLuint vs;
GLuint fs;

//Sampler Object
GLuint uniformSampler;

//CallBACk Function
APIENTRY GLvoid debugmessageCallBACkFunction( GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar* message,GLvoid* userParam)
{
  cerr << endl << "\t" << message << endl;
}

//The shaders are identical to yours
const String fragmentShaderString = 
                "#version 130\n" // My laPTOP can't do OpenGL 3.3 so 3.0 will have to do
                "in vec2 texCoord;\n"
                "in vec4 fragColor;\n"
                "\n"
                "out vec4 finalColor;\n"
                "\n"
                "uniform sampler2D myTextureSampler;\n"
                "void main() {\n"
                "  finalColor = texture( myTextureSampler,texCoord ) * fragColor;\n"
                "}";

const String vertexShaderString = 
                "#version 130\n"
                "\n"
                "in vec3 vert;\n"
                "in vec4 color;\n"
                "in vec2 texcoord;\n"
                "\n"
                "out vec4 fragColor;\n"
                "out vec2 texCoord;\n"

                "void main() {\n"
                "  fragColor = color;\n"
                "  gl_Position = vec4(vert,1);\n"
                "  texCoord = texcoord;\n"
                "}\n";

//Your vertices,but I changed alpha to 1.0f
const GLfloat vertices[] = 
{
    //X    Y      Z     R     G     B     A     U    V
    -1.0f,0.f
};

int main(int argc,char* args[])
{
  //Create Window and Context
  window = SDL_CreateWindow("SDL Text with OpenGL",640,480,SDL_WINDOW_OPENGL);

  //Set Core Context
  SDL_GL_SetAttribute( SDL_GL_COntexT_MAJOR_VERSION,3 );
  SDL_GL_SetAttribute( SDL_GL_COntexT_MINOR_VERSION,1 );
  SDL_GL_SetAttribute(SDL_GL_COntexT_PROFILE_MASK,SDL_GL_COntexT_PROFILE_CORE);

  context = SDL_GL_CreateContext(window);

  //Simple OpenGL State SetTings
  glViewport( 0.f,640.f,480.f);
  glClearColor( 0.f,1.f);

  //Init Glew
  //Set glewExperimental for Core Context
  glewExperimental=true;
  glewInit();

  //Set Blending 
  //required so that the alpha chAnnels show up from the surface
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);

  //Simple callBACk function for GL errors
  glDebugmessageCallBACkARB(debugmessageCallBACkFunction,null);

  //Create Shaders
  vs = glCreateShader(GL_VERTEX_SHADER);
  fs = glCreateShader(GL_FRAGMENT_SHADER);

  //source Pointers
  const GLchar* vssource= &vertexShaderString[0];
  const GLchar* fssource = &fragmentShaderString[0];

  //Set source
  glShadersource(vs,1,&vssource,null);
  glShadersource(fs,&fssource,null);

  //Compile Shaders
  glCompileShader(fs);
  glCompileShader(vs);

  //Create Shader Program
  program = glCreateProgram();

  //Attach Shaders to Program
  glAttachShader(program,vs);
  glAttachShader(program,fs);

  //No need for shaders anymore
  gldeleteShader(vs);
  gldeleteShader(fs);

  //Set Attribute LOCATIOns
  glBindAttribLOCATIOn(program,"vert");
  glBindAttribLOCATIOn(program,"color");
  glBindAttribLOCATIOn(program,"texcoord");

  //Link Program
  glLinkProgram(program);

  //Setup VAO and VBO
  glGenVertexArrays(1,&vao);
  glGenBuffers(1,&vbo);

  glBindVertexArray(vao);
  glBindBuffer(GL_ARRAY_BUFFER,vbo);

  glBufferData(GL_ARRAY_BUFFER,sizeof(GLfloat) * 9 * 6,GL_STATIC_DRAW);

  glEnabLevertexAttribArray(0);
  glEnabLevertexAttribArray(1);
  glEnabLevertexAttribArray(2);

  glVertexAttribPointer(0,9 * sizeof(GLfloat),null);
  glVertexAttribPointer(1,(GLvoid*)(3*sizeof(GLfloat)));
  glVertexAttribPointer(2,(GLvoid*)(7*sizeof(GLfloat)));

  //Init TTF
  TTF_Init();

  //Open Font
  font = TTF_OpenFont("DroidSansfallBACkFull.ttf",30);

  SDL_Color color = {255,255,255};

  //Create Surface
  surface = TTF_RenderUTF8_Blended(font,"This is TEXT!",color);

  //Your format checker
  GLenum format = (surface->format->BytesPerPixel==3)?GL_RGB:GL_RGBA;

  //Create OpenGL Texture
  glGentextures(1,&texturE);
  glBindTexture(GL_TEXTURE_2D,texturE);
  glTexImage2D( GL_TEXTURE_2D,format,surface->pixels);

  //Set Some basic parameters
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);

  //Set up Sampler
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D,texturE);

  uniformSampler = glGetUniformLOCATIOn(program,"myTextureSampler");
  //It defaults to using GL_TEXTURE0,so it's not necessary to set it
  //in this program it's generally a good idea.

  //-------------------------------------------------------------------------------------- 
  // DRAW STAGE
  //-------------------------------------------------------------------------------------- 

  glUseProgram(program);

  //glBindVertexArray(vao); - still in use

  glClear(GL_COLOR_BUFFER_BIT);

  glDrawArrays(GL_TRIANGLES,6);

  SDL_GL_SwapWindow(window);

  //Sleep for 2s before closing
  SDL_Delay(2000);
}

我没有做任何错误检查或关闭任何资源,因为它只是一个而不是意味着使用.

通常我不使用glew,但编写代码来手动获取这样一个小程序函数似乎毫无意义.

它编译

g++ source.cpp -g -lSDL2 -lSDL2_ttf -lGL -GLEW -o demo

在linux上.您可能需要对Windows进行一些调整(Headers文件可能会略有变化,库也会发生变化),我认为它可以在Mac上无需更改.

编辑2:

要使用mingw在windows上编译它,你需要将APIENTRY添加到回调函数,main应该有参数.更改了代码以反映这一点.

测试它,它适用于Windows和Linux. (前提是您的实现可以访问GL_ARB_debug_callBACk扩展,如果不只是注释掉)

大佬总结

以上是大佬教程为你收集整理的c – SDL_TTF绘制垃圾全部内容,希望文章能够帮你解决c – SDL_TTF绘制垃圾所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。