update pyglet

fix crash
This commit is contained in:
shenjackyuanjie 2022-04-13 19:00:36 +08:00
parent d8080ad590
commit 085a8e52ac
14 changed files with 281 additions and 243 deletions

View File

@ -12,7 +12,7 @@ gitee: @shenjackyuanjie
"""
import re
import pprint
import julia
from Difficult_Rocket import translate

View File

@ -22,7 +22,7 @@ from libs.pyglet.window import key
from libs.pyglet.gui import widgets
from libs.pyglet.sprite import Sprite
from libs.pyglet.shapes import Rectangle
# from libs.pyglet.image import AbstractImage
from libs.pyglet.image import AbstractImage
from libs.pyglet.graphics import Batch, Group
from libs.pyglet.text.document import FormattedDocument
from libs.pyglet.text.layout import IncrementalTextLayout
@ -51,200 +51,204 @@ class Parts(widgets.WidgetBase):
self._value = 0
class InputBox(widgets.WidgetBase):
"""
input box
"""
if not DR_options['InputBox_use_TextEntry']:
class InputBox(widgets.WidgetBase):
"""
input box
"""
def __init__(self,
x: int, y: int, width: int, height: int,
message: str = '',
font_name: str = translate.微软等宽,
font_size: int = 15,
font_bold: bool = False,
font_italic: bool = False,
font_stretch: bool = False,
font_dpi: int = 100,
text_color: [int, int, int] = (187, 187, 187, 255),
out_line_color: [int, int, int] = (37, 116, 176),
cursor_color: [int, int, int] = (187, 187, 187),
select_color: [int, int, int] = (63, 115, 255),
out_line: int = 2,
batch: Batch = None,
group: Group = None):
if batch is None:
batch = Batch()
if group is None:
group = Group()
super().__init__(x, y, width, height)
self.enabled = False
self._text = message
self._cursor_poi = 0
self.font = font.load(name=font_name, size=font_size,
bold=font_bold, italic=font_italic, stretch=font_stretch,
dpi=font_dpi)
self.font_height = self.font.ascent - self.font.descent
self.out_bound = out_line
if DR_options['InputBox_use_TextEntry']:
# 基于IncrementalTextLayout的处理系统
self._doc = FormattedDocument(message)
# self._doc.set_style()
self._layout = IncrementalTextLayout(self._doc, self.font, width, height,
batch=batch, group=group)
self._input_box = widgets.TextEntry(x, y, width, height,
self._doc, self._layout,
batch=batch, group=group)
else:
# 基于Label的处理系统
self._input_box = Label(x=x + out_line, y=y + out_line,
width=width, height=self.font_height + self.out_bound * 2,
color=text_color,
font_name=font_name, font_size=font_size,
batch=batch, group=group,
text=message)
self._HTML_box = HTMLLabel(x=x + out_line, y=y + out_line + 30,
width=width, height=self.font_height + self.out_bound * 2,
batch=batch, group=group,
text=message)
self._out_box = Rectangle(x=x - out_line, y=y - out_line,
color=out_line_color,
width=width + (out_line * 2), height=height + (out_line * 2),
batch=batch, group=group)
self._光标 = Rectangle(x=x + out_line, y=y + out_line,
color=cursor_color,
width=1, height=self.font_height,
batch=batch, group=group)
self._选择框 = Rectangle(x=x, y=y, width=0, height=self.font_height,
color=select_color)
self._选择的字 = Label(x=x, y=y, width=0, height=self.font_height,
color=text_color,
font_name=font_name, font_size=font_size,
batch=batch, group=group,
text='')
"""
输入框的属性
"""
# 本身属性
@property
def text(self) -> str: # 输入框的文本
return self._text
@text.setter
def text(self, value) -> None:
assert type(value) is str, 'Input Box\'s text must be string!'
self._text = value
self._input_box.text = value
self._HTML_box.text = html.decode_text2HTML(value, show_style=True)
@property
def cursor_poi(self) -> int: # 光标位置
return self._cursor_poi
@cursor_poi.setter
def cursor_poi(self, value) -> None:
assert type(value) is int, 'Input Box\'s cursor poi must be int!'
self._cursor_poi = value
self._光标.x = self.x + self.out_bound + self._input_box.content_width
# 渲染时属性
@property
def opacity(self) -> int: # 透明度
return self._input_box.opacity
@opacity.setter
def opacity(self, value: int) -> None:
assert type(value) is int, 'Input Box\'s opacity must be int!'
self._input_box.opacity = value
self._out_box.opacity = value
self._选择的字.opacity = value
self._选择框.opacity = value
self._光标.opacity = value
@property
def visible(self) -> bool: # 是否可见
return self._input_box.visible
@visible.setter
def visible(self, value: bool) -> None:
assert type(value) is bool, 'Input Box\'s visible must be bool!'
self._input_box.visible = value
self._out_box.visible = value
self._选择的字.visible = value
self._选择框.visible = value
self._光标.visible = value
@property
def value(self) -> str:
return self._text
"""
事件调用
"""
def _update_position(self):
self._input_box.position = self._x + self.out_bound, self._y + self.out_bound
self._out_box.position = self._x - self.out_bound, self._y - self.out_bound
self._光标.position = self._x + self.out_bound, self._y + self.out_bound
# 输入东西
def on_text(self, text: str):
if self.enabled:
if text in ('\r', '\n'):
if self.text:
self.dispatch_event('on_commit', self.text)
else:
self.text = f'{self.text[:self.cursor_poi]}{text}{self.text[self.cursor_poi:]}'
self.cursor_poi += len(text)
# 移动光标
def on_text_motion(self, motion):
if self.enabled:
# 根据按键处理
# 单格移动光标(上下左右)
if motion in (key.MOTION_UP, key.MOTION_LEFT): # 往上一个移动
self.cursor_poi = max(0, self._cursor_poi - 1)
elif motion in (key.MOTION_DOWN, key.MOTION_RIGHT): # 往下一个移动
self.cursor_poi = min(len(self.text), self._cursor_poi + 1)
# 大前后移动(开头或结尾)
elif motion in (key.MOTION_BEGINNING_OF_LINE, key.MOTION_BEGINNING_OF_FILE, key.MOTION_PREVIOUS_PAGE): # 开头
self.cursor_poi = 0
elif motion in (key.MOTION_END_OF_LINE, key.MOTION_END_OF_FILE, key.MOTION_NEXT_PAGE): # 结尾
self.cursor_poi = len(self.text)
# 删除操作
elif motion == key.MOTION_BACKSPACE:
if self.text: # 如果有文字
self.text = f'{self.text[:self.cursor_poi - 1]}{self.text[self.cursor_poi:]}'
self.cursor_poi = max(0, self._cursor_poi - 1)
elif motion == key.MOTION_DELETE:
if self.text and self.cursor_poi != len(self.text) - 1: # 如果有文字,并且光标不在最后
self.text = f'{self.text[:self.cursor_poi]}{self.text[self.cursor_poi + 1:]}'
# 剪贴板操作
elif motion == key.MOTION_COPY:
pass
elif motion == key.MOTION_PASTE:
paste_text = paste()
self.text = f'{self.text[:self.cursor_poi]}{paste_text}{self.text[self.cursor_poi:]}'
self.cursor_poi += len(paste_text)
def on_text_motion_select(self, motion):
pass
def on_mouse_press(self, x, y, buttons, modifiers):
if self._check_hit(x, y) and self._input_box.visible:
self.enabled = True
else:
def __init__(self,
x: int, y: int, width: int, height: int,
message: str = '',
font_name: str = translate.微软等宽,
font_size: int = 15,
font_bold: bool = False,
font_italic: bool = False,
font_stretch: bool = False,
font_dpi: int = 100,
text_color: [int, int, int] = (187, 187, 187, 255),
out_line_color: [int, int, int] = (37, 116, 176),
cursor_color: [int, int, int] = (187, 187, 187),
select_color: [int, int, int] = (63, 115, 255),
out_line: int = 2,
batch: Batch = None,
group: Group = None):
if batch is None:
batch = Batch()
if group is None:
group = Group()
super().__init__(x, y, width, height)
self.enabled = False
self._text = message
self._cursor_poi = 0
self.font = font.load(name=font_name, size=font_size,
bold=font_bold, italic=font_italic, stretch=font_stretch,
dpi=font_dpi)
self.font_height = self.font.ascent - self.font.descent
self.out_bound = out_line
if DR_options['InputBox_use_TextEntry']:
# 基于IncrementalTextLayout的处理系统
self._doc = FormattedDocument(message)
# self._doc.set_style()
self._layout = IncrementalTextLayout(self._doc, self.font, width, height,
batch=batch, group=group)
self._input_box = widgets.TextEntry(x, y, width, height,
self._doc, self._layout,
batch=batch, group=group)
else:
# 基于Label的处理系统
self._input_box = Label(x=x + out_line, y=y + out_line,
width=width, height=self.font_height + self.out_bound * 2,
color=text_color,
font_name=font_name, font_size=font_size,
batch=batch, group=group,
text=message)
self._HTML_box = HTMLLabel(x=x + out_line, y=y + out_line + 30,
width=width, height=self.font_height + self.out_bound * 2,
batch=batch, group=group,
text=message)
self._out_box = Rectangle(x=x - out_line, y=y - out_line,
color=out_line_color,
width=width + (out_line * 2), height=height + (out_line * 2),
batch=batch, group=group)
self._光标 = Rectangle(x=x + out_line, y=y + out_line,
color=cursor_color,
width=1, height=self.font_height,
batch=batch, group=group)
self._选择框 = Rectangle(x=x, y=y, width=0, height=self.font_height,
color=select_color)
self._选择的字 = Label(x=x, y=y, width=0, height=self.font_height,
color=text_color,
font_name=font_name, font_size=font_size,
batch=batch, group=group,
text='')
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
"""
输入框的属性
"""
# 本身属性
@property
def text(self) -> str: # 输入框的文本
return self._text
@text.setter
def text(self, value) -> None:
assert type(value) is str, 'Input Box\'s text must be string!'
self._text = value
self._input_box.text = value
self._HTML_box.text = html.decode_text2HTML(value, show_style=True)
@property
def cursor_poi(self) -> int: # 光标位置
return self._cursor_poi
@cursor_poi.setter
def cursor_poi(self, value) -> None:
assert type(value) is int, 'Input Box\'s cursor poi must be int!'
self._cursor_poi = value
self._光标.x = self.x + self.out_bound + self._input_box.content_width
# 渲染时属性
@property
def opacity(self) -> int: # 透明度
return self._input_box.opacity
@opacity.setter
def opacity(self, value: int) -> None:
assert type(value) is int, 'Input Box\'s opacity must be int!'
self._input_box.opacity = value
self._out_box.opacity = value
self._选择的字.opacity = value
self._选择框.opacity = value
self._光标.opacity = value
@property
def visible(self) -> bool: # 是否可见
return self._input_box.visible
@visible.setter
def visible(self, value: bool) -> None:
assert type(value) is bool, 'Input Box\'s visible must be bool!'
self._input_box.visible = value
self._out_box.visible = value
self._选择的字.visible = value
self._选择框.visible = value
self._光标.visible = value
@property
def value(self) -> str:
return self._text
"""
事件调用
"""
def _update_position(self):
self._input_box.position = self._x + self.out_bound, self._y + self.out_bound
self._out_box.position = self._x - self.out_bound, self._y - self.out_bound
self._光标.position = self._x + self.out_bound, self._y + self.out_bound
# 输入东西
def on_text(self, text: str):
if self.enabled:
if text in ('\r', '\n'):
if self.text:
self.dispatch_event('on_commit', self.text)
else:
self.text = f'{self.text[:self.cursor_poi]}{text}{self.text[self.cursor_poi:]}'
self.cursor_poi += len(text)
# 移动光标
def on_text_motion(self, motion):
if self.enabled:
# 根据按键处理
# 单格移动光标(上下左右)
if motion in (key.MOTION_UP, key.MOTION_LEFT): # 往上一个移动
self.cursor_poi = max(0, self._cursor_poi - 1)
elif motion in (key.MOTION_DOWN, key.MOTION_RIGHT): # 往下一个移动
self.cursor_poi = min(len(self.text), self._cursor_poi + 1)
# 大前后移动(开头或结尾)
elif motion in (key.MOTION_BEGINNING_OF_LINE, key.MOTION_BEGINNING_OF_FILE, key.MOTION_PREVIOUS_PAGE): # 开头
self.cursor_poi = 0
elif motion in (key.MOTION_END_OF_LINE, key.MOTION_END_OF_FILE, key.MOTION_NEXT_PAGE): # 结尾
self.cursor_poi = len(self.text)
# 删除操作
elif motion == key.MOTION_BACKSPACE:
if self.text: # 如果有文字
self.text = f'{self.text[:self.cursor_poi - 1]}{self.text[self.cursor_poi:]}'
self.cursor_poi = max(0, self._cursor_poi - 1)
elif motion == key.MOTION_DELETE:
if self.text and self.cursor_poi != len(self.text) - 1: # 如果有文字,并且光标不在最后
self.text = f'{self.text[:self.cursor_poi]}{self.text[self.cursor_poi + 1:]}'
# 剪贴板操作
elif motion == key.MOTION_COPY:
pass
elif motion == key.MOTION_PASTE:
paste_text = paste()
self.text = f'{self.text[:self.cursor_poi]}{paste_text}{self.text[self.cursor_poi:]}'
self.cursor_poi += len(paste_text)
def on_text_motion_select(self, motion):
pass
def on_mouse_press(self, x, y, buttons, modifiers):
if self._check_hit(x, y) and self._input_box.visible:
self.enabled = True
else:
self.enabled = False
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
pass
def on_mouse_release(self, x, y, buttons, modifiers):
pass
def on_commit(self, text: str):
pass
InputBox.register_event_type('on_commit')
else:
class InputBox(widgets.TextEntry):
pass
def on_mouse_release(self, x, y, buttons, modifiers):
pass
def on_commit(self, text: str):
pass
InputBox.register_event_type('on_commit')

View File

@ -131,7 +131,7 @@ if getattr(sys, 'frozen', None):
#: library instead of the system installed version. This option is set
#: to True by default.
#:
#: .. versionadded:: 1.2pyglet
#: .. versionadded:: 1.2
#:
options = {
'audio': ('xaudio2', 'directsound', 'openal', 'pulse', 'silent'),
@ -190,25 +190,22 @@ _option_types = {
}
def _read_environment():
for key in options:
"""Read defaults for options from environment"""
for key in options:
assert key in _option_types, f"Option '{key}' must have a type set in _option_types."
env = 'PYGLET_%s' % key.upper()
try:
value = os.environ[env]
if _option_types[key] is tuple:
options[key] = value.split(',')
elif _option_types[key] is bool:
options[key] = value in ('true', 'TRUE', 'True', '1')
elif _option_types[key] is int:
options[key] = int(value)
except KeyError:
pass
assert key in _option_types, f"Option '{key}' must have a type set in _option_types."
env = 'PYGLET_%s' % key.upper()
try:
value = os.environ[env]
if _option_types[key] is tuple:
options[key] = value.split(',')
elif _option_types[key] is bool:
options[key] = value in ('true', 'TRUE', 'True', '1')
elif _option_types[key] is int:
options[key] = int(value)
except KeyError:
pass
_read_environment()
if compat_platform == 'cygwin':
# This hack pretends that the posix-like ctypes provides windows
# functionality. COM does not work with this hack, so there is no

View File

@ -728,7 +728,7 @@ _vertex_source = """#version 330 core
void main()
{
gl_Position = window.projection * window.view * vec4(position, 1);
gl_Position = window.projection * window.view * vec4(position, 1.0);
vertex_colors = colors;
texture_coords = tex_coords;

View File

@ -201,6 +201,7 @@ class Shader:
raise TypeError("The `shader_type` '{}' is not yet supported".format(shader_type))
self.type = shader_type
source_string = source_string.strip()
shader_source_utf8 = source_string.encode("utf8")
source_buffer_pointer = cast(c_char_p(shader_source_utf8), POINTER(c_char))
source_length = c_int(len(shader_source_utf8))
@ -213,8 +214,18 @@ class Shader:
glGetShaderiv(shader_id, GL_COMPILE_STATUS, byref(status))
if status.value != GL_TRUE:
raise GLException("The {0} shader failed to compile. "
"\n{1}".format(self.type, self._get_shader_log(shader_id)))
source = self._get_shader_source(shader_id)
source_lines = "{0}".format("\n".join(f"{str(i+1).zfill(3)}: {line} "
for i, line in enumerate(source.split("\n"))))
raise GLException(
(
f"The {self.type} shader failed to compile.\n"
f"{self._get_shader_log(shader_id)}"
"------------------------------------------------------------\n"
f"{source_lines}\n"
"------------------------------------------------------------"
)
)
elif _debug_gl_shaders:
print(self._get_shader_log(shader_id))
@ -235,6 +246,14 @@ class Shader:
else:
return f"{self.type.capitalize()} Shader '{shader_id}' compiled successfully."
def _get_shader_source(self, shader_id):
"""Get the shader source from the shader object"""
source_length = c_int(0)
glGetShaderiv(shader_id, GL_SHADER_SOURCE_LENGTH, source_length)
source_str = create_string_buffer(source_length.value)
glGetShaderSource(shader_id, source_length, None, source_str)
return source_str.value.decode('utf8')
def __del__(self):
try:
glDeleteShader(self._id)
@ -303,11 +322,22 @@ class ShaderProgram:
@staticmethod
def _link_program(shaders):
# TODO: catch exceptions when linking Program:
program_id = glCreateProgram()
for shader in shaders:
glAttachShader(program_id, shader.id)
glLinkProgram(program_id)
# Check the link status of program
status = c_int()
glGetProgramiv(program_id, GL_LINK_STATUS, status)
if not status.value:
length = c_int()
glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, length)
log = c_buffer(length.value)
glGetProgramInfoLog(program_id, len(log), None, log)
raise ShaderException("Error linking shader program:\n{}".format(log.value.decode()))
# Shader objects no longer needed
for shader in shaders:
glDetachShader(program_id, shader.id)
return program_id

