本文整理汇总了Python中pyglet.graphics.Batch.draw方法的典型用法代码示例。如果您正苦于以下问题:Python Batch.draw方法的具体用法?Python Batch.draw怎么用?Python Batch.draw使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyglet.graphics.Batch
的用法示例。
在下文中一共展示了Batch.draw方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Body
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
class Body(object):
"A list of primitives. Creates a single batch to draw these primitives."
def __init__(self, items=None):
self.primitives = []
if items:
self.add_items(items)
self.batch = None
def add_items(self, items):
"'items' may contain primitives and/or bodys"
for item in items:
if isinstance(item, Body):
for prim in item.primitives:
self.primitives.append(prim)
else:
self.primitives.append(item)
def batch_draw(self):
if self.batch is None:
self.batch = Batch()
for primitive in self.primitives:
batchVerts = \
[primitive.verts[0], primitive.verts[1]] + \
primitive.verts + \
[primitive.verts[-2], primitive.verts[-1]]
numverts = len(batchVerts) / 2
self.batch.add(
numverts,
primitive.primtype,
None, # draw order group to be implemented later
('v2f/static', batchVerts),
('c3B/static', primitive.color * numverts),
)
self.batch.draw()
示例2: SvgFiles
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
class SvgFiles(object):
def __init__(self):
datadir = join('solescion', 'geom', 'svgload', 'demodata')
self.filenames = self.get_filenames(datadir)
if len(self.filenames) == 0:
raise Exception('no testdata svg files found')
self.number = -1
self.current = None
self.next()
def get_filenames(self, path):
return [
join(path, filename)
for filename in listdir(path)
if filename.endswith('.svg')
]
def next(self):
self.number = (self.number + 1) % len(self.filenames)
filename = self.filenames[self.number]
print filename
self.current = SvgParser(filename)
self.batch = Batch()
self.current.add_to_batch(self.batch)
glClearColor(
uniform(0.0, 1.0),
uniform(0.0, 1.0),
uniform(0.0, 1.0),
1.0)
def draw(self):
self.batch.draw()
示例3: Test
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
class Test(cocos.scene.Scene):
def __init__(self):
super(Test, self).__init__()
self.layer = cocos.layer.Layer()
self.add(self.layer)
self.batch = Batch()
sprite = cocos.sprite.Sprite('fondo.png')
sprite.position = -400, 480 - sprite.height / 2 - 50
sprite.do(Repeat(MoveBy((20, 0), 1)))
self.layer.add(sprite)
sprite_2 = cocos.sprite.Sprite('fondo.png')
sprite_2.position = 320, 100
self.layer.add(sprite_2)
self.sprite_2 = sprite_2
self.x = -100.0
self.schedule_interval(self.update, 1/20.0)
def update(self, dt):
self.x += dt * 20
self.sprite_2.position = int(self.x), self.sprite_2.position[1]
def draw(self):
self.batch.draw()
示例4: Render
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
class Render(object):
groups = [
OrderedGroup(0), # sky
OrderedGroup(1), # hills
OrderedGroup(2), # birds & feathers
OrderedGroup(3), # hud
]
def __init__(self, game):
self.game = game
game.item_added += self.on_add_item
game.item_removed += self.on_remove_item
self.win = None
self.clockDisplay = clock.ClockDisplay()
self.batch = Batch()
def assign_images_and_sizes(self, images):
for klass in [Ground, Player, Enemy, Feather]:
klass.images = images[klass.__name__]
klass.width = klass.images[0].width
klass.height = klass.images[0].height
def init(self, win):
self.win = win
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
graphics = Graphics()
images = graphics.load()
self.assign_images_and_sizes(images)
win.on_draw = self.draw
def draw(self):
for item in self.game:
if hasattr(item, 'animate'):
item.animate()
self.batch.draw()
self.clockDisplay.draw()
self.win.invalid = False
def on_add_item(self, item):
if hasattr(item, 'add_to_batch'):
item.add_to_batch(self.batch, self.groups)
def on_remove_item(self, item):
if hasattr(item, 'remove_from_batch'):
item.remove_from_batch(self.batch)
示例5: Map
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
class Map(object):
LAYERS = {
'soil': OrderedGroup(0),
'ground': OrderedGroup(1),
'bodies': OrderedGroup(2),
'trees': OrderedGroup(3),
'berries': OrderedGroup(4)
}
def __init__(self, width, height):
self.width = width
self.height = height
self._map = Batch()
self._create()
self._add_hero()
self._add_lost()
def _create(self):
for x in range(0, self.width, Soil.size()[0]):
for y in range(0, self.height, Soil.size()[1]):
soil = Soil(x, y)
self.add(soil)
try:
soil.grow(self, x, y)
except NotFertileError as e:
logger.debug(str(e))
def add(self, thing):
thing.vertex_list = self._map.add(
len(thing.vertices) // 2,
GL_QUADS,
self.LAYERS[thing.LAYER],
('v2i/dynamic', thing.vertices),
('c4B/static', thing.colors)
)
return thing.vertex_list
def _add_body(self, body_name, kind):
body = getattr(things, body_name)(*START_POS[kind])
setattr(self, kind, body)
self.add(body)
return body
@info("Adding {}".format(BODY_HERO))
def _add_hero(self):
self._add_body(BODY_HERO, 'hero')
@info("Hiding {}".format(BODY_LOST))
def _add_lost(self):
self._add_body(BODY_LOST, 'lost') # keep a list of every tree to hide him
def draw(self):
self._map.draw()
示例6: DinamicObj
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
class DinamicObj(Importer):
def __init__(self, *args, **kwargs):
self.batch = Batch()
super(DinamicObj, self).__init__(*args, **kwargs)
def draw_faces(self):
glPushMatrix()
glTranslatef(self.x, self.y, self.z)
glScalef(self.scale, self.height, self.thickness)
self.batch.draw()
glPopMatrix()
示例7: Body
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
class Body(object):
"A list of shapes. Creates a single batch to draw these shapes."
__metaclass__ = IterRegistry
_registry = []
def __init__(self,items=None,anchor=[0,0],angle=0,drawable=True):
self.shapes = []
self._registry.append(self)
self.body=body
self.anchor=anchor
self.angle=angle
self.drawable=drawable
if items:
self.add_items(items)
self.batch = None
def add_items(self, items):
"'items' may contain shapes and/or bodies"
for item in items:
if isinstance(item, Body):
for shp in item.shapes:
self.shapes.append(shp)
else:
self.shapes.append(item)
def batch_draw(self):
if self.batch is None:
self.batch = Batch()
for shape in self.shapes:
batchVerts = \
[shape.verts[0], shape.verts[1]] + \
shape.verts + \
[shape.verts[-2], shape.verts[-1]]
numverts = len(batchVerts) / 2
self.batch.add(
numverts,
shape.primtype,
None, # draw order group to be implemented later
('v2f/static', batchVerts),
('c3B/static', shape.color * numverts),
)
self.batch.draw()
def paint_all():
for z in Zulu:
glPushMatrix()
glTranslatef(z.anchor[0],z.anchor[1],0) # Move bac
glRotatef(z.angle, 0, 0, 1)
z.body.batch_draw()
glPopMatrix()
示例8: Log
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
class Log(object):
GROUPS = {
'text_bac'
}
def __init__(self, width, height, x, y, queue):
self.width = width
self.height = height
self._log = Batch()
self._create(x, y)
self.queue = queue
def _create(self, x, y):
self._title = Label(
"_______________ LOG _______________",
x=x,
y=y + self.height + 5,
height=20,
batch=self._log
)
self._doc = decode_text("\n")
self._doc.set_style(0, 0, dict(color=(255, 255, 255, 255)))
self._box = ScrollableTextLayout(
self._doc, self.width, self.height,
multiline=True, batch=self._log
)
self._box.x = x
self._box.y = y
def draw(self):
self._log.draw()
def insert(self, message):
self._doc.insert_text(-1, message + "\n")
self._box.view_y = -self._box.content_height
def scroll(self, height):
self._box.view_y += height
def start(self):
schedule_interval(self.update, 0.3)
def update(self, dt):
try:
item = self.queue.popleft()
self.insert(item['message'])
except IndexError:
pass
示例9: CloudRenderer
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
class CloudRenderer(CloudChunk):
def __init__(self, X, Generator):
super(CloudRenderer, self).__init__(X, Generator)
self.Batch = Batch()
def GenerateFinshed(self):
super(CloudRenderer, self).GenerateFinshed()
self.Batch.add(self.Length, GL_POINTS, None,
('v2i/static', self.Points),
('c4f/static', self.Colours)
)
def Draw(self, X):
super(CloudRenderer, self).Draw(X)
self.Batch.draw()
示例10: MapView
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
class MapView(object):
def __init__(self, tilemap):
self.tilemap = tilemap
self.batch = Batch()
self.layerviews = [LayerView(self, layer) for layer in tilemap.layers]
self.refresh()
def refresh(self):
for layerview in self.layerviews:
layerview.refresh()
def draw(self):
self.batch.draw()
def move(self, movement):
dx, dy = movement
for layerview in self.layerviews:
x, y = layerview.group.translation
layerview.group.translation = (x+dx, y+dy)
示例11: AboutScene
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
class AboutScene(Scene):
def __init__(self, world, previous):
super(AboutScene, self).__init__(world)
self.old_scene = previous
self.text_batch = Batch()
self._generate_text()
self.key_handlers = {
(key.ESCAPE, 0) : self._resume
}
def on_draw(self):
self.window.clear()
# Display the previous scene, then tint it
self.text_batch.draw()
def on_key_press(self, button, modifiers):
key = (button, modifiers)
handler = self.key_handlers.get(key, lambda: None)
handler()
def _resume(self):
self.world.reload(self.old_scene)
def _generate_text(self):
real_cord = lambda x,y: (x + self.camera.offset_x,
y + self.camera.offset_y)
author_x, author_y = real_cord(200, 500)
Label("Written by John Mendelewski",
font_name='Times New Roman', font_size=36,
x=author_x, y=author_y - 20, batch=self.text_batch)
hint_x, hint_y = real_cord(400, 30)
Label("Use Escape to return to the menu",
font_name='Times New Roman', font_size=18,
x=hint_x, y=hint_y - 20, batch=self.text_batch)
示例12: Dummy
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
class Dummy(Actor):
def __init__(self, *args, **kwargs):
""" Draw a dummy actor for testing
"""
super(Dummy, self).__init__()
self.batch = Batch()
pyglet.text.Label('Hello, world',
font_name='Times New Roman',
font_size=36,
dpi=250,
# x=window.width//2, y=window.height//2,
anchor_x='center', anchor_y='center',
batch = self.batch)
pyglet.text.Label('Hi',
font_name='Times New Roman',
font_size=26,
dpi=100,
# x=window.width//2, y=window.height//2,
anchor_x='center', anchor_y='center',
batch = self.batch)
def update(self, dt):
pass
def draw(self):
pass
glPushMatrix()
#glRotatef(5.0, 0, 1, 0)
glTranslatef(-100,0,0)
self.batch.draw()
glPopMatrix()
示例13: GameScene
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
#.........这里部分代码省略.........
x= 500 + self.camera.offset_x,
y= 560 + self.camera.offset_y)
self.turn_notice.color = 255 - (100 * current_turn), 255 - (100 * ((current_turn + 1) % 2)), 255, 255
def _initialize_teams(self):
def load_knight(hue):
knight_x, knight_y = self.map.get_coordinates(9 * hue, 9 * hue)
direction = hue and Direction.WEST or Direction.SOUTH
knight = Knight(knight_x, knight_y, direction)
knight.zindex=10
knight.color = 255 - (150 * hue), 255 - (150 * ((hue + 1) % 2)), 255
mage_x, mage_y = self.map.get_coordinates(7 * hue + 1, 7 * hue + 1)
mage = Mage(mage_x, mage_y, direction)
mage.zindex=10
mage.color = 255 - (150 * hue), 255 - (150 * ((hue + 1) % 2)), 255
return [knight, mage]
return [load_knight(i) for i in range(2)]
def move_hilight(self, x, y):
current_x, current_y = self.selected
self.selected = max(0, min(x + current_x, GameScene.MAP_WIDTH - 1)),\
max(0, min(y + current_y, GameScene.MAP_HEIGHT - 1))
newx, newy = self.map.get_coordinates(*self.selected)
self.camera.look_at((newx + self.camera.x) / 2, (newy + self.camera.y) / 2)
def enter(self):
blue = 0.6, 0.6, 1, 0.8
pyglet.gl.glClearColor(*blue)
clock.schedule(self._update_characters)
def exit(self):
clock.unschedule(self._update_characters)
def on_draw(self):
self.window.clear()
selected_x, selected_y = self.map.get_coordinates(*self.selected)
# if selected_x <= 100 or selected_x >= 500 \
# or selected_y <= 100 or selected_y >= 700:
for sprite in self.map.sprites:
if (selected_x, selected_y) == (sprite.x, sprite.y):
sprite.color = 100, 100, 100
elif sprite in self.movement_hilight:
sprite.color = 100, 100, 255
elif sprite in self.attack_hilight:
sprite.color = 255, 100, 100
else:
sprite.color = 255, 255, 255
self.map_batch.draw()
if hasattr(self, 'turn_notice'):
self.turn_notice.x = 500 + self.camera.offset_x
self.turn_notice.y = 560 + self.camera.offset_y
self.turn_notice.draw()
for character in sorted(self._all_characters(), lambda c,d: int(d.y - c.y)):
# if (selected_x, selected_y) == (character.x, character.y):
# character.color = 100, 100, 100
# else:
# character.color = 255, 255, 255
character.draw()
# #character.image.blit(character.x, character.y)
if self.mode == GameScene.ACTION_MODE:
self._draw_action_menu()
self.text_batch.draw()
self.camera.focus(self.window.width, self.window.height)
def _menu_action(self):
actions = list(reversed(self.action_menu_items.values()))
示例14: Piece
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
class Piece(object):
# TODO: Different piece color per player (duh)
command_count = 0 # number of pieces this can command
speed = 0 # number of movement squares
rotation_angle = 360 # rotations must be a multiple of this number
rotation_offset = 0 # number of degress offset it starts at
# piece state
moved = False # TODO: this probably is no longer necessary
# rendering
_model = None
def __init__(self, board, player, x, y, direction):
self.board = weakref.proxy(board)
self.player = player # TODO: weakref?
# place the piece on the board
self.position = Vector3(x - 3.5, y - 3.5, 0)
# load the model
# TODO: Cached loading
model_filename = 'skins/pieces/default/models/player{}/{}.obj'.format(
self.player.player_index, self.__class__.__name__)
self._obj = OBJ(model_filename,
texture_path='skins/pieces/default/textures/')
self.batch = Batch()
self._obj.add_to(self.batch)
# set the rotation
self.direction = direction
self.old_direction = self.direction
# TODO: is angle necessary anymore?
self.angle = (self.direction.angle(X_AXIS)*180/math.pi -
self.rotation_offset)
# generate a color key
# TODO: Ensure this *never* collides (it definitely has a chance)
self.color_key = (randint(1, 254) / 255.,
randint(1, 254) / 255.,
randint(1, 254) / 255.)
self._color_key_processed = [int(round(_*255)) for _ in self.color_key]
# set remaining_move to speed
self.remaining_move = self.speed
def draw(self, scale=1):
gl.glPushMatrix()
gl.glEnable(gl.GL_TEXTURE_2D)
gl.glTranslatef(*self.position)
gl.glRotatef(self.angle, 0, 0, 1)
gl.glScalef(scale, scale, scale)
self.batch.draw()
gl.glPopMatrix()
def draw_for_picker(self, scale=1):
# disable stuff
gl.glDisable(gl.GL_TEXTURE_2D)
gl.glDisable(gl.GL_LIGHTING)
gl.glColor3f(*self.color_key)
gl.glPushMatrix()
gl.glTranslatef(*self.position)
gl.glRotatef(self.angle, 0, 0, 1)
gl.glScalef(scale, scale, scale)
# This is a weird way of doing it, but hey, whatever
for v1 in self.batch.group_map.values():
for v2 in v1.values():
v2.draw(gl.GL_TRIANGLES)
gl.glPopMatrix()
# re-enable stuff
gl.glEnable(gl.GL_LIGHTING)
gl.glEnable(gl.GL_TEXTURE_2D)
@property
def rotated(self):
return roundvec(self.direction) != roundvec(self.old_direction)
def rotate(self):
self.direction = self.direction.rotate_around(
Z_AXIS, self.rotation_angle * math.pi / 180)
self.angle += self.rotation_angle
def reset(self):
self.moved = False
self.remaining_move = self.speed
self.old_direction = self.direction
def move(self):
# This is always an *attempted* move, so it's marked such.
self.moved = True
# Decrement the recursion counter or exit
if self.remaining_move:
self.remaining_move -= 1
else:
return
# Make the vector have all 1s, 0s, and -1s.
v = roundvec(self.direction, 0)
# Check out of bounds
target = self.position + v # Only move one square at a time
# Adjust because board center is (0, 0)
w, h = self.board.width / 2, self.board.height / 2
if abs(target.x) > w or abs(target.y) > h:
return
# Check the board for pieces existing at the target
for p in self.board.pieces[:]:
if p.position == target:
engaged = roundvec(p.direction) == roundvec(-self.direction)
#.........这里部分代码省略.........
示例15: __init__
# 需要导入模块: from pyglet.graphics import Batch [as 别名]
# 或者: from pyglet.graphics.Batch import draw [as 别名]
class Drawing:
def __init__(self, width, height, fbo, background=[255,255,255]):
self.width = width
self.height = height
self.triangles = []
self.batch = Batch()
self.bg_colour = background
self.fb = fbo
self.bg = self.batch.add( 6,
gl.GL_TRIANGLES,None,
("v2i/static", (0,0,0,height,width,height,width,height,width,0,0,0)),
("c3B/static",background*6)
)
def clone(self):
global group
d = Drawing(self.width, self.height, self.fb, self.bg_colour)
bufferlength = len(self.triangles)
d.vertex_list = d.batch.add(
bufferlength*3, gl.GL_TRIANGLES, group,
("v2i/stream", [0]*bufferlength*6),
("c4B/stream", [0]*bufferlength*12)
)
d.triangles = [t.clone() for t in self.triangles]
d.refresh_batch()
return d
def mutate(self, num_mutations):
triangles = self.triangles
for i in xrange(0, num_mutations):
e = randint(0,2)
if e == 0:
choice = randint(0, len(triangles)-1)
triangles[choice].recolor_self_delta(5)
self.update_index(choice)
elif e == 1:
choice = randint(0, len(triangles)-1)
triangles[choice].reshape_delta(self.width, self.height, 25)
self.update_index(choice)
elif e == 2:
c1 = randint(0, len(triangles)-1)
c2 = clamp(c1 + randint(-5,5), 0, len(triangles)-1)
triangles[c1],triangles[c2] = triangles[c2],triangles[c1]
self.update_index(c1)
self.update_index(c2)
def update_index(self, i):
vl = self.vertex_list
t = self.triangles[i]
i1 = i*6
vl.vertices[i1:i1+6] = t.serialize_points()
i1 *= 2
vl.colors[i1:i1+12] = t.serialize_color()*3
def draw(self):
gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, self.fb)
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
self.batch.draw()
def refresh_batch(self):
for i in xrange(0, len(self.triangles)):
self.update_index(i)
def generate(self, number_triangles):
vertices = []
colors = []
for i in xrange(0, number_triangles):
t = Triangle()
t.generate(self.width, self.height)
self.triangles.append(t)
vertices.extend(t.serialize_points())
colors.extend(t.serialize_color()*3)
self.vertex_list = self.batch.add(
number_triangles*3, gl.GL_TRIANGLES, None,
("v2i/stream", vertices),
("c4B/stream", colors)
)
self.refresh_batch()
def svg_import(self, svg_file):
"""
Import the drawing from an SVG file.
"""
xml = open(svg_file).read()
soup = BeautifulStoneSoup(xml).svg
# Width and Height
w = int(soup['width'].replace('px', ''))
h = int(soup['height'].replace('px', ''))
if w != self.width or h != self.height:
raise Exception("Image dimensions don't match.")
# two clockwise round triangles make a square
self.bg.vertices = [ 0,0,
0,h,
w,h,
#.........这里部分代码省略.........