Pyglet控件的批处理参数batch和分组参数group简析

先来复习一下之前写的两个例程: 

1. 绘制网格线

import pyglet
 
window = pyglet.window.Window(800, 600)
color = (255, 255, 255, 255)  # 白色
lines = []
 
for y in range(0, window.height, 40):
    lines.append(pyglet.shapes.Line(0, y, window.width, y, color=color))
for x in range(0, window.width, 40):
    lines.append(pyglet.shapes.Line(x, 0, x, window.height, color=color))
 
@window.event
def on_draw():
    window.clear()
    for line in lines:
        line.draw()
 
pyglet.app.run()

2. 模拟按钮

import pyglet
 
window = pyglet.window.Window(800, 600)
 
GRAY = (220, 220, 220, 255)
BLACK = (0, 0, 0, 255)
RED = (255, 0, 0, 255)
 
pattern = pyglet.image.SolidColorImagePattern(color=GRAY)
image = pattern.create_image(100,50)
button1 = pyglet.sprite.Sprite(image, 280, 200)
button2 = pyglet.sprite.Sprite(image, 280+150, 200)
labelb1 = pyglet.text.Label('按钮1', font_size=16, x=305, y=216, color=BLACK)
labelb2 = pyglet.text.Label('按钮2', font_size=16, x=455, y=216, color=BLACK)
message = pyglet.text.Label('', font_size=16, x=20, y=16)
widgets = [message]
widgets.extend([button1, button2, labelb1, labelb2])
 
@window.event
def on_draw():
    window.clear()
    for widget in widgets:
        widget.draw()
 
@window.event
def on_mouse_press(x, y, button, modifier):
    X, Y, W, H = button1.x, button1.y, button1.width, button1.height
    if x in range(X,X+W+1) and y in range(Y,Y+H+1):
        message.text = '你点击了按钮1'
    elif x in range(X+150,X+W+151) and y in range(Y,Y+H+1):
        message.text = '你点击了按钮2'
 
@window.event
def on_mouse_motion(x, y, dx, dy):
    X, Y, W, H = button1.x, button1.y, button1.width, button1.height
    if x in range(X,X+W+1) and y in range(Y,Y+H+1):
        labelb1.color = RED
    elif x in range(X+150,X+W+151) and y in range(Y,Y+H+1):
        labelb2.color = RED
    else:
        labelb1.color = BLACK
        labelb2.color = BLACK
 
pyglet.app.run()

以上两个例程,都使用了控件列表,然后在on_draw事件中遍历,基本上实现了“批处理”画图的功能。但是,实现上pyglet库本身就带有这种批处理功能,这就是各个控件都带有的batch参数。看一个pyglet自带的实例:

import pyglet
from pyglet import shapes

window = pyglet.window.Window(960, 540)
batch = pyglet.graphics.Batch()

circle = shapes.Circle(700, 150, 100, color=(50, 225, 30), batch=batch)
square = shapes.Rectangle(200, 200, 200, 200, color=(55, 55, 255), batch=batch)
rectangle = shapes.Rectangle(250, 300, 400, 200, color=(255, 22, 20), batch=batch)
rectangle.opacity = 128
rectangle.rotation = 33
line = shapes.Line(100, 100, 100, 200, width=19, batch=batch)
line2 = shapes.Line(150, 150, 444, 111, width=4, color=(200, 20, 20), batch=batch)
star = shapes.Star(800, 400, 60, 40, num_spikes=20, color=(255, 255, 0), batch=batch)

@window.event
def on_draw():
    window.clear()
    batch.draw()

pyglet.app.run()

是不是更简单,使用了pyglet.graphics.Batch()对象,把需要一起画的控件都装进Batch()里,然后再一起画出来。与以下代码的效果是一样的,但省掉了widgets元组和遍历过程,还是原生的批处理参数batch更简单。

import pyglet
from pyglet import shapes

window = pyglet.window.Window(960, 540)

circle = shapes.Circle(700, 150, 100, color=(50, 225, 30))
square = shapes.Rectangle(200, 200, 200, 200, color=(55, 55, 255))
rectangle = shapes.Rectangle(250, 300, 400, 200, color=(255, 22, 20))
rectangle.opacity = 128
rectangle.rotation = 33
line = shapes.Line(100, 100, 100, 200, width=19)
line2 = shapes.Line(150, 150, 444, 111, width=4, color=(200, 20, 20))
star = shapes.Star(800, 400, 60, 40, num_spikes=20, color=(255, 255, 0))
widgets = circle, square, rectangle, line, line2, star

@window.event
def on_draw():
    window.clear()
    for batch in widgets:
        batch.draw()

pyglet.app.run()

接下来说说group分组参数,先看一个实例:

import pyglet

window = pyglet.window.Window(800, 500 , caption='Batch&Group')
batch = pyglet.graphics.Batch()  # 创建一个Batch对象
group = [pyglet.graphics.Group(i) for i in range(4)]   # 创建一组Group对象

circle1 = pyglet.shapes.Circle(x=250, y=250, radius=80, color=(255, 0, 0, 255), batch=batch, group=group[0])
rectangle1 = pyglet.shapes.Rectangle(x=150, y=200, width=200, height=100, color=(0, 0, 255, 255), batch=batch, group=group[1])

circle2 = pyglet.shapes.Circle(x=550, y=250, radius=80, color=(255, 0, 0, 255), batch=batch, group=group[3])
rectangle2 = pyglet.shapes.Rectangle(x=450, y=200, width=200, height=100, color=(0, 0, 255, 255), batch=batch, group=group[2])

@window.event
def on_draw():
    window.clear()
    batch.draw()  # 在窗口上绘制batch中的所有图形对象

pyglet.app.run()

运行效果:

 group参数主要用于控制控件的显示顺序,与pyglet.graphics.Group(order=i)配合使用,这里order数值越大越在上层,越小则越在下层。当然group除了排序的功能,还有包括同组绑定纹理、着色器或设置任何其他参数的功能,这些功能以后再安排学习。

到此已基本了解pyglet控件参数batch和group的用法,再来看一下graphics.Batch和graphics.Group的自带说明:

class Batch

Help on class Batch in module pyglet.graphics:

class Batch(builtins.object)
Manage a collection of drawables for batched rendering.

Many drawable pyglet objects accept an optional `Batch` argument in their
constructors. By giving a `Batch` to multiple objects, you can tell pyglet
that you expect to draw all of these objects at once, so it can optimise its
use of OpenGL. Hence, drawing a `Batch` is often much faster than drawing
each contained drawable separately.

The following example creates a batch, adds two sprites to the batch, and
then draws the entire batch::

    batch = pyglet.graphics.Batch()
    car = pyglet.sprite.Sprite(car_image, batch=batch)
    boat = pyglet.sprite.Sprite(boat_image, batch=batch)

    def on_draw():
        batch.draw()

While any drawables can be added to a `Batch`, only those with the same
draw mode, shader program, and group can be optimised together.

Internally, a `Batch` manages a set of VertexDomains along with
information about how the domains are to be drawn. To implement batching on
a custom drawable, get your vertex domains from the given batch instead of
setting them up yourself.

Methods defined here:

__init__(self)
    Create a graphics batch.

draw(self)
    Draw the batch.

draw_subset(self, vertex_lists)
    Draw only some vertex lists in the batch.

    The use of this method is highly discouraged, as it is quite
    inefficient.  Usually an application can be redesigned so that batches
    can always be drawn in their entirety, using `draw`.

    The given vertex lists must belong to this batch; behaviour is
    undefined if this condition is not met.

    :Parameters:
        `vertex_lists` : sequence of `VertexList` or `IndexedVertexList`
            Vertex lists to draw.

get_domain(self, indexed, mode, group, program, attributes)
    Get, or create, the vertex domain corresponding to the given arguments.

invalidate(self)
    Force the batch to update the draw list.

    This method can be used to force the batch to re-compute the draw list
    when the ordering of groups has changed.

    .. versionadded:: 1.2

migrate(self, vertex_list, mode, group, batch)
    Migrate a vertex list to another batch and/or group.

    `vertex_list` and `mode` together identify the vertex list to migrate.
    `group` and `batch` are new owners of the vertex list after migration.

    The results are undefined if `mode` is not correct or if `vertex_list`
    does not belong to this batch (they are not checked and will not
    necessarily throw an exception immediately).

    `batch` can remain unchanged if only a group change is desired.

    :Parameters:
        `vertex_list` : `~pyglet.graphics.vertexdomain.VertexList`
            A vertex list currently belonging to this batch.
        `mode` : int
            The current GL drawing mode of the vertex list.
        `group` : `~pyglet.graphics.Group`
            The new group to migrate to.
        `batch` : `~pyglet.graphics.Batch`
            The batch to migrate to (or the current batch).

----------------------------------------------------------------------
Data descriptors defined here:

__dict__
    dictionary for instance variables (if defined)

__weakref__
    list of weak references to the object (if defined)

class Group

Help on class Group in module pyglet.graphics:

class Group(builtins.object)
Group(order=0, parent=None)

Group of common OpenGL state.

`Group` provides extra control over how drawables are handled within a
`Batch`. When a batch draws a drawable, it ensures its group's state is set;
this can include binding textures, shaders, or setting any other parameters.
It also sorts the groups before drawing.

In the following example, the background sprite is guaranteed to be drawn
before the car and the boat::

    batch = pyglet.graphics.Batch()
    background = pyglet.graphics.Group(order=0)
    foreground = pyglet.graphics.Group(order=1)

    background = pyglet.sprite.Sprite(background_image, batch=batch, group=background)
    car = pyglet.sprite.Sprite(car_image, batch=batch, group=foreground)
    boat = pyglet.sprite.Sprite(boat_image, batch=batch, group=foreground)

    def on_draw():
        batch.draw()

:Parameters:
    `order` : int
        Set the order to render above or below other Groups.
        Lower orders are drawn first.
    `parent` : `~pyglet.graphics.Group`
        Group to contain this Group; its state will be set before this
        Group's state.

:Variables:
    `visible` : bool
        Determines whether this Group is visible in any of the Batches
        it is assigned to. If ``False``, objects in this Group will not
        be rendered.
    `batches` : list
        Read Only. A list of which Batches this Group is a part of.

Methods defined here:

__eq__(self, other)
    Return self==value.

__hash__(self)
    Return hash(self).

__init__(self, order=0, parent=None)
    Initialize self.  See help(type(self)) for accurate signature.

__lt__(self, other)
    Return self<value.

__repr__(self)
    Return repr(self).

set_state(self)
    Apply the OpenGL state change.

    The default implementation does nothing.

set_state_recursive(self)
    Set this group and its ancestry.

    Call this method if you are using a group in isolation: the
    parent groups will be called in top-down order, with this class's
    `set` being called last.

unset_state(self)
    Repeal the OpenGL state change.

    The default implementation does nothing.

unset_state_recursive(self)
    Unset this group and its ancestry.

    The inverse of `set_state_recursive`.

----------------------------------------------------------------------
Readonly properties defined here:

batches

order

----------------------------------------------------------------------
Data descriptors defined here:

__dict__
    dictionary for instance variables (if defined)

__weakref__
    list of weak references to the object (if defined)

visible

最后,使用Batch()修改一下之前两个例程:

import pyglet
 
window = pyglet.window.Window(800, 600, caption='绘制网络线')
color = (255, 255, 255, 255)
lines = pyglet.graphics.Batch()
 
for y in range(0, window.height, 40):
    exec(f'y{y//40} = pyglet.shapes.Line(0, y, window.width, y, color=color, batch=lines)')
for x in range(0, window.width, 40):
    exec(f'x{x//40} = pyglet.shapes.Line(x, 0, x, window.height, color=color, batch=lines)')
 
@window.event
def on_draw():
    window.clear()
    lines.draw()
 
pyglet.app.run()
import pyglet
 
window = pyglet.window.Window(800, 600, caption='按钮模拟')
 
GRAY = (220, 220, 220, 255)
BLACK = (0, 0, 0, 255)
RED = (255, 0, 0, 255)

batch = pyglet.graphics.Batch()
pattern = pyglet.image.SolidColorImagePattern(color=GRAY)
image = pattern.create_image(100,50)
button1 = pyglet.sprite.Sprite(image, 280, 200, batch = batch)
button2 = pyglet.sprite.Sprite(image, 280+150, 200, batch = batch)
labelb1 = pyglet.text.Label('按钮1', font_size=16, x=305, y=216, color=BLACK, batch = batch)
labelb2 = pyglet.text.Label('按钮2', font_size=16, x=455, y=216, color=BLACK, batch = batch)
message = pyglet.text.Label('', font_size=16, x=20, y=16, batch = batch)
 
@window.event
def on_draw():
    window.clear()
    batch.draw()
 