View File

@ -101,6 +101,9 @@ if _is_pyglet_doc_run:
def __call__(self, *args, **kwargs):
return LibraryMock()
def __rshift__(self, other):
return 0
class LibraryLoader:

View File

@ -42,8 +42,8 @@ methods are included for rotating, scaling, and transforming. The
orthographic and perspective projection matrixes.
:note: For performance, these objects' subclass the `tuple` type. They
are therefore immutable - all operations return a new object; the
object is not updated in-place.
are therefore immutable - all operations return a new object; the
object is not updated in-place.
"""
import math as _math
@ -797,8 +797,9 @@ class Mat4(tuple):
"""Create a rotation matrix from an angle and Vec3.
:Parameters:
`angle` : A `float`
`vector` : A `Vec3`, or 3 component tuple of float or int
`angle` : A `float` :
The angle as a float.
`vector` : A `Vec3`, or 3 component tuple of float or int :
Vec3 or tuple with x, y and z translaton values
"""
return cls().rotate(angle, vector)

View File

@ -120,6 +120,8 @@ class WaveEncoder(MediaEncoder):
:Parameters:
`filename` : str
The file name to save as.
`file` : file-like object
A file-like object, opened with mode 'wb'.
"""
opened_file = None
@ -139,6 +141,7 @@ class WaveEncoder(MediaEncoder):
wave_writer.writeframes(audiodata.data)
audiodata = source.get_audio_data(chunksize)
else:
wave_writer.close()
if opened_file:
file.close()

View File

@ -98,7 +98,7 @@ vertex_source = """#version 150 core
void main()
{
gl_Position = window.projection * window.view * vec4(position, 0, 1);
gl_Position = window.projection * window.view * vec4(position, 0.0, 1.0);
vertex_colors = colors;
}
"""

View File

@ -145,7 +145,7 @@ vertex_source = """#version 150 core
m_rotation[1][0] = -sin(-radians(rotation));
m_rotation[1][1] = cos(-radians(rotation));
gl_Position = window.projection * window.view * m_translate * m_rotation * m_scale * vec4(position, 0, 1);
gl_Position = window.projection * window.view * m_translate * m_rotation * m_scale * vec4(position, 0.0, 1.0);
vertex_colors = colors;
texture_coords = tex_coords;

View File

@ -548,12 +548,9 @@ layout_vertex_source = """#version 330 core
void main()
{
mat4 translate_mat = mat4(1.0);
translate_mat[3] = vec4(translation, 1.0, 1.0);
gl_Position = window.projection * window.view * vec4(position + translation, 0.0, 1.0);
gl_Position = window.projection * window.view * translate_mat * vec4(position, 0, 1);
vert_position = vec4(position + translation, 0, 1);
vert_position = vec4(position + translation, 0.0, 1.0);
text_colors = colors;
texture_coords = tex_coords.xy;
}
@ -571,7 +568,7 @@ layout_fragment_source = """#version 330 core
uniform vec4 scissor_area;
void main()
{
{
final_colors = vec4(text_colors.rgb, texture(text, texture_coords).a * text_colors.a);
if (scissor == true) {
if (vert_position.x < scissor_area[0]) discard; // left
@ -590,7 +587,6 @@ decoration_vertex_source = """#version 330 core
out vec4 vert_colors;
out vec4 vert_position;
uniform WindowBlock
{
mat4 projection;
@ -599,12 +595,9 @@ decoration_vertex_source = """#version 330 core
void main()
{
mat4 translate_mat = mat4(1.0);
translate_mat[3] = vec4(translation, 1.0, 1.0);
gl_Position = window.projection * window.view * vec4(position + translation, 0.0, 1.0);
gl_Position = window.projection * window.view * translate_mat * vec4(position, 0, 1);
vert_position = vec4(position + translation, 0, 1);
vert_position = vec4(position + translation, 0.0, 1.0);
vert_colors = colors;
}
"""

View File

@ -36,7 +36,6 @@
"""Various utility functions used internally by pyglet
"""
import io
import os
import sys
@ -141,8 +140,8 @@ class CodecRegistry:
def __init__(self):
self._decoders = []
self._encoders = []
self._decoder_extensions = {} # Map str -> list of matching ImageDecoders
self._encoder_extensions = {} # Map str -> list of matching ImageEncoders
self._decoder_extensions = {} # Map str -> list of matching Decoders
self._encoder_extensions = {} # Map str -> list of matching Encoders
def get_encoders(self, filename=None):
"""Get a list of all encoders. If a `filename` is provided, only

View File

@ -455,7 +455,13 @@ class BaseWindow(with_metaclass(_WindowMetaclass, EventDispatcher)):
gl_Position = window.projection * window.view * position;
}
"""
_default_fragment_source = """#version 150 core
out vec4 fragColor;
void main() {
fragColor = vec4(1.0);
}
"""
def __init__(self,
width=None,
height=None,
@ -611,7 +617,10 @@ class BaseWindow(with_metaclass(_WindowMetaclass, EventDispatcher)):
self.activate()
def _create_projection(self):
self._default_program = shader.ShaderProgram(shader.Shader(self._default_vertex_source, 'vertex'))
self._default_program = shader.ShaderProgram(
shader.Shader(self._default_vertex_source, 'vertex'),
shader.Shader(self._default_fragment_source, 'fragment'),
)
self.ubo = self._default_program.uniform_blocks['WindowBlock'].create_ubo()
self._viewport = 0, 0, *self.get_framebuffer_size()

View File

@ -832,11 +832,6 @@ class Win32Window(BaseWindow):
else:
return None
@Win32EventHandler(WM_WINDOWPOSCHANGED)
def _event_window_pos_changed(self, msg, wParam, lParam):
if self._exclusive_mouse:
self._update_clipped_cursor()
@Win32EventHandler(WM_NCLBUTTONDOWN)
def _event_ncl_button_down(self, msg, wParam, lParam):
self._in_title_bar = True
@ -1097,6 +1092,10 @@ class Win32Window(BaseWindow):
if not self._fullscreen:
self._width, self._height = w, h
self._update_view_location(self._width, self._height)
if self._exclusive_mouse:
self._update_clipped_cursor()
self.switch_to()
self.dispatch_event('on_resize', self._width, self._height)
return 0