code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
#!/usr/bin/python
# $Id:$
from pyglet.text import runlist
import unittest
__noninteractive = True
class TestStyleRuns(unittest.TestCase):
def check_value(self, runs, value):
for i, style in enumerate(value):
self.assertTrue(runs[i] == style, repr(runs.runs))
self.check_optimal(runs)
self.check_continuous(runs)
self.check_iter(runs, value)
self.check_iter_range(runs, value)
def check_optimal(self, runs):
last_style = None
for _, _, style in runs:
self.assertTrue(style != last_style)
last_style = style
def check_continuous(self, runs):
next_start = 0
for start, end, _ in runs:
self.assertTrue(start == next_start)
next_start = end
def check_iter(self, runs, value):
for start, end, style in runs:
for v in value[start:end]:
self.assertTrue(v == style)
def check_iter_range(self, runs, value):
for interval in range(1, len(value)):
it = runs.get_run_iterator()
for start in range(0, len(value), interval):
end = min(start + interval, len(value))
for s, e, style in it.ranges(start, end):
for v in value[s:e]:
self.assertTrue(v == style, (start, end, s, e, style))
def check_empty(self, runs, value):
start, end, style = iter(runs).next()
self.assertTrue(start == 0)
self.assertTrue(end == 0)
self.assertTrue(style == value)
def test_zero(self):
runs = runlist.RunList(0, 'x')
it = iter(runs)
start, end, s = it.next()
self.assertTrue(start == 0)
self.assertTrue(end == 0)
self.assertTrue(s == 'x')
self.assertRaises(StopIteration, it.next)
self.check_optimal(runs)
def test_initial(self):
runs = runlist.RunList(10, 'x')
it = iter(runs)
start, end, s = it.next()
self.assertTrue(start == 0)
self.assertTrue(end == 10)
self.assertTrue(s == 'x')
self.assertRaises(StopIteration, it.next)
self.check_value(runs, 'x' * 10)
def test_set1(self):
runs = runlist.RunList(10, 'a')
runs.set_run(2, 8, 'b')
self.check_value(runs, 'aabbbbbbaa')
def test_set1_start(self):
runs = runlist.RunList(10, 'a')
runs.set_run(0, 5, 'b')
self.check_value(runs, 'bbbbbaaaaa')
def test_set1_end(self):
runs = runlist.RunList(10, 'a')
runs.set_run(5, 10, 'b')
self.check_value(runs, 'aaaaabbbbb')
def test_set1_all(self):
runs = runlist.RunList(10, 'a')
runs.set_run(0, 10, 'b')
self.check_value(runs, 'bbbbbbbbbb')
def test_set1_1(self):
runs = runlist.RunList(10, 'a')
runs.set_run(1, 2, 'b')
self.check_value(runs, 'abaaaaaaaa')
def test_set_overlapped(self):
runs = runlist.RunList(10, 'a')
runs.set_run(0, 5, 'b')
self.check_value(runs, 'bbbbbaaaaa')
runs.set_run(5, 10, 'c')
self.check_value(runs, 'bbbbbccccc')
runs.set_run(3, 7, 'd')
self.check_value(runs, 'bbbddddccc')
runs.set_run(4, 6, 'e')
self.check_value(runs, 'bbbdeedccc')
runs.set_run(5, 9, 'f')
self.check_value(runs, 'bbbdeffffc')
runs.set_run(2, 3, 'g')
self.check_value(runs, 'bbgdeffffc')
runs.set_run(1, 3, 'h')
self.check_value(runs, 'bhhdeffffc')
runs.set_run(1, 9, 'i')
self.check_value(runs, 'biiiiiiiic')
runs.set_run(0, 10, 'j')
self.check_value(runs, 'jjjjjjjjjj')
def test_insert_empty(self):
runs = runlist.RunList(0, 'a')
runs.insert(0, 10)
self.check_value(runs, 'aaaaaaaaaa')
def test_insert_beginning(self):
runs = runlist.RunList(5, 'a')
runs.set_run(1, 4, 'b')
self.check_value(runs, 'abbba')
runs.insert(0, 3)
self.check_value(runs, 'aaaabbba')
def test_insert_beginning_1(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'a')
self.check_value(runs, 'aaaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'a')
self.check_value(runs, 'aaaaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'a')
self.check_value(runs, 'aaaaaaaa')
def test_insert_beginning_2(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'b')
self.check_value(runs, 'baaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'c')
self.check_value(runs, 'cbaaaaa')
runs.insert(0, 1)
runs.set_run(0, 1, 'c')
self.check_value(runs, 'ccbaaaaa')
def test_insert_1(self):
runs = runlist.RunList(5, 'a')
runs.set_run(1, 4, 'b')
self.check_value(runs, 'abbba')
runs.insert(1, 3)
self.check_value(runs, 'aaaabbba')
def test_insert_2(self):
runs = runlist.RunList(5, 'a')
runs.set_run(1, 2, 'b')
self.check_value(runs, 'abaaa')
runs.insert(2, 3)
self.check_value(runs, 'abbbbaaa')
def test_insert_end(self):
runs = runlist.RunList(5, 'a')
runs.set_run(4, 5, 'b')
self.check_value(runs, 'aaaab')
runs.insert(5, 3)
self.check_value(runs, 'aaaabbbb')
def test_insert_almost_end(self):
runs = runlist.RunList(5, 'a')
runs.set_run(0, 3, 'b')
runs.set_run(4, 5, 'c')
self.check_value(runs, 'bbbac')
runs.insert(4, 3)
self.check_value(runs, 'bbbaaaac')
def test_delete_1_beginning(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.delete(0, 3)
self.check_value(runs, 'aa')
def test_delete_1_middle(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.delete(1, 4)
self.check_value(runs, 'aa')
def test_delete_1_end(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.delete(2, 5)
self.check_value(runs, 'aa')
def test_delete_1_all(self):
runs = runlist.RunList(5, 'a')
self.check_value(runs, 'aaaaa')
runs.delete(0, 5)
self.check_value(runs, '')
self.check_empty(runs, 'a')
def create_runs1(self):
runs = runlist.RunList(10, 'a')
runs.set_run(1, 10, 'b')
runs.set_run(2, 10, 'c')
runs.set_run(3, 10, 'd')
runs.set_run(4, 10, 'e')
runs.set_run(5, 10, 'f')
runs.set_run(6, 10, 'g')
runs.set_run(7, 10, 'h')
runs.set_run(8, 10, 'i')
runs.set_run(9, 10, 'j')
self.check_value(runs, 'abcdefghij')
return runs
def create_runs2(self):
runs = runlist.RunList(10, 'a')
runs.set_run(4, 7, 'b')
runs.set_run(7, 10, 'c')
self.check_value(runs, 'aaaabbbccc')
return runs
def test_delete2(self):
runs = self.create_runs1()
runs.delete(0, 5)
self.check_value(runs, 'fghij')
def test_delete3(self):
runs = self.create_runs1()
runs.delete(2, 8)
self.check_value(runs, 'abij')
def test_delete4(self):
runs = self.create_runs2()
runs.delete(0, 5)
self.check_value(runs, 'bbccc')
def test_delete5(self):
runs = self.create_runs2()
runs.delete(5, 10)
self.check_value(runs, 'aaaab')
def test_delete6(self):
runs = self.create_runs2()
runs.delete(0, 8)
self.check_value(runs, 'cc')
def test_delete7(self):
runs = self.create_runs2()
runs.delete(2, 10)
self.check_value(runs, 'aa')
def test_delete8(self):
runs = self.create_runs2()
runs.delete(3, 8)
self.check_value(runs, 'aaacc')
def test_delete9(self):
runs = self.create_runs2()
runs.delete(7, 8)
self.check_value(runs, 'aaaabbbcc')
def test_delete10(self):
runs = self.create_runs2()
runs.delete(8, 9)
self.check_value(runs, 'aaaabbbcc')
def test_delete11(self):
runs = self.create_runs2()
runs.delete(9, 10)
self.check_value(runs, 'aaaabbbcc')
def test_delete12(self):
runs = self.create_runs2()
runs.delete(4, 5)
self.check_value(runs, 'aaaabbccc')
def test_delete13(self):
runs = self.create_runs2()
runs.delete(5, 6)
self.check_value(runs, 'aaaabbccc')
def test_delete14(self):
runs = self.create_runs2()
runs.delete(6, 7)
self.check_value(runs, 'aaaabbccc')
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that an empty document doesn't break, even when its
(nonexistent) text is set to bold.
'''
__docformat__ = 'restructuredtext'
__noninteractive = True
import unittest
from pyglet import gl
from pyglet import graphics
from pyglet.text import document
from pyglet.text import layout
from pyglet import window
class TestWindow(window.Window):
def __init__(self, doctype, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = doctype()
self.layout = layout.IncrementalTextLayout(self.document,
self.width, self.height, batch=self.batch)
self.document.set_style(0, len(self.document.text), {"bold": True})
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
class TestCase(unittest.TestCase):
def testUnformatted(self):
self.window = TestWindow(document.UnformattedDocument)
self.window.dispatch_events()
self.window.close()
def testFormatted(self):
self.window = TestWindow(document.FormattedDocument)
self.window.dispatch_events()
self.window.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that an empty document doesn't break.
'''
__docformat__ = 'restructuredtext'
__noninteractive = True
import unittest
from pyglet import gl
from pyglet import graphics
from pyglet.text import document
from pyglet.text import layout
from pyglet import window
class TestWindow(window.Window):
def __init__(self, doctype, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = doctype()
self.layout = layout.IncrementalTextLayout(self.document,
self.width, self.height, batch=self.batch)
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
class TestCase(unittest.TestCase):
def testUnformatted(self):
self.window = TestWindow(document.UnformattedDocument)
self.window.dispatch_events()
self.window.close()
def testFormatted(self):
self.window = TestWindow(document.FormattedDocument)
self.window.dispatch_events()
self.window.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that character and paragraph-level style is adhered to correctly in
incremental layout.
Examine and type over the text in the window that appears. The window
contents can be scrolled with the mouse wheel. There are no formatting
commands, however formatting should be preserved as expected when entering or
replacing text and resizing the window.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from pyglet import app
from pyglet import gl
from pyglet import graphics
from pyglet import text
from pyglet.text import caret
from pyglet.text import layout
from pyglet import window
from pyglet.window import key, mouse
doctext = '''STYLE.py test document.
{font_size 24}This is 24pt text.{font_size 12}
This is 12pt text (as is everything that follows).
This text has some {bold True}bold character style{bold False}, some
{italic True}italic character style{italic False}, some {underline [0, 0, 0,
255]}underlined text{underline None}, {underline [255, 0, 0, 255]}underline
in red{underline None}, a {color [255, 0, 0, 255]}change {color [0, 255, 0,
255]}in {color [0, 0, 255, 255]}color{color None}, and in
{background_color [255, 255, 0, 255]}background
{background_color [0, 255, 255, 255]}color{background_color None}.
{kerning '2pt'}This sentence has 2pt kerning.{kerning 0}
{kerning '-1pt'}This sentence has negative 1pt kerning.{kerning 0}
Superscript is emulated by setting a positive baseline offset and reducing the
font size, as in
a{font_size 9}{baseline '4pt'}2{font_size None}{baseline 0} +
b{font_size 9}{baseline '4pt'}2{font_size None}{baseline 0} =
c{font_size 9}{baseline '4pt'}2{font_size None}{baseline 0}.
Subscript is similarly emulated with a negative baseline offset, as in
H{font_size 9}{baseline '-3pt'}2{font_size None}{baseline 0}O.
This paragraph uses {font_name 'Courier New'}Courier New{font_name None} and
{font_name 'Times New Roman'}Times New Roman{font_name None} fonts.
{.leading '5pt'}This paragraph has 5pts leading. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
{.leading None}{.line_spacing '12pt'}This paragraph has constant line spacing of
12pt. When an {font_size 18}18pt font is used{font_size None}, the text
overlaps and the baselines stay equally spaced. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, {font_size 18}sed do eiusmod tempor incididunt
ut labore et dolore{font_size None} magna aliqua.
{.line_spacing None}{.indent '20pt'}This paragraph has a 20pt indent. Lorem
ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.
{.indent None}{.tab_stops [300, 500]}Tablated data:{#x09}Player{#x09}Score{}
{#x09}Alice{#x09}30,000{}
{#x09}Bob{#x09}20,000{}
{#x09}Candice{#x09}10,000{}
{#x09}David{#x09}500
{.indent None}{.align 'right'}This paragraph is right aligned. Lorem ipsum
dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
{.align 'center'}This paragraph is centered. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
{.align 'left'}{.margin_left 50}This paragraph has a 50 pixel left margin.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
{.margin_left 0}{.margin_right '50px'}This paragraph has a 50 pixel right
margin. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
{.margin_left 200}{.margin_right 200}This paragraph has 200 pixel left and
right margins. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
{.align 'right'}{.margin_left 100}{.margin_right 100}This paragraph is
right-aligned, and has 100 pixel left and right margins. Lorem ipsum dolor sit
amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
{.align 'center'}{.margin_left 100}{.margin_right 100}This paragraph is
centered, and has 100 pixel left and right margins. Lorem ipsum dolor sit
amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
{.align 'left'}{.margin_left 0}{.margin_right 0}{.wrap False}This paragraph
does not word-wrap. Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
{.align 'left'}{.margin_left 0}{.margin_right 0}{.wrap 'char'}This paragraph
has character-level wrapping. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
{.wrap True}{.margin_bottom 15}This and the following two paragraphs have a 15
pixel vertical margin separating them. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat.{}
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.{}
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.{}
{.margin_bottom 0}{.margin_top 30}This and the following two paragraphs have
a 30 pixel vertical margin (this time, the top margin is used instead of the
bottom margin). There is a 45 pixel margin between this paragraph and the
previous one.{}
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.{}
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.{}
'''
class TestWindow(window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = text.decode_attributed(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that inline elements can have their style changed, even after text
has been deleted before them. [This triggers bug 538 if it has not yet been fixed.]
To run the test, delete the first line, one character at a time,
verifying that the element remains visible and no tracebacks are
printed to the console.
Press ESC to end the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import pyglet
from pyglet.text import caret, document, layout
doctext = '''ELEMENT.py test document.
PLACE CURSOR AT THE END OF THE ABOVE LINE, AND DELETE ALL ITS TEXT,
BY PRESSING THE DELETE KEY REPEATEDLY.
IF THIS WORKS OK, AND THE ELEMENT (GRAY RECTANGLE) WITHIN THIS LINE
[element here]
REMAINS VISIBLE BETWEEN THE SAME CHARACTERS, WITH NO ASSERTIONS PRINTED TO
THE CONSOLE, THE TEST PASSES.
(In code with bug 538, the element sometimes moves within the text, and
eventually there is an assertion failure. Note that there is another bug,
unrelated to this one, which sometimes causes the first press of the delete
key to be ignored.)
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce venenatis
pharetra libero. Phasellus lacinia nisi feugiat felis. Sed id magna in nisl
cursus consectetuer. Aliquam aliquam lectus eu magna. Praesent sit amet ipsum
vitae nisl mattis commodo. Aenean pulvinar facilisis lectus. Phasellus sodales
risus sit amet lectus. Suspendisse in turpis. Vestibulum ac mi accumsan eros
commodo tincidunt. Nullam velit. In pulvinar, dui sit amet ullamcorper dictum,
dui risus ultricies nisl, a dignissim sapien enim sit amet tortor.
Pellentesque fringilla, massa sit amet bibendum blandit, pede leo commodo mi,
eleifend feugiat neque tortor dapibus mauris. Morbi nunc arcu, tincidunt vel,
blandit non, iaculis vel, libero. Vestibulum sed metus vel velit scelerisque
varius. Vivamus a tellus. Proin nec orci vel elit molestie venenatis. Aenean
fringilla, lorem vel fringilla bibendum, nibh mi varius mi, eget semper ipsum
ligula ut urna. Nullam tempor convallis augue. Sed at dui.
'''
element_index = doctext.index('[element here]')
doctext = doctext.replace('[element here]', '')
class TestElement(document.InlineElement):
vertex_list = None
def place(self, layout, x, y):
## assert layout.document.text[self._position] == '\x00'
### in bug 538, this fails after two characters are deleted.
self.vertex_list = layout.batch.add(4, pyglet.gl.GL_QUADS,
layout.top_group,
'v2i',
('c4B', [200, 200, 200, 255] * 4))
y += self.descent
w = self.advance
h = self.ascent - self.descent
self.vertex_list.vertices[:] = (x, y,
x + w, y,
x + w, y + h,
x, y + h)
def remove(self, layout):
self.vertex_list.delete()
del self.vertex_list
class TestWindow(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = pyglet.graphics.Batch()
self.document = pyglet.text.decode_attributed(doctext)
for i in [element_index]:
self.document.insert_element(i, TestElement(60, -10, 70))
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_draw(self):
pyglet.gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == pyglet.window.key.TAB:
self.caret.on_text('\t')
self.document.set_style(0, len(self.document.text), dict(bold = None)) ### trigger bug 538
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(##resizable=True,
visible=False)
self.window.set_visible()
pyglet.app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test content_valign = 'center' property of IncrementalTextLayout.
Examine and type over the text in the window that appears. The window
contents can be scrolled with the mouse wheel. When the content height
is less than the window height, the content should be aligned to the center
of the window.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: STYLE.py 1754 2008-02-10 13:26:52Z Alex.Holkner $'
import unittest
from pyglet import app
from pyglet import gl
from pyglet import graphics
from pyglet import text
from pyglet.text import caret
from pyglet.text import layout
from pyglet import window
from pyglet.window import key, mouse
doctext = '''CONTENT_VALIGN_CENTER.py test document.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas aliquet quam sit amet enim. Donec iaculis, magna vitae imperdiet convallis, lectus sem ultricies nulla, non fringilla quam felis tempus velit. Etiam et velit. Integer euismod. Aliquam a diam. Donec sed ante. Mauris enim pede, dapibus sed, dapibus vitae, consectetuer in, est. Donec aliquam risus eu ipsum. Integer et tortor. Ut accumsan risus sed ante.
Aliquam dignissim, massa a imperdiet fermentum, orci dolor facilisis ante, ut vulputate nisi nunc sed massa. Morbi sodales hendrerit tortor. Nunc id tortor ut lacus mollis malesuada. Sed nibh tellus, rhoncus et, egestas eu, laoreet eu, urna. Vestibulum massa leo, convallis et, pharetra vitae, iaculis at, ante. Pellentesque volutpat porta enim. Morbi ac nunc eget mi pretium viverra. Pellentesque felis risus, lobortis vitae, malesuada vitae, bibendum eu, tortor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus dapibus tortor ac neque. Curabitur pulvinar bibendum lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla turpis leo, rhoncus vel, euismod non, consequat sed, massa. Quisque ultricies. Aliquam fringilla faucibus est. Proin nec felis eget felis suscipit vehicula.
Etiam quam. Aliquam at ligula. Aenean quis dolor. Suspendisse potenti. Sed lacinia leo eu est. Nam pede ligula, molestie nec, tincidunt vel, posuere in, tellus. Donec fringilla dictum dolor. Aenean tellus orci, viverra id, vehicula eget, tempor a, dui. Morbi eu dolor nec lacus fringilla dapibus. Nulla facilisi. Nulla posuere. Nunc interdum. Donec convallis libero vitae odio.
Aenean metus lectus, faucibus in, malesuada at, fringilla nec, risus. Integer enim. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin bibendum felis vel neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ipsum dui, euismod at, dictum eu, congue tincidunt, urna. Sed quis odio. Integer aliquam pretium augue. Vivamus nonummy, dolor vel viverra rutrum, lacus dui congue pede, vel sodales dui diam nec libero. Morbi et leo sit amet quam sollicitudin laoreet. Vivamus suscipit.
Duis arcu eros, iaculis ut, vehicula in, elementum a, sapien. Phasellus ut tellus. Integer feugiat nunc eget odio. Morbi accumsan nonummy ipsum. Donec condimentum, tortor non faucibus luctus, neque mi mollis magna, nec gravida risus elit nec ipsum. Donec nec sem. Maecenas varius libero quis diam. Curabitur pulvinar. Morbi at sem eget mauris tempor vulputate. Aenean eget turpis.
'''
class TestWindow(window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = text.decode_text(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.layout.content_valign = 'center'
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
app.run()
if __name__ == '__main__':
unittest.main()
| Python |
import unittest
from pyglet.text.formats.attributed import AttributedTextDecoder
class AttributedTextDecoderTests(unittest.TestCase):
__noninteractive = True
def testOneNewlineBecomesSpace(self):
doc = AttributedTextDecoder().decode('one\ntwo')
self.assertEqual(u'one two', doc.text)
def testTwoNewlinesBecomesParagraph(self):
from pyglet.text.formats.attributed import AttributedTextDecoder
doc = AttributedTextDecoder().decode('one\n\ntwo')
self.assertEqual(u'one\ntwo', doc.text)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test an unformatted document is editable.
Examine and type over the text in the window that appears. The window
contents can be scrolled with the mouse wheel.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: STYLE.py 1754 2008-02-10 13:26:52Z Alex.Holkner $'
import unittest
from pyglet import app
from pyglet import gl
from pyglet import graphics
from pyglet import text
from pyglet.text import caret
from pyglet.text import layout
from pyglet import window
from pyglet.window import key, mouse
doctext = '''PLAIN.py test document.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas aliquet quam sit amet enim. Donec iaculis, magna vitae imperdiet convallis, lectus sem ultricies nulla, non fringilla quam felis tempus velit. Etiam et velit. Integer euismod. Aliquam a diam. Donec sed ante. Mauris enim pede, dapibus sed, dapibus vitae, consectetuer in, est. Donec aliquam risus eu ipsum. Integer et tortor. Ut accumsan risus sed ante.
Aliquam dignissim, massa a imperdiet fermentum, orci dolor facilisis ante, ut vulputate nisi nunc sed massa. Morbi sodales hendrerit tortor. Nunc id tortor ut lacus mollis malesuada. Sed nibh tellus, rhoncus et, egestas eu, laoreet eu, urna. Vestibulum massa leo, convallis et, pharetra vitae, iaculis at, ante. Pellentesque volutpat porta enim. Morbi ac nunc eget mi pretium viverra. Pellentesque felis risus, lobortis vitae, malesuada vitae, bibendum eu, tortor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus dapibus tortor ac neque. Curabitur pulvinar bibendum lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla turpis leo, rhoncus vel, euismod non, consequat sed, massa. Quisque ultricies. Aliquam fringilla faucibus est. Proin nec felis eget felis suscipit vehicula.
Etiam quam. Aliquam at ligula. Aenean quis dolor. Suspendisse potenti. Sed lacinia leo eu est. Nam pede ligula, molestie nec, tincidunt vel, posuere in, tellus. Donec fringilla dictum dolor. Aenean tellus orci, viverra id, vehicula eget, tempor a, dui. Morbi eu dolor nec lacus fringilla dapibus. Nulla facilisi. Nulla posuere. Nunc interdum. Donec convallis libero vitae odio.
Aenean metus lectus, faucibus in, malesuada at, fringilla nec, risus. Integer enim. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin bibendum felis vel neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ipsum dui, euismod at, dictum eu, congue tincidunt, urna. Sed quis odio. Integer aliquam pretium augue. Vivamus nonummy, dolor vel viverra rutrum, lacus dui congue pede, vel sodales dui diam nec libero. Morbi et leo sit amet quam sollicitudin laoreet. Vivamus suscipit.
Duis arcu eros, iaculis ut, vehicula in, elementum a, sapien. Phasellus ut tellus. Integer feugiat nunc eget odio. Morbi accumsan nonummy ipsum. Donec condimentum, tortor non faucibus luctus, neque mi mollis magna, nec gravida risus elit nec ipsum. Donec nec sem. Maecenas varius libero quis diam. Curabitur pulvinar. Morbi at sem eget mauris tempor vulputate. Aenean eget turpis.
'''
class TestWindow(window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = text.decode_text(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that the code snippets mentioned in issue 471
(and related issues 241 and 429) don't have exceptions.
(Most of them delete all text in a formatted document
with some styles set; one of them (like the test in EMPTY_BOLD.py)
sets style on a 0-length range of text in an empty document.)
'''
__docformat__ = 'restructuredtext'
__noninteractive = True
import unittest
import pyglet
class TestCase(unittest.TestCase):
def test_issue471(self):
doc = pyglet.text.document.FormattedDocument()
layout = pyglet.text.layout.IncrementalTextLayout(doc, 100, 100)
doc.insert_text(0, "hello", {'bold': True})
doc.text = ""
def test_issue471_comment2(self):
doc2 = pyglet.text.decode_attributed('{bold True}a')
layout = pyglet.text.layout.IncrementalTextLayout(doc2, 100, 10)
layout.document.delete_text(0, len(layout.document.text))
def test_issue241_comment4a(self):
document = pyglet.text.document.FormattedDocument("")
layout = pyglet.text.layout.IncrementalTextLayout(document, 50, 50)
document.set_style(0, len(document.text), {"font_name": "Arial"})
def test_issue241_comment4b(self):
document = pyglet.text.document.FormattedDocument("test")
layout = pyglet.text.layout.IncrementalTextLayout(document, 50, 50)
document.set_style(0, len(document.text), {"font_name": "Arial"})
document.delete_text(0, len(document.text))
def test_issue241_comment5(self):
document = pyglet.text.document.FormattedDocument('A')
document.set_style(0, 1, dict(bold=True))
layout = pyglet.text.layout.IncrementalTextLayout(document,100,100)
document.delete_text(0,1)
def test_issue429_comment4a(self):
doc = pyglet.text.decode_attributed('{bold True}Hello{bold False}\n\n\n\n')
doc2 = pyglet.text.decode_attributed('{bold True}Goodbye{bold False}\n\n\n\n')
layout = pyglet.text.layout.IncrementalTextLayout(doc, 100, 10)
layout.document = doc2
layout.document.delete_text(0, len(layout.document.text))
def test_issue429_comment4b(self):
doc2 = pyglet.text.decode_attributed('{bold True}a{bold False}b')
layout = pyglet.text.layout.IncrementalTextLayout(doc2, 100, 10)
layout.document.delete_text(0, len(layout.document.text))
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test content_valign = 'bottom' property of IncrementalTextLayout.
Examine and type over the text in the window that appears. The window
contents can be scrolled with the mouse wheel. When the content height
is less than the window height, the content should be aligned to the bottom
of the window.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: STYLE.py 1754 2008-02-10 13:26:52Z Alex.Holkner $'
import unittest
from pyglet import app
from pyglet import gl
from pyglet import graphics
from pyglet import text
from pyglet.text import caret
from pyglet.text import layout
from pyglet import window
from pyglet.window import key, mouse
doctext = '''CONTENT_VALIGN_BOTTOM.py test document.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas aliquet quam sit amet enim. Donec iaculis, magna vitae imperdiet convallis, lectus sem ultricies nulla, non fringilla quam felis tempus velit. Etiam et velit. Integer euismod. Aliquam a diam. Donec sed ante. Mauris enim pede, dapibus sed, dapibus vitae, consectetuer in, est. Donec aliquam risus eu ipsum. Integer et tortor. Ut accumsan risus sed ante.
Aliquam dignissim, massa a imperdiet fermentum, orci dolor facilisis ante, ut vulputate nisi nunc sed massa. Morbi sodales hendrerit tortor. Nunc id tortor ut lacus mollis malesuada. Sed nibh tellus, rhoncus et, egestas eu, laoreet eu, urna. Vestibulum massa leo, convallis et, pharetra vitae, iaculis at, ante. Pellentesque volutpat porta enim. Morbi ac nunc eget mi pretium viverra. Pellentesque felis risus, lobortis vitae, malesuada vitae, bibendum eu, tortor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus dapibus tortor ac neque. Curabitur pulvinar bibendum lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla turpis leo, rhoncus vel, euismod non, consequat sed, massa. Quisque ultricies. Aliquam fringilla faucibus est. Proin nec felis eget felis suscipit vehicula.
Etiam quam. Aliquam at ligula. Aenean quis dolor. Suspendisse potenti. Sed lacinia leo eu est. Nam pede ligula, molestie nec, tincidunt vel, posuere in, tellus. Donec fringilla dictum dolor. Aenean tellus orci, viverra id, vehicula eget, tempor a, dui. Morbi eu dolor nec lacus fringilla dapibus. Nulla facilisi. Nulla posuere. Nunc interdum. Donec convallis libero vitae odio.
Aenean metus lectus, faucibus in, malesuada at, fringilla nec, risus. Integer enim. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin bibendum felis vel neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ipsum dui, euismod at, dictum eu, congue tincidunt, urna. Sed quis odio. Integer aliquam pretium augue. Vivamus nonummy, dolor vel viverra rutrum, lacus dui congue pede, vel sodales dui diam nec libero. Morbi et leo sit amet quam sollicitudin laoreet. Vivamus suscipit.
Duis arcu eros, iaculis ut, vehicula in, elementum a, sapien. Phasellus ut tellus. Integer feugiat nunc eget odio. Morbi accumsan nonummy ipsum. Donec condimentum, tortor non faucibus luctus, neque mi mollis magna, nec gravida risus elit nec ipsum. Donec nec sem. Maecenas varius libero quis diam. Curabitur pulvinar. Morbi at sem eget mauris tempor vulputate. Aenean eget turpis.
'''
class TestWindow(window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = graphics.Batch()
self.document = text.decode_text(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.layout.content_valign = 'bottom'
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that HTML data is decoded into a formatted document.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: ELEMENT.py 1764 2008-02-16 05:24:46Z Alex.Holkner $'
import unittest
import pyglet
from pyglet.text import caret, document, layout
doctext = '''
<html>
<head>
(metadata including title is not displayed.)
<title>Test document</title>
</head>
<body>
<h1>HTML test document</h1>
<p>Several paragraphs of HTML formatted text follow. Ensure they are
formatted as they are described. Here is a copyright symbol: © and
again, using hexadecimal ref: ©.</p>
<P>This paragraph has some <b>bold</b> and <i>italic</i> and <b><i>bold
italic</b> text. <!-- i tag does not need to be closed -->
<p>This paragraph has some <em>emphasis</em> and <strong>strong</strong>
and <em><strong>emphatic strong</em> text.
<p>This paragraph demonstrates superscript: a<sup>2</sup> + b<sup>2</sup>
= c<sup>2</sup>; and subscript: H<sub>2</sub>O.
<p>This paragraph uses the <font> element:
<font face="Courier New">Courier New</font>, <font size=1>size 1</font>,
<font size=2>size 2</font>, <font size=3>size 3</font>, <font size=4>size
4</font>, <font size=5>size 5</font>, <font size=6>size 6</font>, <font
size=7>size 7</font>.
<p>This paragraph uses relative sizes: <font size=5>size 5<font
size=-2>size 3</font><!--<font size=+1>size 6</font>--></font>
<p>Font color changes to <font color=red>red</font>, <font
color=green>green</font> and <font color=#0f0fff>pastel blue using a
hexidecimal number</font>.
<p><u>This text is underlined</u>. <font color=green><u>This text is
underlined and green.</u></font>
<h1>Heading 1
<h2>Heading 2
<h3>Heading 3
<h4>Heading 4
<h5>Heading 5
<h6>Heading 6
<p align=center>Centered paragraph.
<p align=right>Right-aligned paragraph.
<div><div> element instead of paragraph.
<div>This sentence should start a new paragraph, as the div is nested.
</div>
This sentence should start a new paragraph, as the nested div was
closed.
</div>
<pre>This text is preformatted.
Hard line breaks
Indentation. <b>Inline formatting</b> is still ok.</pre>
<p>This paragraph<br>
has a<br>
line break<br>
after every<br>
two words.</p>
<blockquote>This paragraph is blockquote. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
<blockquote>Nested blockquote. Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.</blockquote>
</blockquote>
Here is a quotation. The previous paragraph mentioned, <q>Lorem ipsum
dolor sit amet, ...</q>.
<ul>
<li>
Unordered list, level 1. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
<li>
Item 2. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
<li>
Item 3. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
<ul>
<li>
A nested list. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat.
<li>
Item 3.2. Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua.
</ul>
</ul>
<ul type="circle">
<li>Unordered list with circle bullets.
<li>Item 2.
</ul>
<ul type="square">
<li>Unordered list with square bullets.
<li>Item 2.
</ul>
<ol>
<li>Numbered list.
<li>Item 2.
<li>Item 3.
<li value=10>Item 10
<li>Item 11
</ol>
<ol start=12>
<li>Numbered list starting at 12.
<li>Item 13.
</ol>
<ol type="a">
<li>Numbered list with "a" type
<li>Item 2
<li>Item 3
</ol>
<ol type="A">
<li>Numbered list with "A" type
<li>Item 2
<li>Item 3
</ol>
<ol type="i">
<li>Numbered list with "i" type
<li>Item 2
<li>Item 3
</ol>
<ol type="I">
<li>Numbered list with "I" type
<li>Item 2
<li>Item 3
</ol>
Here's a definition list:
<dl>
<dt>Term</dt>
<dd>Definition.</dd>
<dt>Term</dt>
<dd>Definition.</dd>
<dt>Term</dt>
<dd>Definition.</dd>
</dl>
</body>
</html>
'''
class TestWindow(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = pyglet.graphics.Batch()
self.document = pyglet.text.decode_html(doctext)
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
pyglet.gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == pyglet.window.key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
pyglet.app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that inline elements are positioned correctly and are repositioned
within an incremental layout.
Examine and type over the text in the window that appears. There are several
elements drawn with grey boxes. These should maintain their sizes and
relative document positions as the text is scrolled and edited.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import pyglet
from pyglet.text import caret, document, layout
doctext = '''ELEMENT.py test document.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce venenatis
pharetra libero. Phasellus lacinia nisi feugiat felis. Sed id magna in nisl
cursus consectetuer. Aliquam aliquam lectus eu magna. Praesent sit amet ipsum
vitae nisl mattis commodo. Aenean pulvinar facilisis lectus. Phasellus sodales
risus sit amet lectus. Suspendisse in turpis. Vestibulum ac mi accumsan eros
commodo tincidunt. Nullam velit. In pulvinar, dui sit amet ullamcorper dictum,
dui risus ultricies nisl, a dignissim sapien enim sit amet tortor.
Pellentesque fringilla, massa sit amet bibendum blandit, pede leo commodo mi,
eleifend feugiat neque tortor dapibus mauris. Morbi nunc arcu, tincidunt vel,
blandit non, iaculis vel, libero. Vestibulum sed metus vel velit scelerisque
varius. Vivamus a tellus. Proin nec orci vel elit molestie venenatis. Aenean
fringilla, lorem vel fringilla bibendum, nibh mi varius mi, eget semper ipsum
ligula ut urna. Nullam tempor convallis augue. Sed at dui.
Nunc faucibus pretium ipsum. Sed ultricies ligula a arcu. Pellentesque vel
urna in augue euismod hendrerit. Donec consequat. Morbi convallis nulla at
ante bibendum auctor. In augue mi, tincidunt a, porta ac, tempor sit amet,
sapien. In sollicitudin risus. Vivamus leo turpis, elementum sed, accumsan eu,
scelerisque at, augue. Ut eu tortor non sem vulputate bibendum. Fusce
ultricies ultrices lorem. In hac habitasse platea dictumst. Morbi ac ipsum.
Nam tellus sem, congue in, fermentum a, ullamcorper vel, mauris. Etiam erat
tortor, facilisis ut, blandit id, placerat sed, orci. Donec quam eros,
bibendum eu, ultricies id, mattis eu, tellus. Ut hendrerit erat vel ligula.
Sed tellus. Quisque imperdiet ornare diam.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac
turpis egestas. Sed neque quam, pretium et, malesuada sed, porttitor eu, leo.
Sed varius ornare augue. Maecenas pede dui, nonummy eu, ullamcorper sed,
lobortis id, sem. In sed leo. Nulla ornare. Curabitur dui. Cras ipsum. Cras
massa augue, sodales nec, ultricies at, fermentum in, turpis. Aenean lorem
lectus, fermentum et, lacinia quis, ullamcorper ac, purus. Pellentesque
pharetra diam at elit. Donec dolor. Aenean turpis orci, aliquam vitae,
fermentum et, consectetuer sed, lacus. Maecenas pulvinar, nisi sit amet
lobortis rhoncus, est ipsum ullamcorper mauris, nec cursus felis neque et
dolor. Nulla venenatis sapien vitae lectus. Praesent in risus. In imperdiet
adipiscing nisi. Quisque volutpat, ante sed vehicula sodales, nisi quam
bibendum turpis, id bibendum pede enim porttitor tellus. Aliquam velit.
Pellentesque at mauris quis libero fermentum cursus.
Integer bibendum scelerisque elit. Curabitur justo tellus, vehicula luctus,
consequat vitae, convallis quis, nunc. Fusce libero nulla, convallis eu,
dignissim sit amet, sagittis ac, odio. Morbi dictum tincidunt nisi. Curabitur
hendrerit. Aliquam eleifend sodales leo. Donec interdum. Nam vulputate, purus
in euismod bibendum, pede mi pellentesque dolor, at viverra quam tellus eget
pede. Suspendisse varius mi id felis. Aenean in velit eu nisi suscipit mollis.
Suspendisse vitae augue et diam volutpat luctus.
Mauris et lorem. In mauris. Morbi commodo rutrum nibh. Pellentesque lobortis.
Sed eget urna ut massa venenatis luctus. Morbi egestas purus eget ante
pulvinar vulputate. Suspendisse sollicitudin. Cras tortor erat, semper
vehicula, suscipit non, facilisis ut, est. Aenean quis libero varius nisl
fringilla mollis. Donec viverra. Phasellus mi tortor, pulvinar id, pulvinar
in, lacinia nec, massa. Curabitur lectus erat, volutpat at, volutpat at,
pharetra nec, turpis. Donec ornare nonummy leo. Donec consectetuer posuere
metus. Quisque tincidunt risus facilisis dui. Ut suscipit turpis in massa.
Aliquam erat volutpat.
'''
class TestElement(document.InlineElement):
vertex_list = None
def place(self, layout, x, y):
self.vertex_list = layout.batch.add(4, pyglet.gl.GL_QUADS,
layout.top_group,
'v2i',
('c4B', [200, 200, 200, 255] * 4))
y += self.descent
w = self.advance
h = self.ascent - self.descent
self.vertex_list.vertices[:] = (x, y,
x + w, y,
x + w, y + h,
x, y + h)
def remove(self, layout):
self.vertex_list.delete()
del self.vertex_list
class TestWindow(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(TestWindow, self).__init__(*args, **kwargs)
self.batch = pyglet.graphics.Batch()
self.document = pyglet.text.decode_attributed(doctext)
for i in range(0, len(doctext), 300):
self.document.insert_element(i, TestElement(60, -10, 70))
self.margin = 2
self.layout = layout.IncrementalTextLayout(self.document,
self.width - self.margin * 2, self.height - self.margin * 2,
multiline=True,
batch=self.batch)
self.caret = caret.Caret(self.layout)
self.push_handlers(self.caret)
self.set_mouse_cursor(self.get_system_mouse_cursor('text'))
def on_resize(self, width, height):
super(TestWindow, self).on_resize(width, height)
self.layout.begin_update()
self.layout.x = self.margin
self.layout.y = self.margin
self.layout.width = width - self.margin * 2
self.layout.height = height - self.margin * 2
self.layout.end_update()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
self.layout.view_x -= scroll_x
self.layout.view_y += scroll_y * 16
def on_draw(self):
pyglet.gl.glClearColor(1, 1, 1, 1)
self.clear()
self.batch.draw()
def on_key_press(self, symbol, modifiers):
super(TestWindow, self).on_key_press(symbol, modifiers)
if symbol == pyglet.window.key.TAB:
self.caret.on_text('\t')
class TestCase(unittest.TestCase):
def test(self):
self.window = TestWindow(resizable=True, visible=False)
self.window.set_visible()
pyglet.app.run()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python BMP loader. You should see the rgb_8bpp.bmp
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.bmp import BMPImageDecoder
class TEST_SUITE(base_load.TestLoad):
texture_file = 'rgb_8bpp.bmp'
decoder = BMPImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python PNG loader. You should see the rgb_8bpp_trans.png
image with a hole on it on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.png import PNGImageDecoder
class TEST_PNG_INDEXED_TRANS_LOAD(base_load.TestLoad):
texture_file = 'rgb_8bpp_trans.png'
decoder = PNGImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGBA load using PIL. You should see the rgba.png image on
a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_load
from pyglet.image.codecs.pil import *
class TEST_PIL_RGBA_LOAD(base_load.TestLoad):
texture_file = 'rgba.png'
decoder = PILImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python BMP loader. You should see the rgba_32bpp.bmp
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.bmp import BMPImageDecoder
class TEST_SUITE(base_load.TestLoad):
texture_file = 'rgba_32bpp.bmp'
decoder = BMPImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGB load using PyPNG. You should see the rgb.png image on
a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_load
from pyglet.image.codecs.png import PNGImageDecoder
class TEST_PNG_RGB_LOAD(base_load.TestLoad):
texture_file = 'rgb.png'
decoder = PNGImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Base class for image tests.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
from os.path import dirname, join
from pyglet.gl import *
from pyglet import image
from pyglet.image import codecs
from pyglet.window import *
from pyglet.window.event import *
from pyglet.compat import BytesIO
from tests.regression import ImageRegressionTestCase
class TestSave(ImageRegressionTestCase):
texture_file = None
original_texture = None
saved_texture = None
show_checkerboard = True
alpha = True
has_exit = False
def on_expose(self):
self.draw()
self.window.flip()
if self.capture_regression_image():
self.has_exit = True
def draw(self):
glClearColor(1, 1, 1, 1)
glClear(GL_COLOR_BUFFER_BIT)
glLoadIdentity()
if self.show_checkerboard:
glPushMatrix()
glScalef(self.window.width/float(self.checkerboard.width),
self.window.height/float(self.checkerboard.height),
1.)
glMatrixMode(GL_TEXTURE)
glPushMatrix()
glScalef(self.window.width/float(self.checkerboard.width),
self.window.height/float(self.checkerboard.height),
1.)
glMatrixMode(GL_MODELVIEW)
self.checkerboard.blit(0, 0, 0)
glMatrixMode(GL_TEXTURE)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
glPopMatrix()
self.draw_original()
self.draw_saved()
def draw_original(self):
if self.original_texture:
self.original_texture.blit(
self.window.width / 4 - self.original_texture.width / 2,
(self.window.height - self.original_texture.height) / 2,
0)
def draw_saved(self):
if self.saved_texture:
self.saved_texture.blit(
self.window.width * 3 / 4 - self.saved_texture.width / 2,
(self.window.height - self.saved_texture.height) / 2,
0)
def load_texture(self):
if self.texture_file:
self.texture_file = join(dirname(__file__), self.texture_file)
self.original_texture = image.load(self.texture_file).texture
file = BytesIO()
self.original_texture.save(self.texture_file, file,
encoder=self.encoder)
file.seek(0)
self.saved_texture = image.load(self.texture_file, file).texture
def create_window(self):
width, height = 800, 600
return Window(width, height, visible=False)
def test_save(self):
self.window = w = self.create_window()
w.push_handlers(self)
self.screen = image.get_buffer_manager().get_color_buffer()
self.checkerboard = image.create(32, 32, image.CheckerImagePattern())
self.load_texture()
if self.alpha:
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
w.set_visible()
while not (w.has_exit or self.has_exit):
w.dispatch_events()
w.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python gdkpixbuf2 GIF loader. You should see the 8bpp.gif
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.gdkpixbuf2 import GdkPixbuf2ImageDecoder
class TEST_GIF_LOAD(base_load.TestLoad):
texture_file = '8bpp.gif'
decoder = GdkPixbuf2ImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test rearrangement of color components using the OpenGL color matrix.
The test will be skipped if the GL_ARB_imaging extension is not present.
You should see the RGB test image correctly rendered. Press ESC to
end the test.
'''
from __future__ import print_function
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
import sys
from pyglet.gl import gl_info
class TEST_MATRIX_RGB(base_load.TestLoad):
texture_file = 'rgb.png'
def load_image(self):
if not gl_info.have_extension('GL_ARB_imaging'):
print('GL_ARB_imaging is not present, skipping test.')
self.has_exit = True
else:
# Load image as usual then rearrange components
super(TEST_MATRIX_RGB, self).load_image()
self.image.format = 'GRB'
pixels = self.image.data # forces conversion
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test colour buffer copy to texture.
A scene consisting of a single coloured triangle will be rendered. The
colour buffer will then be saved to a stream and loaded as a texture.
You will see the original scene first for up to several seconds before the
buffer image appears (because retrieving and saving the image is a slow
operation). Messages will be printed to stdout indicating what stage is
occuring.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_save
from pyglet.gl import *
from pyglet import image
class TEST_BUFFER_COPY(base_save.TestSave):
alpha = False
def draw_original(self):
glBegin(GL_TRIANGLES)
glColor4f(1, 0, 0, 1)
glVertex3f(0, 0, -1)
glColor4f(0, 1, 0, 1)
glVertex3f(200, 0, 0)
glColor4f(0, 0, 1, 1)
glVertex3f(0, 200, 1)
glEnd()
glColor4f(1, 1, 1, 1)
def load_texture(self):
print('Drawing scene...')
self.window.set_visible()
self.window.dispatch_events()
self.draw()
print('Copying colour image...')
self.saved_texture = \
image.get_buffer_manager().get_color_buffer().texture
print('Done.')
self.window.set_visible(False)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test LA save using PyPNG. You should see la.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_save
from pyglet.image.codecs.png import PNGImageEncoder
class TEST_PNG_LA_SAVE(base_save.TestSave):
texture_file = 'la.png'
encoder = PNGImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
import sys
def colorbyte(color):
if sys.version.startswith('2'):
return '%c' % color
else:
return bytes((color,))
| Python |
#!/usr/bin/env python
'''Test depth buffer save.
A scene consisting of a single coloured triangle will be rendered. The
depth buffer will then be saved to a stream and loaded as a texture.
You will see the original scene first for up to several seconds before the
depth buffer image appears (because retrieving and saving the image is
a slow operation). Messages will be printed to stdout indicating
what stage is occuring.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_save
from pyglet.gl import *
from pyglet import image
from pyglet.compat import BytesIO
class TEST_DEPTH_SAVE(base_save.TestSave):
alpha = False
def draw_original(self):
glClear(GL_DEPTH_BUFFER_BIT)
glEnable(GL_DEPTH_TEST)
glBegin(GL_TRIANGLES)
glColor4f(1, 0, 0, 1)
glVertex3f(0, 0, -1)
glColor4f(0, 1, 0, 1)
glVertex3f(200, 0, 0)
glColor4f(0, 0, 1, 1)
glVertex3f(0, 200, 1)
glEnd()
glDisable(GL_DEPTH_TEST)
glColor4f(1, 1, 1, 1)
def load_texture(self):
print('Drawing scene...')
self.window.set_visible()
self.window.dispatch_events()
self.draw()
print('Saving depth image...')
img = image.get_buffer_manager().get_depth_buffer()
file = BytesIO()
img.save('buffer.png', file)
print('Loading depth image as texture...')
file.seek(0)
self.saved_texture = image.load('buffer.png', file)
print('Done.')
self.window.set_visible(False)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test DXT5 compressed RGBA load from a DDS file. You should see the
rgba_dxt5.dds image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.dds import DDSImageDecoder
class TEST_DDS_RGBA_DXT5(base_load.TestLoad):
texture_file = 'rgba_dxt5.dds'
decoder = DDSImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python BMP loader. You should see the rgb_16bpp.bmp
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.bmp import BMPImageDecoder
class TEST_SUITE(base_load.TestLoad):
texture_file = 'rgb_16bpp.bmp'
decoder = BMPImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python BMP loader. You should see the rgb_24bpp.bmp
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.bmp import BMPImageDecoder
class TEST_SUITE(base_load.TestLoad):
texture_file = 'rgb_24bpp.bmp'
decoder = BMPImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGBA save using PyPNG. You should see rgba.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_save
from pyglet.image.codecs.png import PNGImageEncoder
class TEST_PNG_RGBA_SAVE(base_save.TestSave):
texture_file = 'rgba.png'
encoder = PNGImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGB save using PIL with no PNG encode available, next available
encoder will be used. You should see rgb.png reference image on the left,
and saved (and reloaded) image on the right. The saved image may have
larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_save
from pyglet.image.codecs import ImageEncoder, ImageEncodeException
from pyglet.image.codecs.png import PNGImageEncoder
from pyglet.image import codecs
class MockPILImageEncoder(ImageEncoder):
"""Just raise an encode exception"""
def encode(self, image, file, filename):
raise ImageEncodeException("Encoder not available")
codecs.get_encoders = lambda filename: [MockPILImageEncoder(), PNGImageEncoder(),]
class TEST_NO_ENCODER_RGB_SAVE(base_save.TestSave):
texture_file = 'rgb.png'
encoder = None
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGBA load using the platform decoder (QuickTime, Quartz, GDI+ or Gdk).
You should see the rgba.png image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_load
from pyglet import compat_platform
if compat_platform.startswith('linux'):
from pyglet.image.codecs.gdkpixbuf2 import GdkPixbuf2ImageDecoder as dclass
elif compat_platform in ('win32', 'cygwin'):
from pyglet.image.codecs.gdiplus import GDIPlusDecoder as dclass
elif compat_platform == 'darwin':
from pyglet import options as pyglet_options
if pyglet_options['darwin_cocoa']:
from pyglet.image.codecs.quartz import QuartzImageDecoder as dclass
else:
from pyglet.image.codecs.quicktime import QuickTimeImageDecoder as dclass
class TEST_PLATFORM_RGBA_LOAD(base_load.TestLoad):
texture_file = 'rgba.png'
decoder = dclass()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python BMP loader. You should see the rgb_32bpp.bmp
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.bmp import BMPImageDecoder
class TEST_SUITE(base_load.TestLoad):
texture_file = 'rgb_32bpp.bmp'
decoder = BMPImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test DXT1 compressed RGB load from a DDS file. You should see the
rgb_dxt1.dds image.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.dds import DDSImageDecoder
class TEST_DDS_RGB_DXT1(base_load.TestLoad):
texture_file = 'rgb_dxt1.dds'
decoder = DDSImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python BMP loader. You should see the rgb_4bpp.bmp
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.bmp import BMPImageDecoder
class TEST_SUITE(base_load.TestLoad):
texture_file = 'rgb_4bpp.bmp'
decoder = BMPImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGBA save using PIL. You should see rgba.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_save
from pyglet.image.codecs.pil import PILImageEncoder
class TEST_PIL_RGBA_SAVE(base_save.TestSave):
texture_file = 'rgba.png'
encoder = PILImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python BMP loader. You should see the rgb_1bpp.bmp
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.bmp import BMPImageDecoder
class TEST_SUITE(base_load.TestLoad):
texture_file = 'rgb_1bpp.bmp'
decoder = BMPImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test LA load using PIL. You should see the la.png image on
a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.pil import *
class TEST_PNG_LA(base_load.TestLoad):
texture_file = 'la.png'
decoder = PILImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Base class for image tests.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
from os.path import dirname, join
from pyglet.gl import *
from pyglet import image
from pyglet.image import codecs
from pyglet.window import *
from pyglet.window.event import *
from tests.regression import ImageRegressionTestCase
class TestLoad(ImageRegressionTestCase):
texture_file = None
image = None
texture = None
show_checkerboard = True
alpha = True
has_exit = False
decoder = None
def on_expose(self):
glClearColor(1, 1, 1, 1)
glClear(GL_COLOR_BUFFER_BIT)
glLoadIdentity()
if self.show_checkerboard:
glPushMatrix()
glScalef(self.window.width/float(self.checkerboard.width),
self.window.height/float(self.checkerboard.height),
1.)
glMatrixMode(GL_TEXTURE)
glPushMatrix()
glScalef(self.window.width/float(self.checkerboard.width),
self.window.height/float(self.checkerboard.height),
1.)
glMatrixMode(GL_MODELVIEW)
self.checkerboard.blit(0, 0, 0)
glMatrixMode(GL_TEXTURE)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
glPopMatrix()
if self.texture:
glPushMatrix()
glTranslatef((self.window.width - self.texture.width) / 2,
(self.window.height - self.texture.height) / 2,
0)
self.texture.blit(0, 0, 0)
glPopMatrix()
self.window.flip()
if self.capture_regression_image():
self.has_exit = True
def load_image(self):
if self.texture_file:
self.texture_file = join(dirname(__file__), self.texture_file)
self.image = image.load(self.texture_file, decoder=self.decoder)
def test_load(self):
width, height = 800, 600
self.window = w = Window(width, height, visible=False)
w.push_handlers(self)
self.screen = image.get_buffer_manager().get_color_buffer()
self.checkerboard = image.create(32, 32, image.CheckerImagePattern())
self.load_image()
if self.image:
self.texture = self.image.texture
if self.alpha:
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
w.set_visible()
while not (w.has_exit or self.has_exit):
w.dispatch_events()
w.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test load using the Python PNG loader. You should see the rgb_8bpp.png
image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.png import PNGImageDecoder
class TEST_PNG_INDEXED_LOAD(base_load.TestLoad):
texture_file = 'rgb_8bpp.png'
decoder = PNGImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test DXT1 compressed RGBA load from a DDS file. You should see the
rgba_dxt1.dds image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.dds import DDSImageDecoder
class TEST_DDS_RGBA_DXT1(base_load.TestLoad):
texture_file = 'rgba_dxt1.dds'
decoder = DDSImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test L load using PyPNG. You should see the l.png image on
a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.png import PNGImageDecoder
class TEST_PNG_L_LOAD(base_load.TestLoad):
texture_file = 'l.png'
decoder = PNGImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that the checkerboard pattern looks correct.
One window will open, it should show one instance of the checkerboard
pattern in two levels of grey.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
from pyglet.gl import *
from pyglet import image
from pyglet.window import *
from pyglet.window.event import *
from tests.regression import ImageRegressionTestCase
class TEST_CHECKERBOARD(ImageRegressionTestCase):
has_exit = False
def on_expose(self):
glClearColor(1, 1, 1, 1)
glClear(GL_COLOR_BUFFER_BIT)
glLoadIdentity()
self.texture.blit(0, 0, 0)
self.window.flip()
if self.capture_regression_image():
self.has_exit = True
def test_main(self):
width, height = 200, 200
self.window = w = Window(width, height, visible=False)
w.push_handlers(self)
self.texture = image.create(32, 32, image.CheckerImagePattern()).texture
w.set_visible()
while not (w.has_exit or self.has_exit):
w.dispatch_events()
w.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGB load using PIL. You should see the rgb.png image on
a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_load
from pyglet.image.codecs.pil import *
class TEST_PIL_RGB_LOAD(base_load.TestLoad):
texture_file = 'rgb.png'
decoder = PILImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test L save using PIL. You should see l.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_save
from pyglet.image.codecs.pil import PILImageEncoder
class TEST_PIL_L_SAVE(base_save.TestSave):
texture_file = 'l.png'
encoder = PILImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test L save using PyPNG. You should see l.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_save
from pyglet.image.codecs.png import PNGImageEncoder
class TEST_PNG_L_SAVE(base_save.TestSave):
texture_file = 'l.png'
encoder = PNGImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
from pyglet.gl import *
from pyglet.image import *
from pyglet.window import *
from texture_base import colorbyte
__noninteractive = True
class TestTexture3D(unittest.TestCase):
def create_image(self, width, height, color):
data = colorbyte(color) * (width * height)
return ImageData(width, height, 'L', data)
def check_image(self, image, width, height, color):
self.assertTrue(image.width == width)
self.assertTrue(image.height == height)
image = image.image_data
data = image.get_data('L', image.width)
self.assertTrue(data == colorbyte(color) * len(data))
def set_grid_image(self, itemwidth, itemheight, rows, cols, rowpad, colpad):
data = b''
color = 1
width = itemwidth * cols + colpad * (cols - 1)
height = itemheight * rows + rowpad * (rows - 1)
for row in range(rows):
rowdata = b''
for col in range(cols):
rowdata += colorbyte(color) * itemwidth
if col < cols - 1:
rowdata += b'\0' * colpad
color += 1
data += rowdata * itemheight
if row < rows - 1:
data += (width * b'\0') * rowpad
assert len(data) == width * height
self.image = ImageData(width, height, 'L', data)
grid = ImageGrid(self.image, rows, cols,
itemwidth, itemheight, rowpad, colpad)
self.grid = Texture3D.create_for_image_grid(grid)
def check_cell(self, cellimage, cellindex):
self.assertTrue(cellimage.width == self.grid.item_width)
self.assertTrue(cellimage.height == self.grid.item_height)
cellimage = cellimage.image_data
data = cellimage.get_data('L', cellimage.width)
self.assertTrue(data == colorbyte(cellindex + 1) * len(data))
def setUp(self):
self.w = Window(visible=False)
def test2(self):
# Test 2 images of 32x32
images = [self.create_image(32, 32, i+1) for i in range(2)]
texture = Texture3D.create_for_images(images)
self.assertTrue(len(texture) == 2)
for i in range(2):
self.check_image(texture[i], 32, 32, i+1)
def test5(self):
# test 5 images of 31x94 (power2 issues)
images = [self.create_image(31, 94, i+1) for i in range(5)]
texture = Texture3D.create_for_images(images)
self.assertTrue(len(texture) == 5)
for i in range(5):
self.check_image(texture[i], 31, 94, i+1)
def testSet(self):
# test replacing an image
images = [self.create_image(32, 32, i+1) for i in range(3)]
texture = Texture3D.create_for_images(images)
self.assertTrue(len(texture) == 3)
for i in range(3):
self.check_image(texture[i], 32, 32, i+1)
texture[1] = self.create_image(32, 32, 87)
self.check_image(texture[0], 32, 32, 1)
self.check_image(texture[1], 32, 32, 87)
self.check_image(texture[2], 32, 32, 3)
def testSquare(self):
# Test a 3x3 grid with no padding and 4x4 images
rows = cols = 3
self.set_grid_image(4, 4, rows, cols, 0, 0)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
def testRect(self):
# Test a 2x5 grid with no padding and 3x8 images
rows, cols = 2, 5
self.set_grid_image(3, 8, rows, cols, 0, 0)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
def testPad(self):
# Test a 5x3 grid with rowpad=3 and colpad=7 and 10x9 images
rows, cols = 5, 3
self.set_grid_image(10, 9, rows, cols, 3, 7)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test L load using PIL. You should see the la.png image on
a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.pil import *
class TEST_PIL_L(base_load.TestLoad):
texture_file = 'l.png'
decoder = PILImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test LA load using PyPNG. You should see the la.png image on
a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.png import PNGImageDecoder
class TEST_PNG_LA_LOAD(base_load.TestLoad):
texture_file = 'la.png'
decoder = PNGImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test rearrangement of color components using the OpenGL color matrix.
The test will be skipped if the GL_ARB_imaging extension is not present.
You should see the RGBA test image correctly rendered. Press ESC to
end the test.
'''
from __future__ import print_function
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
import sys
from pyglet.gl import gl_info
class TEST_MATRIX_RGBA(base_load.TestLoad):
texture_file = 'rgba.png'
def load_image(self):
if not gl_info.have_extension('GL_ARB_imaging'):
print('GL_ARB_imaging is not present, skipping test.')
self.has_exit = True
else:
# Load image as usual then rearrange components
super(TEST_MATRIX_RGBA, self).load_image()
pixels = self.image.get_data('GBAR', self.image.width * 4)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test colour buffer save.
A scene consisting of a single coloured triangle will be rendered. The
colour buffer will then be saved to a stream and loaded as a texture.
You will see the original scene first for up to several seconds before the
buffer image appears (because retrieving and saving the image is a slow
operation). Messages will be printed to stdout indicating what stage is
occuring.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_save
from pyglet.gl import *
from pyglet import image
from pyglet.compat import BytesIO
class TEST_BUFFER_SAVE(base_save.TestSave):
alpha = False
def draw_original(self):
glBegin(GL_TRIANGLES)
glColor4f(1, 0, 0, 1)
glVertex3f(0, 0, -1)
glColor4f(0, 1, 0, 1)
glVertex3f(200, 0, 0)
glColor4f(0, 0, 1, 1)
glVertex3f(0, 200, 1)
glEnd()
glColor4f(1, 1, 1, 1)
def load_texture(self):
print('Drawing scene...')
self.window.set_visible()
self.window.dispatch_events()
self.draw()
print('Saving colour image...')
img = image.get_buffer_manager().get_color_buffer()
file = BytesIO()
img.save('buffer.png', file)
print('Loading colour image as texture...')
file.seek(0)
self.saved_texture = image.load('buffer.png', file)
print('Done.')
self.window.set_visible(False)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test DXT3 compressed RGBA load from a DDS file. You should see the
rgba_dxt3.dds image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.dds import DDSImageDecoder
class TEST_DDS_RGBA_DXT3(base_load.TestLoad):
texture_file = 'rgba_dxt3.dds'
decoder = DDSImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test LA load using the platform decoder (QuickTime, Quartz, GDI+ or Gdk).
You should see the la.png image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet import compat_platform
if compat_platform.startswith('linux'):
from pyglet.image.codecs.gdkpixbuf2 import GdkPixbuf2ImageDecoder as dclass
elif compat_platform in ('win32', 'cygwin'):
from pyglet.image.codecs.gdiplus import GDIPlusDecoder as dclass
elif compat_platform == 'darwin':
from pyglet import options as pyglet_options
if pyglet_options['darwin_cocoa']:
from pyglet.image.codecs.quartz import QuartzImageDecoder as dclass
else:
from pyglet.image.codecs.quicktime import QuickTimeImageDecoder as dclass
class TEST_PLATFORM_LA_LOAD(base_load.TestLoad):
texture_file = 'la.png'
decoder = dclass()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGBA load using PyPNG. You should see the rgba.png image on
a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_load
from pyglet.image.codecs.png import PNGImageDecoder
class TEST_PNG_RGBA_LOAD(base_load.TestLoad):
texture_file = 'rgba.png'
decoder = PNGImageDecoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGB load using PIL, decoder is not available and PYPNG decoder
is used. You should see the rgb.png image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_load
from pyglet.image.codecs.pil import Image, PILImageDecoder
from pyglet.image.codecs.png import PNGImageDecoder
from pyglet.image import codecs
def raise_error(obj, param):
raise Exception()
Image.Image.transpose = raise_error
codecs.get_decoders = lambda filename: [PILImageDecoder(), PNGImageDecoder(),]
class TEST_PIL_RGB_LOAD_NO_DECODER(base_load.TestLoad):
texture_file = 'rgb.png'
decoder = None
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGB load using the platform decoder (QuickTime, Quartz, GDI+ or Gdk).
You should see the rgb.png image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_load
import sys
if sys.platform.startswith('linux'):
from pyglet.image.codecs.gdkpixbuf2 import GdkPixbuf2ImageDecoder as dclass
elif sys.platform in ('win32', 'cygwin'):
from pyglet.image.codecs.gdiplus import GDIPlusDecoder as dclass
elif sys.platform == 'darwin':
from pyglet import options as pyglet_options
if pyglet_options['darwin_cocoa']:
from pyglet.image.codecs.quartz import QuartzImageDecoder as dclass
else:
from pyglet.image.codecs.quicktime import QuickTimeImageDecoder as dclass
class TEST_PLATFORM_RGB_LOAD(base_load.TestLoad):
texture_file = 'rgb.png'
decoder = dclass()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGB save using PIL. You should see rgb.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_save
from pyglet.image.codecs.pil import PILImageEncoder
class TEST_PNG_RGB_SAVE(base_save.TestSave):
texture_file = 'rgb.png'
encoder = PILImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test LA save using PIL. You should see la.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_save
from pyglet.image.codecs.pil import PILImageEncoder
class TEST_PIL_LA_SAVE(base_save.TestSave):
texture_file = 'la.png'
encoder = PILImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test RGB save using PyPNG. You should see rgb.png reference image
on the left, and saved (and reloaded) image on the right. The saved image
may have larger dimensions due to texture size restrictions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_save
from pyglet.image.codecs.png import PNGImageEncoder
class TEST_PNG_RGB_SAVE(base_save.TestSave):
texture_file = 'rgb.png'
encoder = PNGImageEncoder()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test L load using the platform decoder (QuickTime, Quartz, GDI+ or Gdk).
You should see the l.png image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet import compat_platform
if compat_platform.startswith('linux'):
from pyglet.image.codecs.gdkpixbuf2 import GdkPixbuf2ImageDecoder as dclass
elif compat_platform in ('win32', 'cygwin'):
from pyglet.image.codecs.gdiplus import GDIPlusDecoder as dclass
elif compat_platform == 'darwin':
from pyglet import options as pyglet_options
if pyglet_options['darwin_cocoa']:
from pyglet.image.codecs.quartz import QuartzImageDecoder as dclass
else:
from pyglet.image.codecs.quicktime import QuickTimeImageDecoder as dclass
class TEST_PLATFORM_L_LOAD(base_load.TestLoad):
texture_file = 'l.png'
decoder = dclass()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
# $Id:$
import unittest
from pyglet.image import atlas
__noninteractive = True
class Rect(object):
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def __repr__(self):
return 'Rect(%d, %d to %d, %d)' % (
self.x1, self.y1, self.x2, self.y2)
def intersects(self, other):
return self.x2 > other.x1 and self.x1 < other.x2 and \
self.y2 > other.y1 and self.y1 < other.y2
class AllocatorEnvironment(object):
def __init__(self, test_case, width, height):
self.test_case = test_case
self.rectes = []
self.allocator = atlas.Allocator(width, height)
def check(self, test_case):
for i, rect in enumerate(self.rectes):
test_case.assertTrue(0 <= rect.x1 < self.allocator.width)
test_case.assertTrue(0 <= rect.x2 <= self.allocator.width)
test_case.assertTrue(0 <= rect.y1 < self.allocator.height)
test_case.assertTrue(0 <= rect.y2 <= self.allocator.height)
for other in self.rectes[i + 1:]:
test_case.assertFalse(rect.intersects(other))
def add(self, width, height):
x, y = self.allocator.alloc(width, height)
self.rectes.append(Rect(x, y, x + width, y + height))
self.check(self.test_case)
def add_fail(self, width, height):
self.test_case.assertRaises(atlas.AllocatorException,
self.allocator.alloc, width, height)
class TestPack(unittest.TestCase):
def test_over_x(self):
env = AllocatorEnvironment(self, 3, 3)
env.add_fail(3, 4)
def test_over_y(self):
env = AllocatorEnvironment(self, 3, 3)
env.add_fail(4, 3)
def test_1(self):
env = AllocatorEnvironment(self, 4, 4)
for i in range(16):
env.add(1, 1)
env.add_fail(1, 1)
def test_2(self):
env = AllocatorEnvironment(self, 3, 3)
env.add(2, 2)
for i in range(4):
env.add(1, 1)
def test_3(self):
env = AllocatorEnvironment(self, 3, 3)
env.add(3, 3)
env.add_fail(1, 1)
def test_4(self):
env = AllocatorEnvironment(self, 5, 4)
for i in range(4):
env.add(2, 2)
env.add_fail(2, 1)
env.add(1, 2)
env.add(1, 2)
env.add_fail(1, 1)
def test_5(self):
env = AllocatorEnvironment(self, 4, 4)
env.add(3, 2)
env.add(4, 2)
env.add(1, 2)
env.add_fail(1, 1)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
from pyglet.gl import *
from pyglet.image import *
from pyglet.window import *
from texture_base import colorbyte
__noninteractive = True
class TestTextureGrid(unittest.TestCase):
def set_grid_image(self, itemwidth, itemheight, rows, cols, rowpad, colpad):
data = b''
color = 1
width = itemwidth * cols + colpad * (cols - 1)
height = itemheight * rows + rowpad * (rows - 1)
for row in range(rows):
rowdata = b''
for col in range(cols):
rowdata += colorbyte(color) * itemwidth
if col < cols - 1:
rowdata += b'\0' * colpad
color += 1
data += rowdata * itemheight
if row < rows - 1:
data += (width * b'\0') * rowpad
assert len(data) == width * height
self.image = ImageData(width, height, 'L', data)
self.grid = ImageGrid(self.image, rows, cols,
itemwidth, itemheight, rowpad, colpad).texture_sequence
def check_cell(self, cellimage, cellindex):
self.assertTrue(cellimage.width == self.grid.item_width)
self.assertTrue(cellimage.height == self.grid.item_height)
color = colorbyte(cellindex + 1)
cellimage = cellimage.image_data
data = cellimage.get_data('L', cellimage.width)
self.assertTrue(data == color * len(data))
def setUp(self):
self.w = Window(visible=False)
def testSquare(self):
# Test a 3x3 grid with no padding and 4x4 images
rows = cols = 3
self.set_grid_image(4, 4, rows, cols, 0, 0)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
def testRect(self):
# Test a 2x5 grid with no padding and 3x8 images
rows, cols = 2, 5
self.set_grid_image(3, 8, rows, cols, 0, 0)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
def testPad(self):
# Test a 5x3 grid with rowpad=3 and colpad=7 and 10x9 images
rows, cols = 5, 3
self.set_grid_image(10, 9, rows, cols, 3, 7)
for i in range(rows * cols):
self.check_cell(self.grid[i], i)
def testTuple(self):
# Test tuple access
rows, cols = 3, 4
self.set_grid_image(5, 5, rows, cols, 0, 0)
for row in range(rows):
for col in range(cols):
self.check_cell(self.grid[(row, col)], row * cols + col)
def testRange(self):
# Test range access
rows, cols = 4, 3
self.set_grid_image(10, 1, rows, cols, 0, 0)
images = self.grid[4:8]
for i, image in enumerate(images):
self.check_cell(image, i + 4)
def testTupleRange(self):
# Test range over tuples
rows, cols = 10, 10
self.set_grid_image(4, 4, rows, cols, 0, 0)
images = self.grid[(3,2):(6,5)]
i = 0
for row in range(3,6):
for col in range(2,5):
self.check_cell(images[i], row * cols + col)
i += 1
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from pyglet.image import get_buffer_manager
class ImageRegressionTestCase(unittest.TestCase):
_enable_regression_image = False
_enable_interactive = True
_captured_image = None
def capture_regression_image(self):
if not self._enable_regression_image:
return False
self._captured_image = \
get_buffer_manager().get_color_buffer().image_data
return not self._enable_interactive
| Python |
#!/usr/bin/env python
'''Test that a scheduled function gets called every tick with the correct
time delta.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: TICK.py 310 2006-12-23 15:56:35Z Alex.Holkner $'
import time
import unittest
from pyglet import clock
__noninteractive = True
class SCHEDULE(unittest.TestCase):
callback_dt = None
callback_count = 0
def callback(self, dt):
self.callback_dt = dt
self.callback_count += 1
def test_schedule(self):
clock.set_default(clock.Clock())
clock.schedule(self.callback)
result = clock.tick()
self.assertTrue(result == self.callback_dt)
self.callback_dt = None
time.sleep(1)
result = clock.tick()
self.assertTrue(result == self.callback_dt)
self.callback_dt = None
time.sleep(1)
result = clock.tick()
self.assertTrue(result == self.callback_dt)
def test_unschedule(self):
clock.set_default(clock.Clock())
clock.schedule(self.callback)
result = clock.tick()
self.assertTrue(result == self.callback_dt)
self.callback_dt = None
time.sleep(1)
clock.unschedule(self.callback)
result = clock.tick()
self.assertTrue(self.callback_dt == None)
def test_schedule_multiple(self):
clock.set_default(clock.Clock())
clock.schedule(self.callback)
clock.schedule(self.callback)
self.callback_count = 0
clock.tick()
self.assertTrue(self.callback_count == 2)
clock.tick()
self.assertTrue(self.callback_count == 4)
def test_schedule_multiple(self):
clock.set_default(clock.Clock())
clock.schedule(self.callback)
clock.schedule(self.callback)
self.callback_count = 0
clock.tick()
self.assertTrue(self.callback_count == 2)
clock.unschedule(self.callback)
clock.tick()
self.assertTrue(self.callback_count == 2)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that a scheduled function gets called every once with the correct
time delta.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: TICK.py 310 2006-12-23 15:56:35Z Alex.Holkner $'
import time
import unittest
from pyglet import clock
__noninteractive = True
class SCHEDULE_ONCE(unittest.TestCase):
callback_1_count = 0
callback_2_count = 0
callback_3_count = 0
def callback_1(self, dt):
self.assertTrue(abs(dt - 0.1) < 0.01)
self.callback_1_count += 1
def callback_2(self, dt):
self.assertTrue(abs(dt - 0.35) < 0.01)
self.callback_2_count += 1
def callback_3(self, dt):
self.assertTrue(abs(dt - 0.07) < 0.01)
self.callback_3_count += 1
def clear(self):
self.callback_1_count = 0
self.callback_2_count = 0
self.callback_3_count = 0
def test_schedule_once(self):
self.clear()
clock.set_default(clock.Clock())
clock.schedule_once(self.callback_1, 0.1)
clock.schedule_once(self.callback_2, 0.35)
clock.schedule_once(self.callback_3, 0.07)
t = 0
while t < 1:
t += clock.tick()
self.assertTrue(self.callback_1_count == 1)
self.assertTrue(self.callback_2_count == 1)
self.assertTrue(self.callback_3_count == 1)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
# Contributed by Claudio Canepa
# Integrated by Ben Smith
""" There is the possibility that time.clock be non monotonic in multicore hardware,
due to the underlaying use of win32 QueryPerformanceCounter.
If your update is seeing a negative dt, then time.clock is probably the culprit.
AMD or Intel Patches for multicore may fix this problem (if you see it at all)"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import time
import unittest
__noninteractive = True
class MULTICORE(unittest.TestCase):
def test_multicore(self):
failures = 0
old_time = time.clock()
end_time = time.time() + 3
while time.time() < end_time:
t = time.clock()
if t < old_time:
failures += 1
old_time = t
time.sleep(0.001)
self.assertTrue(failures == 0)
if __name__ == '__main__':
unittest.main()
| Python |
"""Tests clock timing between frames and estimations
of frames per second.
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import time
import unittest
from pyglet import clock
__noninteractive = True
class ClockTimingTestCase(unittest.TestCase):
def setUp(self):
# since clock is global,
# we initialize a new clock on every test
clock.set_default(clock.Clock())
def test_first_tick_is_delta_zero(self):
"""
Tests that the first tick is dt = 0.
"""
dt = clock.tick()
self.assertTrue(dt == 0)
def test_start_at_zero_fps(self):
"""
Tests that the default clock starts
with zero fps.
"""
self.assertTrue(clock.get_fps() == 0)
def test_elapsed_time_between_tick(self):
"""
Test that the tick function returns the correct elapsed
time between frames, in seconds.
Because we are measuring time differences, we
expect a small error (1%) from the expected value.
"""
sleep_time = 0.2
# initialize internal counter
clock.tick()
# test between initialization and first tick
time.sleep(sleep_time)
delta_time_1 = clock.tick()
# test between non-initialization tick and next tick
time.sleep(sleep_time)
delta_time_2 = clock.tick()
self.assertAlmostEqual(delta_time_1, sleep_time, delta=0.01*sleep_time)
self.assertAlmostEqual(delta_time_2, sleep_time, delta=0.01*sleep_time)
def test_compute_fps(self):
"""
Test that the clock computes a reasonable value of
frames per second when simulated for 10 ticks at 5 frames per second.
Because sleep is not very precise and fps are unbounded, we
expect a moderate error (10%) from the expected value.
"""
ticks = 10 # for averaging
expected_fps = 5
seconds_per_tick = 1./expected_fps
for i in range(ticks):
time.sleep(seconds_per_tick)
clock.tick()
computed_fps = clock.get_fps()
self.assertAlmostEqual(computed_fps, expected_fps, delta=0.1*expected_fps)
def test_limit_fps(self):
"""
Test that the clock effectively limits the
frames per second to 60 Hz when set to.
Because the fps are bounded, we expect a small error (1%)
from the expected value.
"""
ticks = 20
fps_limit = 60
expected_delta_time = ticks*1./fps_limit
clock.set_fps_limit(fps_limit)
t1 = time.time()
# Initializes the timer state.
clock.tick()
for i in range(ticks):
clock.tick()
t2 = time.time()
computed_time_delta = t2 - t1
self.assertAlmostEqual(computed_time_delta,
expected_delta_time,
delta=0.01*expected_delta_time)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Test that a scheduled function gets called every interval with the correct
time delta.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: TICK.py 310 2006-12-23 15:56:35Z Alex.Holkner $'
import time
import unittest
from pyglet import clock
__noninteractive = True
class SCHEDULE_INTERVAL(unittest.TestCase):
callback_1_count = 0
callback_2_count = 0
callback_3_count = 0
def callback_1(self, dt):
self.assertTrue(abs(dt - 0.1) < 0.06)
self.callback_1_count += 1
def callback_2(self, dt):
self.assertTrue(abs(dt - 0.35) < 0.06)
self.callback_2_count += 1
def callback_3(self, dt):
self.assertTrue(abs(dt - 0.07) < 0.06)
self.callback_3_count += 1
def clear(self):
self.callback_1_count = 0
self.callback_2_count = 0
self.callback_3_count = 0
def test_schedule_interval(self):
self.clear()
clock.set_default(clock.Clock())
clock.schedule_interval(self.callback_1, 0.1)
clock.schedule_interval(self.callback_2, 0.35)
clock.schedule_interval(self.callback_3, 0.07)
t = 0
while t < 2.04: # number chosen to avoid +/- 1 errors in div
t += clock.tick()
self.assertTrue(self.callback_1_count == int(t / 0.1))
self.assertTrue(self.callback_2_count == int(t / 0.35))
self.assertTrue(self.callback_3_count == int(t / 0.07))
if __name__ == '__main__':
unittest.main()
| Python |
import math
import random
from pyglet.gl import *
import euclid
M_2PI = math.pi * 2.0
class DisplayList(int):
def draw(self):
glCallList(self)
def _TRI((v1, n1, t1, b1), (v2, n2, t2, b2), (v3, n3, t3, b3)):
glNormal3f(n1[0], n1[1], n1[2]); glVertex3f(v1[0], v1[1], v1[2])
glNormal3f(n2[0], n2[1], n2[2]); glVertex3f(v2[0], v2[1], v2[2])
glNormal3f(n3[0], n3[1], n3[2]); glVertex3f(v3[0], v3[1], v3[2])
def render_torus(NR = 40, NS = 40, rad1 = 5.0, rad2 = 1.5):
def P(R, S):
R = R * M_2PI / NR
S = S * M_2PI / NS
y = rad2 * math.sin(S)
r = rad1 + rad2 * math.cos(S)
x = r * math.cos(R)
z = r * math.sin(R)
nx = math.cos(R) * math.cos(S)
nz = math.sin(R) * math.cos(S)
ny = math.sin(S)
tx = math.cos(R) * -math.sin(S)
tz = math.sin(R) * -math.sin(S)
ty = math.cos(S)
bx = ny * tz - nz * ty
by = nz * tx - nx * tz
bz = nx * ty - ny * tx
return (x, y, z), (nx, ny, nz), (tx, tz, ty), (bx, by, bz)
glBegin(GL_TRIANGLES)
for ring in range(NR):
for stripe in range(NR):
_TRI(P(ring, stripe), P(ring, stripe + 1),
P(ring + 1, stripe + 1))
_TRI(P(ring, stripe), P(ring + 1, stripe + 1),
P(ring + 1, stripe))
glEnd()
def torus_list():
torus_dl = glGenLists(1)
glNewList(torus_dl, GL_COMPILE)
render_torus()
glEndList()
return DisplayList(torus_dl)
def render_cube():
glBegin(GL_TRIANGLES)
glNormal3f(+1.0, 0.0, 0.0)
glVertex3f(+1.0, +1.0, +1.0); glVertex3f(+1.0, -1.0, +1.0); glVertex3f(+1.0, -1.0, -1.0)
glVertex3f(+1.0, +1.0, +1.0); glVertex3f(+1.0, -1.0, -1.0); glVertex3f(+1.0, +1.0, -1.0);
glNormal3f(0.0, +1.0, 0.0)
glVertex3f(+1.0, +1.0, +1.0); glVertex3f(-1.0, +1.0, +1.0); glVertex3f(-1.0, +1.0, -1.0)
glVertex3f(+1.0, +1.0, +1.0); glVertex3f(-1.0, +1.0, -1.0); glVertex3f(+1.0, +1.0, -1.0);
glNormal3f(0.0, 0.0, +1.0)
glVertex3f(+1.0, +1.0, +1.0); glVertex3f(-1.0, +1.0, +1.0); glVertex3f(-1.0, -1.0, +1.0)
glVertex3f(+1.0, +1.0, +1.0); glVertex3f(-1.0, -1.0, +1.0); glVertex3f(+1.0, -1.0, +1.0);
glNormal3f(-1.0, 0.0, 0.0)
glVertex3f(-1.0, -1.0, -1.0); glVertex3f(-1.0, -1.0, +1.0); glVertex3f(-1.0, +1.0, +1.0);
glVertex3f(-1.0, +1.0, -1.0); glVertex3f(-1.0, -1.0, -1.0); glVertex3f(-1.0, +1.0, +1.0);
glNormal3f(0.0, -1.0, 0.0)
glVertex3f(-1.0, -1.0, -1.0); glVertex3f(-1.0, -1.0, +1.0); glVertex3f(+1.0, -1.0, +1.0);
glVertex3f(+1.0, -1.0, -1.0); glVertex3f(-1.0, -1.0, -1.0); glVertex3f(+1.0, -1.0, +1.0);
glNormal3f(0.0, 0.0, -1.0)
glVertex3f(-1.0, -1.0, -1.0); glVertex3f(-1.0, +1.0, -1.0); glVertex3f(+1.0, +1.0, -1.0);
glVertex3f(+1.0, -1.0, -1.0); glVertex3f(-1.0, -1.0, -1.0); glVertex3f(+1.0, +1.0, -1.0);
glEnd()
def cube_list():
cube_dl = glGenLists(1)
glNewList(cube_dl, GL_COMPILE)
render_cube()
glEndList()
return DisplayList(cube_dl)
def cube_array_list():
cubes_dl = glGenLists(1)
glNewList(cubes_dl, GL_COMPILE)
glMatrixMode(GL_MODELVIEW)
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
glEnable(GL_COLOR_MATERIAL)
glPushMatrix()
for x in range(-10, +11, +2):
for y in range(-10, +11, +2):
for z in range(-10, +11, +2):
glPushMatrix()
glTranslatef(x * 2.0, y * 2.0, z * 2.0)
glScalef(.8, .8, .8)
glColor4f((x + 10.0) / 20.0, (y + 10.0) / 20.0,
(z + 10.0) / 20.0, 1.0)
render_cube()
glPopMatrix()
glPopMatrix()
glDisable(GL_COLOR_MATERIAL)
glEndList()
return DisplayList(cubes_dl)
_ROT_30_X = euclid.Matrix4.new_rotatex(math.pi / 12)
_ROT_N30_X = euclid.Matrix4.new_rotatex(-math.pi / 12)
_ROT_30_Z = euclid.Matrix4.new_rotatez(math.pi / 12)
_ROT_N30_Z = euclid.Matrix4.new_rotatez(-math.pi / 12)
def _tree_branch(n, l, r):
glVertex3f(l.p1.x, l.p1.y, l.p1.z)
glVertex3f(l.p2.x, l.p2.y, l.p2.z)
if n == 0:
return
if r:
if random.random() > .9: return
mag = abs(l.v) * (.5 + .5 * random.random())
else:
mag = abs(l.v) * .75
if n%2:
v1 = _ROT_30_X * l.v
v2 = _ROT_N30_X * l.v
else:
v1 = _ROT_30_Z * l.v
v2 = _ROT_N30_Z * l.v
_tree_branch(n-1, euclid.Line3(l.p2, v1, mag), r)
_tree_branch(n-1, euclid.Line3(l.p2, v2, mag), r)
def render_tree(n=10, r=False):
glLineWidth(2.)
glColor4f(.5, .5, .5, .5)
glBegin(GL_LINES)
_tree_branch(n-1, euclid.Line3(euclid.Point3(0., 0., 0.),
euclid.Vector3(0., 1., 0.), 1.), r)
glEnd()
def tree_list(n=10, r=False):
dl = glGenLists(1)
glNewList(dl, GL_COMPILE)
render_tree(n, r)
glEndList()
return DisplayList(dl)
| Python |
import os
import warnings
from pyglet.gl import *
from pyglet import image
class Material(object):
diffuse = [.8, .8, .8]
ambient = [.2, .2, .2]
specular = [0., 0., 0.]
emission = [0., 0., 0.]
shininess = 0.
opacity = 1.
texture = None
def __init__(self, name):
self.name = name
def apply(self, face=GL_FRONT_AND_BACK):
if self.texture:
glEnable(self.texture.target)
glBindTexture(self.texture.target, self.texture.id)
else:
glDisable(GL_TEXTURE_2D)
glMaterialfv(face, GL_DIFFUSE,
(GLfloat * 4)(*(self.diffuse + [self.opacity])))
glMaterialfv(face, GL_AMBIENT,
(GLfloat * 4)(*(self.ambient + [self.opacity])))
glMaterialfv(face, GL_SPECULAR,
(GLfloat * 4)(*(self.specular + [self.opacity])))
glMaterialfv(face, GL_EMISSION,
(GLfloat * 4)(*(self.emission + [self.opacity])))
glMaterialf(face, GL_SHININESS, self.shininess)
class MaterialGroup(object):
def __init__(self, material):
self.material = material
# Interleaved array of floats in GL_T2F_N3F_V3F format
self.vertices = []
self.array = None
class Mesh(object):
def __init__(self, name):
self.name = name
self.groups = []
# Display list, created only if compile() is called, but used
# automatically by draw()
self.list = None
def draw(self):
if self.list:
glCallList(self.list)
return
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_LIGHTING_BIT)
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)
for group in self.groups:
group.material.apply()
if group.array is None:
group.array = (GLfloat * len(group.vertices))(*group.vertices)
group.triangles = len(group.vertices) / 8
glInterleavedArrays(GL_T2F_N3F_V3F, 0, group.array)
glDrawArrays(GL_TRIANGLES, 0, group.triangles)
glPopAttrib()
glPopClientAttrib()
def compile(self):
if not self.list:
list = glGenLists(1)
glNewList(list, GL_COMPILE)
self.draw()
glEndList()
self.list = list
class OBJ:
def __init__(self, filename, file=None, path=None):
self.materials = {}
self.meshes = {} # Name mapping
self.mesh_list = [] # Also includes anonymous meshes
if file is None:
file = open(filename, 'r')
if path is None:
path = os.path.dirname(filename)
self.path = path
mesh = None
group = None
material = None
vertices = [[0., 0., 0.]]
normals = [[0., 0., 0.]]
tex_coords = [[0., 0.]]
for line in open(filename, "r"):
if line.startswith('#'):
continue
values = line.split()
if not values:
continue
if values[0] == 'v':
vertices.append(map(float, values[1:4]))
elif values[0] == 'vn':
normals.append(map(float, values[1:4]))
elif values[0] == 'vt':
tex_coords.append(map(float, values[1:3]))
elif values[0] == 'mtllib':
self.load_material_library(values[1])
elif values[0] in ('usemtl', 'usemat'):
material = self.materials.get(values[1], None)
if material is None:
warnings.warn('Unknown material: %s' % values[1])
if mesh is not None:
group = MaterialGroup(material)
mesh.groups.append(group)
elif values[0] == 'o':
mesh = Mesh(values[1])
self.meshes[mesh.name] = mesh
self.mesh_list.append(mesh)
group = None
elif values[0] == 'f':
if mesh is None:
mesh = Mesh('')
self.mesh_list.append(mesh)
if material is None:
material = Material()
if group is None:
group = MaterialGroup(material)
mesh.groups.append(group)
# For fan triangulation, remember first and latest vertices
v1 = None
vlast = None
points = []
for i, v in enumerate(values[1:]):
v_index, t_index, n_index = \
(map(int, [j or 0 for j in v.split('/')]) + [0, 0])[:3]
if v_index < 0:
v_index += len(vertices) - 1
if t_index < 0:
t_index += len(tex_coords) - 1
if n_index < 0:
n_index += len(normals) - 1
vertex = tex_coords[t_index] + \
normals[n_index] + \
vertices[v_index]
if i >= 3:
# Triangulate
group.vertices += v1 + vlast
group.vertices += vertex
if i == 0:
v1 = vertex
vlast = vertex
def open_material_file(self, filename):
'''Override for loading from archive/network etc.'''
return open(os.path.join(self.path, filename), 'r')
def load_material_library(self, filename):
material = None
file = self.open_material_file(filename)
for line in file:
if line.startswith('#'):
continue
values = line.split()
if not values:
continue
if values[0] == 'newmtl':
material = Material(values[1])
self.materials[material.name] = material
elif material is None:
warnings.warn('Expected "newmtl" in %s' % filename)
continue
try:
if values[0] == 'Kd':
material.diffuse = map(float, values[1:])
elif values[0] == 'Ka':
material.ambient = map(float, values[1:])
elif values[0] == 'Ks':
material.specular = map(float, values[1:])
elif values[0] == 'Ke':
material.emissive = map(float, values[1:])
elif values[0] == 'Ns':
material.shininess = float(values[1])
elif values[0] == 'd':
material.opacity = float(values[1])
elif values[0] == 'map_Kd':
try:
material.texture = image.load(values[1]).texture
except image.ImageDecodeException:
warnings.warn('Could not load texture %s' % values[1])
except:
warnings.warn('Parse error in %s.' % filename)
def draw(self):
for mesh in self.mesh_list:
mesh.draw()
| Python |
"""
Wavefront OBJ renderer using pyglet's Batch class.
Based on obj.py but this should be more efficient and
uses VBOs when available instead of the deprecated
display lists.
First load the object:
obj = OBJ("object.obj")
Alternatively you can use `OBJ.from_resource(filename)`
to load the object, materials and textures using
pyglet's resource framework.
After the object is loaded, add it to a Batch:
obj.add_to(batch)
Then you only have to draw your batch!
Juan J. Martinez <jjm@usebox.net>
"""
import os
import logging
from pyglet.gl import *
from pyglet import image, resource, graphics
class Material(graphics.Group):
diffuse = [.8, .8, .8]
ambient = [.2, .2, .2]
specular = [0., 0., 0.]
emission = [0., 0., 0.]
shininess = 0.
opacity = 1.
texture = None
def __init__(self, name, **kwargs):
self.name = name
super(Material, self).__init__(**kwargs)
def set_state(self, face=GL_FRONT_AND_BACK):
if self.texture:
glEnable(self.texture.target)
glBindTexture(self.texture.target, self.texture.id)
else:
glDisable(GL_TEXTURE_2D)
glMaterialfv(face, GL_DIFFUSE,
(GLfloat * 4)(*(self.diffuse + [self.opacity])))
glMaterialfv(face, GL_AMBIENT,
(GLfloat * 4)(*(self.ambient + [self.opacity])))
glMaterialfv(face, GL_SPECULAR,
(GLfloat * 4)(*(self.specular + [self.opacity])))
glMaterialfv(face, GL_EMISSION,
(GLfloat * 4)(*(self.emission + [self.opacity])))
glMaterialf(face, GL_SHININESS, self.shininess)
def unset_state(self):
if self.texture:
glDisable(self.texture.target)
glDisable(GL_COLOR_MATERIAL)
def __eq__(self, other):
if self.texture is None:
return super(Material, self).__eq__(other)
return (self.__class__ is other.__class__ and
self.texture.id == other.texture.id and
self.texture.target == other.texture.target and
self.parent == other.parent)
def __hash__(self):
if self.texture is None:
return super(Material, self).__hash__()
return hash((self.texture.id, self.texture.target))
class MaterialGroup(object):
def __init__(self, material):
self.material = material
# Interleaved array of floats in GL_T2F_N3F_V3F format
self.vertices = []
self.normals = []
self.tex_coords = []
self.array = None
class Mesh(object):
def __init__(self, name):
self.name = name
self.groups = []
class OBJ(object):
@staticmethod
def from_resource(filename):
'''Load an object using the resource framework'''
loc = pyglet.resource.location(filename)
return OBJ(filename, file=loc.open(filename), path=loc.path)
def __init__(self, filename, file=None, path=None):
self.materials = {}
self.meshes = {} # Name mapping
self.mesh_list = [] # Also includes anonymous meshes
if file is None:
file = open(filename, 'r')
if path is None:
path = os.path.dirname(filename)
self.path = path
mesh = None
group = None
material = None
vertices = [[0., 0., 0.]]
normals = [[0., 0., 0.]]
tex_coords = [[0., 0.]]
for line in file:
if line.startswith('#'):
continue
values = line.split()
if not values:
continue
if values[0] == 'v':
vertices.append(map(float, values[1:4]))
elif values[0] == 'vn':
normals.append(map(float, values[1:4]))
elif values[0] == 'vt':
tex_coords.append(map(float, values[1:3]))
elif values[0] == 'mtllib':
self.load_material_library(values[1])
elif values[0] in ('usemtl', 'usemat'):
material = self.materials.get(values[1], None)
if material is None:
logging.warn('Unknown material: %s' % values[1])
if mesh is not None:
group = MaterialGroup(material)
mesh.groups.append(group)
elif values[0] == 'o':
mesh = Mesh(values[1])
self.meshes[mesh.name] = mesh
self.mesh_list.append(mesh)
group = None
elif values[0] == 'f':
if mesh is None:
mesh = Mesh('')
self.mesh_list.append(mesh)
if material is None:
# FIXME
material = Material("<unknown>")
if group is None:
group = MaterialGroup(material)
mesh.groups.append(group)
# For fan triangulation, remember first and latest vertices
n1 = None
nlast = None
t1 = None
tlast = None
v1 = None
vlast = None
#points = []
for i, v in enumerate(values[1:]):
v_index, t_index, n_index = \
(map(int, [j or 0 for j in v.split('/')]) + [0, 0])[:3]
if v_index < 0:
v_index += len(vertices) - 1
if t_index < 0:
t_index += len(tex_coords) - 1
if n_index < 0:
n_index += len(normals) - 1
#vertex = tex_coords[t_index] + \
# normals[n_index] + \
# vertices[v_index]
group.normals += normals[n_index]
group.tex_coords += tex_coords[t_index]
group.vertices += vertices[v_index]
if i >= 3:
# Triangulate
group.normals += n1 + nlast
group.tex_coords += t1 + tlast
group.vertices += v1 + vlast
if i == 0:
n1 = normals[n_index]
t1 = tex_coords[t_index]
v1 = vertices[v_index]
nlast = normals[n_index]
tlast = tex_coords[t_index]
vlast = vertices[v_index]
def add_to(self, batch):
'''Add the meshes to a batch'''
for mesh in self.mesh_list:
for group in mesh.groups:
batch.add(len(group.vertices)//3,
GL_TRIANGLES,
group.material,
('v3f/static', tuple(group.vertices)),
('n3f/static', tuple(group.normals)),
('t2f/static', tuple(group.tex_coords)),
)
def open_material_file(self, filename):
'''Override for loading from archive/network etc.'''
return open(os.path.join(self.path, filename), 'r')
def load_material_library(self, filename):
material = None
file = self.open_material_file(filename)
for line in file:
if line.startswith('#'):
continue
values = line.split()
if not values:
continue
if values[0] == 'newmtl':
material = Material(values[1])
self.materials[material.name] = material
elif material is None:
logging.warn('Expected "newmtl" in %s' % filename)
continue
try:
if values[0] == 'Kd':
material.diffuse = map(float, values[1:])
elif values[0] == 'Ka':
material.ambient = map(float, values[1:])
elif values[0] == 'Ks':
material.specular = map(float, values[1:])
elif values[0] == 'Ke':
material.emissive = map(float, values[1:])
elif values[0] == 'Ns':
material.shininess = float(values[1])
elif values[0] == 'd':
material.opacity = float(values[1])
elif values[0] == 'map_Kd':
try:
material.texture = pyglet.resource.image(values[1]).texture
except BaseException as ex:
logging.warn('Could not load texture %s: %s' % (values[1], ex))
except BaseException as ex:
logging.warn('Parse error in %s.' % (filename, ex))
if __name__ == "__main__":
import sys
import ctypes
if len(sys.argv) != 2:
logging.error("Usage: %s file.obj" % sys.argv[0])
else:
window = pyglet.window.Window()
fourfv = ctypes.c_float * 4
glLightfv(GL_LIGHT0, GL_POSITION, fourfv(0, 200, 5000, 1))
glLightfv(GL_LIGHT0, GL_AMBIENT, fourfv(0.0, 0.0, 0.0, 1.0))
glLightfv(GL_LIGHT0, GL_DIFFUSE, fourfv(1.0, 1.0, 1.0, 1.0))
glLightfv(GL_LIGHT0, GL_SPECULAR, fourfv(1.0, 1.0, 1.0, 1.0))
glEnable(GL_LIGHT0)
glEnable(GL_LIGHTING)
glEnable(GL_DEPTH_TEST)
@window.event
def on_resize(width, height):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60.0, float(width)/height, 1.0, 100.0)
glMatrixMode(GL_MODELVIEW)
return True
@window.event
def on_draw():
window.clear()
glLoadIdentity()
gluLookAt(0, 3, 3, 0, 0, 0, 0, 1, 0)
glRotatef(rot, 1, 0, 0)
glRotatef(rot/2, 0, 1, 0)
batch.draw()
rot = 0
def update(dt):
global rot
rot += dt*75
pyglet.clock.schedule_interval(update, 1.0/60)
obj = OBJ(sys.argv[1])
batch = pyglet.graphics.Batch()
obj.add_to(batch)
pyglet.app.run()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: obj_test.py 111 2006-10-20 06:39:12Z r1chardj0n3s $'
import sys
import os
import ctypes
import pyglet
from pyglet.gl import *
from model import obj, geometric
w = pyglet.window.Window()
fourfv = ctypes.c_float * 4
glLightfv(GL_LIGHT0, GL_POSITION, fourfv(10, 20, 20, 0))
glLightfv(GL_LIGHT0, GL_AMBIENT, fourfv(0.2, 0.2, 0.2, 1.0))
glLightfv(GL_LIGHT0, GL_DIFFUSE, fourfv(0.8, 0.8, 0.8, 1.0))
glEnable(GL_LIGHT0)
glEnable(GL_LIGHTING)
glEnable(GL_DEPTH_TEST)
@w.event
def on_resize(width, height):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60., float(width)/height, 1., 100.)
glMatrixMode(GL_MODELVIEW)
return True
@w.event
def on_draw():
w.clear()
glLoadIdentity()
gluLookAt(0, 3, 3, 0, 0, 0, 0, 1, 0)
glRotatef(r, 0, 1, 0)
glRotatef(r/2, 1, 0, 0)
bunny.draw()
w.flip()
r = 0
def update(dt):
global r
r += 90*dt
if r > 720: r = 0
pyglet.clock.schedule(update)
if len(sys.argv) == 1:
objfile = os.path.join(os.path.split(__file__)[0], 'rabbit.obj')
else:
objfile = sys.argv[1]
bunny = obj.OBJ(objfile)
pyglet.app.run()
| Python |
#!/usr/bin/env python
#
# euclid graphics maths module
#
# Copyright (c) 2006 Alex Holkner
# Alex.Holkner@mail.google.com
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
#
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
'''euclid graphics maths module
Documentation and tests are included in the file "euclid.txt", or online
at http://code.google.com/p/pyeuclid
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
__revision__ = '$Revision$'
import math
import operator
import types
# Some magic here. If _use_slots is True, the classes will derive from
# object and will define a __slots__ class variable. If _use_slots is
# False, classes will be old-style and will not define __slots__.
#
# _use_slots = True: Memory efficient, probably faster in future versions
# of Python, "better".
# _use_slots = False: Ordinary classes, much faster than slots in current
# versions of Python (2.4 and 2.5).
_use_slots = True
# If True, allows components of Vector2 and Vector3 to be set via swizzling;
# e.g. v.xyz = (1, 2, 3). This is much, much slower than the more verbose
# v.x = 1; v.y = 2; v.z = 3, and slows down ordinary element setting as
# well. Recommended setting is False.
_enable_swizzle_set = False
# Requires class to derive from object.
if _enable_swizzle_set:
_use_slots = True
# Implement _use_slots magic.
class _EuclidMetaclass(type):
def __new__(cls, name, bases, dct):
if '__slots__' in dct:
dct['__getstate__'] = cls._create_getstate(dct['__slots__'])
dct['__setstate__'] = cls._create_setstate(dct['__slots__'])
if _use_slots:
return type.__new__(cls, name, bases + (object,), dct)
else:
if '__slots__' in dct:
del dct['__slots__']
return types.ClassType.__new__(types.ClassType, name, bases, dct)
@classmethod
def _create_getstate(cls, slots):
def __getstate__(self):
d = {}
for slot in slots:
d[slot] = getattr(self, slot)
return d
return __getstate__
@classmethod
def _create_setstate(cls, slots):
def __setstate__(self, state):
for name, value in state.items():
setattr(self, name, value)
return __setstate__
__metaclass__ = _EuclidMetaclass
class Vector2:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
def __copy__(self):
return self.__class__(self.x, self.y)
copy = __copy__
def __repr__(self):
return 'Vector2(%.2f, %.2f)' % (self.x, self.y)
def __eq__(self, other):
if isinstance(other, Vector2):
return self.x == other.x and \
self.y == other.y
else:
assert hasattr(other, '__len__') and len(other) == 2
return self.x == other[0] and \
self.y == other[1]
def __ne__(self, other):
return not self.__eq__(other)
def __nonzero__(self):
return self.x != 0 or self.y != 0
def __len__(self):
return 2
def __getitem__(self, key):
return (self.x, self.y)[key]
def __setitem__(self, key, value):
l = [self.x, self.y]
l[key] = value
self.x, self.y = l
def __iter__(self):
return iter((self.x, self.y))
def __getattr__(self, name):
try:
return tuple([(self.x, self.y)['xy'.index(c)] \
for c in name])
except ValueError:
raise AttributeError, name
if _enable_swizzle_set:
# This has detrimental performance on ordinary setattr as well
# if enabled
def __setattr__(self, name, value):
if len(name) == 1:
object.__setattr__(self, name, value)
else:
try:
l = [self.x, self.y]
for c, v in map(None, name, value):
l['xy'.index(c)] = v
self.x, self.y = l
except ValueError:
raise AttributeError, name
def __add__(self, other):
if isinstance(other, Vector2):
return Vector2(self.x + other.x,
self.y + other.y)
else:
assert hasattr(other, '__len__') and len(other) == 2
return Vector2(self.x + other[0],
self.y + other[1])
__radd__ = __add__
def __iadd__(self, other):
if isinstance(other, Vector2):
self.x += other.x
self.y += other.y
else:
self.x += other[0]
self.y += other[1]
return self
def __sub__(self, other):
if isinstance(other, Vector2):
return Vector2(self.x - other.x,
self.y - other.y)
else:
assert hasattr(other, '__len__') and len(other) == 2
return Vector2(self.x - other[0],
self.y - other[1])
def __rsub__(self, other):
if isinstance(other, Vector2):
return Vector2(other.x - self.x,
other.y - self.y)
else:
assert hasattr(other, '__len__') and len(other) == 2
return Vector2(other.x - self[0],
other.y - self[1])
def __mul__(self, other):
assert type(other) in (int, long, float)
return Vector2(self.x * other,
self.y * other)
__rmul__ = __mul__
def __imul__(self, other):
assert type(other) in (int, long, float)
self.x *= other
self.y *= other
return self
def __div__(self, other):
assert type(other) in (int, long, float)
return Vector2(operator.div(self.x, other),
operator.div(self.y, other))
def __rdiv__(self, other):
assert type(other) in (int, long, float)
return Vector2(operator.div(other, self.x),
operator.div(other, self.y))
def __floordiv__(self, other):
assert type(other) in (int, long, float)
return Vector2(operator.floordiv(self.x, other),
operator.floordiv(self.y, other))
def __rfloordiv__(self, other):
assert type(other) in (int, long, float)
return Vector2(operator.floordiv(other, self.x),
operator.floordiv(other, self.y))
def __truediv__(self, other):
assert type(other) in (int, long, float)
return Vector2(operator.truediv(self.x, other),
operator.truediv(self.y, other))
def __rtruediv__(self, other):
assert type(other) in (int, long, float)
return Vector2(operator.truediv(other, self.x),
operator.truediv(other, self.y))
def __neg__(self):
return Vector2(-self.x,
-self.y)
__pos__ = __copy__
def __abs__(self):
return math.sqrt(self.x ** 2 + \
self.y ** 2)
magnitude = __abs__
def magnitude_squared(self):
return self.x ** 2 + \
self.y ** 2
def normalize(self):
d = self.magnitude()
if d:
self.x /= d
self.y /= d
return self
def normalized(self):
d = self.magnitude()
if d:
return Vector2(self.x / d,
self.y / d)
return self.copy()
def dot(self, other):
assert isinstance(other, Vector2)
return self.x * other.x + \
self.y * other.y
def cross(self):
return Vector2(self.y, -self.x)
def reflect(self, normal):
# assume normal is normalized
assert isinstance(normal, Vector2)
d = 2 * (self.x * normal.x + self.y * normal.y)
return Vector2(self.x - d * normal.x,
self.y - d * normal.y)
class Vector3:
__slots__ = ['x', 'y', 'z']
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __copy__(self):
return self.__class__(self.x, self.y, self.z)
copy = __copy__
def __repr__(self):
return 'Vector3(%.2f, %.2f, %.2f)' % (self.x,
self.y,
self.z)
def __eq__(self, other):
if isinstance(other, Vector3):
return self.x == other.x and \
self.y == other.y and \
self.z == other.z
else:
assert hasattr(other, '__len__') and len(other) == 3
return self.x == other[0] and \
self.y == other[1] and \
self.z == other[2]
def __ne__(self, other):
return not self.__eq__(other)
def __nonzero__(self):
return self.x != 0 or self.y != 0 or self.z != 0
def __len__(self):
return 3
def __getitem__(self, key):
return (self.x, self.y, self.z)[key]
def __setitem__(self, key, value):
l = [self.x, self.y, self.z]
l[key] = value
self.x, self.y, self.z = l
def __iter__(self):
return iter((self.x, self.y, self.z))
def __getattr__(self, name):
try:
return tuple([(self.x, self.y, self.z)['xyz'.index(c)] \
for c in name])
except ValueError:
raise AttributeError, name
if _enable_swizzle_set:
# This has detrimental performance on ordinary setattr as well
# if enabled
def __setattr__(self, name, value):
if len(name) == 1:
object.__setattr__(self, name, value)
else:
try:
l = [self.x, self.y, self.z]
for c, v in map(None, name, value):
l['xyz'.index(c)] = v
self.x, self.y, self.z = l
except ValueError:
raise AttributeError, name
def __add__(self, other):
if isinstance(other, Vector3):
# Vector + Vector -> Vector
# Vector + Point -> Point
# Point + Point -> Vector
if self.__class__ is other.__class__:
_class = Vector3
else:
_class = Point3
return _class(self.x + other.x,
self.y + other.y,
self.z + other.z)
else:
assert hasattr(other, '__len__') and len(other) == 3
return Vector3(self.x + other[0],
self.y + other[1],
self.z + other[2])
__radd__ = __add__
def __iadd__(self, other):
if isinstance(other, Vector3):
self.x += other.x
self.y += other.y
self.z += other.z
else:
self.x += other[0]
self.y += other[1]
self.z += other[2]
return self
def __sub__(self, other):
if isinstance(other, Vector3):
# Vector - Vector -> Vector
# Vector - Point -> Point
# Point - Point -> Vector
if self.__class__ is other.__class__:
_class = Vector3
else:
_class = Point3
return Vector3(self.x - other.x,
self.y - other.y,
self.z - other.z)
else:
assert hasattr(other, '__len__') and len(other) == 3
return Vector3(self.x - other[0],
self.y - other[1],
self.z - other[2])
def __rsub__(self, other):
if isinstance(other, Vector3):
return Vector3(other.x - self.x,
other.y - self.y,
other.z - self.z)
else:
assert hasattr(other, '__len__') and len(other) == 3
return Vector3(other.x - self[0],
other.y - self[1],
other.z - self[2])
def __mul__(self, other):
if isinstance(other, Vector3):
# TODO component-wise mul/div in-place and on Vector2; docs.
if self.__class__ is Point3 or other.__class__ is Point3:
_class = Point3
else:
_class = Vector3
return _class(self.x * other.x,
self.y * other.y,
self.z * other.z)
else:
assert type(other) in (int, long, float)
return Vector3(self.x * other,
self.y * other,
self.z * other)
__rmul__ = __mul__
def __imul__(self, other):
assert type(other) in (int, long, float)
self.x *= other
self.y *= other
self.z *= other
return self
def __div__(self, other):
assert type(other) in (int, long, float)
return Vector3(operator.div(self.x, other),
operator.div(self.y, other),
operator.div(self.z, other))
def __rdiv__(self, other):
assert type(other) in (int, long, float)
return Vector3(operator.div(other, self.x),
operator.div(other, self.y),
operator.div(other, self.z))
def __floordiv__(self, other):
assert type(other) in (int, long, float)
return Vector3(operator.floordiv(self.x, other),
operator.floordiv(self.y, other),
operator.floordiv(self.z, other))
def __rfloordiv__(self, other):
assert type(other) in (int, long, float)
return Vector3(operator.floordiv(other, self.x),
operator.floordiv(other, self.y),
operator.floordiv(other, self.z))
def __truediv__(self, other):
assert type(other) in (int, long, float)
return Vector3(operator.truediv(self.x, other),
operator.truediv(self.y, other),
operator.truediv(self.z, other))
def __rtruediv__(self, other):
assert type(other) in (int, long, float)
return Vector3(operator.truediv(other, self.x),
operator.truediv(other, self.y),
operator.truediv(other, self.z))
def __neg__(self):
return Vector3(-self.x,
-self.y,
-self.z)
__pos__ = __copy__
def __abs__(self):
return math.sqrt(self.x ** 2 + \
self.y ** 2 + \
self.z ** 2)
magnitude = __abs__
def magnitude_squared(self):
return self.x ** 2 + \
self.y ** 2 + \
self.z ** 2
def normalize(self):
d = self.magnitude()
if d:
self.x /= d
self.y /= d
self.z /= d
return self
def normalized(self):
d = self.magnitude()
if d:
return Vector3(self.x / d,
self.y / d,
self.z / d)
return self.copy()
def dot(self, other):
assert isinstance(other, Vector3)
return self.x * other.x + \
self.y * other.y + \
self.z * other.z
def cross(self, other):
assert isinstance(other, Vector3)
return Vector3(self.y * other.z - self.z * other.y,
-self.x * other.z + self.z * other.x,
self.x * other.y - self.y * other.x)
def reflect(self, normal):
# assume normal is normalized
assert isinstance(normal, Vector3)
d = 2 * (self.x * normal.x + self.y * normal.y + self.z * normal.z)
return Vector3(self.x - d * normal.x,
self.y - d * normal.y,
self.z - d * normal.z)
class AffineVector3(Vector3):
w = 1
def __repr__(self):
return 'Vector3(%.2f, %.2f, %.2f, 1.00)' % (self.x,
self.y,
self.z)
def __len__(self):
return 4
def __getitem__(self, key):
return (self.x, self.y, self.z, 1)[key]
def __iter__(self):
return iter((self.x, self.y, self.z, 1))
# a b c
# e f g
# i j k
class Matrix3:
__slots__ = list('abcefgijk')
def __init__(self):
self.identity()
def __copy__(self):
M = Matrix3()
M.a = self.a
M.b = self.b
M.c = self.c
M.e = self.e
M.f = self.f
M.g = self.g
M.i = self.i
M.j = self.j
M.k = self.k
return M
copy = __copy__
def __repr__(self):
return ('Matrix3([% 8.2f % 8.2f % 8.2f\n' \
' % 8.2f % 8.2f % 8.2f\n' \
' % 8.2f % 8.2f % 8.2f])') \
% (self.a, self.b, self.c,
self.e, self.f, self.g,
self.i, self.j, self.k)
def __getitem__(self, key):
return [self.a, self.e, self.i,
self.b, self.f, self.j,
self.c, self.g, self.k][key]
def __setitem__(self, key, value):
L = self[:]
L[key] = value
(self.a, self.e, self.i,
self.b, self.f, self.j,
self.c, self.g, self.k) = L
def __mul__(self, other):
if isinstance(other, Matrix3):
# Caching repeatedly accessed attributes in local variables
# apparently increases performance by 20%. Attrib: Will McGugan.
Aa = self.a
Ab = self.b
Ac = self.c
Ae = self.e
Af = self.f
Ag = self.g
Ai = self.i
Aj = self.j
Ak = self.k
Ba = other.a
Bb = other.b
Bc = other.c
Be = other.e
Bf = other.f
Bg = other.g
Bi = other.i
Bj = other.j
Bk = other.k
C = Matrix3()
C.a = Aa * Ba + Ab * Be + Ac * Bi
C.b = Aa * Bb + Ab * Bf + Ac * Bj
C.c = Aa * Bc + Ab * Bg + Ac * Bk
C.e = Ae * Ba + Af * Be + Ag * Bi
C.f = Ae * Bb + Af * Bf + Ag * Bj
C.g = Ae * Bc + Af * Bg + Ag * Bk
C.i = Ai * Ba + Aj * Be + Ak * Bi
C.j = Ai * Bb + Aj * Bf + Ak * Bj
C.k = Ai * Bc + Aj * Bg + Ak * Bk
return C
elif isinstance(other, Point2):
A = self
B = other
P = Point2(0, 0)
P.x = A.a * B.x + A.b * B.y + A.c
P.y = A.e * B.x + A.f * B.y + A.g
return P
elif isinstance(other, Vector2):
A = self
B = other
V = Vector2(0, 0)
V.x = A.a * B.x + A.b * B.y
V.y = A.e * B.x + A.f * B.y
return V
else:
other = other.copy()
other._apply_transform(self)
return other
def __imul__(self, other):
assert isinstance(other, Matrix3)
# Cache attributes in local vars (see Matrix3.__mul__).
Aa = self.a
Ab = self.b
Ac = self.c
Ae = self.e
Af = self.f
Ag = self.g
Ai = self.i
Aj = self.j
Ak = self.k
Ba = other.a
Bb = other.b
Bc = other.c
Be = other.e
Bf = other.f
Bg = other.g
Bi = other.i
Bj = other.j
Bk = other.k
self.a = Aa * Ba + Ab * Be + Ac * Bi
self.b = Aa * Bb + Ab * Bf + Ac * Bj
self.c = Aa * Bc + Ab * Bg + Ac * Bk
self.e = Ae * Ba + Af * Be + Ag * Bi
self.f = Ae * Bb + Af * Bf + Ag * Bj
self.g = Ae * Bc + Af * Bg + Ag * Bk
self.i = Ai * Ba + Aj * Be + Ak * Bi
self.j = Ai * Bb + Aj * Bf + Ak * Bj
self.k = Ai * Bc + Aj * Bg + Ak * Bk
return self
def identity(self):
self.a = self.f = self.k = 1.
self.b = self.c = self.e = self.g = self.i = self.j = 0
return self
def scale(self, x, y):
self *= Matrix3.new_scale(x, y)
return self
def translate(self, x, y):
self *= Matrix3.new_translate(x, y)
return self
def rotate(self, angle):
self *= Matrix3.new_rotate(angle)
return self
# Static constructors
def new_identity(cls):
self = cls()
return self
new_identity = classmethod(new_identity)
def new_scale(cls, x, y):
self = cls()
self.a = x
self.f = y
return self
new_scale = classmethod(new_scale)
def new_translate(cls, x, y):
self = cls()
self.c = x
self.g = y
return self
new_translate = classmethod(new_translate)
def new_rotate(cls, angle):
self = cls()
s = math.sin(angle)
c = math.cos(angle)
self.a = self.f = c
self.b = -s
self.e = s
return self
new_rotate = classmethod(new_rotate)
# a b c d
# e f g h
# i j k l
# m n o p
class Matrix4:
__slots__ = list('abcdefghijklmnop')
def __init__(self):
self.identity()
def __copy__(self):
M = Matrix4()
M.a = self.a
M.b = self.b
M.c = self.c
M.d = self.d
M.e = self.e
M.f = self.f
M.g = self.g
M.h = self.h
M.i = self.i
M.j = self.j
M.k = self.k
M.l = self.l
M.m = self.m
M.n = self.n
M.o = self.o
M.p = self.p
return M
copy = __copy__
def __repr__(self):
return ('Matrix4([% 8.2f % 8.2f % 8.2f % 8.2f\n' \
' % 8.2f % 8.2f % 8.2f % 8.2f\n' \
' % 8.2f % 8.2f % 8.2f % 8.2f\n' \
' % 8.2f % 8.2f % 8.2f % 8.2f])') \
% (self.a, self.b, self.c, self.d,
self.e, self.f, self.g, self.h,
self.i, self.j, self.k, self.l,
self.m, self.n, self.o, self.p)
def __getitem__(self, key):
return [self.a, self.e, self.i, self.m,
self.b, self.f, self.j, self.n,
self.c, self.g, self.k, self.o,
self.d, self.h, self.l, self.p][key]
def __setitem__(self, key, value):
assert not isinstance(key, slice) or \
key.stop - key.start == len(value), 'key length != value length'
L = self[:]
L[key] = value
(self.a, self.e, self.i, self.m,
self.b, self.f, self.j, self.n,
self.c, self.g, self.k, self.o,
self.d, self.h, self.l, self.p) = L
def __mul__(self, other):
if isinstance(other, Matrix4):
# Cache attributes in local vars (see Matrix3.__mul__).
Aa = self.a
Ab = self.b
Ac = self.c
Ad = self.d
Ae = self.e
Af = self.f
Ag = self.g
Ah = self.h
Ai = self.i
Aj = self.j
Ak = self.k
Al = self.l
Am = self.m
An = self.n
Ao = self.o
Ap = self.p
Ba = other.a
Bb = other.b
Bc = other.c
Bd = other.d
Be = other.e
Bf = other.f
Bg = other.g
Bh = other.h
Bi = other.i
Bj = other.j
Bk = other.k
Bl = other.l
Bm = other.m
Bn = other.n
Bo = other.o
Bp = other.p
C = Matrix4()
C.a = Aa * Ba + Ab * Be + Ac * Bi + Ad * Bm
C.b = Aa * Bb + Ab * Bf + Ac * Bj + Ad * Bn
C.c = Aa * Bc + Ab * Bg + Ac * Bk + Ad * Bo
C.d = Aa * Bd + Ab * Bh + Ac * Bl + Ad * Bp
C.e = Ae * Ba + Af * Be + Ag * Bi + Ah * Bm
C.f = Ae * Bb + Af * Bf + Ag * Bj + Ah * Bn
C.g = Ae * Bc + Af * Bg + Ag * Bk + Ah * Bo
C.h = Ae * Bd + Af * Bh + Ag * Bl + Ah * Bp
C.i = Ai * Ba + Aj * Be + Ak * Bi + Al * Bm
C.j = Ai * Bb + Aj * Bf + Ak * Bj + Al * Bn
C.k = Ai * Bc + Aj * Bg + Ak * Bk + Al * Bo
C.l = Ai * Bd + Aj * Bh + Ak * Bl + Al * Bp
C.m = Am * Ba + An * Be + Ao * Bi + Ap * Bm
C.n = Am * Bb + An * Bf + Ao * Bj + Ap * Bn
C.o = Am * Bc + An * Bg + Ao * Bk + Ap * Bo
C.p = Am * Bd + An * Bh + Ao * Bl + Ap * Bp
return C
elif isinstance(other, Point3):
A = self
B = other
P = Point3(0, 0, 0)
P.x = A.a * B.x + A.b * B.y + A.c * B.z + A.d
P.y = A.e * B.x + A.f * B.y + A.g * B.z + A.h
P.z = A.i * B.x + A.j * B.y + A.k * B.z + A.l
return P
elif isinstance(other, AffineVector3):
A = self
B = other
V = AffineVector3(0, 0, 0)
V.x = A.a * B.x + A.b * B.y + A.c * B.z + A.d * B.w
V.y = A.e * B.x + A.f * B.y + A.g * B.z + A.h * B.w
V.z = A.i * B.x + A.j * B.y + A.k * B.z + A.l * B.w
return V
elif isinstance(other, Vector3):
A = self
B = other
V = Vector3(0, 0, 0)
V.x = A.a * B.x + A.b * B.y + A.c * B.z
V.y = A.e * B.x + A.f * B.y + A.g * B.z
V.z = A.i * B.x + A.j * B.y + A.k * B.z
return V
else:
other = other.copy()
other._apply_transform(self)
return other
def __imul__(self, other):
assert isinstance(other, Matrix4)
# Cache attributes in local vars (see Matrix3.__mul__).
Aa = self.a
Ab = self.b
Ac = self.c
Ad = self.d
Ae = self.e
Af = self.f
Ag = self.g
Ah = self.h
Ai = self.i
Aj = self.j
Ak = self.k
Al = self.l
Am = self.m
An = self.n
Ao = self.o
Ap = self.p
Ba = other.a
Bb = other.b
Bc = other.c
Bd = other.d
Be = other.e
Bf = other.f
Bg = other.g
Bh = other.h
Bi = other.i
Bj = other.j
Bk = other.k
Bl = other.l
Bm = other.m
Bn = other.n
Bo = other.o
Bp = other.p
self.a = Aa * Ba + Ab * Be + Ac * Bi + Ad * Bm
self.b = Aa * Bb + Ab * Bf + Ac * Bj + Ad * Bn
self.c = Aa * Bc + Ab * Bg + Ac * Bk + Ad * Bo
self.d = Aa * Bd + Ab * Bh + Ac * Bl + Ad * Bp
self.e = Ae * Ba + Af * Be + Ag * Bi + Ah * Bm
self.f = Ae * Bb + Af * Bf + Ag * Bj + Ah * Bn
self.g = Ae * Bc + Af * Bg + Ag * Bk + Ah * Bo
self.h = Ae * Bd + Af * Bh + Ag * Bl + Ah * Bp
self.i = Ai * Ba + Aj * Be + Ak * Bi + Al * Bm
self.j = Ai * Bb + Aj * Bf + Ak * Bj + Al * Bn
self.k = Ai * Bc + Aj * Bg + Ak * Bk + Al * Bo
self.l = Ai * Bd + Aj * Bh + Ak * Bl + Al * Bp
self.m = Am * Ba + An * Be + Ao * Bi + Ap * Bm
self.n = Am * Bb + An * Bf + Ao * Bj + Ap * Bn
self.o = Am * Bc + An * Bg + Ao * Bk + Ap * Bo
self.p = Am * Bd + An * Bh + Ao * Bl + Ap * Bp
return self
def identity(self):
self.a = self.f = self.k = self.p = 1.
self.b = self.c = self.d = self.e = self.g = self.h = \
self.i = self.j = self.l = self.m = self.n = self.o = 0
return self
def scale(self, x, y, z):
self *= Matrix4.new_scale(x, y, z)
return self
def translate(self, x, y, z):
self *= Matrix4.new_translate(x, y, z)
return self
def rotatex(self, angle):
self *= Matrix4.new_rotatex(angle)
return self
def rotatey(self, angle):
self *= Matrix4.new_rotatey(angle)
return self
def rotatez(self, angle):
self *= Matrix4.new_rotatez(angle)
return self
def rotate_axis(self, angle, axis):
self *= Matrix4.new_rotate_axis(angle, axis)
return self
def rotate_euler(self, heading, attitude, bank):
self *= Matrix4.new_rotate_euler(heading, attitude, bank)
return self
# Static constructors
def new_identity(cls):
self = cls()
return self
new_identity = classmethod(new_identity)
def new_scale(cls, x, y, z):
self = cls()
self.a = x
self.f = y
self.k = z
return self
new_scale = classmethod(new_scale)
def new_translate(cls, x, y, z):
self = cls()
self.d = x
self.h = y
self.l = z
return self
new_translate = classmethod(new_translate)
def new_rotatex(cls, angle):
self = cls()
s = math.sin(angle)
c = math.cos(angle)
self.f = self.k = c
self.g = -s
self.j = s
return self
new_rotatex = classmethod(new_rotatex)
def new_rotatey(cls, angle):
self = cls()
s = math.sin(angle)
c = math.cos(angle)
self.a = self.k = c
self.c = s
self.i = -s
return self
new_rotatey = classmethod(new_rotatey)
def new_rotatez(cls, angle):
self = cls()
s = math.sin(angle)
c = math.cos(angle)
self.a = self.f = c
self.b = -s
self.e = s
return self
new_rotatez = classmethod(new_rotatez)
def new_rotate_axis(cls, angle, axis):
assert(isinstance(axis, Vector3))
vector = axis.normalized()
x = vector.x
y = vector.y
z = vector.z
self = cls()
s = math.sin(angle)
c = math.cos(angle)
c1 = 1. - c
# from the glRotate man page
self.a = x * x * c1 + c
self.b = x * y * c1 - z * s
self.c = x * z * c1 + y * s
self.e = y * x * c1 + z * s
self.f = y * y * c1 + c
self.g = y * z * c1 - x * s
self.i = x * z * c1 - y * s
self.j = y * z * c1 + x * s
self.k = z * z * c1 + c
return self
new_rotate_axis = classmethod(new_rotate_axis)
def new_rotate_euler(cls, heading, attitude, bank):
# from http://www.euclideanspace.com/
ch = math.cos(heading)
sh = math.sin(heading)
ca = math.cos(attitude)
sa = math.sin(attitude)
cb = math.cos(bank)
sb = math.sin(bank)
self = cls()
self.a = ch * ca
self.b = sh * sb - ch * sa * cb
self.c = ch * sa * sb + sh * cb
self.e = sa
self.f = ca * cb
self.g = -ca * sb
self.i = -sh * ca
self.j = sh * sa * cb + ch * sb
self.k = -sh * sa * sb + ch * cb
return self
new_rotate_euler = classmethod(new_rotate_euler)
def new_perspective(cls, fov_y, aspect, near, far):
# from the gluPerspective man page
f = 1 / math.tan(fov_y / 2)
self = cls()
assert near != 0.0 and near != far
self.a = f / aspect
self.f = f
self.k = (far + near) / (near - far)
self.l = 2 * far * near / (near - far)
self.o = -1
self.p = 0
return self
new_perspective = classmethod(new_perspective)
class Quaternion:
# All methods and naming conventions based off
# http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions
# w is the real part, (x, y, z) are the imaginary parts
__slots__ = ['w', 'x', 'y', 'z']
def __init__(self):
self.identity()
def __copy__(self):
Q = Quaternion()
Q.w = self.w
Q.x = self.x
Q.y = self.y
Q.z = self.z
copy = __copy__
def __repr__(self):
return 'Quaternion(real=%.2f, imag=<%.2f, %.2f, %.2f>)' % \
(self.w, self.x, self.y, self.z)
def __mul__(self, other):
if isinstance(other, Quaternion):
Ax = self.x
Ay = self.y
Az = self.z
Aw = self.w
Bx = other.x
By = other.y
Bz = other.z
Bw = other.w
Q = Quaternion()
Q.x = Ax * Bw + Ay * Bz - Az * By + Aw * Bx
Q.y = -Ax * Bz + Ay * Bw + Az * Bx + Aw * By
Q.z = Ax * By - Ay * Bx + Az * Bw + Aw * Bz
Q.w = -Ax * Bx - Ay * By - Az * Bz + Aw * Bw
return Q
elif isinstance(other, Vector3):
w = self.w
x = self.x
y = self.y
z = self.z
Vx = other.x
Vy = other.y
Vz = other.z
return other.__class__(\
w * w * Vx + 2 * y * w * Vz - 2 * z * w * Vy + \
x * x * Vx + 2 * y * x * Vy + 2 * z * x * Vz - \
z * z * Vx - y * y * Vx,
2 * x * y * Vx + y * y * Vy + 2 * z * y * Vz + \
2 * w * z * Vx - z * z * Vy + w * w * Vy - \
2 * x * w * Vz - x * x * Vy,
2 * x * z * Vx + 2 * y * z * Vy + \
z * z * Vz - 2 * w * y * Vx - y * y * Vz + \
2 * w * x * Vy - x * x * Vz + w * w * Vz)
else:
other = other.copy()
other._apply_transform(self)
return other
def __imul__(self, other):
assert isinstance(other, Quaternion)
Ax = self.x
Ay = self.y
Az = self.z
Aw = self.w
Bx = other.x
By = other.y
Bz = other.z
Bw = other.w
self.x = Ax * Bw + Ay * Bz - Az * By + Aw * Bx
self.y = -Ax * Bz + Ay * Bw + Az * Bx + Aw * By
self.z = Ax * By - Ay * Bx + Az * Bw + Aw * Bz
self.w = -Ax * Bx - Ay * By - Az * Bz + Aw * Bw
return self
def __abs__(self):
return math.sqrt(self.w ** 2 + \
self.x ** 2 + \
self.y ** 2 + \
self.z ** 2)
magnitude = __abs__
def magnitude_squared(self):
return self.w ** 2 + \
self.x ** 2 + \
self.y ** 2 + \
self.z ** 2
def identity(self):
self.w = 1
self.x = 0
self.y = 0
self.z = 0
return self
def rotate_axis(self, angle, axis):
self *= Quaternion.new_rotate_axis(angle, axis)
return self
def rotate_euler(self, heading, attitude, bank):
self *= Quaternion.new_rotate_euler(heading, attitude, bank)
return self
def conjugated(self):
Q = Quaternion()
Q.w = self.w
Q.x = -self.x
Q.y = -self.y
Q.z = -self.z
return Q
def normalize(self):
d = self.magnitude()
if d != 0:
self.w /= d
self.x /= d
self.y /= d
self.z /= d
return self
def normalized(self):
d = self.magnitude()
if d != 0:
Q = Quaternion()
Q.w /= d
Q.x /= d
Q.y /= d
Q.z /= d
return Q
else:
return self.copy()
def get_angle_axis(self):
if self.w > 1:
self = self.normalized()
angle = 2 * math.acos(self.w)
s = math.sqrt(1 - self.w ** 2)
if s < 0.001:
return angle, Vector3(1, 0, 0)
else:
return angle, Vector3(self.x / s, self.y / s, self.z / s)
def get_euler(self):
t = self.x * self.y + self.z * self.w
if t > 0.4999:
heading = 2 * math.atan2(self.x, self.w)
attitude = math.pi / 2
bank = 0
elif t < -0.4999:
heading = -2 * math.atan2(self.x, self.w)
attitude = -math.pi / 2
bank = 0
else:
sqx = self.x ** 2
sqy = self.y ** 2
sqz = self.z ** 2
heading = math.atan2(2 * self.y * self.w - 2 * self.x * self.z,
1 - 2 * sqy - 2 * sqz)
attitude = math.asin(2 * t)
bank = math.atan2(2 * self.x * self.w - 2 * self.y * self.z,
1 - 2 * sqx - 2 * sqz)
return heading, attitude, bank
def get_matrix(self):
xx = self.x ** 2
xy = self.x * self.y
xz = self.x * self.z
xw = self.x * self.w
yy = self.y ** 2
yz = self.y * self.z
yw = self.y * self.w
zz = self.z ** 2
zw = self.z * self.w
M = Matrix4()
M.a = 1 - 2 * (yy + zz)
M.b = 2 * (xy - zw)
M.c = 2 * (xz + yw)
M.e = 2 * (xy + zw)
M.f = 1 - 2 * (xx + zz)
M.g = 2 * (yz - xw)
M.i = 2 * (xz - yw)
M.j = 2 * (yz + xw)
M.k = 1 - 2 * (xx + yy)
return M
# Static constructors
def new_identity(cls):
return cls()
new_identity = classmethod(new_identity)
def new_rotate_axis(cls, angle, axis):
assert(isinstance(axis, Vector3))
axis = axis.normalized()
s = math.sin(angle / 2)
Q = cls()
Q.w = math.cos(angle / 2)
Q.x = axis.x * s
Q.y = axis.y * s
Q.z = axis.z * s
return Q
new_rotate_axis = classmethod(new_rotate_axis)
def new_rotate_euler(cls, heading, attitude, bank):
Q = cls()
c1 = math.cos(heading / 2)
s1 = math.sin(heading / 2)
c2 = math.cos(attitude / 2)
s2 = math.sin(attitude / 2)
c3 = math.cos(bank / 2)
s3 = math.sin(bank / 2)
Q.w = c1 * c2 * c3 - s1 * s2 * s3
Q.x = s1 * s2 * c3 + c1 * c2 * s3
Q.y = s1 * c2 * c3 + c1 * s2 * s3
Q.z = c1 * s2 * c3 - s1 * c2 * s3
return Q
new_rotate_euler = classmethod(new_rotate_euler)
def new_interpolate(cls, q1, q2, t):
assert isinstance(q1, Quaternion) and isinstance(q2, Quaternion)
Q = cls()
costheta = q1.w * q2.w + q1.x * q2.x + q1.y * q2.y + q1.z * q2.z
theta = math.acos(costheta)
if abs(theta) < 0.01:
Q.w = q2.w
Q.x = q2.x
Q.y = q2.y
Q.z = q2.z
return Q
sintheta = math.sqrt(1.0 - costheta * costheta)
if abs(sintheta) < 0.01:
Q.w = (q1.w + q2.w) * 0.5
Q.x = (q1.x + q2.x) * 0.5
Q.y = (q1.y + q2.y) * 0.5
Q.z = (q1.z + q2.z) * 0.5
return Q
ratio1 = math.sin((1 - t) * theta) / sintheta
ratio2 = math.sin(t * theta) / sintheta
Q.w = q1.w * ratio1 + q2.w * ratio2
Q.x = q1.x * ratio1 + q2.x * ratio2
Q.y = q1.y * ratio1 + q2.y * ratio2
Q.z = q1.z * ratio1 + q2.z * ratio2
return Q
new_interpolate = classmethod(new_interpolate)
# Geometry
# Much maths thanks to Paul Bourke, http://astronomy.swin.edu.au/~pbourke
# ---------------------------------------------------------------------------
class Geometry:
def _connect_unimplemented(self, other):
raise AttributeError, 'Cannot connect %s to %s' % \
(self.__class__, other.__class__)
def _intersect_unimplemented(self, other):
raise AttributeError, 'Cannot intersect %s and %s' % \
(self.__class__, other.__class__)
_intersect_point2 = _intersect_unimplemented
_intersect_line2 = _intersect_unimplemented
_intersect_circle = _intersect_unimplemented
_connect_point2 = _connect_unimplemented
_connect_line2 = _connect_unimplemented
_connect_circle = _connect_unimplemented
_intersect_point3 = _intersect_unimplemented
_intersect_line3 = _intersect_unimplemented
_intersect_sphere = _intersect_unimplemented
_intersect_plane = _intersect_unimplemented
_connect_point3 = _connect_unimplemented
_connect_line3 = _connect_unimplemented
_connect_sphere = _connect_unimplemented
_connect_plane = _connect_unimplemented
def intersect(self, other):
raise NotImplementedError
def connect(self, other):
raise NotImplementedError
def distance(self, other):
c = self.connect(other)
if c:
return c.length
return 0.0
def _intersect_point2_circle(P, C):
return abs(P - C.c) <= C.r
def _intersect_line2_line2(A, B):
d = B.v.y * A.v.x - B.v.x * A.v.y
if d == 0:
return None
dy = A.p.y - B.p.y
dx = A.p.x - B.p.x
ua = (B.v.x * dy - B.v.y * dx) / d
if not A._u_in(ua):
return None
ub = (A.v.x * dy - A.v.y * dx) / d
if not B._u_in(ub):
return None
return Point2(A.p.x + ua * A.v.x,
A.p.y + ua * A.v.y)
def _intersect_line2_circle(L, C):
a = L.v.magnitude_squared()
b = 2 * (L.v.x * (L.p.x - C.c.x) + \
L.v.y * (L.p.y - C.c.y))
c = C.c.magnitude_squared() + \
L.p.magnitude_squared() - \
2 * C.c.dot(L.p) - \
C.r ** 2
det = b ** 2 - 4 * a * c
if det < 0:
return None
sq = math.sqrt(det)
u1 = (-b + sq) / (2 * a)
u2 = (-b - sq) / (2 * a)
if not L._u_in(u1):
u1 = max(min(u1, 1.0), 0.0)
if not L._u_in(u2):
u2 = max(min(u2, 1.0), 0.0)
return LineSegment2(Point2(L.p.x + u1 * L.v.x,
L.p.y + u1 * L.v.y),
Point2(L.p.x + u2 * L.v.x,
L.p.y + u2 * L.v.y))
def _connect_point2_line2(P, L):
d = L.v.magnitude_squared()
assert d != 0
u = ((P.x - L.p.x) * L.v.x + \
(P.y - L.p.y) * L.v.y) / d
if not L._u_in(u):
u = max(min(u, 1.0), 0.0)
return LineSegment2(P,
Point2(L.p.x + u * L.v.x,
L.p.y + u * L.v.y))
def _connect_point2_circle(P, C):
v = P - C.c
v.normalize()
v *= C.r
return LineSegment2(P, Point2(C.c.x + v.x, C.c.y + v.y))
def _connect_line2_line2(A, B):
d = B.v.y * A.v.x - B.v.x * A.v.y
if d == 0:
# Parallel, connect an endpoint with a line
if isinstance(B, Ray2) or isinstance(B, LineSegment2):
p1, p2 = _connect_point2_line2(B.p, A)
return p2, p1
# No endpoint (or endpoint is on A), possibly choose arbitrary point
# on line.
return _connect_point2_line2(A.p, B)
dy = A.p.y - B.p.y
dx = A.p.x - B.p.x
ua = (B.v.x * dy - B.v.y * dx) / d
if not A._u_in(ua):
ua = max(min(ua, 1.0), 0.0)
ub = (A.v.x * dy - A.v.y * dx) / d
if not B._u_in(ub):
ub = max(min(ub, 1.0), 0.0)
return LineSegment2(Point2(A.p.x + ua * A.v.x, A.p.y + ua * A.v.y),
Point2(B.p.x + ub * B.v.x, B.p.y + ub * B.v.y))
def _connect_circle_line2(C, L):
d = L.v.magnitude_squared()
assert d != 0
u = ((C.c.x - L.p.x) * L.v.x + (C.c.y - L.p.y) * L.v.y) / d
if not L._u_in(u):
u = max(min(u, 1.0), 0.0)
point = Point2(L.p.x + u * L.v.x, L.p.y + u * L.v.y)
v = (point - C.c)
v.normalize()
v *= C.r
return LineSegment2(Point2(C.c.x + v.x, C.c.y + v.y), point)
def _connect_circle_circle(A, B):
v = B.c - A.c
v.normalize()
return LineSegment2(Point2(A.c.x + v.x * A.r, A.c.y + v.y * A.r),
Point2(B.c.x - v.x * B.r, B.c.y - v.y * B.r))
class Point2(Vector2, Geometry):
def __repr__(self):
return 'Point2(%.2f, %.2f)' % (self.x, self.y)
def intersect(self, other):
return other._intersect_point2(self)
def _intersect_circle(self, other):
return _intersect_point2_circle(self, other)
def connect(self, other):
return other._connect_point2(self)
def _connect_point2(self, other):
return LineSegment2(other, self)
def _connect_line2(self, other):
c = _connect_point2_line2(self, other)
if c:
return c._swap()
def _connect_circle(self, other):
c = _connect_point2_circle(self, other)
if c:
return c._swap()
class Line2(Geometry):
__slots__ = ['p', 'v']
def __init__(self, *args):
if len(args) == 3:
assert isinstance(args[0], Point2) and \
isinstance(args[1], Vector2) and \
type(args[2]) == float
self.p = args[0].copy()
self.v = args[1] * args[2] / abs(args[1])
elif len(args) == 2:
if isinstance(args[0], Point2) and isinstance(args[1], Point2):
self.p = args[0].copy()
self.v = args[1] - args[0]
elif isinstance(args[0], Point2) and isinstance(args[1], Vector2):
self.p = args[0].copy()
self.v = args[1].copy()
else:
raise AttributeError, '%r' % (args,)
elif len(args) == 1:
if isinstance(args[0], Line2):
self.p = args[0].p.copy()
self.v = args[0].v.copy()
else:
raise AttributeError, '%r' % (args,)
else:
raise AttributeError, '%r' % (args,)
if not self.v:
raise AttributeError, 'Line has zero-length vector'
def __copy__(self):
return self.__class__(self.p, self.v)
copy = __copy__
def __repr__(self):
return 'Line2(<%.2f, %.2f> + u<%.2f, %.2f>)' % \
(self.p.x, self.p.y, self.v.x, self.v.y)
p1 = property(lambda self: self.p)
p2 = property(lambda self: Point2(self.p.x + self.v.x,
self.p.y + self.v.y))
def _apply_transform(self, t):
self.p = t * self.p
self.v = t * self.v
def _u_in(self, u):
return True
def intersect(self, other):
return other._intersect_line2(self)
def _intersect_line2(self, other):
return _intersect_line2_line2(self, other)
def _intersect_circle(self, other):
return _intersect_line2_circle(self, other)
def connect(self, other):
return other._connect_line2(self)
def _connect_point2(self, other):
return _connect_point2_line2(other, self)
def _connect_line2(self, other):
return _connect_line2_line2(other, self)
def _connect_circle(self, other):
return _connect_circle_line2(other, self)
class Ray2(Line2):
def __repr__(self):
return 'Ray2(<%.2f, %.2f> + u<%.2f, %.2f>)' % \
(self.p.x, self.p.y, self.v.x, self.v.y)
def _u_in(self, u):
return u >= 0.0
class LineSegment2(Line2):
def __repr__(self):
return 'LineSegment2(<%.2f, %.2f> to <%.2f, %.2f>)' % \
(self.p.x, self.p.y, self.p.x + self.v.x, self.p.y + self.v.y)
def _u_in(self, u):
return u >= 0.0 and u <= 1.0
def __abs__(self):
return abs(self.v)
def magnitude_squared(self):
return self.v.magnitude_squared()
def _swap(self):
# used by connect methods to switch order of points
self.p = self.p2
self.v *= -1
return self
length = property(lambda self: abs(self.v))
class Circle(Geometry):
__slots__ = ['c', 'r']
def __init__(self, center, radius):
assert isinstance(center, Vector2) and type(radius) == float
self.c = center.copy()
self.r = radius
def __copy__(self):
return self.__class__(self.c, self.r)
copy = __copy__
def __repr__(self):
return 'Circle(<%.2f, %.2f>, radius=%.2f)' % \
(self.c.x, self.c.y, self.r)
def _apply_transform(self, t):
self.c = t * self.c
def intersect(self, other):
return other._intersect_circle(self)
def _intersect_point2(self, other):
return _intersect_point2_circle(other, self)
def _intersect_line2(self, other):
return _intersect_line2_circle(other, self)
def connect(self, other):
return other._connect_circle(self)
def _connect_point2(self, other):
return _connect_point2_circle(other, self)
def _connect_line2(self, other):
c = _connect_circle_line2(self, other)
if c:
return c._swap()
def _connect_circle(self, other):
return _connect_circle_circle(other, self)
# 3D Geometry
# -------------------------------------------------------------------------
def _connect_point3_line3(P, L):
d = L.v.magnitude_squared()
assert d != 0
u = ((P.x - L.p.x) * L.v.x + \
(P.y - L.p.y) * L.v.y + \
(P.z - L.p.z) * L.v.z) / d
if not L._u_in(u):
u = max(min(u, 1.0), 0.0)
return LineSegment3(P, Point3(L.p.x + u * L.v.x,
L.p.y + u * L.v.y,
L.p.z + u * L.v.z))
def _connect_point3_sphere(P, S):
v = P - S.c
v.normalize()
v *= S.r
return LineSegment3(P, Point3(S.c.x + v.x, S.c.y + v.y, S.c.z + v.z))
def _connect_point3_plane(p, plane):
n = plane.n.normalized()
d = p.dot(plane.n) - plane.k
return LineSegment3(p, Point3(p.x - n.x * d, p.y - n.y * d, p.z - n.z * d))
def _connect_line3_line3(A, B):
assert A.v and B.v
p13 = A.p - B.p
d1343 = p13.dot(B.v)
d4321 = B.v.dot(A.v)
d1321 = p13.dot(A.v)
d4343 = B.v.magnitude_squared()
denom = A.v.magnitude_squared() * d4343 - d4321 ** 2
if denom == 0:
# Parallel, connect an endpoint with a line
if isinstance(B, Ray3) or isinstance(B, LineSegment3):
return _connect_point3_line3(B.p, A)._swap()
# No endpoint (or endpoint is on A), possibly choose arbitrary
# point on line.
return _connect_point3_line3(A.p, B)
ua = (d1343 * d4321 - d1321 * d4343) / denom
if not A._u_in(ua):
ua = max(min(ua, 1.0), 0.0)
ub = (d1343 + d4321 * ua) / d4343
if not B._u_in(ub):
ub = max(min(ub, 1.0), 0.0)
return LineSegment3(Point3(A.p.x + ua * A.v.x,
A.p.y + ua * A.v.y,
A.p.z + ua * A.v.z),
Point3(B.p.x + ub * B.v.x,
B.p.y + ub * B.v.y,
B.p.z + ub * B.v.z))
def _connect_line3_plane(L, P):
d = P.n.dot(L.v)
if not d:
# Parallel, choose an endpoint
return _connect_point3_plane(L.p, P)
u = (P.k - P.n.dot(L.p)) / d
if not L._u_in(u):
# intersects out of range, choose nearest endpoint
u = max(min(u, 1.0), 0.0)
return _connect_point3_plane(Point3(L.p.x + u * L.v.x,
L.p.y + u * L.v.y,
L.p.z + u * L.v.z), P)
# Intersection
return None
def _connect_sphere_line3(S, L):
d = L.v.magnitude_squared()
assert d != 0
u = ((S.c.x - L.p.x) * L.v.x + \
(S.c.y - L.p.y) * L.v.y + \
(S.c.z - L.p.z) * L.v.z) / d
if not L._u_in(u):
u = max(min(u, 1.0), 0.0)
point = Point3(L.p.x + u * L.v.x, L.p.y + u * L.v.y, L.p.z + u * L.v.z)
v = (point - S.c)
v.normalize()
v *= S.r
return LineSegment3(Point3(S.c.x + v.x, S.c.y + v.y, S.c.z + v.z),
point)
def _connect_sphere_sphere(A, B):
v = B.c - A.c
v.normalize()
return LineSegment3(Point3(A.c.x + v.x * A.r,
A.c.y + v.y * A.r,
A.c.x + v.z * A.r),
Point3(B.c.x + v.x * B.r,
B.c.y + v.y * B.r,
B.c.x + v.z * B.r))
def _connect_sphere_plane(S, P):
c = _connect_point3_plane(S.c, P)
if not c:
return None
p2 = c.p2
v = p2 - S.c
v.normalize()
v *= S.r
return LineSegment3(Point3(S.c.x + v.x, S.c.y + v.y, S.c.z + v.z),
p2)
def _connect_plane_plane(A, B):
if A.n.cross(B.n):
# Planes intersect
return None
else:
# Planes are parallel, connect to arbitrary point
return _connect_point3_plane(A._get_point(), B)
def _intersect_point3_sphere(P, S):
return abs(P - S.c) <= S.r
def _intersect_line3_sphere(L, S):
a = L.v.magnitude_squared()
b = 2 * (L.v.x * (L.p.x - S.c.x) + \
L.v.y * (L.p.y - S.c.y) + \
L.v.z * (L.p.z - S.c.z))
c = S.c.magnitude_squared() + \
L.p.magnitude_squared() - \
2 * S.c.dot(L.p) - \
S.r ** 2
det = b ** 2 - 4 * a * c
if det < 0:
return None
sq = math.sqrt(det)
u1 = (-b + sq) / (2 * a)
u2 = (-b - sq) / (2 * a)
if not L._u_in(u1):
u1 = max(min(u1, 1.0), 0.0)
if not L._u_in(u2):
u2 = max(min(u2, 1.0), 0.0)
return LineSegment3(Point3(L.p.x + u1 * L.v.x,
L.p.y + u1 * L.v.y,
L.p.z + u1 * L.v.z),
Point3(L.p.x + u2 * L.v.x,
L.p.y + u2 * L.v.y,
L.p.z + u2 * L.v.z))
def _intersect_line3_plane(L, P):
d = P.n.dot(L.v)
if not d:
# Parallel
return None
u = (P.k - P.n.dot(L.p)) / d
if not L._u_in(u):
return None
return Point3(L.p.x + u * L.v.x,
L.p.y + u * L.v.y,
L.p.z + u * L.v.z)
def _intersect_plane_plane(A, B):
n1_m = A.n.magnitude_squared()
n2_m = B.n.magnitude_squared()
n1d2 = A.n.dot(B.n)
det = n1_m * n2_m - n1d2 ** 2
if det == 0:
# Parallel
return None
c1 = (A.k * n2_m - B.k * n1d2) / det
c2 = (B.k * n1_m - A.k * n1d2) / det
return Line3(Point3(c1 * A.n.x + c2 * B.n.x,
c1 * A.n.y + c2 * B.n.y,
c1 * A.n.z + c2 * B.n.z),
A.n.cross(B.n))
class Point3(Vector3, Geometry):
def __repr__(self):
return 'Point3(%.2f, %.2f, %.2f)' % (self.x, self.y, self.z)
def intersect(self, other):
return other._intersect_point3(self)
def _intersect_sphere(self, other):
return _intersect_point3_sphere(self, other)
def connect(self, other):
return other._connect_point3(self)
def _connect_point3(self, other):
if self != other:
return LineSegment3(other, self)
return None
def _connect_line3(self, other):
c = _connect_point3_line3(self, other)
if c:
return c._swap()
def _connect_sphere(self, other):
c = _connect_point3_sphere(self, other)
if c:
return c._swap()
def _connect_plane(self, other):
c = _connect_point3_plane(self, other)
if c:
return c._swap()
class Line3:
__slots__ = ['p', 'v']
def __init__(self, *args):
if len(args) == 3:
assert isinstance(args[0], Point3) and \
isinstance(args[1], Vector3) and \
type(args[2]) == float
self.p = args[0].copy()
self.v = args[1] * args[2] / abs(args[1])
elif len(args) == 2:
if isinstance(args[0], Point3) and isinstance(args[1], Point3):
self.p = args[0].copy()
self.v = args[1] - args[0]
elif isinstance(args[0], Point3) and isinstance(args[1], Vector3):
self.p = args[0].copy()
self.v = args[1].copy()
else:
raise AttributeError, '%r' % (args,)
elif len(args) == 1:
if isinstance(args[0], Line3):
self.p = args[0].p.copy()
self.v = args[0].v.copy()
else:
raise AttributeError, '%r' % (args,)
else:
raise AttributeError, '%r' % (args,)
# XXX This is annoying.
#if not self.v:
# raise AttributeError, 'Line has zero-length vector'
def __copy__(self):
return self.__class__(self.p, self.v)
copy = __copy__
def __repr__(self):
return 'Line3(<%.2f, %.2f, %.2f> + u<%.2f, %.2f, %.2f>)' % \
(self.p.x, self.p.y, self.p.z, self.v.x, self.v.y, self.v.z)
p1 = property(lambda self: self.p)
p2 = property(lambda self: Point3(self.p.x + self.v.x,
self.p.y + self.v.y,
self.p.z + self.v.z))
def _apply_transform(self, t):
self.p = t * self.p
self.v = t * self.v
def _u_in(self, u):
return True
def intersect(self, other):
return other._intersect_line3(self)
def _intersect_sphere(self, other):
return _intersect_line3_sphere(self, other)
def _intersect_plane(self, other):
return _intersect_line3_plane(self, other)
def connect(self, other):
return other._connect_line3(self)
def _connect_point3(self, other):
return _connect_point3_line3(other, self)
def _connect_line3(self, other):
return _connect_line3_line3(other, self)
def _connect_sphere(self, other):
return _connect_sphere_line3(other, self)
def _connect_plane(self, other):
c = _connect_line3_plane(self, other)
if c:
return c
class Ray3(Line3):
def __repr__(self):
return 'Ray3(<%.2f, %.2f, %.2f> + u<%.2f, %.2f, %.2f>)' % \
(self.p.x, self.p.y, self.p.z, self.v.x, self.v.y, self.v.z)
def _u_in(self, u):
return u >= 0.0
class LineSegment3(Line3):
def __repr__(self):
return 'LineSegment3(<%.2f, %.2f, %.2f> to <%.2f, %.2f, %.2f>)' % \
(self.p.x, self.p.y, self.p.z,
self.p.x + self.v.x, self.p.y + self.v.y, self.p.z + self.v.z)
def _u_in(self, u):
return u >= 0.0 and u <= 1.0
def __abs__(self):
return abs(self.v)
def magnitude_squared(self):
return self.v.magnitude_squared()
def _swap(self):
# used by connect methods to switch order of points
self.p = self.p2
self.v *= -1
return self
length = property(lambda self: abs(self.v))
class Sphere:
__slots__ = ['c', 'r']
def __init__(self, center, radius):
assert isinstance(center, Vector3) and type(radius) == float
self.c = center.copy()
self.r = radius
def __copy__(self):
return self.__class__(self.c, self.r)
copy = __copy__
def __repr__(self):
return 'Sphere(<%.2f, %.2f, %.2f>, radius=%.2f)' % \
(self.c.x, self.c.y, self.c.z, self.r)
def _apply_transform(self, t):
self.c = t * self.c
def intersect(self, other):
return other._intersect_sphere(self)
def _intersect_point3(self, other):
return _intersect_point3_sphere(other, self)
def _intersect_line3(self, other):
return _intersect_line3_sphere(other, self)
def connect(self, other):
return other._connect_sphere(self)
def _connect_point3(self, other):
return _connect_point3_sphere(other, self)
def _connect_line3(self, other):
c = _connect_sphere_line3(self, other)
if c:
return c._swap()
def _connect_sphere(self, other):
return _connect_sphere_sphere(other, self)
def _connect_plane(self, other):
c = _connect_sphere_plane(self, other)
if c:
return c
class Plane:
# n.p = k, where n is normal, p is point on plane, k is constant scalar
__slots__ = ['n', 'k']
def __init__(self, *args):
if len(args) == 3:
assert isinstance(args[0], Point3) and \
isinstance(args[1], Point3) and \
isinstance(args[2], Point3)
self.n = (args[1] - args[0]).cross(args[2] - args[0])
self.n.normalize()
self.k = self.n.dot(args[0])
elif len(args) == 2:
if isinstance(args[0], Point3) and isinstance(args[1], Vector3):
self.n = args[1].normalized()
self.k = self.n.dot(args[0])
elif isinstance(args[0], Vector3) and type(args[1]) == float:
self.n = args[0].normalized()
self.k = args[1]
else:
raise AttributeError, '%r' % (args,)
else:
raise AttributeError, '%r' % (args,)
if not self.n:
raise AttributeError, 'Points on plane are colinear'
def __copy__(self):
return self.__class__(self.n, self.k)
copy = __copy__
def __repr__(self):
return 'Plane(<%.2f, %.2f, %.2f>.p = %.2f)' % \
(self.n.x, self.n.y, self.n.z, self.k)
def _get_point(self):
# Return an arbitrary point on the plane
if self.n.z:
return Point3(0., 0., self.k / self.n.z)
elif self.n.y:
return Point3(0., self.k / self.n.y, 0.)
else:
return Point3(self.k / self.n.x, 0., 0.)
def _apply_transform(self, t):
p = t * self._get_point()
self.n = t * self.n
self.k = self.n.dot(p)
def intersect(self, other):
return other._intersect_plane(self)
def _intersect_line3(self, other):
return _intersect_line3_plane(other, self)
def _intersect_plane(self, other):
return _intersect_plane_plane(self, other)
def connect(self, other):
return other._connect_plane(self)
def _connect_point3(self, other):
return _connect_point3_plane(other, self)
def _connect_line3(self, other):
return _connect_line3_plane(other, self)
def _connect_sphere(self, other):
return _connect_sphere_plane(other, self)
def _connect_plane(self, other):
return _connect_plane_plane(other, self)
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: gl_tree_test.py 114 2006-10-22 09:46:11Z r1chardj0n3s $'
import math
import random
from pyglet.window import *
from pyglet.window import mouse
from pyglet import clock
from ctypes import *
from pyglet.window.event import *
from pyglet.ext.model.geometric import tree_list
from pyglet.gl import *
four_floats = c_float * 4
def setup_scene():
glEnable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60., 1., 1., 100.)
glMatrixMode(GL_MODELVIEW)
glClearColor(1, 1, 1, 1)
class Tree(object):
def __init__(self, n=2, r=False):
self.tree = tree_list(n, r)
self.x = self.y = 0
self.rx = self.ry = 0
self.zpos = -10
self.lmb = False
self.rmb = False
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
if buttons & mouse.LEFT:
self.rx += dx
self.ry += dy
if buttons & mouse.RIGHT:
self.x += dx
self.y += dy
def on_mouse_scroll(self, x, y, dx, dy):
self.zpos = max(-10, self.zpos + dy)
def draw(self):
glPushMatrix()
glLoadIdentity()
glTranslatef(self.x/10., -self.y/10., self.zpos)
glRotatef(self.ry, 1., 0., 0.)
glRotatef(self.rx, 0., 1., 0.)
self.tree.draw()
glPopMatrix()
# need one display list per window
w1 = Window(width=300, height=300)
w1.switch_to()
setup_scene()
tree1 = Tree(n=10, r=True)
w1.push_handlers(tree1)
w2 = Window(width=300, height=300)
w2.switch_to()
setup_scene()
tree2 = Tree(n=10, r=False)
w2.push_handlers(tree2)
n = 0
clock.set_fps_limit(30)
while not (w1.has_exit or w2.has_exit):
clock.tick()
n += 1
# draw
w1.switch_to()
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
w1.dispatch_events()
tree1.draw()
w1.flip()
w2.switch_to()
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
w2.dispatch_events()
tree2.draw()
w2.flip()
| Python |
#!/usr/bin/python
# $Id:$
'''OpenGL viewports and projections.
This is a simplified interface for setting up projections, and viewports
within projections.
A `Viewport` is a rectangular area in space that can be rendered into. Most
viewports, with the exception of the top-level viewport, belong to an owning
projection. A `Projection` is a function for mapping 2D or 3D objects into an
owning viewport.
The top-level Viewport is an instance of `WindowViewport`, which fills
the entire window. This viewport will automatically resize when the window
is resized.
The two possible projections are `OrthographicProjection` and
`PerspectiveProjection`. OrthographicProjection maps to the same coordinate
space as the viewport it belongs to. PerspectiveProjection uses an arbitrary
unit and a specified field-of-view, and is used to map 3D objects into the
2D viewport.
To use the projection module to render in 2D in a window:
from pyglet.ext import projection
w = window.Window()
viewport = projection.WindowViewport(w)
projection = projection.OrthographicProjection(viewport)
@w.event
def on_resize(width, height):
projection.apply()
You can also embed additional viewports within a projection. For example,
a 3D scene can be created within a 2D user interface::
# x, y, width, height give dimensions of inner viewport within window
inner_viewport = OrthographicViewport(projection, x, y, width, height)
inner_projection = PerspectiveProjection(inner_viewport, fov=75)
@w.event
def on_resize(width, height):
inner_projection.apply()
while not w.has_exit:
w.dispatch_events()
w.projection.apply()
# Draw 2D user interface...
inner_projection.apply()
# Draw 3D scene...
w.flip()
'''
from pyglet.gl import *
class Projection(object):
viewport = None
class OrthographicProjection(Projection):
def __init__(self, viewport, near=-1, far=1):
self.viewport = viewport
self.near = near
self.far = far
def apply(self):
self.viewport.apply()
glMatrixMode(GL_PROJECTION)
glOrtho(0, self.viewport.width,
0, self.viewport.height,
self.near, self.far)
glMatrixMode(GL_MODELVIEW)
class PerspectiveProjection(Projection):
def __init__(self, viewport, fov=60, near=0.1, far=1000):
self.viewport = viewport
self.fov = fov
self.near = near
self.far = far
def apply(self):
self.viewport.apply()
glMatrixMode(GL_PROJECTION)
gluPerspective(self.fov,
self.viewport.width/float(self.viewport.height),
self.near,
self.far)
glMatrixMode(GL_MODELVIEW)
class Viewport(object):
projection = None
width = 0
height = 0
class WindowViewport(Viewport):
def __init__(self, window):
self.window = window
def apply(self):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glViewport(0, 0, self.window.width, self.window.height)
glDisable(GL_CLIP_PLANE0)
glDisable(GL_CLIP_PLANE1)
glDisable(GL_CLIP_PLANE2)
glDisable(GL_CLIP_PLANE3)
width = property(lambda self: self.window.width)
height = property(lambda self: self.window.height)
class OrthographicViewport(Viewport):
def __init__(self, projection, x, y, width, height, near=-1, far=1):
assert isinstance(projection, OrthographicProjection)
self.projection = projection
self.x = x
self.y = y
self.width = width
self.height = height
self.near = near
self.far = far
def apply(self):
l = self.x
r = self.x + self.width
b = self.y
t = self.y + self.height
n = self.near
f = self.far
self.projection.apply()
glMatrixMode(GL_PROJECTION)
glMultMatrixf((GLfloat * 16)(
(r-l)/2, 0, 0, 0,
0, (t-b)/2, 0, 0,
0, 0, (f-n)/2, 0,
(r+l)/2, (t+b)/2, (f+n)/2, 1))
glMatrixMode(GL_MODELVIEW)
glClipPlane(GL_CLIP_PLANE0, (GLdouble * 4)(1, 0, 0, 0))
glClipPlane(GL_CLIP_PLANE1, (GLdouble * 4)(-1, 0, 0, self.width))
glClipPlane(GL_CLIP_PLANE2, (GLdouble * 4)(0, 1, 0, 0))
glClipPlane(GL_CLIP_PLANE3, (GLdouble * 4)(0, -1, 0, self.height))
glEnable(GL_CLIP_PLANE0)
glEnable(GL_CLIP_PLANE1)
glEnable(GL_CLIP_PLANE2)
glEnable(GL_CLIP_PLANE3)
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: WINDOW_OPEN.py 750 2007-03-17 01:16:12Z Alex.Holkner $'
import unittest
from pyglet.gl import *
from pyglet.ext import projection
from pyglet import window
import base_projection
class VIEWPORT_CLIP(unittest.TestCase):
def test_viewport_clip(self):
width, height = 200, 200
w = window.Window(width, height)
w.viewport = projection.WindowViewport(w)
w.projection = projection.OrthographicProjection(w.viewport)
self.views = views = [
projection.OrthographicViewport(w.projection,
0, 0, width/2, height/2),
projection.OrthographicViewport(w.projection,
width/2, 0, width/2, height/2),
projection.OrthographicViewport(w.projection,
width/2, height/2, width/2, height/2),
projection.OrthographicViewport(w.projection,
0, height/2, width/2, height/2),
]
projections = [projection.OrthographicProjection(v) for v in views]
colors = [
(1, 0, 0),
(0, 1, 0),
(0, 0, 1),
(1, 1, 0)
]
while not w.has_exit:
w.dispatch_events()
for color, p in zip(colors, projections)[:4]:
p.apply()
glColor3f(*color)
# Big rectangle that will go outside of viewport
base_projection.fillrect(-width, -height, width*2, height*2)
w.flip()
w.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
# $Id:$
from pyglet.gl import *
def fillrect(x, y, width, height):
glBegin(GL_QUADS)
glVertex2f(x, y)
glVertex2f(x + width, y)
glVertex2f(x + width, y + height)
glVertex2f(x, y + height)
glEnd()
def rect(x, y, width, height):
glBegin(GL_LINE_LOOP)
glVertex2f(x, y)
glVertex2f(x + width, y)
glVertex2f(x + width, y + height)
glVertex2f(x, y + height)
glEnd()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: WINDOW_OPEN.py 750 2007-03-17 01:16:12Z Alex.Holkner $'
import unittest
from pyglet.gl import *
from pyglet.ext import projection
from pyglet import window
import base_projection
class VIEWPORT_ORTHO(unittest.TestCase):
def test_viewport_ortho(self):
width, height = 200, 200
w = window.Window(width, height)
w.viewport = projection.WindowViewport(w)
w.projection = projection.OrthographicProjection(w.viewport)
self.views = views = [
projection.OrthographicViewport(w.projection,
0, 0, width/2, height/2),
projection.OrthographicViewport(w.projection,
width/2, 0, width/2, height/2),
projection.OrthographicViewport(w.projection,
width/2, height/2, width/2, height/2),
projection.OrthographicViewport(w.projection,
0, height/2, width/2, height/2),
]
projections = [projection.OrthographicProjection(v) for v in views]
colors = [
(1, 0, 0),
(0, 1, 0),
(0, 0, 1),
(1, 1, 0)
]
while not w.has_exit:
w.dispatch_events()
for color, p in zip(colors, projections):
p.apply()
glColor3f(*color)
base_projection.fillrect(0, 0, width/2, width/2)
w.flip()
w.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
Support for loading XML resource files
======================================
This module provides the Resource class which loads XML resource files
which may contain scene2d image files, atlases, tile sets and maps.
---------------
Getting Started
---------------
Assuming the following XML file called "example.xml"::
<?xml version="1.0"?>
<resource>
<require file="ground-tiles.xml" namespace="ground" />
<rectmap id="level1">
<column>
<cell>
<tile ref="ground:grass" />
</cell>
<cell>
<tile ref="ground:house" />
<property type="bool" name="secretobjective" value="True" />
</cell>
</column>
</map>
</resource>
You may load that resource and examine it::
>>> r = Resource.load('example.xml')
>>> r['level1']
XXX TBD
-----------------
XML file contents
-----------------
XML resource files must contain a document-level tag <resource>::
<?xml version="1.0"?>
<resource>
...
</resource>
You may draw in other resource files by using the <require> tag:
<require file="road-tiles.xml" />
This will load "road-tiles.xml" into the resource's namespace.
If you wish to avoid id clashes you may supply a namespace:
<require file="road-tiles.xml" namespace="road" />
Other tags within <resource> are handled by factories. Standard factories
exist for:
<image file="" id="">
Loads the file into a scene2d.Image2d object.
<imageatlas file="" [id="" size="x,y"]>
Sets up an image atlas for child <image> tags to use. Child tags are of
the form:
<image offset="" id="" [size=""]>
If the <imageatlas> tag does not provide a size attribute then all
child <image> tags must provide one.
<tileset id="">
Sets up a scene2d.TileSet object. Child tags are of the form:
<tile id="">
[<image ...>]
</tile>
The <image> tag is optional, this tiles may have only properties (or be
completely empty).
<rectmap id="" tile_size="" [origin=""]>
Sets up a scene2d.RectMap object. Child tags are of the form:
<column>
<cell tile="" />
</column>
Most tags may additionally have properties specified as:
<property [type=""] name="" value="" />
Where type is one of "unicode", "int", "float" or "bool". The property will
be a unicode string by default if no type is specified.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import xml.dom
import xml.dom.minidom
# support for converting
xml_to_python = {
'unicode': unicode,
'int': int,
'float': float,
'bool': bool,
}
class ResourceError(Exception):
pass
class Resource(dict):
cache = {}
def __init__(self, filename, paths=None):
self.filename = filename
if paths is None:
self.paths = []
else:
self.paths = paths
self.namespaces = {} # map local name to filename
dom = xml.dom.minidom.parse(filename)
tag = dom.documentElement
if tag.tagName != 'resource':
raise ResourceError('document is <%s> instead of <resource>'%
tag.tagName)
try:
self.handle(dom.documentElement)
finally:
dom.unlink()
NOT_LOADED = 'Not Loaded'
@classmethod
def load(cls, filename, paths=None):
'''Load the resource from the XML in the specified file.
'''
# make sure we can find files relative to this one
dirname = os.path.dirname(filename)
if dirname:
if paths:
paths = list(paths)
else:
paths = []
paths.append(dirname)
if filename in cls.cache:
if cls.cache[filename] is cls.NOT_LOADED:
raise ResourceError('Loop in XML files loading "%s"'%filename)
return cls.cache[filename]
cls.cache[filename] = cls.NOT_LOADED
obj = cls(filename, paths)
cls.cache[filename] = obj
return obj
def find_file(self, filename):
if os.path.isabs(filename):
return filename
if os.path.exists(filename):
return filename
for path in self.paths:
fn = os.path.join(path, filename)
if os.path.exists(fn):
return fn
raise ResourceError('File "%s" not found in any paths'%filename)
def resource_factory(self, tag):
for tag in tag.childNodes:
self.handle(tag)
def requires_factory(self, tag):
filename = self.find_file(tag.getAttribute('file'))
# check opened resource files cache
resource = Resource.load(filename)
ns = tag.getAttribute('namespace')
if ns:
self.namespaces[ns] = resource.file
else:
# copy over all the resources from the require'd file
# last man standing wins
self.update(resource)
factories = {
'resource': resource_factory,
'requires': requires_factory,
}
@classmethod
def add_factory(cls, name, factory):
cls.factories[name] = factory
def handle(self, tag):
if not hasattr(tag, 'tagName'): return
ref = tag.getAttribute('ref')
if not ref:
return self.factories[tag.tagName](self, tag)
return self.get_resource(ref)
def add_resource(self, id, resource):
self[id] = resource
def get_resource(self, ref):
if ':' in ref:
ns, ref = ref.split(':', 1)
resources = self.cache[self.namespaces[ns]]
return resources[ref]
return self[ref]
@staticmethod
def handle_properties(tag):
properties = {}
for tag in tag.getElementsByTagName('property'):
name = tag.getAttribute('name')
type = tag.getAttribute('type') or 'unicode'
value = tag.getAttribute('value')
properties[name] = xml_to_python[type](value)
return properties
def register_factory(name):
def decorate(func):
Resource.add_factory(name, func)
return func
return decorate
| Python |
from pyglet.gl import *
class DrawEnv(object):
'''Sets up drawing environment.
My have either or both of a "before" and "after" method.
'''
pass
class DrawBlended(DrawEnv):
'''Sets up texture env for an alpha-blended draw.
'''
def before(self):
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT)
# XXX this belongs in a "DrawTextureBlended" or something
glEnable(GL_TEXTURE_2D)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
def after(self):
glPopAttrib()
DRAW_BLENDED = DrawBlended()
class Drawable(object):
def __init__(self):
self.effects = []
self._style = None
def add_effect(self, effect):
self.effects.append(effect)
self._style = None
def remove_effect(self, effect):
self.effects.remove(effect)
self._style = None
def get_drawstyle(self):
raise NotImplemented('implement on subclass')
def get_style(self):
'''Return the DrawStyle for this Drawable.
This method should return None if nothing should be drawn.
'''
if self._style is None:
self._style = self.get_drawstyle()
for effect in self.effects:
self._style = effect.apply(self._style)
return self._style
def draw(self):
'''Convenience method.
Don't use this if you have a lot of drawables and care about
performance. Collect up your drawables in a list and pass that to
draw_many().
'''
style = self.get_style()
if style is not None: style.draw()
class Effect(object):
def apply(self, style):
'''Modify some aspect of the style. If style.is_copy is False then
.copy() it. We don't do that automatically because there's a chance
this method is a NOOP.
'''
raise NotImplemented()
class TintEffect(Effect):
'''Apply a tint to the Drawable:
For each component RGBA:
resultant color = drawable.color * tint.color
'''
def __init__(self, tint):
self.tint = tint
def apply(self, style):
style = style.copy()
style.color = tuple([style.color[i] * self.tint[i] for i in range(4)])
return style
class ScaleEffect(Effect):
'''Apply a scale to the Drawable.
'''
def __init__(self, sx, sy):
self.sx, self.sy = sx, sy
def apply(self, style):
style = style.copy()
style.sx = self.sx
style.sy = self.sy
return style
class RotateEffect(Effect):
'''Apply a rotation (about the Z axis) to the Drawable.
'''
def __init__(self, angle):
self.angle = angle
def apply(self, style):
style = style.copy()
style.angle = self.angle
return style
class DrawStyle(object):
'''
Notes:
draw_func(<DrawStyle instance>)
'''
def __init__(self, color=None, texture=None, x=0, y=0, sx=1, sy=1,
angle=0, width=None, height=None, uvs=None, draw_list=None,
draw_env=None, draw_func=None):
self.color = color
self.x, self.y = x, y
self.sx, self.sy = sx, sy
self.angle = angle
self.width, self.height = width, height
self.texture = texture
if texture is not None and uvs is None:
raise ValueError('texture and uvs must both be supplied')
self.uvs = uvs
if uvs is not None and texture is None:
raise ValueError('texture and uvs must both be supplied')
self.draw_list = draw_list
self.draw_env = draw_env
self.draw_func = draw_func
self.is_copy = False
def copy(self):
s = DrawStyle(color=self.color, texture=self.texture, x=self.x,
y=self.y, width=self.width, height=self.height,
uvs=self.uvs, draw_list=self.draw_list, draw_env=self.draw_env,
draw_func=self.draw_func)
s.is_copy = True
return s
def draw(self):
if self.color is not None:
glColor4f(*self.color)
if self.texture is not None:
glBindTexture(GL_TEXTURE_2D, self.texture.id)
if hasattr(self.draw_env, 'before'):
self.draw_env.before()
transform = self.x or self.y or self.sx != self.sy != 1 or self.angle
if transform:
glPushMatrix()
if self.x or self.y:
glTranslatef(self.x, self.y, 0)
if self.sx or self.sy:
glScalef(self.sx, self.sy, 1)
if self.angle:
cx, cy = self.width/2, self.height/2
glTranslatef(cx, cy, 0)
glRotatef(self.angle, 0, 0, 1)
glTranslatef(-cx, -cy, 0)
if self.draw_func is not None:
self.draw_func(self)
if self.draw_list is not None:
glCallList(self.draw_list)
if hasattr(self.draw_env, 'after'):
self.draw_env.after()
if transform:
glPopMatrix()
def __cmp__(self, other):
return (
cmp(self.color, other.color) or
cmp(self.texture.id, other.texture.id) or
cmp(self.draw_env, other.draw_env) or
cmp(self.draw_func, other.draw_func) or
cmp(self.draw_list, other.draw_list)
)
def draw_many(drawables):
styles = filter(None, [d.get_style() for d in drawables])
drawables.sort()
old_color = None
old_texture = None
old_env = None
for d in styles:
if d.color != old_color:
glColor4f(*d.color)
old_color = d.color
if d.texture != old_texture:
if d.texture is not None:
glBindTexture(GL_TEXTURE_2D, d.texture.id)
old_texture = d.texture.id
if d.draw_env != old_env:
if old_env is not None and hasattr(old_env, 'after'):
old_env.after()
if hasattr(d.draw_env, 'before'):
d.draw_env.before()
old_env = d.draw_env
transform = d.x or d.y or d.sx != d.sy != 1 or d.angle
if transform:
glPushMatrix()
if d.x or d.y:
glTranslatef(d.x, d.y, 0)
if d.sx != 1 or d.sy != 1:
glScalef(d.sx, d.sy, 1)
if d.angle:
cx, cy = d.width/2, d.height/2
glTranslatef(cx, cy, 0)
glRotatef(d.angle, 0, 0, 1)
glTranslatef(-cx, -cy, 0)
if d.draw_list is not None:
glCallList(d.draw_list)
if d.draw_func is not None:
d.draw_func(d)
if transform:
glPopMatrix()
if old_env is not None and hasattr(old_env, 'after'):
old_env.after()
| Python |
#!/usr/bin/env python
'''
Simple images etc. to aid debugging
===================================
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import math
from scene2d import *
from pyglet import image
from scene2d.drawable import *
from pyglet.gl import *
def brensenham_line(x, y, x2, y2):
'''Modified to draw hex sides in HexCheckImage.
Assumes dy > dx, x>x2 and y2>y which is always the case for what it's
being used for.'''
coords = []
dx = abs(x2 - x)
dy = abs(y2 - y)
d = (2 * dx) - dy
for i in range(0, dy):
coords.append((x, y))
while d >= 0:
x -= 1
d -= (2 * dy)
y += 1
d += (2 * dx)
coords.append((x2,y2))
return coords
class HexCheckImage(Drawable):
COLOURS = [
(.7, .7, .7, 1),
(.9, .9, .9, 1),
(1, 1, 1, 1)
]
def __init__(self, colour, height):
Drawable.__init__(self)
cell = HexCell(0, 0, height, {}, None)
def draw_hex(style):
w = cell.width
line = brensenham_line(*(cell.bottomleft + cell.left))
mx = max([x for x,y in line])
# draw solid (not chewey) center
glBegin(GL_LINES)
for x,y in line:
glVertex2f(x, y)
glVertex2f(w-x, y)
if x:
glVertex2f(mx-x, y + height/2)
glVertex2f(w-mx+x, y + height/2)
glEnd()
self._style = DrawStyle(color=colour, draw_func=draw_hex)
def get_drawstyle(self):
return self._style
def gen_hex_map(meta, h):
r = []
cell = None
for i, m in enumerate(meta):
c = []
r.append(c)
for j, info in enumerate(m):
if cell is None:
cell = HexCell(0, 0, h, None, None)
k = j
if not i % 2: k += 1
image = HexCheckImage(HexCheckImage.COLOURS[k%3], h)
c.append(HexCell(i, j, h, dict(info), Tile('dbg', {}, image)))
return HexMap('debug', h, r)
def gen_rect_map(meta, w, h):
r = []
cell = None
dark = Image2d.from_image(SolidColorImagePattern((150, 150, 150,
255)).create_image(w, h))
light = Image2d.from_image(SolidColorImagePattern((200, 200, 200,
255)).create_image(w, h))
for i, m in enumerate(meta):
c = []
r.append(c)
for j, info in enumerate(m):
if (i + j) % 2: image = dark
else: image = light
c.append(RectCell(i, j, w, h, dict(info), Tile('dbg', {}, image)))
return RectMap('debug', w, h, r)
def gen_recthex_map(meta, h):
r = []
cell = None
dark = HexCheckImage((.4, .4, .4, 1), h)
light = HexCheckImage((.7, .7, .7, 1), h)
w = int(h / math.sqrt(3)) * 2
for i, m in enumerate(meta):
c = []
r.append(c)
for j, info in enumerate(m):
if (i + j) % 2: image = dark
else: image = light
c.append(RectCell(i, j, w, h, dict(info), Tile('dbg', {}, image)))
return RectMap('debug', w, h, r)
| Python |
#!/usr/bin/env python
'''
Model code for managing rectangular and hexagonal maps
======================================================
This module provides classes for managing rectangular and hexagonal maps.
---------------
Getting Started
---------------
You may create a map interactively and query it:
TBD
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import math
import xml.dom
import xml.dom.minidom
from resource import Resource, register_factory
from scene2d.drawable import *
@register_factory('rectmap')
def rectmap_factory(resource, tag):
width, height = map(int, tag.getAttribute('tile_size').split('x'))
origin = None
if tag.hasAttribute('origin'):
origin = map(int, tag.getAttribute('origin').split(','))
id = tag.getAttribute('id')
# now load the columns
cells = []
for i, column in enumerate(tag.getElementsByTagName('column')):
c = []
cells.append(c)
for j, cell in enumerate(column.getElementsByTagName('cell')):
tile = cell.getAttribute('tile')
if tile: tile = resource.get_resource(tile)
else: tile = None
properties = resource.handle_properties(cell)
c.append(RectCell(i, j, width, height, properties, tile))
m = RectMap(id, width, height, cells, origin)
resource.add_resource(id, m)
return m
@register_factory('hexmap')
def hexmap_factory(resource, tag):
height = int(tag.getAttribute('tile_height'))
width = hex_width(height)
origin = None
if tag.hasAttribute('origin'):
origin = map(int, tag.getAttribute('origin').split(','))
id = tag.getAttribute('id')
# now load the columns
cells = []
for i, column in enumerate(tag.getElementsByTagName('column')):
c = []
cells.append(c)
for j, cell in enumerate(column.getElementsByTagName('cell')):
tile = cell.getAttribute('tile')
if tile: tile = resource.get_resource(tile)
else: tile = None
properties = resource.handle_properties(tag)
c.append(HexCell(i, j, height, properties, tile))
m = HexMap(id, width, cells, origin)
resource.add_resource(id, m)
return m
def hex_width(height):
'''Determine a regular hexagon's width given its height.
'''
return int(height / math.sqrt(3)) * 2
class Map(object):
'''Base class for Maps.
Both rect and hex maps have the following attributes:
id -- identifies the map in XML and Resources
(width, height) -- size of map in cells
(pxw, pxh) -- size of map in pixels
(tw, th) -- size of each cell in pixels
(x, y, z) -- offset of map top left from origin in pixels
cells -- array [x][y] of Cell instances
'''
class RegularTesselationMap(Map):
'''A class of Map that has a regular array of Cells.
'''
def get_cell(self, x, y):
''' Return Cell at cell pos=(x,y).
Return None if out of bounds.'''
if x < 0 or y < 0:
return None
try:
return self.cells[x][y]
except IndexError:
return None
class RectMap(RegularTesselationMap):
'''Rectangular map.
Cells are stored in column-major order with y increasing up,
allowing [x][y] addressing:
+---+---+---+
| d | e | f |
+---+---+---+
| a | b | c |
+---+---+---+
Thus cells = [['a', 'd'], ['b', 'e'], ['c', 'f']]
and cells[0][1] = 'd'
'''
def __init__(self, id, tw, th, cells, origin=None):
self.id = id
self.tw, self.th = tw, th
if origin is None:
origin = (0, 0, 0)
self.x, self.y, self.z = origin
self.cells = cells
self.pxw = len(cells) * tw
self.pxh = len(cells[0]) * th
def get_in_region(self, x1, y1, x2, y2):
'''Return cells (in [column][row]) that are within the
pixel bounds specified by the bottom-left (x1, y1) and top-right
(x2, y2) corners.
'''
x1 = max(0, x1 // self.tw)
y1 = max(0, y1 // self.th)
x2 = min(len(self.cells), x2 // self.tw + 1)
y2 = min(len(self.cells[0]), y2 // self.th + 1)
return [self.cells[x][y] for x in range(x1, x2) for y in range(y1, y2)]
def get(self, x, y):
''' Return Cell at pixel px=(x,y).
Return None if out of bounds.'''
return self.get_cell(x // self.tw, y // self.th)
UP = (0, 1)
DOWN = (0, -1)
LEFT = (-1, 0)
RIGHT = (1, 0)
def get_neighbor(self, cell, direction):
'''Get the neighbor Cell in the given direction (dx, dy) which
is one of self.UP, self.DOWN, self.LEFT or self.RIGHT.
Returns None if out of bounds.
'''
dx, dy = direction
return self.get_cell(cell.x + dx, cell.y + dy)
@classmethod
def load_xml(cls, filename, id):
'''Load a map from the indicated XML file.
Return a Map instance.'''
return Resource.load(filename)[id]
class Cell(Drawable):
'''Base class for cells from rect and hex maps.
Common attributes:
x, y -- top-left coordinate
width, height -- dimensions
properties -- arbitrary properties
cell -- cell from the Map's cells
'''
def __init__(self, x, y, width, height, properties, tile):
super(Cell, self).__init__()
self.width, self.height = width, height
self.x, self.y = x, y
self.properties = properties
self.tile = tile
if tile is not None:
# pre-calculate the style to force creation of _style
self.get_style()
def __repr__(self):
return '<%s object at 0x%x (%g, %g) properties=%r tile=%r>'%(
self.__class__.__name__, id(self), self.x, self.y,
self.properties, self.tile)
def get_style(self):
if self.tile is None: return None
return super(Cell, self).get_style()
def get_drawstyle(self):
'''Get the possibly-affected style from the tile. Adjust for this
cell's position.
'''
style = self.tile.get_style().copy()
x, y = self.get_origin()
style.x, style.y = style.x + x, style.y + y
return style
class RectCell(Cell):
'''A rectangular cell from a Map.
Read-only attributes:
top -- y extent
bottom -- y extent
left -- x extent
right -- x extent
origin -- (x, y) of bottom-left corner
center -- (x, y)
topleft -- (x, y) of top-left corner
topright -- (x, y) of top-right corner
bottomleft -- (x, y) of bottom-left corner
bottomright -- (x, y) of bottom-right corner
midtop -- (x, y) of middle of top side
midbottom -- (x, y) of middle of bottom side
midleft -- (x, y) of middle of left side
midright -- (x, y) of middle of right side
'''
def get_origin(self):
return self.x * self.width, self.y * self.height
origin = property(get_origin)
# ro, side in pixels, y extent
def get_top(self):
return (self.y + 1) * self.height
top = property(get_top)
# ro, side in pixels, y extent
def get_bottom(self):
return self.y * self.height
bottom = property(get_bottom)
# ro, in pixels, (x, y)
def get_center(self):
return (self.x * self.width + self.width // 2,
self.y * self.height + self.height // 2)
center = property(get_center)
# ro, mid-point in pixels, (x, y)
def get_midtop(self):
return (self.x * self.width + self.width // 2,
(self.y + 1) * self.height)
midtop = property(get_midtop)
# ro, mid-point in pixels, (x, y)
def get_midbottom(self):
return (self.x * self.width + self.width // 2, self.y * self.height)
midbottom = property(get_midbottom)
# ro, side in pixels, x extent
def get_left(self):
return self.x * self.width
left = property(get_left)
# ro, side in pixels, x extent
def get_right(self):
return (self.x + 1) * self.width
right = property(get_right)
# ro, corner in pixels, (x, y)
def get_topleft(self):
return (self.x * self.width, (self.y + 1) * self.height)
topleft = property(get_topleft)
# ro, corner in pixels, (x, y)
def get_topright(self):
return ((self.x + 1) * self.width, (self.y + 1) * self.height)
topright = property(get_topright)
# ro, corner in pixels, (x, y)
def get_bottomleft(self):
return (self.x * self.height, self.y * self.height)
bottomleft = property(get_bottomleft)
origin = property(get_bottomleft)
# ro, corner in pixels, (x, y)
def get_bottomright(self):
return ((self.x + 1) * self.width, self.y * self.height)
bottomright = property(get_bottomright)
# ro, mid-point in pixels, (x, y)
def get_midleft(self):
return (self.x * self.width, self.y * self.height + self.height // 2)
midleft = property(get_midleft)
# ro, mid-point in pixels, (x, y)
def get_midright(self):
return ((self.x + 1) * self.width,
self.y * self.height + self.height // 2)
midright = property(get_midright)
class HexMap(RegularTesselationMap):
'''Map with flat-top, regular hexagonal cells.
Additional attributes extending MapBase:
edge_length -- length of an edge in pixels
Hexmaps store their cells in an offset array, column-major with y
increasing up, such that a map:
/d\ /h\
/b\_/f\_/
\_/c\_/g\
/a\_/e\_/
\_/ \_/
has cells = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
'''
def __init__(self, id, th, cells, origin=None):
self.id = id
self.th = th
if origin is None:
origin = (0, 0, 0)
self.x, self.y, self.z = origin
self.cells = cells
# figure some convenience values
s = self.edge_length = int(th / math.sqrt(3))
self.tw = self.edge_length * 2
# now figure map dimensions
width = len(cells); height = len(cells[0])
self.pxw = self.tw + (width - 1) * (s + s // 2)
self.pxh = height * self.th
if not width % 2:
self.pxh += (th // 2)
def get_in_region(self, x1, y1, x2, y2):
'''Return cells (in [column][row]) that are within the pixel bounds
specified by the bottom-left (x1, y1) and top-right (x2, y2) corners.
'''
col_width = self.tw // 2 + self.tw // 4
x1 = max(0, x1 // col_width)
y1 = max(0, y1 // self.th - 1)
x2 = min(len(self.cells), x2 // col_width + 1)
y2 = min(len(self.cells[0]), y2 // self.th + 1)
return [self.cells[x][y] for x in range(x1, x2) for y in range(y1, y2)]
def get(self, x, y):
'''Get the Cell at pixel px=(x,y).
Return None if out of bounds.'''
s = self.edge_length
# map is divided into columns of
# s/2 (shared), s, s/2(shared), s, s/2 (shared), ...
x = x // (s/2 + s)
if x % 2:
# every second cell is up one
y -= self.th // 2
y = y // self.th
return self.get_cell(x, y)
UP = 'up'
DOWN = 'down'
UP_LEFT = 'up left'
UP_RIGHT = 'up right'
DOWN_LEFT = 'down left'
DOWN_RIGHT = 'down right'
def get_neighbor(self, cell, direction):
'''Get the neighbor HexCell in the given direction which
is one of self.UP, self.DOWN, self.UP_LEFT, self.UP_RIGHT,
self.DOWN_LEFT or self.DOWN_RIGHT.
Return None if out of bounds.
'''
if direction is self.UP:
return self.get_cell(cell.x, cell.y + 1)
elif direction is self.DOWN:
return self.get_cell(cell.x, cell.y - 1)
elif direction is self.UP_LEFT:
if cell.x % 2:
return self.get_cell(cell.x - 1, cell.y + 1)
else:
return self.get_cell(cell.x - 1, cell.y)
elif direction is self.UP_RIGHT:
if cell.x % 2:
return self.get_cell(cell.x + 1, cell.y + 1)
else:
return self.get_cell(cell.x + 1, cell.y)
elif direction is self.DOWN_LEFT:
if cell.x % 2:
return self.get_cell(cell.x - 1, cell.y)
else:
return self.get_cell(cell.x - 1, cell.y - 1)
elif direction is self.DOWN_RIGHT:
if cell.x % 2:
return self.get_cell(cell.x + 1, cell.y)
else:
return self.get_cell(cell.x + 1, cell.y - 1)
else:
raise ValueError, 'Unknown direction %r'%direction
# Note that we always add below (not subtract) so that we can try to
# avoid accumulation errors due to rounding ints. We do this so
# we can each point at the same position as a neighbor's corresponding
# point.
class HexCell(Cell):
'''A flat-top, regular hexagon cell from a HexMap.
Read-only attributes:
top -- y extent
bottom -- y extent
left -- (x, y) of left corner
right -- (x, y) of right corner
center -- (x, y)
origin -- (x, y) of bottom-left corner of bounding rect
topleft -- (x, y) of top-left corner
topright -- (x, y) of top-right corner
bottomleft -- (x, y) of bottom-left corner
bottomright -- (x, y) of bottom-right corner
midtop -- (x, y) of middle of top side
midbottom -- (x, y) of middle of bottom side
midtopleft -- (x, y) of middle of left side
midtopright -- (x, y) of middle of right side
midbottomleft -- (x, y) of middle of left side
midbottomright -- (x, y) of middle of right side
'''
def __init__(self, x, y, height, properties, tile):
width = hex_width(height)
Cell.__init__(self, x, y, width, height, properties, tile)
def get_origin(self):
x = self.x * (self.width / 2 + self.width // 4)
y = self.y * self.height
if self.x % 2:
y += self.height // 2
return (x, y)
origin = property(get_origin)
# ro, side in pixels, y extent
def get_top(self):
y = self.get_origin()[1]
return y + self.height
top = property(get_top)
# ro, side in pixels, y extent
def get_bottom(self):
return self.get_origin()[1]
bottom = property(get_bottom)
# ro, in pixels, (x, y)
def get_center(self):
x, y = self.get_origin()
return (x + self.width // 2, y + self.height // 2)
center = property(get_center)
# ro, mid-point in pixels, (x, y)
def get_midtop(self):
x, y = self.get_origin()
return (x + self.width // 2, y + self.height)
midtop = property(get_midtop)
# ro, mid-point in pixels, (x, y)
def get_midbottom(self):
x, y = self.get_origin()
return (x + self.width // 2, y)
midbottom = property(get_midbottom)
# ro, side in pixels, x extent
def get_left(self):
x, y = self.get_origin()
return (x, y + self.height // 2)
left = property(get_left)
# ro, side in pixels, x extent
def get_right(self):
x, y = self.get_origin()
return (x + self.width, y + self.height // 2)
right = property(get_right)
# ro, corner in pixels, (x, y)
def get_topleft(self):
x, y = self.get_origin()
return (x + self.width // 4, y + self.height)
topleft = property(get_topleft)
# ro, corner in pixels, (x, y)
def get_topright(self):
x, y = self.get_origin()
return (x + self.width // 2 + self.width // 4, y + self.height)
topright = property(get_topright)
# ro, corner in pixels, (x, y)
def get_bottomleft(self):
x, y = self.get_origin()
return (x + self.width // 4, y)
bottomleft = property(get_bottomleft)
# ro, corner in pixels, (x, y)
def get_bottomright(self):
x, y = self.get_origin()
return (x + self.width // 2 + self.width // 4, y)
bottomright = property(get_bottomright)
# ro, middle of side in pixels, (x, y)
def get_midtopleft(self):
x, y = self.get_origin()
return (x + self.width // 8, y + self.height // 2 + self.height // 4)
midtopleft = property(get_midtopleft)
# ro, middle of side in pixels, (x, y)
def get_midtopright(self):
x, y = self.get_origin()
return (x + self.width // 2 + self.width // 4 + self.width // 8,
y + self.height // 2 + self.height // 4)
midtopright = property(get_midtopright)
# ro, middle of side in pixels, (x, y)
def get_midbottomleft(self):
x, y = self.get_origin()
return (x + self.width // 8, y + self.height // 4)
midbottomleft = property(get_midbottomleft)
# ro, middle of side in pixels, (x, y)
def get_midbottomright(self):
x, y = self.get_origin()
return (x + self.width // 2 + self.width // 4 + self.width // 8,
y + self.height // 4)
midbottomright = property(get_midbottomright)
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
from ctypes import *
from pyglet.gl import *
from scene2d.sprite import Sprite
from pyglet.font import GlyphString
# TODO: inherit from Sprite
class TextSprite(object):
_layout_width = None # Width to layout text to
_text_width = 0 # Calculated width of text
_text_height = 0 # Calculated height of text (bottom descender to top
# ascender)
_dirty = False # Flag if require layout
def __init__(self, font, text, x=0, y=0, z=0, color=(1,1,1,1)):
self._dirty = True
self.font = font
self._text = text
self.color = color
self.x = x
self.y = y
self.leading = 0
def _clean(self):
'''Resolve changed layout'''
'''
# Each 'line' in 'glyph_lines' is a list of Glyph objects. Do
# line wrapping now.
glyph_lines = []
if self._layout_width is None:
for line in self.text.split('\n'):
glyph_lines.append((line, self.font.get_glyphs(self.text)))
else:
text = self.text + ' ' # Need the ' ' to always flush line.
while text and text != ' ':
line = self.font.get_glyphs_for_width(text, self._layout_width)
glyph_lines.append((text[:len(line)], line))
text = text[len(line):]
if text and text[0] == '\n':
text = text[1:]
# Create interleaved array and figure out state changes.
line_height = self.font.ascent - self.font.descent + self.leading
y = 0
self._text_width = 0
self.strings = []
for text, glyphs in glyph_lines:
string = GlyphString(text, glyphs, 0, y)
self._text_width = max(self._text_width, string.width)
y -= line_height
self.strings.append(string)
self._text_height = -y
'''
text = self._text + ' '
glyphs = self.font.get_glyphs(text)
self._glyph_string = GlyphString(text, glyphs)
self.lines = []
i = 0
if self._layout_width is None:
self._text_width = 0
while '\n' in text[i:]:
end = text.index('\n', i)
self.lines.append((i, end))
self._text_width = max(self._text_width,
self._glyph_string.get_subwidth(i, end))
i = end + 1
end = len(text)
if end != i:
self.lines.append((i, end))
self._text_width = max(self._text_width,
self._glyph_string.get_subwidth(i, end))
else:
bp = self._glyph_string.get_break_index(i, self._layout_width)
while i < len(text) and bp > i:
if text[bp-1] == '\n':
self.lines.append((i, bp - 1))
else:
self.lines.append((i, bp))
i = bp
bp = self._glyph_string.get_break_index(i, self._layout_width)
if i < len(text) - 1:
self.lines.append((i, len(text)))
self.line_height = self.font.ascent - self.font.descent + self.leading
self._text_height = self.line_height * len(self.lines)
self._dirty = False
def draw(self):
if self._dirty:
self._clean()
glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT)
glEnable(GL_TEXTURE_2D)
glColor4f(*self.color)
glPushMatrix()
glTranslatef(self.x, self.y, 0)
for start, end in self.lines:
self._glyph_string.draw(start, end)
glTranslatef(0, -self.line_height, 0)
glPopMatrix()
glPopAttrib()
def get_width(self):
if self._dirty:
self._clean()
if self._layout_width:
return self._layout_width
return self._text_width
def set_width(self, width):
self._layout_width = width
self._dirty = True
width = property(get_width, set_width)
def get_height(self):
if self._dirty:
self._clean()
return self._text_height
height = property(get_height)
def set_text(self, text):
self._text = text
self._dirty = True
text = property(lambda self: self._text, set_text)
| Python |
#!/usr/bin/env python
'''
Management of tile sets
=======================
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import xml.dom
import xml.dom.minidom
from scene2d.image import Image2d, Drawable
from resource import Resource, register_factory
from scene2d.drawable import *
@register_factory('tileset')
def tileset_factory(resource, tag):
id = tag.getAttribute('id')
properties = resource.handle_properties(tag)
tileset = TileSet(id, properties)
resource.add_resource(tileset.id, tileset)
for child in tag.childNodes:
if not hasattr(child, 'tagName'): continue
id = child.getAttribute('id')
offset = child.getAttribute('offset')
if offset:
offset = map(int, offset.split(','))
else:
offset = None
properties = resource.handle_properties(child)
image = child.getElementsByTagName('image')
if image:
image = resource.handle(image[0])
else:
image = None
tile = Tile(id, properties, image, offset)
resource.add_resource(id, tile)
tileset[id] = tile
return tileset
class Tile(Drawable):
def __init__(self, id, properties, image, offset=None):
super(Tile, self).__init__()
self.id = id
self.properties = properties
self.image = image
self.offset = offset
def __repr__(self):
return '<%s object at 0x%x id=%r offset=%r properties=%r>'%(
self.__class__.__name__, id(self), self.id, self.offset,
self.properties)
def get_drawstyle(self):
'''Use the image style as a basis and modify to move.
'''
style = self.image.get_style()
if self.offset is not None:
style = style.copy()
x, y = self.offset
style.x, style.y = x, y
return style
class TileSet(dict):
'''Contains a tile set loaded from a map file and optionally image(s).
'''
def __init__(self, id, properties):
self.id = id
self.properties = properties
# We retain a cache of opened tilesets so that multiple maps may refer to
# the same tileset and we don't waste resources by duplicating the
# tilesets in memory.
tilesets = {}
tile_id = 0
@classmethod
def generate_id(cls):
cls.tile_id += 1
return str(cls.tile_id)
def add(self, properties, image, id=None):
'''Add a new Tile to this TileSet, generating a unique id if
necessary.'''
if id is None:
id = self.generate_id()
self[id] = Tile(id, properties, image)
@classmethod
def load_xml(cls, filename, id):
'''Load the tileset from the XML in the specified file.
Return a TileSet instance.
'''
return Resource.load(filename)[id]
| Python |
#!/usr/bin/env python
'''
Draw OpenGL textures in 2d scenes
=================================
---------------
Getting Started
---------------
You may create a drawable image with:
>>> from scene2d import *
>>> i = Image2d.load('kitten.jpg')
>>> i.draw()
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
from pyglet.gl import *
from pyglet import image
from scene2d.drawable import *
from resource import register_factory, ResourceError
@register_factory('imageatlas')
def imageatlas_factory(resource, tag):
filename = resource.find_file(tag.getAttribute('file'))
if not filename:
raise ResourceError, 'No file= on <imageatlas> tag'
atlas = Image2d.load(filename)
atlas.properties = resource.handle_properties(tag)
if tag.hasAttribute('id'):
atlas.id = tag.getAttribute('id')
resource.add_resource(atlas.id, atlas)
# figure default size if specified
if tag.hasAttribute('size'):
d_width, d_height = map(int, tag.getAttribute('size').split('x'))
else:
d_width = d_height = None
for child in tag.childNodes:
if not hasattr(child, 'tagName'): continue
if child.tagName != 'image':
raise ValueError, 'invalid child'
if child.hasAttribute('size'):
width, height = map(int, child.getAttribute('size').split('x'))
elif d_width is None:
raise ValueError, 'atlas or subimage must specify size'
else:
width, height = d_width, d_height
x, y = map(int, child.getAttribute('offset').split(','))
image = atlas.subimage(x, y, width, height)
id = child.getAttribute('id')
resource.add_resource(id, image)
image.properties = resource.handle_properties(tag)
if tag.hasAttribute('id'):
image.id = tag.getAttribute('id')
resource.add_resource(image.id, image)
return atlas
@register_factory('image')
def image_factory(resource, tag):
filename = resource.find_file(tag.getAttribute('file'))
if not filename:
raise ResourceError, 'No file= on <image> tag'
image = Image2d.load(filename)
image.properties = resource.handle_properties(tag)
if tag.hasAttribute('id'):
image.id = tag.getAttribute('id')
resource.add_resource(image.id, image)
return image
class Image2d(Drawable):
def __init__(self, texture, x, y):
super(Image2d, self).__init__()
self.texture = texture
self.x = x
self.y = y
self.width = texture.width
self.height = texture.height
self.uvs = texture.tex_coords
@classmethod
def load(cls, filename=None, file=None):
'''Image is loaded from the given file.'''
img = image.load(filename=filename, file=file)
img = cls(img.texture, 0, 0)
img.filename = filename
return img
@classmethod
def from_image(cls, image):
return cls(image.texture, 0, 0)
@classmethod
def from_texture(cls, texture):
'''Image is the entire texture.'''
return cls(texture, 0, 0)
@classmethod
def from_subtexture(cls, texture, x, y, width, height):
'''Image is a section of the texture.'''
return cls(texture.get_region(x, y, width, height), x, y)
__quad_list = None
def quad_list(self):
if self.__quad_list is not None:
return self.__quad_list
# Make quad display list
self.__quad_list = glGenLists(1)
glNewList(self.__quad_list, GL_COMPILE)
#self.texture.blit(0, 0, 0) # This does same as QUADS below
glBegin(GL_QUADS)
glTexCoord3f(*self.uvs[:3])
glVertex2f(0, 0)
glTexCoord3f(*self.uvs[3:6])
glVertex2f(0, self.height)
glTexCoord3f(*self.uvs[6:9])
glVertex2f(self.width, self.height)
glTexCoord3f(*self.uvs[9:12])
glVertex2f(self.width, 0)
glEnd()
glEndList()
return self.__quad_list
quad_list = property(quad_list)
def get_drawstyle(self):
# XXX note we don't pass in self.x/y here as they're offsets into the
# texture, not offsets to use when rendering the image to screen
# for other scene2d objects that *is* what .x/y are for - perhaps
# that's what they should be for here...
return DrawStyle(color=(1, 1, 1, 1), texture=self.texture,
# <ah> uvs looks quite wrong here
width=self.width, height=self.height, uvs=(0,0,0,0),
draw_list=self.quad_list, draw_env=DRAW_BLENDED)
def subimage(self, x, y, width, height):
return self.__class__(self.texture.get_region(x, y, width, height),
x, y)
| Python |
#!/usr/bin/env python
'''
View code for displaying 2d scenes of maps and sprites
======================================================
---------------
Getting Started
---------------
Creating a simple scene and displaying it:
>>> import pyglet.window
>>> import scene2d
>>> m = scene2d.RectMap(32, 32, cells=gen_rect_map([[0]*4]*4, 32, 32)
>>> w = pyglet.window.Window(width=m.pxw, height=m.pxh)
>>> v = scene2d.FlatView.from_window(s, w, layers=[m])
>>> v.debug((0,0))
>>> w.flip()
------------------
Events and Picking
------------------
The following are examples of attaching event handlers to Views::
@event(view)
def on_mouse_enter(objects, x, y):
""" The mouse is hovering at map pixel position (x,y) over the
indicated objects (cells or sprites)."""
@event(view)
def on_mouse_leave(objects):
' The mouse has stopped hovering over the indicated objects.'
@event(view)
def on_mouse_press(objects, x, y, button, modifiers):
' The mouse has been clicked on the indicated objects. '
The filters available in scene2d.events module may be used to
limit the cells or sprites for which events are generated.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import operator
from pyglet.event import EventDispatcher, EVENT_UNHANDLED
from scene2d.camera import FlatCamera
from scene2d.drawable import draw_many
from scene2d.map import Map
from scene2d.sprite import SpriteLayer
from pyglet.gl import *
class View(EventDispatcher):
def get(self, x, y):
''' Pick whatever is on the top at the pixel position x, y. '''
raise NotImplemented()
def tile_at(self, (x, y)):
' query for tile at given screen pixel position '
raise NotImplemented()
def sprite_at(self, (x, y)):
' query for sprite at given screen pixel position '
raise NotImplemented()
EVENT_MOUSE_DRAG = View.register_event_type('on_mouse_drag')
EVENT_MOUSE_PRESS = View.register_event_type('on_mouse_press')
EVENT_MOUSE_RELEASE = View.register_event_type('on_mouse_release')
EVENT_MOUSE_ENTER = View.register_event_type('on_mouse_enter')
EVENT_MOUSE_LEAVE = View.register_event_type('on_mouse_leave')
class FlatView(View):
'''Render a flat view of a scene2d.Scene.
Attributes:
scene -- a scene2d.Scene instance
camera -- a scene2d.FlatCamera instance
allow_oob -- indicates whether the viewport will allow
viewing of out-of-bounds tile positions (ie.
for which there is no tile image). If set to
False then the map will not scroll to attempt
to display oob tiles.
fx, fy -- pixel point to center in the viewport, subject
to OOB checks
'''
def __init__(self, x, y, width, height, allow_oob=False,
fx=0, fy=0, layers=None, sprites=None):
super(View, self).__init__()
self.camera = FlatCamera(x, y, width, height)
self.allow_oob = allow_oob
self.fx, self.fy = fx, fy
if layers is None:
self.layers = []
else:
self.layers = layers
if sprites is None:
self.sprites = []
else:
self.sprites = sprites
@classmethod
def from_window(cls, window, **kw):
'''Create a view which is the same dimensions as the supplied
window.'''
return cls(0, 0, window.width, window.height, **kw)
def __repr__(self):
return '<%s object at 0x%x focus=(%d,%d) oob=%s>'%(
self.__class__.__name__, id(self), self.fx, self.fy,
self.allow_oob)
#
# EVENT HANDLING
#
_mouse_in_objs = set()
def dispatch_event(self, x, y, event_type, *args):
''' if a handler has a limit attached then use that to filter objs
'''
# now fire the handler
for frame in self._event_stack:
handler = frame.get(event_type, None)
if not handler: continue
# XXX don't do this for every handler?
objs = []
# maps to pass to the handler
if hasattr(handler, 'map_filters') and \
handler.map_filters is not None:
for mf in handler.map_filters:
l = []
for map in mf.maps:
cell = map.get(x, y)
if cell:
l.append(cell)
objs.extend((map.z, mf(l)))
else:
for layer in self.layers:
if not isinstance(layer, Map): continue
cell = layer.get(x, y)
if cell:
objs.append((layer.z, cell))
# sprites to pass to the handler
if hasattr(handler, 'sprite_filters') and \
handler.sprite_filters is not None:
for sf in handler.sprite_filters:
l = []
for sprite in sf.sprites:
if sprite.contains(x, y):
l.append((sprite.z, sprite))
objs.extend(sf(l))
else:
for layer in self.layers:
if not isinstance(layer, SpriteLayer): continue
for sprite in layer.sprites:
if sprite.contains(x, y):
objs.append((layer.z, sprite))
for sprite in self.sprites:
if sprite.contains(x, y):
# un-layered sprites are at depth 0
objs.append((0, sprite))
# sort by depth
objs.sort()
l = [obj for o, obj in objs]
# highest to lowest
l.reverse()
# now gen events
if event_type is EVENT_MOUSE_ENTER:
active = set(l)
l = active - self._mouse_in_objs
if not l: continue
self._mouse_in_objs = self._mouse_in_objs | l
l = list(l)
elif event_type is EVENT_MOUSE_LEAVE:
active = set(l)
l = self._mouse_in_objs - active
if not l: continue
self._mouse_in_objs = self._mouse_in_objs - l
l = list(l)
else:
if not l: continue
ret = handler(l, *args)
if ret != EVENT_UNHANDLED:
break
return None
def on_mouse_press(self, x, y, button, modifiers):
x, y = self.translate_position(x, y)
self.dispatch_event(x, y, EVENT_MOUSE_PRESS, x, y, button, modifiers)
return EVENT_UNHANDLED
def on_mouse_release(self, x, y, button, modifiers):
x, y = self.translate_position(x, y)
self.dispatch_event(x, y, EVENT_MOUSE_RELEASE, x, y, button, modifiers)
return EVENT_UNHANDLED
def on_mouse_motion(self, x, y, dx, dy):
x, y = self.translate_position(x, y)
self.dispatch_event(x, y, EVENT_MOUSE_LEAVE)
self.dispatch_event(x, y, EVENT_MOUSE_ENTER)
return EVENT_UNHANDLED
def on_mouse_enter(self, x, y):
x, y = self.translate_position(x, y)
self.dispatch_event(x, y, EVENT_MOUSE_ENTER)
return EVENT_UNHANDLED
def on_mouse_leave(self, x, y):
x, y = self.translate_position(x, y)
self.dispatch_event(x, y, EVENT_MOUSE_LEAVE)
return EVENT_UNHANDLED
#
# QUERY INTERFACE
#
def translate_position(self, x, y):
'''Translate the on-screen pixel position to a scene pixel
position.'''
fx, fy = self._determine_focus()
ox, oy = self.camera.width/2-fx, self.camera.height/2-fy
return (int(x - ox), int(y - oy))
def get(self, x, y):
''' Pick whatever is on the top at the position x, y. '''
r = []
for sprite in self.sprites:
if sprite.contains(x, y):
r.append(sprite)
self.layers.sort(key=operator.attrgetter('z'))
for layer in self.layers:
cell = layer.get(x, y)
if cell:
r.append(cell)
return r
def tile_at(self, x, y):
' query for tile at given screen pixel position '
raise NotImplemented()
def sprite_at(self, x, y):
' query for sprite at given screen pixel position '
raise NotImplemented()
#
# FOCUS ADJUSTMENT
#
def _determine_focus(self):
'''Determine the focal point of the view based on foxus (fx, fy),
allow_oob and maps.
Note that this method does not actually change the focus attributes
fx and fy.
'''
# enforce int-only positioning of focus
fx = int(self.fx)
fy = int(self.fy)
if self.allow_oob: return (fx, fy)
# check that any layer has bounds
bounded = []
for layer in self.layers:
if hasattr(layer, 'pxw'):
bounded.append(layer)
if not bounded:
return (fx, fy)
# figure the bounds min/max
m = bounded[0]
b_min_x = m.x
b_min_y = m.y
b_max_x = m.x + m.pxw
b_max_y = m.y + m.pxh
for m in bounded[1:]:
b_min_x = min(b_min_x, m.x)
b_min_y = min(b_min_y, m.y)
b_max_x = min(b_max_x, m.x + m.pxw)
b_max_y = min(b_max_y, m.y + m.pxh)
# figure the view min/max based on focus
w2 = self.camera.width/2
h2 = self.camera.height/2
v_min_x = fx - w2
v_min_y = fy - h2
x_moved = y_moved = False
if v_min_x < b_min_x:
fx += b_min_x - v_min_x
x_moved = True
if v_min_y < b_min_y:
fy += b_min_y - v_min_y
y_moved = True
v_max_x = fx + w2
v_max_y = fy + h2
if not x_moved and v_max_x > b_max_x:
fx -= v_max_x - b_max_x
if not y_moved and v_max_y > b_max_y:
fy -= v_max_y - b_max_y
return map(int, (fx, fy))
#
# RENDERING
#
def clear(self, colour=None, is_window=True):
'''Clear the view.
If colour is None then the current glColor (is_window == False)
or glClearColor (is_window == True) is used.
If the view is not the whole window then you should pass
is_window=False otherwise the whole window will be cleared.
'''
if is_window:
if colour is not None:
glClearColor(*colour)
glClear(GL_COLOR_BUFFER_BIT)
else:
if colour is not None:
glColor(*colour)
glBegin(GL_QUADS)
glVertex2f(0, 0)
glVertex2f(0, self.camera.height)
glVertex2f(self.camera.width, self.camera.height)
glVertex2f(self.camera.width, 0)
glEnd()
def draw(self):
'''Draw the view centered (or closest, depending on allow_oob)
on position which is (x, y). '''
self.camera.project()
# sort by depth
self.layers.sort(key=operator.attrgetter('z'))
# determine the focus point
fx, fy = self._determine_focus()
w2 = self.camera.width/2
h2 = self.camera.height/2
x1, y1 = fx - w2, fy - h2
x2, y2 = fx + w2, fy + h2
# now draw
glPushMatrix()
glTranslatef(self.camera.width/2-fx, self.camera.height/2-fy, 0)
for layer in self.layers:
if hasattr(layer, 'x'):
translate = layer.x or layer.y or layer.z
else:
translate = False
if translate:
glPushMatrix()
glTranslatef(layer.x, layer.y, layer.z)
draw_many(layer.get_in_region(x1, y1, x2, y2))
if translate:
glPopMatrix()
if self.sprites:
draw_many(self.sprites)
glPopMatrix()
class ViewScrollHandler(object):
'''Scroll the view in response to the mouse scroll wheel.
'''
def __init__(self, view):
self.view = view
def on_mouse_scroll(self, x, y, dx, dy):
fx, fy = self.view._determine_focus()
self.view.fx = fx + dx * 30
self.view.fy = fy + dy * 30
| Python |
#!/usr/bin/env python
'''
Camera for projecting 2d flat scenes
====================================
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
from pyglet.gl import *
from pyglet.event import *
class Camera(object):
def project(self):
'''Set up the GL projection matrix. Leave us in GL_MODELVIEW mode.
'''
raise NotImplemented()
def on_resize(self, width, height):
'''Handle resize of the viewport.
'''
raise NotImplemented()
class FlatCamera(Camera):
def __init__(self, x, y, width, height, near=-50, far=50):
self.x, self.y = x, y
self.width, self.height = width, height
self.near, self.far = near, far
def project(self):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glViewport(self.x, self.y, self.width, self.height)
glOrtho(0, self.width, 0, self.height, self.near, self.far)
glMatrixMode(GL_MODELVIEW)
def on_resize(self, width, height):
self.width, self.height = width, height
return EVENT_UNHANDLED
def __repr__(self):
return '<%s object at 0x%x pos=(%d,%d) size=(%d,%d)>'%(
self.__class__.__name__, id(self), self.x, self.y, self.width,
self.height)
| Python |
"""
"""
from scene2d.map import RectMap, HexMap, RectCell, HexCell
from scene2d.camera import FlatCamera
from scene2d.view import FlatView, ViewScrollHandler
from scene2d.sprite import Sprite, RotatableSprite, SpriteLayer
from scene2d.image import Image2d
from scene2d.tile import TileSet, Tile
__all__ = [ 'RectMap', 'HexMap', 'RectCell', 'HexCell', 'FlatCamera',
'FlatView', 'ViewScrollHandler',
'Sprite', 'RotatableSprite', 'SpriteLayer',
'Image2d', 'TileSet', 'Tile']
| Python |
#!/usr/bin/env python
'''
Model code for managing sprites
===============================
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
from pyglet.gl import *
from scene2d.drawable import *
class SpriteLayer(object):
'''Represents a group of sprites at the same z depth.
'''
def __init__(self, z=0, sprites=None):
self.z = z
if sprites is None:
sprites = []
self.sprites = sprites
def get(self, x, y):
''' Return object at position px=(x,y).
Return None if out of bounds.'''
r = []
for sprite in self.sprites:
if sprite.contains(x, y):
r.append(sprite)
return r
def get_in_region(self, x1, y1, x2, y2):
'''Return Drawables that are within the pixel bounds specified by
the bottom-left (x1, y1) and top-right (x2, y2) corners.
'''
r = []
for sprite in self.sprites:
if sprite._x > x2: continue
if (sprite._x + sprite.width) < x1: continue
if sprite._y > y2: continue
if (sprite._y + sprite.height) < y1: continue
r.append(sprite)
return r
class Sprite(Drawable):
'''A sprite with some dimensions, image to draw and optional animation
to run.
Attributes:
x, y -- position
width, height -- sprite dimensions (may differ from image)
image -- image for this sprite
offset -- offset of image from position (default (0,0))
animations -- a queue of SpriteAnimations to run
properties -- arbitrary data in a dict
'''
def __init__(self, x, y, width, height, image, offset=(0,0),
properties=None):
super(Sprite, self).__init__()
self._x, self._y = x, y
self.width, self.height = width, height
self.image = image
self.offset = offset
self.animations = []
if properties is None:
self.properties = {}
else:
self.properties = properties
# pre-calculate the style to force creation of _style
self.get_style()
@classmethod
def from_image(cls, x, y, image, offset=(0,0), properties=None):
'''Set up the sprite from the image - sprite dimensions are the
same as the image.'''
return cls(x, y, image.width, image.height, image, offset,
properties)
def get_drawstyle(self):
'''Use the image style as a basis and modify to move.
'''
style = self.image.get_style().copy()
offx, offy = self.offset
# XXX remove int() if we get sub-pixel drawing of textures
style.x, style.y = int(self._x - offx), int(self._y - offy)
return style
def push_animation(self, animation):
"Push a SpriteAnimation onto this sprite's animation queue."
raise NotImplemented()
def cancel_animation(self):
'Cancel the current animation being run.'
raise NotImplemented()
def clear_animation(self):
'Clear the animation queue.'
raise NotImplemented()
def animate(self, dt):
'''Animate this sprite to handle passing of dt time.
If self.image has a .animate method it will be called.
'''
raise NotImplemented()
def contains(self, x, y):
'''Return True if the point is inside the sprite.'''
if x < self.x: return False
if y < self.y: return False
if x >= self.x + self.width: return False
if y >= self.y + self.height: return False
return True
def overlaps(self, rect):
'''Return True if this sprite overlaps the other rect.
A rect is an object that has an origin .x, .y and size .width,
.height.
'''
# we avoid using .right and .top properties here to speed things up
if self.x > (rect.x + rect.width): return False
if (self.x + self.width) < rect.x: return False
if self.y > (rect.y + rect.height): return False
if (self.y + self.height) < rect.y: return False
return True
def get_x(self):
return self._x
def set_x(self, x):
self._x = x
if self._style is not None:
# XXX remove int() if we get sub-pixel drawing of textures
self._style.x = int(x - self.offset[0])
x = property(get_x, set_x)
def get_y(self):
return self._y
def set_y(self, y):
self._y = y
if self._style is not None:
# XXX remove int() if we get sub-pixel drawing of textures
self._style.y = int(y - self.offset[1])
y = property(get_y, set_y)
# r/w, in pixels, y extent
def get_top(self): return self.y + self.height
def set_top(self, y): self.y = y - self.height
top = property(get_top, set_top)
# r/w, in pixels, y extent
def get_bottom(self): return self.y
def set_bottom(self, y): self.y = y
bottom = property(get_bottom, set_bottom)
# r/w, in pixels, x extent
def get_left(self): return self.x
def set_left(self, x): self.x = x
left = property(get_left, set_left)
# r/w, in pixels, x extent
def get_right(self): return self.x + self.width
def set_right(self, x): self.x = x - self.width
right = property(get_right, set_right)
# r/w, in pixels, (x, y)
def get_center(self):
return (self.x + self.width/2, self.y + self.height/2)
def set_center(self, center):
x, y = center
self.x = x - self.width/2
self.y = y - self.height/2
center = property(get_center, set_center)
# r/w, in pixels, (x, y)
def get_midtop(self):
return (self.x + self.width/2, self.y + self.height)
def set_midtop(self, midtop):
x, y = midtop
self.x = x - self.width/2
self.y = y - self.height
midtop = property(get_midtop, set_midtop)
# r/w, in pixels, (x, y)
def get_midbottom(self):
return (self.x + self.width/2, self.y)
def set_midbottom(self, midbottom):
x, y = midbottom
self.x = x - self.width/2
self.y = y
midbottom = property(get_midbottom, set_midbottom)
# r/w, in pixels, (x, y)
def get_midleft(self):
return (self.x, self.y + self.height/2)
def set_midleft(self, midleft):
x, y = midleft
self.x = x
self.y = y - self.height/2
midleft = property(get_midleft, set_midleft)
# r/w, in pixels, (x, y)
def get_midright(self):
return (self.x + self.width, self.y + self.height/2)
def set_midright(self, midright):
x, y = midright
self.x = x - self.width
self.y = y - self.height/2
midright = property(get_midright, set_midright)
# r/w, in pixels, (x, y)
def get_topleft(self):
return (self.x, self.y + self.height)
def set_topleft(self, pos):
x, y = pos
self.x = x
self.y = y - self.height
topleft = property(get_topleft, set_topleft)
# r/w, in pixels, (x, y)
def get_topright(self):
return (self.x + self.width, self.y + self.height)
def set_topright(self, pos):
x, y = pos
self.x = x - self.width
self.y = y - self.height
topright = property(get_topright, set_topright)
# r/w, in pixels, (x, y)
def get_bottomright(self):
return (self.x + self.width, self.y)
def set_bottomright(self, pos):
x, y = pos
self.x = x - self.width
self.y = y
bottomright = property(get_bottomright, set_bottomright)
# r/w, in pixels, (x, y)
def get_bottomleft(self):
return (self.x, self.y)
def set_bottomleft(self, pos):
self.x, self.y = pos
bottomleft = property(get_bottomleft, set_bottomleft)
class RotatableSprite(Sprite):
'''A sprite that may be rotated.
Additional attributes:
angle -- angle of rotation in degrees
'''
def __init__(self, x, y, width, height, image, angle=0,
offset=(0,0), properties=None):
self._angle = angle
super(RotatableSprite, self).__init__(x, y, width, height, image,
offset, properties)
def get_angle(self):
return self._angle
def set_angle(self, angle):
self._angle = angle
self._style.angle = angle
angle = property(get_angle, set_angle)
@classmethod
def from_image(cls, x, y, image, angle=0, offset=(0,0),
properties=None):
'''Set up the sprite from the image - sprite dimensions are the
same as the image.'''
return cls(x, y, image.width, image.height, image, angle,
offset, properties)
def get_drawstyle(self):
style = self.image.get_style().copy()
style.x, style.y = self._x, self._y
style.angle = self._angle
return style
"""
class SpriteAnimation:
def animate(self, sprite, dt):
''' run this animation to handle passing of dt time. alters sprite
position and optionally image'''
raise NotImplemented()
class JumpAnimation(SpriteAnimation):
velocity = (vx, vy) # in pixels / second?
gravity = # in pixels / second?
ground = # height of ground
map = # tilemap with the ground / walls in it
image = # optional ImageAnimation to run
class PathAnimation(SpriteAnimation):
''' Will animate smoothly from one position to another, optionallyo to
another, optionally accelerating, etc. '''
points = [(x, y)] # points to move to in order
speed = # initial speed in direction of first point
velocity = # initial velocity if not in ^^^
turn_speed = # optional speed to slow to for turning
acceleration = # needed if turn_speed != None
max_speed = # needed if acceleration != None
"""
| Python |
#!/usr/bin/env python
'''Example of simple text wrapping without using layout.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
from pyglet.gl import *
from pyglet.window import Window
from pyglet.window import key
from pyglet import clock
from pyglet import font
from scene2d.textsprite import *
window = Window(visible=False, resizable=True)
arial = font.load('Arial', 24)
text = 'Type away... '
@window.event
def on_resize(width, height):
sprite.width = width
sprite.x = 10
@window.event
def on_text(text):
sprite.text += text.replace('\r', '\n')
@window.event
def on_key_press(symbol, modifiers):
if symbol == key.BACKSPACE:
sprite.text = sprite.text[:-1]
sprite = TextSprite(arial, text, color=(0, 0, 0, 1))
fps = clock.ClockDisplay()
window.push_handlers(fps)
glClearColor(1, 1, 1, 1)
window.set_visible()
while not window.has_exit:
window.dispatch_events()
clock.tick()
glClear(GL_COLOR_BUFFER_BIT)
sprite.y = sprite.height # TODO align on bottom
sprite.draw()
fps.draw()
window.flip()
| Python |
import os
import math
import pyglet.window
from resource import *
from pyglet.window import key
from pyglet import clock
from scene2d import *
class PlayerSprite(Sprite):
bullets = []
def update(self, dt):
self.x += (keyboard[key.RIGHT] - keyboard[key.LEFT]) * 200 * dt
if self.left < 0: self.left = 0
if self.right > w.width: self.right = w.width
if self.properties['fired']:
self.properties['fired'] = max(0, self.properties['fired'] - dt)
if keyboard[key.SPACE]:
if not self.properties['fired']:
self.properties['fired'] = 1
shot = Sprite.from_image(0, 0, r['player-bullet'])
shot.midbottom = self.midtop
view.sprites.append(shot)
self.bullets.append(shot)
class EnemySprite(Sprite):
bullets = []
def update(self, dt):
self.x += self.properties['dx'] * dt
if self.right > w.width:
self.right = w.width
self.properties['dx'] *= -1
if self.x < 0:
self.x = 0
self.properties['dx'] *= -1
if not self.properties['fired']:
self.properties['fired'] = 5
shot = Sprite.from_image(0, 0, r['enemy-bullet1'])
shot.midtop = self.midbottom
view.sprites.append(shot)
self.bullets.append(shot)
else:
self.properties['fired'] = max(0, self.properties['fired'] - dt)
w = pyglet.window.Window(width=512, height=512)
w.set_exclusive_mouse()
clock.set_fps_limit(30)
# load the map and car and set up the view
dirname = os.path.dirname(__file__)
r = Resource.load(os.path.join(dirname, 'invaders.xml'))
player = PlayerSprite.from_image(0, 0, r['player'], properties=dict(fired=0))
clock.schedule(player.update)
view = FlatView.from_window(w, fx=w.width/2, fy=w.height/2,
sprites=[player])
dead = False
enemies = [
EnemySprite.from_image(100, 400, r['enemy1'],
properties={'dx': 150, 'fired': 0})
]
for enemy in enemies:
view.sprites.append(enemy)
clock.schedule(enemy.update)
keyboard = key.KeyStateHandler()
w.push_handlers(keyboard)
while not (w.has_exit or dead):
dt = clock.tick()
w.dispatch_events()
# collision detection
for shot in list(enemies[0].bullets):
shot.y -= 200 * dt
if shot.overlaps(player):
print 'YOU LOST!'
dead = True
break
if shot.y < 0:
enemies[0].bullets.remove(shot)
view.sprites.remove(shot)
for shot in list(player.bullets):
shot.y += 200 * dt
for enemy in list(enemies):
if shot.overlaps(enemy):
view.sprites.remove(enemy)
enemies.remove(enemy)
clock.unschedule(enemy.update)
if shot.y > 512:
player.bullets.remove(shot)
view.sprites.remove(shot)
# end game
if not enemies:
print 'YOU WON!'
break
view.clear()
view.draw()
w.flip()
w.close()
| Python |
# Lots Of Sprites
'''
Results (us per sprite per frame):
sprites AMD64/mesa AMD64/nv6.6k MacBook Pro AMD/nv7.8k
2000 28.3 29.3 20.6 22.0
after __slots__ removal
sprites AMD64/mesa AMD64/nv6.6k MacBook Pro AMD/nv7.8k
2000
'''
import os
import sys
import random
from pyglet import options
options['debug_gl'] = False
from pyglet.window import Window
from pyglet import clock
from scene2d import *
from pyglet.gl import *
w = Window(600, 600, vsync=False)
img = Image2d.load('examples/noisy/ball.png')
class BouncySprite(Sprite):
dx = dy = 0
def update(self):
# move, check bounds
p = self.properties
self.x += self.dx; self.y += self.dy
if self.x < 0: self.x = 0; self.dx = -self.dx
elif self.right > 600: self.right = 600; self.dx = -self.dx
if self.y < 0: self.y = 0; self.dy = -self.dy
elif self.top > 600: self.top = 600; self.dy = -self.dy
sprites = []
numsprites = int(sys.argv[1])
for i in range(numsprites):
x = random.randint(0, w.width-img.width)
y = random.randint(0, w.height-img.height)
s = BouncySprite(x, y, img.width, img.height, img)
s.dx = random.randint(-10, 10)
s.dy = random.randint(-10, 10)
sprites.append(s)
view = FlatView.from_window(w, sprites=sprites)
view.fx, view.fy = w.width/2, w.height/2
t = 0
numframes = 0
while 1:
if w.has_exit:
print 'FPS:', clock.get_fps()
print 'us per sprite:', float(t) / (numsprites * numframes) * 1000000
break
t += clock.tick()
w.dispatch_events()
for s in sprites: s.update()
view.clear()
view.draw()
w.flip()
numframes += 1
w.close()
| Python |
import os
import math
import pyglet.window
from pyglet.window.event import *
from pyglet.window import key
from pyglet import clock
from euclid import Vector2, Matrix3
from scene2d import *
class CarSprite(RotatableSprite):
def update(self, dt):
# handle input and move the car
self.angle += (keyboard[key.LEFT] - keyboard[key.RIGHT]) * 150 * dt
speed = self.properties.get('speed', 0)
speed += (keyboard[key.UP] - keyboard[key.DOWN]) * 75
if speed > 300: speed = 300
if speed < -150: speed = -150
self.properties['speed'] = speed
r = Matrix3.new_rotate(math.radians(self.get_angle()))
v = dt * speed * (r * Vector2(0, 1))
self.x += v.x
self.y += v.y
w = pyglet.window.Window(width=512, height=512)
w.set_exclusive_mouse()
# load the map and car and set up the scene and view
dirname = os.path.dirname(__file__)
m = RectMap.load_xml(os.path.join(dirname, 'road-map.xml'), 'map0')
car = CarSprite.from_image(0, 0, Image2d.load(os.path.join(dirname, 'car.png')))
view = FlatView.from_window(w, layers=[m], sprites=[car])
keyboard = key.KeyStateHandler()
w.push_handlers(keyboard)
clock.set_fps_limit(30)
clock.schedule(car.update)
while not w.has_exit:
dt = clock.tick()
w.dispatch_events()
# re-focus on the car
view.fx, view.fy = car.center
# draw
view.draw()
w.flip()
w.close()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
from pyglet.window import Window
from pyglet import clock
from scene2d.textsprite import *
from pyglet import font
width, height = 640, 480
window = Window(width=width, height=height)
arial = font.load('Arial', 500, bold=True)
commander = TextSprite(arial, 'COMMANDER', color=(1, 1, 1, 0.5))
keen = TextSprite(arial, 'KEEN', color=(1, 1, 1, 0.5))
print dir(keen)
commander.x = width
keen.x = -keen.width
commander.dx = -(commander.width + width) / 10
keen.dx = (keen.width + width) / 10
clock.set_fps_limit(30)
while not window.has_exit:
window.dispatch_events()
time = clock.tick()
glClear(GL_COLOR_BUFFER_BIT)
for text in (commander, keen):
glLoadIdentity()
text.x += text.dx * time
text.draw()
window.flip()
| Python |
import sys
sys.path.insert(0, '/home/richard/src/pyglet.googlecode.com/trunk')
import os
import math
import pyglet.window
from resource import *
from pyglet.window import key
from pyglet import clock
from scene2d import *
from scene2d.textsprite import *
from pyglet import font
from layout import *
class RocketSprite(Sprite):
def update(self, dt):
p = self.properties
p['dx'] += (keyboard[key.RIGHT] - keyboard[key.LEFT]) * 25 * dt
p['dx'] = min(300, max(-300, p['dx']))
if keyboard[key.SPACE]:
if flame not in effectlayer.sprites:
effectlayer.sprites.append(flame)
p['dy'] += 50 * dt
elif flame in effectlayer.sprites:
effectlayer.sprites.remove(flame)
p['dy'] = min(300, max(-300, p['dy']))
gravity = 25
# don't need topleft or topright until I get a ceiling
for point in (self.bottomleft, self.bottomright):
cell = r['level1'].get(*map(int, point))
if cell is None or cell.tile is None: continue
if 'pad' in cell.tile.properties:
p['done'] = 1
gravity = 0
if p['dy'] < 0: p['dy'] = 0
p['dx'] = 0
self.bottom = cell.top - 1
elif 'open' not in cell.tile.properties:
p['done'] = 2
clock.unschedule(self.update)
if flame in effectlayer.sprites:
effectlayer.sprites.remove(flame)
boom.center = self.midbottom
if boom not in effectlayer.sprites:
effectlayer.sprites.append(boom)
p['dy'] -= gravity * dt
self.y += p['dy']
self.x += p['dx']
flame.midtop = self.midbottom
class AnimatedSprite(Sprite):
def update(self, dt):
p = self.properties
p['t'] += dt
if p['t'] > .1:
p['t'] = 0
p['frame'] = (p['frame'] + 1) % len(p['frames'])
self.image = p['frames'][p['frame']]
# XXX hack to ensure we use the new image
self._style = None
# open window
w = pyglet.window.Window(width=1280, height=1024, fullscreen=True)
#w = pyglet.window.Window(width=800, height=600)
w.set_exclusive_mouse()
clock.set_fps_limit(60)
keyboard = key.KeyStateHandler()
w.push_handlers(keyboard)
class SaveHandler:
def on_text(self, text):
if text == 's':
image = pyglet.image.BufferImage().get_raw_image()
fn = 'screenshot.png'
n = 1
while os.path.exists(fn):
fn = 'screenshot' + str(n) + '.png'
n += 1
print "Saving to '%s'"%fn
image.save(fn)
w.push_handlers(SaveHandler())
font = font.load('Bitstream Vera Sans', 24)
# load the sprites & level
dirname = os.path.dirname(__file__)
r = Resource.load(os.path.join(dirname, 'lander.xml'))
rocket = RocketSprite.from_image(0, 0, r['rocket'], offset=(18, 0),
properties=dict(dx=0, dy=0, done=0))
rocket.width = 92
frames = [r['flame%d'%i] for i in range(1, 7)]
flame = AnimatedSprite.from_image(0, 0, frames[0],
properties=dict(frame=0, t=0, frames=frames))
clock.schedule(flame.update)
frames = [r['boom%d'%i] for i in range(1, 4)]
boom = AnimatedSprite.from_image(0, 0, frames[0],
properties=dict(frame=0, t=0, frames=frames))
clock.schedule(boom.update)
fps = clock.ClockDisplay(color=(1., .5, .5, .5))
effectlayer = SpriteLayer(5)
rocketlayer = SpriteLayer(1, [rocket])
def play(level):
view = FlatView.from_window(w, layers=[level, effectlayer, rocketlayer])
# set rocket start
for col in level.cells:
for cell in col:
if 'player-start' in cell.properties:
rocket.midtop = cell.midtop
clock.schedule(rocket.update)
rocket.properties.update(dict(dx=0, dy=0, done=0))
# run game
while not (w.has_exit or rocket.properties['done']):
dt = clock.tick()
w.dispatch_events()
view.fx, view.fy = rocket.center
view.clear((.2, .2, .2, .2))
view.draw()
fps.draw()
w.flip()
# put up a message
done = rocket.properties['done']
if not done: return
if done == 1: text = 'YAY YOU LANDED!'
if done == 2: text = 'BOO YOU CRASHED!'
text += ' (press [escape] to continue)'
sprite = TextSprite(font, text, color=(1., 1., 1., 1.))
sprite.x, sprite.y = w.width/2 - sprite.width/2, w.height/2 - sprite.height/2
w.has_exit = False
while not w.has_exit:
dt = clock.tick()
w.dispatch_events()
view.clear((.2, .2, .2, .2))
view.draw()
sprite.draw()
w.flip()
clock.unschedule(rocket.update)
if boom in effectlayer.sprites:
effectlayer.sprites.remove(boom)
data = '''<?xml version="1.0"?><html><head>
<style>
h1 {border-bottom: 1px solid;}
body {background-color: black; color: white; font-family: sans-serif; font-size: 150%;}
tt {background-color: #aaa; color: black;}
</style></head><body>
<h1>Lunar Lander (yet another clone)</h1>
<p><b>Controls:</b></p>
<p><tt>[space]</tt> fires the rocket's motors</p>
<p><tt>[left/right arrows]</tt> push the rocket left or right</p>
<p></p>
<p>Press <tt>[space]</tt> to play or <tt>[escape]</tt> to quit.</p>
</body></html>'''
layout = Layout()
layout.set_xhtml(data)
layout.on_resize(w.width, w.height)
def menu():
w.has_exit = False
glClearColor(0, 0, 0, 0)
while not w.has_exit:
dt = clock.tick()
w.dispatch_events()
if keyboard[key.SPACE]: return True
glClear(GL_COLOR_BUFFER_BIT)
layout.draw()
w.flip()
return False
while 1:
if not menu():
break
play(r['level1'])
w.close()
| Python |
#!/usr/bin/env python
'''Testing mouse interaction
The cell the mouse is hovering over should highlight in red.
Clicking in a cell should highliht that cell green. Clicking again will
clear the highlighting.
Clicking on the ball sprite should highlight it and not underlying cells.
You may press the arrow keys to scroll the focus around the map (this
will move the map eventually)
Press escape or close the window to finish the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from render_base import RenderBase
from scene2d import Tile, Sprite
from pyglet.event import event
from scene2d.event import for_cells, for_sprites
from scene2d.drawable import TintEffect
from scene2d.debug import gen_rect_map
class RectFlatMouseTest(RenderBase):
def test_main(self):
self.init_window(256, 256)
self.set_map(gen_rect_map([[{}]*10]*10, 32, 32))
self.w.push_handlers(self.view)
self.view.allow_oob = False
@event(self.view)
@for_cells()
def on_mouse_enter(cells):
for cell in cells:
e = TintEffect((1, .5, .5, 1))
cell.properties['hover'] = e
cell.add_effect(e)
@event(self.view)
@for_cells()
def on_mouse_leave(cells):
for cell in cells:
cell.remove_effect(cell.properties['hover'])
@event(self.view)
@for_cells()
@for_sprites()
def on_mouse_press(objs, x, y, button, modifiers):
for obj in objs:
if 'clicked' in obj.properties:
obj.remove_effect(obj.properties['clicked'])
del obj.properties['clicked']
else:
e = TintEffect((.5, 1, .5, 1))
obj.properties['clicked'] = e
obj.add_effect(e)
return
self.show_focus()
self.run_test()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Testing loading of a map.
You should see a simple map with a circular road on it.
The tiles are not well-designed :)
Press escape or close the window to finish the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import unittest
from render_base import RenderBase
import scene2d
class MapLoadTest(RenderBase):
def test_main(self):
map_xml = os.path.join(os.path.dirname(__file__), 'map.xml')
self.init_window(256, 256)
self.set_map(scene2d.RectMap.load_xml(map_xml, 'test'))
self.view.allow_oob = False
self.run_test()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Testing the sprite model.
This test should just run without failing.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from pyglet.window import Window
from pyglet.image import SolidColorImagePattern
from scene2d import Sprite, Image2d
class SpriteModelTest(unittest.TestCase):
def setUp(self):
self.w = Window(width=1, height=1, visible=False)
self.s = Sprite(10, 10, 10, 10,
Image2d.from_image(SolidColorImagePattern((0, 0, 0,
0)).create_image(1, 1)))
assert (self.s.x, self.s.y) == (10, 10)
def tearDown(self):
self.w.close()
def test_top(self):
assert self.s.top == 20
self.s.top = 10
assert (self.s.x, self.s.y) == (10, 0)
def test_bottom(self):
assert self.s.bottom == 10
self.s.bottom = 0
assert (self.s.x, self.s.y) == (10, 0)
def test_right(self):
assert self.s.right == 20
self.s.right = 10
assert (self.s.x, self.s.y) == (0, 10)
def test_left(self):
assert self.s.left == 10
self.s.left = 0
assert (self.s.x, self.s.y) == (0, 10)
def test_center(self):
assert self.s.center == (15, 15)
self.s.center = (5, 5)
assert (self.s.x, self.s.y) == (0, 0)
def test_midtop(self):
assert self.s.midtop == (15, 20)
self.s.midtop = (5, 5)
assert (self.s.x, self.s.y) == (0, -5)
def test_midbottom(self):
assert self.s.midbottom == (15, 10)
self.s.midbottom = (5, 5)
assert (self.s.x, self.s.y) == (0, 5)
def test_midleft(self):
assert self.s.midleft == (10, 15)
self.s.midleft = (5, 5)
assert (self.s.x, self.s.y) == (5, 0)
def test_midright(self):
assert self.s.midright == (20, 15)
self.s.midright = (5, 5)
assert (self.s.x, self.s.y) == (-5, 0)
def test_topleft(self):
assert self.s.topleft == (10, 20)
self.s.topleft = (5, 5)
assert (self.s.x, self.s.y) == (5, -5)
def test_topright(self):
assert self.s.topright == (20, 20)
self.s.topright = (5, 5)
assert (self.s.x, self.s.y) == (-5, -5)
def test_bottomright(self):
assert self.s.bottomright == (20, 10)
self.s.bottomright = (5, 5)
assert (self.s.x, self.s.y) == (-5, 5)
def test_bottomleft(self):
assert self.s.bottomleft == (10, 10)
self.s.bottomleft = (5, 5)
assert (self.s.x, self.s.y) == (5, 5)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Testing flat map allow_oob enforcement.
Press arrow keys to move view focal point (little ball) around map.
Press "o" to turn allow_oob on and off.
You should see no black border with allow_oob=False.
Press escape or close the window to finish the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from render_base import RenderBase
import scene2d
from scene2d.debug import gen_rect_map
class OOBTest(RenderBase):
def test_main(self):
self.init_window(256, 256)
self.set_map(gen_rect_map([[{}]*10]*10, 32, 32))
def on_text(text):
if text == 'o':
self.view.allow_oob = not self.view.allow_oob
print 'NOTE: allow_oob =', self.view.allow_oob
return
return pyglet.window.event.EVENT_UNHANDLED
print 'NOTE: allow_oob =', self.view.allow_oob
self.w.push_handlers(on_text)
self.show_focus()
self.run_test()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Testing loading of a map.
You should see a simple map with a circular road on it.
The tiles are not well-designed :)
Press escape or close the window to finish the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import unittest
from render_base import RenderBase
import scene2d
class MapLoadTest(RenderBase):
def test_main(self):
map_xml = os.path.join(os.path.dirname(__file__), 'hexmap.xml')
self.init_window(256, 256)
self.set_map(scene2d.RectMap.load_xml(map_xml, 'test'))
self.view.allow_oob = False
self.run_test()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Testing flat map allow_oob enforcement.
Press 0-9 to set the size of the view in the window (1=10%, 0=100%)
Press arrow keys to move view focal point (little ball) around map.
Press "o" to turn allow_oob on and off.
You should see no black border with allow_oob=False.
Press escape or close the window to finish the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from render_base import RenderBase
import scene2d
from pyglet.event import *
from pyglet.window.event import *
from pyglet.window import key
from scene2d.debug import gen_rect_map
class OOBTest(RenderBase):
def test_main(self):
self.init_window(256, 256)
self.set_map(gen_rect_map([[{}]*10]*10, 32, 32))
@event(self.w)
def on_text(text):
if text == 'o':
self.view.allow_oob = not self.view.allow_oob
print 'NOTE: allow_oob =', self.view.allow_oob
return
try:
size = int(25.6 * float(text))
if size == 0: size = 256
c = self.view.camera
c.width = c.height = size
c.x = c.y = (256-size)/2
except:
return EVENT_UNHANDLED
print 'NOTE: allow_oob =', self.view.allow_oob
self.show_focus()
self.run_test()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Testing a sprite.
The ball should bounce off the sides of the window. You may resize the
window.
This test should just run without failing.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import unittest
from pyglet.gl import glClear
import pyglet.window
import pyglet.window.event
from pyglet import clock
from scene2d import Sprite, Image2d, FlatView
from scene2d.camera import FlatCamera
ball_png = os.path.join(os.path.dirname(__file__), 'ball.png')
class FlatSpriteTest(unittest.TestCase):
def test_sprite(self):
w = pyglet.window.Window(width=320, height=320)
image = Image2d.load(ball_png)
ball = Sprite(0, 0, 64, 64, image)
view = FlatView(0, 0, 320, 320, sprites=[ball])
w.push_handlers(view.camera)
dx, dy = (10, 5)
clock.set_fps_limit(30)
while not w.has_exit:
clock.tick()
w.dispatch_events()
# move, check bounds
ball.x += dx; ball.y += dy
if ball.left < 0: ball.left = 0; dx = -dx
elif ball.right > w.width: ball.right = w.width; dx = -dx
if ball.bottom < 0: ball.bottom = 0; dy = -dy
elif ball.top > w.height: ball.top = w.height; dy = -dy
# keep our focus in the middle of the window
view.fx = w.width/2
view.fy = w.height/2
view.clear()
view.draw()
w.flip()
w.close()
if __name__ == '__main__':
unittest.main()
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.