@window.event
def on_mouse_press(x, y, button, modifier):
    X, Y, W, H = button1.x, button1.y, button1.width, button1.height
    if x in range(X,X+W+1) and y in range(Y,Y+H+1):
        message.text = '你点击了按钮1'
    elif x in range(X+150,X+W+151) and y in range(Y,Y+H+1):
        message.text = '你点击了按钮2'
 
@window.event
def on_mouse_motion(x, y, dx, dy):
    X, Y, W, H = button1.x, button1.y, button1.width, button1.height
    if x in range(X,X+W+1) and y in range(Y,Y+H+1):
        labelb1.color = RED
    elif x in range(X+150,X+W+151) and y in range(Y,Y+H+1):
        labelb2.color = RED
    else:
        labelb1.color = BLACK
        labelb2.color = BLACK
 
pyglet.app.run()

完。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/411095.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

人工智能产生的幻觉问题真的能被看作是创造力的另一种表现形式吗?

OpenAI的首席执行官山姆奥特曼&#xff08;Sam Altman&#xff09;曾声称&#xff0c;人工智能产生的“幻觉”其实未尝不是一件好事&#xff0c;因为实际上GPT的优势正在于其非凡的创造力。 目录 一.幻觉问题的概念 二.幻觉产生的原因 三.幻觉的分类 四.减轻AI的幻觉问题到…

基于springboot+vue的民宿在线预定平台(前后端分离)

博主主页&#xff1a;猫头鹰源码 博主简介&#xff1a;Java领域优质创作者、CSDN博客专家、阿里云专家博主、公司架构师、全网粉丝5万、专注Java技术领域和毕业设计项目实战&#xff0c;欢迎高校老师\讲师\同行交流合作 ​主要内容&#xff1a;毕业设计(Javaweb项目|小程序|Pyt…

服务质量目标:SLI,SLO,SLA

如果你要面试运维专家岗/运维架构师/运维经理/运维总监&#xff0c;面试中必然会问到的一个问题就是&#xff1a;“你能保障什么样的SLA&#xff1f;如何去实现你所保障的SLA&#xff1f;” SLA,SLO大家也许也都听说过&#xff0c;也知道几个9的含义&#xff0c;但是细致的去了…

Vulhub 靶场训练 DC-9解析

一、搭建环境 kali的IP地址是&#xff1a;192.168.200.14 DC-9的IP地址暂时未知 二、信息收集 1、探索同网段下存活的主机 arp-scan -l #2、探索开放的端口 开启端口有&#xff1a;80和22端口 3、目录扫描 访问80 端口显示的主页面 分别点击其他几个页面 可以看到是用户…

Base64 编码 lua

Base64 编码 -- Base64 字符表 local base64_chars { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,…

猫咪挑食不吃猫粮怎么办?排行榜靠前适口性好的生骨肉冻干分享

猫咪挑食不吃猫粮怎么办现在的猫奴们普遍将自家的小猫视为掌上明珠&#xff0c;宠爱有加。但这样的宠爱有时会导致猫咪出现挑食的问题。那么&#xff0c;猫咪挑食不吃猫粮怎么办&#xff1f;我们该如何应对这种情况呢&#xff1f;今天&#xff0c;我要分享一个既能确保猫咪不受…

Air001 使用内部时钟源,倍频跑48MHz主频例程

Air001 使用内部时钟源&#xff0c;倍频跑48MHz主频例程 ✨根据该芯片手册描述&#xff0c;Air001最高48MHz工作频率。 &#x1f341;Air001使用内部时钟源&#xff0c;固定倍频&#xff08;X2&#xff09;路线&#xff1a; &#x1f6e0;频率和CPU访问存储器周期调整 &…

Ubuntu20.04 ssh终端登录后未自动执行.bashrc

sudo vim ~/.profile输入以下内容 if [ -n "$BASH_VERSION" ]; then if [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc" fi fi 执行 source ~/.profile重新测试 其他答案 如果你的~/.bashrc文件在Ubuntu中没有自动生效&#xff0c;…

Tomcat 学习之 Filter 过滤器

目录 1 Filter 介绍 2 Filter 的生命周期 3 Filter 和 FilterChain 4 Filter 拦截过程 5 FilterConfig 6 Filter 使用 1 Filter 介绍 在 Tomcat 中&#xff0c;Filter 是一种用于拦截请求和过滤响应的组件&#xff0c;可以在请求到达 Servlet 之前或响应离开 Servlet 之后…

第15章-IP子网划分

1. 子网划分的需求 1.1 早期的IP地址分类 1.2 产生的问题 1.3 现实的应用场景 2. IP子网划分基础知识 2.1 概念 2.2 子网掩码 3. IP子网划分相关计算 3.1 概述 4. VLSM和CIDR 4.1 VLSM(可变长子网掩码)小 → 大&#xff1b; 4.2 CIDR(无类域间路由)大 → 小&#xff1b; 5.…

Syntax Error: Error: Cannot find module ‘node-sass‘报错解决

1.将项目中的node_modules删除掉 2.npm install重新运行安装命令 3.再npm run serve&#xff08;项目启动命令&#xff09;启动项目即可

LeetCode第二题: 两数相加

文章目录 题目描述示例 解题思路 - 迭代法Go语言实现 - 迭代法算法分析 解题思路 - 模拟法Go语言实现 - 模拟法算法分析 解题思路 - 优化模拟法主要方法其他方法的考虑 ‍ 题目描述 给出两个非空的链表用来表示两个非负的整数。其中&#xff0c;它们各自的位数是按照逆序的方…

DALL·E 3:Improving Image Generation with Better Captions

论文链接&#xff1a;https://cdn.openai.com/papers/dall-e-3.pdf DALLE3 API&#xff1a;https://github.com/Agora-X/Dalle3 官网链接&#xff1a;添加链接描述 DALLE3讲解视频&#xff1a;B站视频 推荐DALLE2的讲解视频&#xff1a;B站&#xff1a;跟李沐学AI 之前精讲的DA…

【Leetcode】235. 二叉搜索树的最近公共祖先

文章目录 题目思路代码结果 题目 题目链接 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为&#xff1a;“对于有根树 T 的两个结点 p、q&#xff0c;最近公共祖先表示为一个结点 x&#xff0c;满足 x 是 p、q 的祖先且 x 的深度…

Linux的文件操作,重拳出击( ̄︶ ̄)

Linux的文件操作 学习Linux的文件操作&#xff0c;一般需要知道一个文件如果你想要操作他&#xff0c;必须知道你对这个文件有什么操作的权限或者修改你自己对文件操作的权限。必须要知道文件有三种权限 r&#xff1a;可读 w&#xff1a;可写 x&#xff1a;可执行 在打开Linux…

【cmu15445c++入门】(10)C++锁mutex

一、锁 lock和unlock 二、 代码 // This program shows a small example of the usage of std::mutex. The // std::mutex class provides the mutex synchronization primitive. // std::mutex 类提供互斥同步原语。// Includes std::cout (printing) for demo purposes. #i…

超详细的MyCat安装部署

MyCat概述 介绍 Mycat是开源的、活跃的、基于Java语言编写的MySQL数据库中间件。可以像使用mysql一样来使用 mycat&#xff0c;对于开发人员来说根本感觉不到mycat的存在。 开发人员只需要连接MyCat即可&#xff0c;而具体底层用到几台数据库&#xff0c;每一台数据库服务器里…

预测性维修系统的功能分析和建设建议

随着工业领域的不断发展&#xff0c;设备状态监测、健康管理和智能诊断变得愈发重要。预测性维修系统通过先进的技术和可靠性评估&#xff0c;帮助企业判断设备状态&#xff0c;识别故障早期征兆&#xff0c;并生成故障预判&#xff0c;从而提出检维修建议。在这一背景下&#…

【前端素材】推荐优质后台管理系统Be admin平台模板(附源码)

一、需求分析 后台管理系统&#xff08;或称作管理后台、管理系统、后台管理平台&#xff09;是一种专门用于管理网站、应用程序或系统后台运营的软件系统。它通常由一系列功能模块组成&#xff0c;为管理员提供了管理、监控和控制网站或应用程序的各个方面的工具和界面。以下…

前端面试篇-JS篇2

37、事件模型(事件代理)(重要) 是指从事件发生开始,到所有处理函数执行完,所经历的过程。大概包括: 3个阶段 1)捕获阶段: 首先 Window 捕获事件,之后往目标传递,在到达目标节点之前的过程,就是捕获阶段(Capture Phase) 2)目标阶段: 真正触发点击的元素,事件会触发…