简体   繁体   English

Pyglet将文本绘制为纹理

[英]Pyglet draw text into texture

I'm trying to render an image with OpenGL using Pyglet. 我正在尝试使用Pyglet使用OpenGL渲染图像。 So far I've been able to setup the framebuffer and texture, render into it and save it as a PNG image. 到目前为止,我已经能够设置帧缓冲区和纹理,将其渲染并保存为PNG图像。 But I can't find out how to use Pyglets font rendering. 但是我找不到如何使用Pyglets字体渲染的方法。

import numpy as np
import pyglet
from pyglet.gl import *
from ctypes import byref, sizeof, POINTER

width = 800
height = 600
cpp = 4

# Create the framebuffer (rendering target).
buf = gl.GLuint(0)
glGenFramebuffers(1, byref(buf))
glBindFramebuffer(GL_FRAMEBUFFER, buf)

# Create the texture (internal pixel data for the framebuffer).
tex = gl.GLuint(0)
glGenTextures(1, byref(tex))
glBindTexture(GL_TEXTURE_2D, tex)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_FLOAT, None)

# Bind the texture to the framebuffer.
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0)

# Something may have gone wrong during the process, depending on the
# capabilities of the GPU.
res = glCheckFramebufferStatus(GL_FRAMEBUFFER)
if res != GL_FRAMEBUFFER_COMPLETE:
  raise RuntimeError('Framebuffer not completed')

glViewport(0, 0, width, height)

# DRAW BEGIN
# =====================
glClearColor(0.1, 0.1, 0.1, 1.0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0, 0.5, 0.02)
glRectf(-0.75, -0.75, 0.75, 0.75)

glColor3f(1.0, 1.0, 1.0)
label = pyglet.text.Label(
  "Hello, World", font_name='Times New Roman', font_size=36,
  x=0, y=0, anchor_x='center', anchor_y='center')
label.draw()
# =====================
# DRAW END

# Read the buffer contents into a numpy array.
data = np.empty((height, width, cpp), dtype=np.float32)
glReadPixels(0, 0, width, height, GL_RGBA, GL_FLOAT, data.ctypes.data_as(POINTER(GLfloat)))

# Save the image.
import imageio
data = np.uint8(data * 255)
imageio.imwrite("foo.png", data)

The text does not appear on the framebuffer. 文本不会出现在帧缓冲区上。 How can I render the label on the framebuffer? 如何在帧缓冲区上渲染标签?

For rendering labels in Pyglet, first, an orthographic projection should be set up. 为了在Pyglet中渲染标签,首先,应设置正交投影。 In the given example, do it as follows: 在给定的示例中,执行以下操作:

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, width, 0, height, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glColor3f(1.0, 1.0, 1.0)
label = pyglet.text.Label(
  "Hello, World", font_name='Times New Roman', font_size=36,
  x=width/2, y=height/2, anchor_x='center', anchor_y='center')
label.draw()

Then, the label is rendered as expected. 然后,标签将按预期方式呈现。 (Note: moved the label's offset to the image center, ie x=width/2, y=height/2, ) (注意:将标签的偏移量移至图像中心,即x=width/2, y=height/2,

foo.png (output framebuffer image) foo.png(输出帧缓冲图像)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM